blob: d85cbb2451c2ad3cf9137aa8e2c0d8eb771d4f6c [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
12 * Used for both the console version and the Win32 GUI. A lot of code is for
Bram Moolenaar4f974752019-02-17 17:44:42 +010013 * the console version only, so there is a lot of "#ifndef FEAT_GUI_MSWIN".
Bram Moolenaar071d4272004-06-13 20:20:40 +000014 *
Nir Lichtman563e8ec2024-09-30 19:42:28 +020015 * Win32 system-dependent routines.
Bram Moolenaar071d4272004-06-13 20:20:40 +000016 * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17 * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18 *
19 * George V. Reilly <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
Bram Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010032
Bram Moolenaar0f873732019-12-05 20:28:46 +010033// cproto fails on missing include files
Bram Moolenaar82881492012-11-20 16:53:39 +010034#ifndef PROTO
35# include <process.h>
Bram Moolenaare7bebc42021-02-01 20:50:37 +010036# include <winternl.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000037# include <direct.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000038
Bram Moolenaar651fca82021-11-29 20:39:38 +000039# if !defined(FEAT_GUI_MSWIN)
Bram Moolenaar82881492012-11-20 16:53:39 +010040# include <shellapi.h>
41# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000042
K.Takata56f587b2024-06-19 19:56:03 +020043# ifdef FEAT_JOB_CHANNEL
44# include <tlhelp32.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000045# endif
46#endif
47
Bram Moolenaar0f873732019-12-05 20:28:46 +010048// Record all output and all keyboard & mouse input
49// #define MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +000050
51#ifdef MCH_WRITE_DUMP
52FILE* fdDump = NULL;
53#endif
54
55/*
56 * When generating prototypes for Win32 on Unix, these lines make the syntax
57 * errors disappear. They do not need to be correct.
58 */
59#ifdef PROTO
Bram Moolenaar912bc4a2019-12-01 18:58:11 +010060# define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000061typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000062typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +000063typedef int ACCESS_MASK;
64typedef int BOOL;
Paul Ollis65745772022-06-05 16:55:54 +010065typedef int BOOLEAN;
66typedef int CALLBACK;
Bram Moolenaar071d4272004-06-13 20:20:40 +000067typedef int COLORREF;
68typedef int CONSOLE_CURSOR_INFO;
69typedef int COORD;
70typedef int DWORD;
71typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +010072typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000073typedef int HDC;
74typedef int HFONT;
75typedef int HICON;
76typedef int HINSTANCE;
77typedef int HWND;
78typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +020079typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +000080typedef int KEY_EVENT_RECORD;
81typedef int LOGFONT;
82typedef int LPBOOL;
83typedef int LPCTSTR;
84typedef int LPDWORD;
85typedef int LPSTR;
86typedef int LPTSTR;
87typedef int LPVOID;
88typedef int MOUSE_EVENT_RECORD;
89typedef int PACL;
90typedef int PDWORD;
91typedef int PHANDLE;
92typedef int PRINTDLG;
93typedef int PSECURITY_DESCRIPTOR;
94typedef int PSID;
95typedef int SECURITY_INFORMATION;
96typedef int SHORT;
97typedef int SMALL_RECT;
98typedef int TEXTMETRIC;
99typedef int TOKEN_INFORMATION_CLASS;
100typedef int TRUSTEE;
101typedef int WORD;
102typedef int WCHAR;
103typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100104typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200105typedef int SE_OBJECT_TYPE;
106typedef int PSNSECINFO;
107typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100108typedef int STARTUPINFO;
109typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200110typedef int LPSECURITY_ATTRIBUTES;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100111# define __stdcall // empty
Bram Moolenaar071d4272004-06-13 20:20:40 +0000112#endif
113
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200114#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100115// Win32 Console handles for input and output
Bram Moolenaar071d4272004-06-13 20:20:40 +0000116static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
117static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
118
Bram Moolenaar0f873732019-12-05 20:28:46 +0100119// Win32 Screen buffer,coordinate,console I/O information
Bram Moolenaar071d4272004-06-13 20:20:40 +0000120static SMALL_RECT g_srScrollRegion;
Saleem Abdulrasool38bea302023-12-27 18:57:12 +0100121// This is explicitly initialised to work around a LTCG issue on Windows ARM64
122// (at least of 19.39.33321). This pushes this into the `.data` rather than
123// `.bss` which corrects code generation in `write_chars` (#13453).
124static COORD g_coord = {0, 0}; // 0-based, but external coords are 1-based
Bram Moolenaar071d4272004-06-13 20:20:40 +0000125
Bram Moolenaar0f873732019-12-05 20:28:46 +0100126// The attribute of the screen when the editor was started
127static WORD g_attrDefault = 7; // lightgray text on black background
Bram Moolenaar071d4272004-06-13 20:20:40 +0000128static WORD g_attrCurrent;
129
Bram Moolenaar0f873732019-12-05 20:28:46 +0100130static int g_fCBrkPressed = FALSE; // set by ctrl-break interrupt
131static int g_fCtrlCPressed = FALSE; // set when ctrl-C or ctrl-break detected
132static int g_fForceExit = FALSE; // set when forcefully exiting
Bram Moolenaar071d4272004-06-13 20:20:40 +0000133
Bram Moolenaar071d4272004-06-13 20:20:40 +0000134static void scroll(unsigned cLines);
135static void set_scroll_region(unsigned left, unsigned top,
136 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100137static void set_scroll_region_tb(unsigned top, unsigned bottom);
138static void set_scroll_region_lr(unsigned left, unsigned right);
139static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000140static void delete_lines(unsigned cLines);
141static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000142static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000143static int s_cursor_visible = TRUE;
144static int did_create_conin = FALSE;
Christopher Plewright20b795e2022-12-20 20:01:58 +0000145// The 'input_record_buffer' is an internal dynamic fifo queue of MS-Windows
146// console INPUT_RECORD events that are normally read from the console input
147// buffer. This provides an injection point for testing the low-level handling
148// of INPUT_RECORDs.
149typedef struct input_record_buffer_node_S
150{
151 INPUT_RECORD ir;
152 struct input_record_buffer_node_S *next;
153} input_record_buffer_node_T;
154typedef struct input_record_buffer_S
155{
156 input_record_buffer_node_T *head;
157 input_record_buffer_node_T *tail;
158 int length;
159} input_record_buffer_T;
160static input_record_buffer_T input_record_buffer;
Christopher Plewright20b795e2022-12-20 20:01:58 +0000161static int read_input_record_buffer(INPUT_RECORD* irEvents, int nMaxLength);
162static int write_input_record_buffer(INPUT_RECORD* irEvents, int nLength);
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200163#endif
164#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000165static int s_dont_use_vimrun = TRUE;
166static int need_vimrun_warning = FALSE;
167static char *vimrun_path = "vimrun ";
168#endif
169
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200170static int win32_getattrs(char_u *name);
171static int win32_setattrs(char_u *name, int attrs);
172static int win32_set_archive(char_u *name);
173
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100174static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200175static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100176static int conpty_stable = 0;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +0200177static int conpty_fix_type = 0;
John Marriott2c7ccaa2025-05-26 20:25:38 +0200178static void vtp_flag_init(void);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100179
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200180#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100181static int vtp_working = 0;
John Marriott2c7ccaa2025-05-26 20:25:38 +0200182static void vtp_init(void);
183static void vtp_exit(void);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100184static void vtp_sgr_bulk(int arg);
185static void vtp_sgr_bulks(int argc, int *argv);
186
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200187static int wt_working = 0;
Christopher Plewright1140b512022-11-12 18:46:05 +0000188static void wt_init(void);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200189
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200190static int g_color_index_bg = 0;
191static int g_color_index_fg = 7;
192
193# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +0000194static guicolor_T save_console_bg_rgb;
195static guicolor_T save_console_fg_rgb;
196static guicolor_T store_console_bg_rgb;
197static guicolor_T store_console_fg_rgb;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +0100198static int default_console_color_bg = 0x000000; // black
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200199static int default_console_color_fg = 0xc0c0c0; // white
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +0000200# define USE_VTP (vtp_working && is_term_win32() \
201 && (p_tgc || t_colors >= 256))
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200202# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100203# else
204# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200205# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100206# endif
207
208static void set_console_color_rgb(void);
209static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100210static void restore_console_color_rgb(void);
Christopher Plewright20b795e2022-12-20 20:01:58 +0000211#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100212
Bram Moolenaar0f873732019-12-05 20:28:46 +0100213// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100214#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
215# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
216#endif
217
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200218#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100219static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000220#endif
221
K.Takatace3189d2023-02-15 19:13:43 +0000222static WCHAR *exe_pathw = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200223
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100224static BOOL win8_or_later = FALSE;
Christopher Plewrightc8b126d2022-12-22 13:45:23 +0000225static BOOL win10_22H2_or_later = FALSE;
Bram Moolenaar9fca1332022-12-22 21:06:41 +0000226#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Christopher Plewrightc8b126d2022-12-22 13:45:23 +0000227static BOOL use_alternate_screen_buffer = FALSE;
Bram Moolenaar9fca1332022-12-22 21:06:41 +0000228#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100229
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100230/*
231 * Get version number including build number
232 */
233typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100234#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100235 (((major) << 24) | ((minor) << 16) | (build))
236
237 static DWORD
238get_build_number(void)
239{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100240 OSVERSIONINFOW osver;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100241 HMODULE hNtdll;
242 PfnRtlGetVersion pRtlGetVersion;
243 DWORD ver = MAKE_VER(0, 0, 0);
244
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100245 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100246 hNtdll = GetModuleHandle("ntdll.dll");
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000247 if (hNtdll == NULL)
248 return ver;
249
250 pRtlGetVersion =
251 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
252 pRtlGetVersion(&osver);
253 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
254 min(osver.dwMinorVersion, 255),
255 min(osver.dwBuildNumber, 32767));
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100256 return ver;
257}
258
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200259#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200260 static BOOL
261is_ambiwidth_event(
262 INPUT_RECORD *ir)
263{
264 return ir->EventType == KEY_EVENT
265 && ir->Event.KeyEvent.bKeyDown
266 && ir->Event.KeyEvent.wRepeatCount == 1
267 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
268 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000269 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200270 && ir->Event.KeyEvent.dwControlKeyState == 2;
271}
272
273 static void
274make_ambiwidth_event(
275 INPUT_RECORD *down,
276 INPUT_RECORD *up)
277{
278 down->Event.KeyEvent.wVirtualKeyCode = 0;
279 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000280 down->Event.KeyEvent.uChar.UnicodeChar
281 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200282 down->Event.KeyEvent.dwControlKeyState = 0;
283}
284
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100285/*
286 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100287 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100288 */
289 static BOOL
290read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100291 HANDLE hInput,
292 INPUT_RECORD *lpBuffer,
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100293 int nLength,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100294 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100295{
296 enum
297 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100298 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100299 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100300 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100301 static DWORD s_dwIndex = 0;
302 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100303 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100304 int head;
305 int tail;
306 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200307 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100308
Christopher Plewright20b795e2022-12-20 20:01:58 +0000309 if (s_dwMax == 0 && input_record_buffer.length > 0)
310 {
311 dwEvents = read_input_record_buffer(s_irCache, IRSIZE);
312 s_dwIndex = 0;
313 s_dwMax = dwEvents;
314 }
315
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200316 if (nLength == -2)
317 return (s_dwMax > 0) ? TRUE : FALSE;
318
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100319 if (!win8_or_later)
320 {
321 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200322 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
323 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100324 }
325
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100326 if (s_dwMax == 0)
327 {
Christopher Plewright38804d62022-11-09 23:55:52 +0000328 if (!vtp_working && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200329 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200330 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
331 if (dwEvents == 0 && nLength == -1)
332 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
333 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100334 s_dwIndex = 0;
335 s_dwMax = dwEvents;
336 if (dwEvents == 0)
337 {
338 *lpEvents = 0;
339 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100340 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100341
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200342 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
343 if (is_ambiwidth_event(&s_irCache[i]))
344 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
345
Bram Moolenaardd415a62014-02-05 14:02:27 +0100346 if (s_dwMax > 1)
347 {
348 head = 0;
349 tail = s_dwMax - 1;
350 while (head != tail)
351 {
352 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
353 && s_irCache[head + 1].EventType
354 == WINDOW_BUFFER_SIZE_EVENT)
355 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100356 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100357 for (i = head; i < tail; ++i)
358 s_irCache[i] = s_irCache[i + 1];
359 --tail;
360 continue;
361 }
362 head++;
363 }
364 s_dwMax = tail + 1;
365 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100366 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100367
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200368 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
369 {
370 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
371 {
372 s_irPseudo = s_irCache[s_dwIndex];
373 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
374 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
375 *lpBuffer = s_irPseudo;
376 *lpEvents = 1;
377 return TRUE;
378 }
379 }
380
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100381 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200382 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100383 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100384 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100385 return TRUE;
386}
387
388/*
389 * Version of PeekConsoleInput() that works with IME.
390 */
391 static BOOL
392peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100393 HANDLE hInput,
394 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200395 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100396 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100397{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100398 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100399}
400
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100401# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200402 static DWORD
403msg_wait_for_multiple_objects(
404 DWORD nCount,
405 LPHANDLE pHandles,
406 BOOL fWaitAll,
407 DWORD dwMilliseconds,
408 DWORD dwWakeMask)
409{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100410 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200411 return WAIT_OBJECT_0;
412 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
413 dwMilliseconds, dwWakeMask);
414}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100415# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200416
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100417# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200418 static DWORD
419wait_for_single_object(
420 HANDLE hHandle,
421 DWORD dwMilliseconds)
422{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100423 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200424 return WAIT_OBJECT_0;
425 return WaitForSingleObject(hHandle, dwMilliseconds);
426}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100427# endif
Christopher Plewright20b795e2022-12-20 20:01:58 +0000428#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200429
K.Takatace3189d2023-02-15 19:13:43 +0000430 void
431mch_get_exe_name(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000432{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100433 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
K.Takataf741e3e2023-05-15 16:41:40 +0100434 // as the maximum length that works. Add 1 for a NUL byte and 5 for
435 // "PATH=".
436#define MAX_ENV_PATH_LEN (8191 + 1 + 5)
437 WCHAR temp[MAX_ENV_PATH_LEN];
K.Takatace3189d2023-02-15 19:13:43 +0000438 WCHAR buf[MAX_PATH];
439 int updated = FALSE;
440 static int enc_prev = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000441
K.Takatace3189d2023-02-15 19:13:43 +0000442 if (exe_name == NULL || exe_pathw == NULL || enc_prev != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000443 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100444 // store the name of the executable, may be used for $VIM
K.Takatace3189d2023-02-15 19:13:43 +0000445 GetModuleFileNameW(NULL, buf, MAX_PATH);
446 if (*buf != NUL)
447 {
448 if (enc_codepage == -1)
449 enc_codepage = GetACP();
K.Takataf741e3e2023-05-15 16:41:40 +0100450 vim_free(exe_name);
K.Takatace3189d2023-02-15 19:13:43 +0000451 exe_name = utf16_to_enc(buf, NULL);
452 enc_prev = enc_codepage;
453
454 WCHAR *wp = wcsrchr(buf, '\\');
455 if (wp != NULL)
456 *wp = NUL;
K.Takataf741e3e2023-05-15 16:41:40 +0100457 vim_free(exe_pathw);
K.Takatace3189d2023-02-15 19:13:43 +0000458 exe_pathw = _wcsdup(buf);
459 updated = TRUE;
460 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000461 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000462
K.Takatace3189d2023-02-15 19:13:43 +0000463 if (exe_pathw == NULL || !updated)
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000464 return;
465
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000466 // Append our starting directory to $PATH, so that when doing
467 // "!xxd" it's found in our starting directory. Needed because
468 // SearchPath() also looks there.
K.Takataf741e3e2023-05-15 16:41:40 +0100469 WCHAR *p = _wgetenv(L"PATH");
470 if (p == NULL || wcslen(p) + wcslen(exe_pathw) + 2 + 5 < MAX_ENV_PATH_LEN)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000471 {
K.Takataf741e3e2023-05-15 16:41:40 +0100472 wcscpy(temp, L"PATH=");
473
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000474 if (p == NULL || *p == NUL)
K.Takataf741e3e2023-05-15 16:41:40 +0100475 wcscat(temp, exe_pathw);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000476 else
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000477 {
K.Takataf741e3e2023-05-15 16:41:40 +0100478 wcscat(temp, p);
479
480 // Check if exe_path is already included in $PATH.
481 if (wcsstr(temp, exe_pathw) == NULL)
482 {
483 // Append ';' if $PATH doesn't end with it.
484 size_t len = wcslen(temp);
485 if (temp[len - 1] != L';')
486 wcscat(temp, L";");
487
488 wcscat(temp, exe_pathw);
489 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000490 }
K.Takataf741e3e2023-05-15 16:41:40 +0100491 _wputenv(temp);
492#ifdef libintl_wputenv
493 libintl_wputenv(temp);
494#endif
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000495 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000496}
497
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200498/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100499 * Unescape characters in "p" that appear in "escaped".
500 */
501 static void
502unescape_shellxquote(char_u *p, char_u *escaped)
503{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100504 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100505 int n;
506
507 while (*p != NUL)
508 {
509 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
510 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100511 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100512 p += n;
513 l -= n;
514 }
515}
516
517/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200518 * Load library "name".
519 */
520 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000521vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200522{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200523 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200524
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200525 // No need to load any library when registering OLE.
526 if (found_register_arg)
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000527 return NULL;
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200528
Bram Moolenaar0f873732019-12-05 20:28:46 +0100529 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
530 // vimLoadLib() recursively, which causes a stack overflow.
K.Takatace3189d2023-02-15 19:13:43 +0000531 if (exe_pathw == NULL)
K.Takataf741e3e2023-05-15 16:41:40 +0100532 {
K.Takatace3189d2023-02-15 19:13:43 +0000533 mch_get_exe_name();
K.Takataf741e3e2023-05-15 16:41:40 +0100534 if (exe_pathw == NULL)
535 return NULL;
536 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000537
538 WCHAR old_dirw[MAXPATHL];
539
540 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) == 0)
541 return NULL;
542
543 // Change directory to where the executable is, both to make
544 // sure we find a .dll there and to avoid looking for a .dll
545 // in the current directory.
K.Takatace3189d2023-02-15 19:13:43 +0000546 SetCurrentDirectoryW(exe_pathw);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000547 dll = LoadLibrary(name);
548 SetCurrentDirectoryW(old_dirw);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200549 return dll;
550}
551
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200552#if defined(VIMDLL) || defined(PROTO)
553/*
554 * Check if the current executable file is for the GUI subsystem.
555 */
556 int
557mch_is_gui_executable(void)
558{
559 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
560 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
561 PIMAGE_NT_HEADERS pPE;
562
563 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
564 return FALSE;
565 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
566 if (pPE->Signature != IMAGE_NT_SIGNATURE)
567 return FALSE;
568 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
569 return TRUE;
570 return FALSE;
571}
572#endif
573
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000574#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
575 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100576/*
577 * Get related information about 'funcname' which is imported by 'hInst'.
578 * If 'info' is 0, return the function address.
579 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000580 * If 'info' is 2, hook the function with 'ptr', and return the original
581 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100582 */
583 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000584get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
585 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100586{
587 PBYTE pImage = (PBYTE)hInst;
588 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
589 PIMAGE_NT_HEADERS pPE;
590 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100591 PIMAGE_THUNK_DATA pIAT; // Import Address Table
592 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100593 PIMAGE_IMPORT_BY_NAME pImpName;
Ken Takata119fdd92023-10-04 20:05:05 +0200594 DWORD ImpVA;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100595
596 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
597 return NULL;
598 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
599 if (pPE->Signature != IMAGE_NT_SIGNATURE)
600 return NULL;
Ken Takata119fdd92023-10-04 20:05:05 +0200601
602 ImpVA = pPE->OptionalHeader
603 .DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
604 if (ImpVA == 0)
605 return NULL; // No Import Table
606 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage + ImpVA);
607
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100608 for (; pImpDesc->FirstThunk; ++pImpDesc)
609 {
610 if (!pImpDesc->OriginalFirstThunk)
611 continue;
612 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
613 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
614 for (; pIAT->u1.Function; ++pIAT, ++pINT)
615 {
616 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
617 continue;
618 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
619 + (UINT_PTR)(pINT->u1.AddressOfData));
620 if (strcmp((char *)pImpName->Name, funcname) == 0)
621 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000622 void *original;
623 DWORD old, new = PAGE_READWRITE;
624
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100625 switch (info)
626 {
627 case 0:
628 return (void *)pIAT->u1.Function;
629 case 1:
630 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000631 case 2:
632 original = (void *)pIAT->u1.Function;
633 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
634 new, &old);
635 pIAT->u1.Function = (UINT_PTR)ptr;
636 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
637 old, &new);
638 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100639 default:
640 return NULL;
641 }
642 }
643 }
644 }
645 return NULL;
646}
647
648/*
649 * Get the module handle which 'funcname' in 'hInst' is imported from.
650 */
651 HINSTANCE
652find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
653{
654 char *modulename;
655
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000656 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100657 if (modulename != NULL)
658 return GetModuleHandleA(modulename);
659 return NULL;
660}
661
662/*
663 * Get the address of 'funcname' which is imported by 'hInst' DLL.
664 */
665 void *
666get_dll_import_func(HINSTANCE hInst, const char *funcname)
667{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000668 return get_imported_func_info(hInst, funcname, 0, NULL);
669}
670
671/*
672 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
673 * and return the original function address.
674 */
675 void *
676hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
677{
678 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100679}
680#endif
681
Ken Takata119fdd92023-10-04 20:05:05 +0200682#if defined(FEAT_PYTHON3) || defined(PROTO)
683/*
684 * Check if the specified DLL is a function forwarder.
685 * If yes, return the instance of the forwarded DLL.
686 * If no, return the specified DLL.
687 * If error, return NULL.
688 * This assumes that the DLL forwards all the function to a single DLL.
689 */
690 HINSTANCE
691get_forwarded_dll(HINSTANCE hInst)
692{
693 PBYTE pImage = (PBYTE)hInst;
694 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
695 PIMAGE_NT_HEADERS pPE;
696 PIMAGE_EXPORT_DIRECTORY pExpDir;
697 DWORD ExpVA;
698 DWORD ExpSize;
699 LPDWORD pFunctionTable;
700
701 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
702 return NULL;
703 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
704 if (pPE->Signature != IMAGE_NT_SIGNATURE)
705 return NULL;
706
707 ExpVA = pPE->OptionalHeader
708 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
709 ExpSize = pPE->OptionalHeader
710 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
711 if (ExpVA == 0)
712 return hInst; // No Export Directory
713 pExpDir = (PIMAGE_EXPORT_DIRECTORY)(pImage + ExpVA);
714 pFunctionTable = (LPDWORD)(pImage + pExpDir->AddressOfFunctions);
715
716 if (pExpDir->NumberOfNames == 0)
717 return hInst; // No export names.
718
719 // Check only the first entry.
720 if ((pFunctionTable[0] < ExpVA) || (pFunctionTable[0] >= ExpVA + ExpSize))
721 // The first entry is not a function forwarder.
722 return hInst;
723
724 // The first entry is a function forwarder.
725 // The name is represented as "DllName.FunctionName".
726 const char *name = (const char *)(pImage + pFunctionTable[0]);
727 const char *p = strchr(name, '.');
728 if (p == NULL)
729 return hInst;
730
731 // Extract DllName.
732 char buf[MAX_PATH];
733 if (p - name + 1 > sizeof(buf))
734 return NULL;
735 strncpy(buf, name, p - name);
736 buf[p - name] = '\0';
737 return GetModuleHandleA(buf);
738}
739#endif
740
Bram Moolenaar071d4272004-06-13 20:20:40 +0000741#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
742# ifndef GETTEXT_DLL
743# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200744# define GETTEXT_DLL_ALT1 "libintl-8.dll"
745# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000746# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100747// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000748static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200749static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000750static char *null_libintl_textdomain(const char *);
751static char *null_libintl_bindtextdomain(const char *, const char *);
752static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100753static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000754
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200755static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000756char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200757char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
758 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000759char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
760char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000761 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000762char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
763 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100764int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000765
766 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100767dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000768{
769 int i;
770 static struct
771 {
772 char *name;
773 FARPROC *ptr;
774 } libintl_entry[] =
775 {
776 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200777 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000778 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
779 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
780 {NULL, NULL}
781 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100782 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000783
Bram Moolenaar7554c542018-10-06 15:03:15 +0200784 // No need to initialize twice.
785 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000786 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200787 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100788 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100789# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100790 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200791 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100792# endif
793# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200794 if (!hLibintlDLL)
795 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100796# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100797 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000798 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200799 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000800 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200801 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000802 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200803 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000804 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200805 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000806 }
807 for (i = 0; libintl_entry[i].name != NULL
808 && libintl_entry[i].ptr != NULL; ++i)
809 {
K.Takata54119102022-02-03 13:33:03 +0000810 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000811 libintl_entry[i].name)) == NULL)
812 {
813 dyn_libintl_end();
814 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000815 {
816 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000817 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000818 verbose_leave();
819 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000820 return 0;
821 }
822 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000823
Bram Moolenaar0f873732019-12-05 20:28:46 +0100824 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100825 dyn_libintl_bind_textdomain_codeset = (char *(*)(const char *, const char *))
826 GetProcAddress(hLibintlDLL, "bind_textdomain_codeset");
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000827 if (dyn_libintl_bind_textdomain_codeset == NULL)
828 dyn_libintl_bind_textdomain_codeset =
829 null_libintl_bind_textdomain_codeset;
830
Bram Moolenaar0f873732019-12-05 20:28:46 +0100831 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100832 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
833 if (hmsvcrt != NULL)
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100834 dyn_libintl_wputenv = (int (*)(const wchar_t *))
835 GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100836 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
837 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100838
Bram Moolenaar071d4272004-06-13 20:20:40 +0000839 return 1;
840}
841
842 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100843dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000844{
845 if (hLibintlDLL)
846 FreeLibrary(hLibintlDLL);
847 hLibintlDLL = NULL;
848 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200849 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000850 dyn_libintl_textdomain = null_libintl_textdomain;
851 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000852 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100853 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000854}
855
856 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000857null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000858{
859 return (char*)msgid;
860}
861
862 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200863null_libintl_ngettext(
864 const char *msgid,
865 const char *msgid_plural,
866 unsigned long n)
867{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200868 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200869}
870
Bram Moolenaaree695f72016-08-03 22:08:45 +0200871 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100872null_libintl_bindtextdomain(
873 const char *domainname UNUSED,
874 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000875{
876 return NULL;
877}
878
879 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100880null_libintl_bind_textdomain_codeset(
881 const char *domainname UNUSED,
882 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000883{
884 return NULL;
885}
886
887 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100888null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000889{
890 return NULL;
891}
892
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200893 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100894null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100895{
896 return 0;
897}
898
Bram Moolenaar0f873732019-12-05 20:28:46 +0100899#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000900
Bram Moolenaar0f873732019-12-05 20:28:46 +0100901// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000902
903#ifndef VER_PLATFORM_WIN32_WINDOWS
904# define VER_PLATFORM_WIN32_WINDOWS 1
905#endif
906
Bram Moolenaar071d4272004-06-13 20:20:40 +0000907#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100908# ifndef PROTO
909# include <aclapi.h>
910# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200911# ifndef PROTECTED_DACL_SECURITY_INFORMATION
912# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
913# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000914#endif
915
Bram Moolenaar27515922013-06-29 15:36:26 +0200916#ifdef HAVE_ACL
917/*
918 * Enables or disables the specified privilege.
919 */
920 static BOOL
Nir Lichtmanb5165982024-10-13 19:44:07 +0200921win32_enable_privilege(LPTSTR lpszPrivilege)
Bram Moolenaar27515922013-06-29 15:36:26 +0200922{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100923 LUID luid;
924 HANDLE hToken;
925 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200926
927 if (!OpenProcessToken(GetCurrentProcess(),
928 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
929 return FALSE;
930
931 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
932 {
933 CloseHandle(hToken);
934 return FALSE;
935 }
936
Bram Moolenaar45500912014-07-09 20:51:07 +0200937 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200938 tokenPrivileges.Privileges[0].Luid = luid;
Nir Lichtmanb5165982024-10-13 19:44:07 +0200939 tokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
Bram Moolenaar27515922013-06-29 15:36:26 +0200940
Nir Lichtmanb5165982024-10-13 19:44:07 +0200941 if (!AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges, 0, NULL, NULL))
942 {
943 CloseHandle(hToken);
944 return FALSE;
945 }
946
947 if (GetLastError() != ERROR_SUCCESS)
948 {
949 CloseHandle(hToken);
950 return FALSE;
951 }
Bram Moolenaar27515922013-06-29 15:36:26 +0200952
953 CloseHandle(hToken);
Nir Lichtmanb5165982024-10-13 19:44:07 +0200954 return TRUE;
Bram Moolenaar27515922013-06-29 15:36:26 +0200955}
956#endif
957
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100958#ifdef _MSC_VER
959// Suppress the deprecation warning for using GetVersionEx().
960// It is needed for implementing "windowsversion()".
961# pragma warning(push)
962# pragma warning(disable: 4996)
963#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000964/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200965 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000966 */
967 void
968PlatformId(void)
969{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000970 OSVERSIONINFO ovi;
971
972 ovi.dwOSVersionInfoSize = sizeof(ovi);
Nir Lichtmanb5165982024-10-13 19:44:07 +0200973 if (!GetVersionEx(&ovi))
Naruhiko Nishinoc2a90002025-05-04 20:05:47 +0200974 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000975
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200976#ifdef FEAT_EVAL
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000977 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
978 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200979#endif
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000980 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
981 || ovi.dwMajorVersion > 6)
982 win8_or_later = TRUE;
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100983
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000984 if ((ovi.dwMajorVersion == 10 && ovi.dwBuildNumber >= 19045)
985 || ovi.dwMajorVersion > 10)
986 win10_22H2_or_later = TRUE;
Christopher Plewright1140b512022-11-12 18:46:05 +0000987
Bram Moolenaar071d4272004-06-13 20:20:40 +0000988#ifdef HAVE_ACL
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000989 // Enable privilege for getting or setting SACLs.
Nir Lichtmanb5165982024-10-13 19:44:07 +0200990 if (!win32_enable_privilege(SE_SECURITY_NAME))
Naruhiko Nishinoc2a90002025-05-04 20:05:47 +0200991 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000992#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000993}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100994#ifdef _MSC_VER
995# pragma warning(pop)
996#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000997
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200998#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000999
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001000# define SHIFT (SHIFT_PRESSED)
1001# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
1002# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
1003# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001004
1005
Bram Moolenaar0f873732019-12-05 20:28:46 +01001006// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
1007// We map function keys to their ANSI terminal equivalents, as produced
1008// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
1009// ANSI key with a value >= '\300' is nonstandard, but provided anyway
1010// so that the user can have access to all SHIFT-, CTRL-, and ALT-
1011// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001012
Bram Moolenaard6f676d2005-06-01 21:51:55 +00001013static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +00001014{
1015 WORD wVirtKey;
1016 BOOL fAnsiKey;
1017 int chAlone;
1018 int chShift;
1019 int chCtrl;
1020 int chAlt;
1021} VirtKeyMap[] =
1022{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001023// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +00001024 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
1025
1026 { VK_F1, TRUE, ';', 'T', '^', 'h', },
1027 { VK_F2, TRUE, '<', 'U', '_', 'i', },
1028 { VK_F3, TRUE, '=', 'V', '`', 'j', },
1029 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
1030 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
1031 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
1032 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
1033 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
1034 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
1035 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001036 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
1037 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001038
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001039 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
1040 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
1041 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
1042 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
1043 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
1044 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
1045 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
1046 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
1047 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
1048 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001049 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +00001050
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001051 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +00001052
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001053# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001054 // Most people don't have F13-F20, but what the hell...
1055 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
1056 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
1057 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
1058 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
1059 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
1060 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
1061 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
1062 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001063# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001064 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
1065 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
1066 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
1067 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001068
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001069 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
1070 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
1071 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
1072 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
1073 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
1074 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
1075 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
1076 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
1077 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
1078 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001079 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001080};
1081
1082
Bram Moolenaar0f873732019-12-05 20:28:46 +01001083/*
1084 * The return code indicates key code size.
1085 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001086 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001087win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001088 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001089{
1090 UINT uMods = pker->dwControlKeyState;
1091 static int s_iIsDead = 0;
1092 static WORD awAnsiCode[2];
1093 static BYTE abKeystate[256];
1094
1095
1096 if (s_iIsDead == 2)
1097 {
K.Takata972db232022-02-04 10:45:38 +00001098 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001099 s_iIsDead = 0;
1100 return 1;
1101 }
1102
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001103 // check if it already has a valid unicode character.
Christopher Plewright566f76e2023-01-10 13:43:04 +00001104 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001105 return 1;
1106
Bram Moolenaara80faa82020-04-12 19:37:17 +02001107 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001108
Bram Moolenaar0f873732019-12-05 20:28:46 +01001109 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001110 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001111
1112 if (uMods & SHIFT_PRESSED)
1113 abKeystate[VK_SHIFT] = 0x80;
1114 if (uMods & CAPSLOCK_ON)
1115 abKeystate[VK_CAPITAL] = 1;
1116
1117 if ((uMods & ALT_GR) == ALT_GR)
1118 {
1119 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1120 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1121 }
1122
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001123 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1124 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001125
1126 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001127 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001128
1129 return s_iIsDead;
1130}
1131
Bram Moolenaar071d4272004-06-13 20:20:40 +00001132static BOOL g_fJustGotFocus = FALSE;
1133
1134/*
1135 * Decode a KEY_EVENT into one or two keystrokes
1136 */
1137 static BOOL
1138decode_key_event(
1139 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001140 WCHAR *pch,
1141 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001142 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001143 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001144{
1145 int i;
1146 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1147
1148 *pch = *pch2 = NUL;
1149 g_fJustGotFocus = FALSE;
1150
Bram Moolenaar0f873732019-12-05 20:28:46 +01001151 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001152 if (!pker->bKeyDown)
1153 return FALSE;
1154
Bram Moolenaar0f873732019-12-05 20:28:46 +01001155 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001156 switch (pker->wVirtualKeyCode)
1157 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001158 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001159 case VK_SHIFT:
1160 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001161 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001162 return FALSE;
1163
1164 default:
1165 break;
1166 }
1167
Bram Moolenaar0f873732019-12-05 20:28:46 +01001168 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001169 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1170 {
1171 *pch = K_NUL;
1172 *pch2 = '\017';
1173 return TRUE;
1174 }
1175
K.Takataeeec2542021-06-02 13:28:16 +02001176 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001177 {
1178 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1179 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001180 *pch = VirtKeyMap[i].chAlone;
1181 if ((nModifs & SHIFT) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001182 *pch = VirtKeyMap[i].chShift;
1183 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1184 *pch = VirtKeyMap[i].chCtrl;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001185 else if ((nModifs & ALT) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001186 *pch = VirtKeyMap[i].chAlt;
1187
1188 if (*pch != 0)
1189 {
1190 if (VirtKeyMap[i].fAnsiKey)
1191 {
1192 *pch2 = *pch;
1193 *pch = K_NUL;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001194 if (pmodifiers)
1195 {
1196 if (pker->wVirtualKeyCode >= VK_F1
1197 && pker->wVirtualKeyCode <= VK_F12)
1198 {
1199 if ((nModifs & ALT) != 0)
1200 {
1201 *pmodifiers |= MOD_MASK_ALT;
1202 if ((nModifs & SHIFT) == 0)
1203 *pch2 = VirtKeyMap[i].chAlone;
1204 }
1205 if ((nModifs & CTRL) != 0)
1206 {
1207 *pmodifiers |= MOD_MASK_CTRL;
1208 if ((nModifs & SHIFT) == 0)
1209 *pch2 = VirtKeyMap[i].chAlone;
1210 }
1211 }
1212 else if (pker->wVirtualKeyCode >= VK_END
1213 && pker->wVirtualKeyCode <= VK_DOWN)
1214 {
Christopher Plewright566f76e2023-01-10 13:43:04 +00001215 // (0x23 - 0x28): VK_END, VK_HOME,
1216 // VK_LEFT, VK_UP, VK_RIGHT, VK_DOWN
1217
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001218 *pmodifiers = 0;
1219 *pch2 = VirtKeyMap[i].chAlone;
1220 if ((nModifs & SHIFT) != 0
1221 && (nModifs & ~SHIFT) == 0)
1222 {
1223 *pch2 = VirtKeyMap[i].chShift;
1224 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001225 if ((nModifs & CTRL) != 0
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001226 && (nModifs & ~CTRL) == 0)
1227 {
1228 *pch2 = VirtKeyMap[i].chCtrl;
1229 if (pker->wVirtualKeyCode == VK_UP
1230 || pker->wVirtualKeyCode == VK_DOWN)
1231 {
1232 *pmodifiers |= MOD_MASK_CTRL;
1233 *pch2 = VirtKeyMap[i].chAlone;
1234 }
1235 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001236 if ((nModifs & SHIFT) != 0
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001237 && (nModifs & CTRL) != 0)
1238 {
1239 *pmodifiers |= MOD_MASK_CTRL;
1240 *pch2 = VirtKeyMap[i].chShift;
1241 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001242 if ((nModifs & ALT) != 0)
1243 {
1244 *pch2 = VirtKeyMap[i].chAlt;
1245 *pmodifiers |= MOD_MASK_ALT;
1246 if ((nModifs & ~ALT) == 0)
1247 {
1248 *pch2 = VirtKeyMap[i].chAlone;
1249 }
1250 else if ((nModifs & SHIFT) != 0)
1251 {
1252 *pch2 = VirtKeyMap[i].chShift;
1253 }
1254 else if ((nModifs & CTRL) != 0)
1255 {
1256 if (pker->wVirtualKeyCode == VK_UP
1257 || pker->wVirtualKeyCode == VK_DOWN)
1258 {
1259 *pmodifiers |= MOD_MASK_CTRL;
1260 *pch2 = VirtKeyMap[i].chAlone;
1261 }
1262 else
1263 {
1264 *pch2 = VirtKeyMap[i].chCtrl;
1265 }
1266 }
1267 }
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001268 }
Christopher Plewrightf5f69e82024-08-04 19:57:44 +02001269 else if (pker->wVirtualKeyCode == VK_INSERT
1270 && (nModifs & SHIFT) != 0
1271 && (nModifs & ~SHIFT) == 0)
1272 {
1273 *pmodifiers = 0;
1274 *pch2 = VirtKeyMap[i].chShift;
1275 }
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001276 else
1277 {
1278 *pch2 = VirtKeyMap[i].chAlone;
1279 if ((nModifs & SHIFT) != 0)
1280 *pmodifiers |= MOD_MASK_SHIFT;
1281 if ((nModifs & CTRL) != 0)
1282 *pmodifiers |= MOD_MASK_CTRL;
1283 if ((nModifs & ALT) != 0)
1284 *pmodifiers |= MOD_MASK_ALT;
1285 }
1286 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001287 }
1288
1289 return TRUE;
1290 }
1291 }
1292 }
1293
1294 i = win32_kbd_patch_key(pker);
1295
1296 if (i < 0)
1297 *pch = NUL;
1298 else
1299 {
K.Takata972db232022-02-04 10:45:38 +00001300 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001301
1302 if (pmodifiers != NULL)
1303 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001304 // Pass on the ALT key as a modifier, but only when not combined
1305 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001306 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1307 *pmodifiers |= MOD_MASK_ALT;
1308
Bram Moolenaar0f873732019-12-05 20:28:46 +01001309 // Pass on SHIFT only for special keys, because we don't know when
1310 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001311 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1312 *pmodifiers |= MOD_MASK_SHIFT;
1313
Bram Moolenaar0f873732019-12-05 20:28:46 +01001314 // Pass on CTRL only for non-special keys, because we don't know
1315 // when it's already included with the character. And not when
1316 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001317 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1318 && *pch >= 0x20 && *pch < 0x80)
1319 *pmodifiers |= MOD_MASK_CTRL;
1320 }
1321 }
1322
1323 return (*pch != NUL);
1324}
1325
Christopher Plewright20b795e2022-12-20 20:01:58 +00001326# if defined(FEAT_EVAL)
1327 static int
1328encode_key_event(dict_T *args, INPUT_RECORD *ir)
1329{
1330 static int s_dwMods = 0;
1331
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001332 char_u *action = dict_get_string(args, "event", TRUE);
1333 if (action && (STRICMP(action, "keydown") == 0
1334 || STRICMP(action, "keyup") == 0))
Christopher Plewright20b795e2022-12-20 20:01:58 +00001335 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001336 BOOL isKeyDown = STRICMP(action, "keydown") == 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001337 WORD vkCode = dict_get_number_def(args, "keycode", 0);
1338 if (vkCode <= 0 || vkCode >= 0xFF)
1339 {
1340 semsg(_(e_invalid_argument_nr), (long)vkCode);
1341 return FALSE;
1342 }
1343
1344 ir->EventType = KEY_EVENT;
1345 KEY_EVENT_RECORD ker;
1346 ZeroMemory(&ker, sizeof(ker));
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001347 ker.bKeyDown = isKeyDown;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001348 ker.wRepeatCount = 1;
1349 ker.wVirtualScanCode = 0;
1350 ker.dwControlKeyState = 0;
1351 int mods = (int)dict_get_number(args, "modifiers");
1352 // Encode the win32 console key modifiers from Vim keyboard modifiers.
1353 if (mods)
1354 {
1355 // If "modifiers" is explicitly set in the args, then we reset any
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00001356 // remembered modifier key state that may have been set from
1357 // earlier mod-key-down events, even if they are not yet unset by
1358 // earlier mod-key-up events.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001359 s_dwMods = 0;
1360 if (mods & MOD_MASK_SHIFT)
1361 ker.dwControlKeyState |= SHIFT_PRESSED;
1362 if (mods & MOD_MASK_CTRL)
1363 ker.dwControlKeyState |= LEFT_CTRL_PRESSED;
1364 if (mods & MOD_MASK_ALT)
1365 ker.dwControlKeyState |= LEFT_ALT_PRESSED;
1366 }
1367
1368 if (vkCode == VK_LSHIFT || vkCode == VK_RSHIFT || vkCode == VK_SHIFT)
1369 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001370 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001371 s_dwMods |= SHIFT_PRESSED;
1372 else
1373 s_dwMods &= ~SHIFT_PRESSED;
1374 }
1375 else if (vkCode == VK_LCONTROL || vkCode == VK_CONTROL)
1376 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001377 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001378 s_dwMods |= LEFT_CTRL_PRESSED;
1379 else
1380 s_dwMods &= ~LEFT_CTRL_PRESSED;
1381 }
1382 else if (vkCode == VK_RCONTROL)
1383 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001384 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001385 s_dwMods |= RIGHT_CTRL_PRESSED;
1386 else
1387 s_dwMods &= ~RIGHT_CTRL_PRESSED;
1388 }
1389 else if (vkCode == VK_LMENU || vkCode == VK_MENU)
1390 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001391 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001392 s_dwMods |= LEFT_ALT_PRESSED;
1393 else
1394 s_dwMods &= ~LEFT_ALT_PRESSED;
1395 }
1396 else if (vkCode == VK_RMENU)
1397 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001398 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001399 s_dwMods |= RIGHT_ALT_PRESSED;
1400 else
1401 s_dwMods &= ~RIGHT_ALT_PRESSED;
1402 }
1403 ker.dwControlKeyState |= s_dwMods;
1404 ker.wVirtualKeyCode = vkCode;
Christopher Plewright566f76e2023-01-10 13:43:04 +00001405 ker.uChar.UnicodeChar = 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001406 ir->Event.KeyEvent = ker;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001407 vim_free(action);
Christopher Plewright20b795e2022-12-20 20:01:58 +00001408 }
1409 else
1410 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001411 if (action == NULL)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001412 {
1413 semsg(_(e_missing_argument_str), "event");
1414 }
1415 else
1416 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001417 semsg(_(e_invalid_value_for_argument_str_str), "event", action);
1418 vim_free(action);
Christopher Plewright20b795e2022-12-20 20:01:58 +00001419 }
1420 return FALSE;
1421 }
1422 return TRUE;
1423}
1424# endif // FEAT_EVAL
1425#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00001426
1427
Bram Moolenaar071d4272004-06-13 20:20:40 +00001428/*
1429 * For the GUI the mouse handling is in gui_w32.c.
1430 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001431#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001432 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001433mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001434{
1435}
Christopher Plewright20b795e2022-12-20 20:01:58 +00001436#else // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar0f873732019-12-05 20:28:46 +01001437static int g_fMouseAvail = FALSE; // mouse present
1438static int g_fMouseActive = FALSE; // mouse enabled
1439static int g_nMouseClick = -1; // mouse status
1440static int g_xMouse; // mouse x coordinate
1441static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001442static DWORD g_cmodein = 0; // Original console input mode
1443static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001444
1445/*
1446 * Enable or disable mouse input
1447 */
1448 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001449mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001450{
1451 DWORD cmodein;
1452
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001453# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001454 if (gui.in_use)
1455 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001456# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001457 if (!g_fMouseAvail)
1458 return;
1459
1460 g_fMouseActive = on;
1461 GetConsoleMode(g_hConIn, &cmodein);
1462
1463 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001464 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001465 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001466 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1467 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001468 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001469 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001470 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001471 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1472 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001473
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001474 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001475}
1476
Bram Moolenaar157d8132018-03-06 17:09:20 +01001477
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001478# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001479/*
1480 * Called when 'balloonevalterm' changed.
1481 */
1482 void
1483mch_bevalterm_changed(void)
1484{
1485 mch_setmouse(g_fMouseActive);
1486}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001487# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001488
Christopher Plewright2a46f812022-10-16 19:47:45 +01001489/*
1490 * Win32 console mouse scroll event handler.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001491 * Console version of the _OnMouseWheel() function in gui_w32.c
Christopher Plewright2a46f812022-10-16 19:47:45 +01001492 *
1493 * This encodes the mouse scroll direction and keyboard modifiers into
1494 * g_nMouseClick, and the mouse position into g_xMouse and g_yMouse
1495 *
1496 * The direction of the scroll is decoded from two fields of the win32 console
1497 * mouse event record;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001498 * 1. The orientation - vertical or horizontal flag - from dwEventFlags
Christopher Plewright2a46f812022-10-16 19:47:45 +01001499 * 2. The sign - positive or negative (aka delta flag) - from dwButtonState
1500 *
Christopher Plewright20b795e2022-12-20 20:01:58 +00001501 * When scroll orientation is HORIZONTAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001502 * - If the high word of the dwButtonState member contains a positive
1503 * value, the wheel was rotated to the right.
1504 * - Otherwise, the wheel was rotated to the left.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001505 * When scroll orientation is VERTICAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001506 * - If the high word of the dwButtonState member contains a positive value,
1507 * the wheel was rotated forward, away from the user.
1508 * - Otherwise, the wheel was rotated backward, toward the user.
1509 */
1510 static void
1511decode_mouse_wheel(MOUSE_EVENT_RECORD *pmer)
1512{
Christopher Plewright2a46f812022-10-16 19:47:45 +01001513 int horizontal = (pmer->dwEventFlags == MOUSE_HWHEELED);
1514 int zDelta = pmer->dwButtonState;
1515
1516 g_xMouse = pmer->dwMousePosition.X;
1517 g_yMouse = pmer->dwMousePosition.Y;
1518
K.Takata161b6ac2022-11-14 15:31:07 +00001519# ifdef FEAT_PROP_POPUP
Christopher Plewright605d02a2022-10-19 11:54:46 +01001520 int lcol = g_xMouse;
1521 int lrow = g_yMouse;
Christopher Plewright38804d62022-11-09 23:55:52 +00001522 win_T *wp = mouse_find_win(&lrow, &lcol, FIND_POPUP);
Christopher Plewright2a46f812022-10-16 19:47:45 +01001523 if (wp != NULL && popup_is_popup(wp))
1524 {
1525 g_nMouseClick = -1;
1526 cmdarg_T cap;
1527 oparg_T oa;
1528 CLEAR_FIELD(cap);
1529 clear_oparg(&oa);
1530 cap.oap = &oa;
1531 if (horizontal)
1532 {
1533 cap.arg = zDelta < 0 ? MSCR_LEFT : MSCR_RIGHT;
1534 cap.cmdchar = zDelta < 0 ? K_MOUSELEFT : K_MOUSERIGHT;
1535 }
1536 else
1537 {
1538 cap.cmdchar = zDelta < 0 ? K_MOUSEUP : K_MOUSEDOWN;
1539 cap.arg = zDelta < 0 ? MSCR_UP : MSCR_DOWN;
1540 }
1541
1542 // Mouse hovers over popup window, scroll it if possible.
1543 mouse_row = wp->w_winrow;
1544 mouse_col = wp->w_wincol;
1545 nv_mousescroll(&cap);
1546 update_screen(0);
1547 setcursor();
1548 out_flush();
1549 return;
1550 }
K.Takata161b6ac2022-11-14 15:31:07 +00001551# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01001552 mouse_col = g_xMouse;
1553 mouse_row = g_yMouse;
1554
1555 char_u modifiers = 0;
1556 char_u direction = 0;
1557
1558 // Decode the direction into an event that Vim can process
1559 if (horizontal)
1560 direction = zDelta >= 0 ? KE_MOUSELEFT : KE_MOUSERIGHT;
1561 else
1562 direction = zDelta >= 0 ? KE_MOUSEDOWN : KE_MOUSEUP;
1563
dundargocc57b5bc2022-11-02 13:30:51 +00001564 // Decode the win32 console key modifiers into Vim mouse modifiers.
Christopher Plewright2a46f812022-10-16 19:47:45 +01001565 if (pmer->dwControlKeyState & SHIFT_PRESSED)
Christopher Plewright605d02a2022-10-19 11:54:46 +01001566 modifiers |= MOD_MASK_SHIFT; // MOUSE_SHIFT;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001567 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
Christopher Plewright605d02a2022-10-19 11:54:46 +01001568 modifiers |= MOD_MASK_CTRL; // MOUSE_CTRL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001569 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1570 modifiers |= MOD_MASK_ALT; // MOUSE_ALT;
1571
1572 // add (bitwise or) the scroll direction and the key modifier chars
1573 // together.
1574 g_nMouseClick = ((direction << 8) | modifiers);
1575
1576 return;
1577}
1578
Bram Moolenaar071d4272004-06-13 20:20:40 +00001579/*
1580 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1581 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1582 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1583 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1584 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1585 * and we return the mouse position in g_xMouse and g_yMouse.
1586 *
1587 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1588 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1589 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1590 *
1591 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1592 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1593 *
1594 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1595 * moves, even if it stays within the same character cell. We ignore
1596 * all MOUSE_MOVED messages if the position hasn't really changed, and
1597 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1598 * we're only interested in MOUSE_DRAG).
1599 *
1600 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1601 * 2-button mouses by pressing the left & right buttons simultaneously.
1602 * In practice, it's almost impossible to click both at the same time,
1603 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1604 * in such cases, if the user is clicking quickly.
1605 */
1606 static BOOL
1607decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001608 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001609{
1610 static int s_nOldButton = -1;
1611 static int s_nOldMouseClick = -1;
1612 static int s_xOldMouse = -1;
1613 static int s_yOldMouse = -1;
1614 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001615# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001616 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001617# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001618 static int s_cClicks = 1;
1619 static BOOL s_fReleased = TRUE;
1620 static DWORD s_dwLastClickTime = 0;
1621 static BOOL s_fNextIsMiddle = FALSE;
1622
Bram Moolenaar0f873732019-12-05 20:28:46 +01001623 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001624
1625 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1626 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1627 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1628 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1629
1630 int nButton;
1631
1632 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1633 cButtons = 2;
1634
1635 if (!g_fMouseAvail || !g_fMouseActive)
1636 {
1637 g_nMouseClick = -1;
1638 return FALSE;
1639 }
1640
Bram Moolenaar0f873732019-12-05 20:28:46 +01001641 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001642 if (g_fJustGotFocus)
1643 {
1644 g_fJustGotFocus = FALSE;
1645 return FALSE;
1646 }
1647
Christopher Plewright605d02a2022-10-19 11:54:46 +01001648 // If there is an unprocessed mouse click drop this one.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001649 if (g_nMouseClick != -1)
1650 return TRUE;
Christopher Plewright605d02a2022-10-19 11:54:46 +01001651
Christopher Plewright2a46f812022-10-16 19:47:45 +01001652 if (pmer->dwEventFlags == MOUSE_WHEELED
1653 || pmer->dwEventFlags == MOUSE_HWHEELED)
1654 {
1655 decode_mouse_wheel(pmer);
1656 return TRUE; // we now should have a mouse scroll in g_nMouseClick
1657 }
Christopher Plewright605d02a2022-10-19 11:54:46 +01001658
Bram Moolenaar071d4272004-06-13 20:20:40 +00001659 nButton = -1;
1660 g_xMouse = pmer->dwMousePosition.X;
1661 g_yMouse = pmer->dwMousePosition.Y;
1662
1663 if (pmer->dwEventFlags == MOUSE_MOVED)
1664 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001665 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1666 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001667 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1668 return FALSE;
1669 }
1670
Bram Moolenaar0f873732019-12-05 20:28:46 +01001671 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001672 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1673 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001674 nButton = MOUSE_RELEASE;
1675
Bram Moolenaar0f873732019-12-05 20:28:46 +01001676 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001677 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001678 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001679# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001680 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001681 if (p_bevalterm)
1682 nButton = MOUSE_DRAG;
1683 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001684# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001685 return FALSE;
1686 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001687
Bram Moolenaar071d4272004-06-13 20:20:40 +00001688 s_fReleased = TRUE;
1689 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001690 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001691 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001692 // on a 2-button mouse, hold down left and right buttons
1693 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001694
1695 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1696 {
1697 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1698
Bram Moolenaar0f873732019-12-05 20:28:46 +01001699 // if either left or right button only is pressed, see if the
1700 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001701 if (dwLR == LEFT || dwLR == RIGHT)
1702 {
1703 for (;;)
1704 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001705 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001706 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1707 != WAIT_OBJECT_0)
1708 break;
1709 else
1710 {
1711 DWORD cRecords = 0;
1712 INPUT_RECORD ir;
1713 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1714
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001715 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001716
1717 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1718 || !(pmer2->dwButtonState & LEFT_RIGHT))
1719 break;
1720 else
1721 {
1722 if (pmer2->dwEventFlags != MOUSE_MOVED)
1723 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001724 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001725
1726 return decode_mouse_event(pmer2);
1727 }
1728 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1729 s_yOldMouse == pmer2->dwMousePosition.Y)
1730 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001731 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001732 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001733
Bram Moolenaar0f873732019-12-05 20:28:46 +01001734 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001735 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001736
1737 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1738 break;
1739 }
1740 else
1741 break;
1742 }
1743 }
1744 }
1745 }
1746 }
1747
1748 if (s_fNextIsMiddle)
1749 {
1750 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1751 ? MOUSE_DRAG : MOUSE_MIDDLE;
1752 s_fNextIsMiddle = FALSE;
1753 }
1754 else if (cButtons == 2 &&
1755 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1756 {
1757 nButton = MOUSE_MIDDLE;
1758
1759 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1760 {
1761 s_fNextIsMiddle = TRUE;
1762 nButton = MOUSE_RELEASE;
1763 }
1764 }
1765 else if ((pmer->dwButtonState & LEFT) == LEFT)
1766 nButton = MOUSE_LEFT;
1767 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1768 nButton = MOUSE_MIDDLE;
1769 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1770 nButton = MOUSE_RIGHT;
1771
1772 if (! s_fReleased && ! s_fNextIsMiddle
1773 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1774 return FALSE;
1775
1776 s_fReleased = s_fNextIsMiddle;
1777 }
1778
1779 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1780 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001781 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001782 if (nButton != -1 && nButton != MOUSE_RELEASE)
1783 {
1784 DWORD dwCurrentTime = GetTickCount();
1785
1786 if (s_xOldMouse != g_xMouse
1787 || s_yOldMouse != g_yMouse
1788 || s_nOldButton != nButton
1789 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001790# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001791 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001792# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001793 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1794 {
1795 s_cClicks = 1;
1796 }
1797 else if (++s_cClicks > 4)
1798 {
1799 s_cClicks = 1;
1800 }
1801
1802 s_dwLastClickTime = dwCurrentTime;
1803 }
1804 }
1805 else if (pmer->dwEventFlags == MOUSE_MOVED)
1806 {
1807 if (nButton != -1 && nButton != MOUSE_RELEASE)
1808 nButton = MOUSE_DRAG;
1809
1810 s_cClicks = 1;
1811 }
1812
1813 if (nButton == -1)
1814 return FALSE;
1815
1816 if (nButton != MOUSE_RELEASE)
1817 s_nOldButton = nButton;
1818
1819 g_nMouseClick = nButton;
1820
1821 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1822 g_nMouseClick |= MOUSE_SHIFT;
1823 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1824 g_nMouseClick |= MOUSE_CTRL;
1825 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1826 g_nMouseClick |= MOUSE_ALT;
1827
1828 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1829 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1830
Bram Moolenaar0f873732019-12-05 20:28:46 +01001831 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001832 if (s_xOldMouse == g_xMouse
1833 && s_yOldMouse == g_yMouse
1834 && s_nOldMouseClick == g_nMouseClick)
1835 {
1836 g_nMouseClick = -1;
1837 return FALSE;
1838 }
1839
1840 s_xOldMouse = g_xMouse;
1841 s_yOldMouse = g_yMouse;
1842 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001843# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001844 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001845# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001846 s_nOldMouseClick = g_nMouseClick;
1847
1848 return TRUE;
1849}
1850
Christopher Plewright20b795e2022-12-20 20:01:58 +00001851# ifdef FEAT_EVAL
1852 static int
1853encode_mouse_event(dict_T *args, INPUT_RECORD *ir)
1854{
1855 int button;
1856 int row;
1857 int col;
1858 int repeated_click;
Bram Moolenaar9b8a3652022-12-20 20:47:28 +00001859 int_u mods = 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001860 int move;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001861
Christopher Plewright20b795e2022-12-20 20:01:58 +00001862 if (!dict_has_key(args, "row") || !dict_has_key(args, "col"))
1863 return FALSE;
1864
1865 // Note: "move" is optional, requires fewer arguments
1866 move = (int)dict_get_bool(args, "move", FALSE);
1867 if (!move && (!dict_has_key(args, "button")
1868 || !dict_has_key(args, "multiclick")
1869 || !dict_has_key(args, "modifiers")))
1870 return FALSE;
1871
1872 row = (int)dict_get_number(args, "row") - 1;
1873 col = (int)dict_get_number(args, "col") - 1;
1874
1875 ir->EventType = MOUSE_EVENT;
1876 MOUSE_EVENT_RECORD mer;
1877 ZeroMemory(&mer, sizeof(mer));
1878 mer.dwMousePosition.X = col;
1879 mer.dwMousePosition.Y = row;
1880
1881 if (move)
1882 {
1883 mer.dwButtonState = 0;
1884 mer.dwEventFlags = MOUSE_MOVED;
1885 }
1886 else
1887 {
1888 button = (int)dict_get_number(args, "button");
1889 repeated_click = (int)dict_get_number(args, "multiclick");
1890 mods = (int)dict_get_number(args, "modifiers");
1891 // Reset the scroll values to known values.
1892 // XXX: Remove this when/if the scroll step is made configurable.
1893 mouse_set_hor_scroll_step(6);
1894 mouse_set_vert_scroll_step(3);
1895
1896 switch (button)
1897 {
1898 case MOUSE_LEFT:
1899 mer.dwButtonState = FROM_LEFT_1ST_BUTTON_PRESSED;
1900 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1901 break;
1902 case MOUSE_MIDDLE:
1903 mer.dwButtonState = FROM_LEFT_2ND_BUTTON_PRESSED;
1904 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1905 break;
1906 case MOUSE_RIGHT:
1907 mer.dwButtonState = RIGHTMOST_BUTTON_PRESSED;
1908 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1909 break;
1910 case MOUSE_RELEASE:
1911 // umm? Assume Left Release?
1912 mer.dwEventFlags = 0;
1913
1914 case MOUSE_MOVE:
1915 mer.dwButtonState = 0;
1916 mer.dwEventFlags = MOUSE_MOVED;
1917 break;
1918 case MOUSE_X1:
1919 mer.dwButtonState = FROM_LEFT_3RD_BUTTON_PRESSED;
1920 break;
1921 case MOUSE_X2:
1922 mer.dwButtonState = FROM_LEFT_4TH_BUTTON_PRESSED;
1923 break;
1924 case MOUSE_4: // KE_MOUSEDOWN;
1925 mer.dwButtonState = -1;
1926 mer.dwEventFlags = MOUSE_WHEELED;
1927 break;
1928 case MOUSE_5: // KE_MOUSEUP;
1929 mer.dwButtonState = +1;
1930 mer.dwEventFlags = MOUSE_WHEELED;
1931 break;
1932 case MOUSE_6: // KE_MOUSELEFT;
1933 mer.dwButtonState = -1;
1934 mer.dwEventFlags = MOUSE_HWHEELED;
1935 break;
1936 case MOUSE_7: // KE_MOUSERIGHT;
1937 mer.dwButtonState = +1;
1938 mer.dwEventFlags = MOUSE_HWHEELED;
1939 break;
1940 default:
1941 semsg(_(e_invalid_argument_str), "button");
1942 return FALSE;
1943 }
1944 }
1945
1946 mer.dwControlKeyState = 0;
1947 if (mods != 0)
1948 {
1949 // Encode the win32 console key modifiers from Vim MOUSE modifiers.
1950 if (mods & MOUSE_SHIFT)
1951 mer.dwControlKeyState |= SHIFT_PRESSED;
1952 if (mods & MOUSE_CTRL)
1953 mer.dwControlKeyState |= LEFT_CTRL_PRESSED;
1954 if (mods & MOUSE_ALT)
1955 mer.dwControlKeyState |= LEFT_ALT_PRESSED;
1956 }
1957 ir->Event.MouseEvent = mer;
1958 return TRUE;
1959}
1960# endif // FEAT_EVAL
1961
1962 static int
1963write_input_record_buffer(INPUT_RECORD* irEvents, int nLength)
1964{
John Marriott738df382025-06-05 20:49:39 +02001965 int nCount = 0;
1966 input_record_buffer_node_T *event_node;
1967
Christopher Plewright20b795e2022-12-20 20:01:58 +00001968 while (nCount < nLength)
1969 {
John Marriott738df382025-06-05 20:49:39 +02001970 event_node = alloc(sizeof(input_record_buffer_node_T));
1971 if (event_node == NULL)
1972 return -1;
1973
Christopher Plewright20b795e2022-12-20 20:01:58 +00001974 event_node->ir = irEvents[nCount++];
1975 event_node->next = NULL;
John Marriott738df382025-06-05 20:49:39 +02001976
1977 input_record_buffer.length++;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001978 if (input_record_buffer.tail == NULL)
1979 {
1980 input_record_buffer.head = event_node;
1981 input_record_buffer.tail = event_node;
1982 }
1983 else
1984 {
1985 input_record_buffer.tail->next = event_node;
1986 input_record_buffer.tail = input_record_buffer.tail->next;
1987 }
1988 }
1989 return nCount;
1990}
1991
1992 static int
1993read_input_record_buffer(INPUT_RECORD* irEvents, int nMaxLength)
1994{
1995 int nCount = 0;
1996 while (nCount < nMaxLength && input_record_buffer.head != NULL)
1997 {
1998 input_record_buffer.length--;
1999 input_record_buffer_node_T *pop_head = input_record_buffer.head;
2000 irEvents[nCount++] = pop_head->ir;
2001 input_record_buffer.head = pop_head->next;
2002 vim_free(pop_head);
2003 if (input_record_buffer.length == 0)
2004 input_record_buffer.tail = NULL;
2005 }
2006 return nCount;
2007}
Christopher Plewright20b795e2022-12-20 20:01:58 +00002008#endif // !FEAT_GUI_MSWIN || VIMDLL
2009
2010#ifdef FEAT_EVAL
2011/*
2012 * The 'test_mswin_event' function is for testing Vim's low-level handling of
2013 * user input events. ie, this manages the encoding of INPUT_RECORD events
2014 * so that we have a way to test how Vim decodes INPUT_RECORD events in Windows
2015 * consoles.
2016 *
2017 * The 'test_mswin_event' function is based on 'test_gui_event'. In fact, when
2018 * the Windows GUI is running, the arguments; 'event' and 'args', are the same.
2019 * So, it acts as an alias for 'test_gui_event' for the Windows GUI.
2020 *
2021 * When the Windows console is running, the arguments; 'event' and 'args', are
2022 * a subset of what 'test_gui_event' handles, ie, only "key" and "mouse"
2023 * events are encoded as INPUT_RECORD events.
2024 *
2025 * Note: INPUT_RECORDs are only used by the Windows console, not the GUI. The
2026 * GUI sends MSG structs instead.
2027 */
2028 int
2029test_mswin_event(char_u *event, dict_T *args)
2030{
2031 int lpEventsWritten = 0;
2032
2033# if defined(VIMDLL) || defined(FEAT_GUI_MSWIN)
2034 if (gui.in_use)
2035 return test_gui_w32_sendevent(event, args);
2036# endif
2037
2038# if defined(VIMDLL) || !defined(FEAT_GUI_MSWIN)
2039
2040// Currently implemented event record types are; KEY_EVENT and MOUSE_EVENT
2041// Potentially could also implement: FOCUS_EVENT and WINDOW_BUFFER_SIZE_EVENT
2042// Maybe also: MENU_EVENT
2043
2044 INPUT_RECORD ir;
2045 BOOL input_encoded = FALSE;
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002046 BOOL execute = FALSE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00002047 if (STRCMP(event, "key") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002048 {
2049 execute = dict_get_bool(args, "execute", FALSE);
2050 if (dict_has_key(args, "event"))
2051 input_encoded = encode_key_event(args, &ir);
2052 else if (!execute)
2053 {
2054 semsg(_(e_missing_argument_str), "event");
2055 return FALSE;
2056 }
2057 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002058 else if (STRCMP(event, "mouse") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002059 {
2060 execute = TRUE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00002061 input_encoded = encode_mouse_event(args, &ir);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002062 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002063 else
2064 {
2065 semsg(_(e_invalid_value_for_argument_str_str), "event", event);
2066 return FALSE;
2067 }
2068
2069 // Ideally, WriteConsoleInput would be used to inject these low-level
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00002070 // events. But, this doesn't work well in the CI test environment. So
Christopher Plewright20b795e2022-12-20 20:01:58 +00002071 // implementing an input_record_buffer instead.
2072 if (input_encoded)
John Marriott738df382025-06-05 20:49:39 +02002073 {
2074 if ((lpEventsWritten = write_input_record_buffer(&ir, 1)) < 0)
2075 {
2076 semsg(_(e_out_of_memory), "event");
2077 return FALSE;
2078 }
2079 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002080
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002081 // Set flags to execute the event, ie. like feedkeys mode X.
2082 if (execute)
2083 {
2084 int save_msg_scroll = msg_scroll;
2085 // Avoid a 1 second delay when the keys start Insert mode.
2086 msg_scroll = FALSE;
2087 ch_log(NULL, "test_mswin_event() executing");
Christopher Plewright20b795e2022-12-20 20:01:58 +00002088 exec_normal(TRUE, TRUE, TRUE);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002089 msg_scroll |= save_msg_scroll;
2090 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002091
2092# endif
2093 return lpEventsWritten;
2094}
2095#endif // FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002096
2097#ifdef MCH_CURSOR_SHAPE
2098/*
2099 * Set the shape of the cursor.
2100 * 'thickness' can be from 1 (thin) to 99 (block)
2101 */
2102 static void
2103mch_set_cursor_shape(int thickness)
2104{
Christopher Plewright38804d62022-11-09 23:55:52 +00002105 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01002106 {
2107 if (*T_CSI == NUL)
2108 {
2109 // If 't_SI' is not set, use the default cursor styles.
2110 if (thickness < 50)
2111 vtp_printf("\033[3 q"); // underline
2112 else
2113 vtp_printf("\033[0 q"); // default
2114 }
2115 }
2116 else
2117 {
2118 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
2119 ConsoleCursorInfo.dwSize = thickness;
2120 ConsoleCursorInfo.bVisible = s_cursor_visible;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002121
K.Takatadf5320c2022-09-01 13:20:16 +01002122 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
2123 if (s_cursor_visible)
2124 SetConsoleCursorPosition(g_hConOut, g_coord);
2125 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002126}
2127
2128 void
2129mch_update_cursor(void)
2130{
2131 int idx;
2132 int thickness;
2133
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002134# ifdef VIMDLL
2135 if (gui.in_use)
2136 return;
2137# endif
2138
Bram Moolenaar071d4272004-06-13 20:20:40 +00002139 /*
2140 * How the cursor is drawn depends on the current mode.
2141 */
2142 idx = get_shape_idx(FALSE);
2143
2144 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002145 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00002146 else
2147 thickness = shape_table[idx].percentage;
2148 mch_set_cursor_shape(thickness);
2149}
2150#endif
2151
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002152#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002153/*
2154 * Handle FOCUS_EVENT.
2155 */
2156 static void
2157handle_focus_event(INPUT_RECORD ir)
2158{
2159 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
2160 ui_focus_change((int)g_fJustGotFocus);
2161}
2162
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002163static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
2164
Bram Moolenaar071d4272004-06-13 20:20:40 +00002165/*
2166 * Wait until console input from keyboard or mouse is available,
2167 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002168 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002169 * Return TRUE if something is available FALSE if not.
2170 */
2171 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002172WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002173{
2174 DWORD dwNow = 0, dwEndTime = 0;
2175 INPUT_RECORD ir;
2176 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002177 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002178# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02002179 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002180# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002181
2182 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002183 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002184 dwEndTime = GetTickCount() + msec;
2185 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002186 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002187 dwEndTime = INFINITE;
2188
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002189 // We need to loop until the end of the time period, because
2190 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002191 for (;;)
2192 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002193 // Only process messages when waiting.
2194 if (msec != 0)
2195 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002196# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002197 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002198# endif
2199# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002200 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002201# endif
2202# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002203 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002204# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002205 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002206
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02002207 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002208# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002209 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002210# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002211 )
2212 return TRUE;
2213
2214 if (msec > 0)
2215 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002216 // If the specified wait time has passed, return. Beware that
2217 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002218 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02002219 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002220 break;
2221 }
2222 if (msec != 0)
2223 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00002224 DWORD dwWaitTime = dwEndTime - dwNow;
2225
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002226 // Don't wait for more than 11 msec to avoid dropping characters,
2227 // check channel while waiting for input and handle a callback from
2228 // 'balloonexpr'.
2229 if (dwWaitTime > 11)
2230 dwWaitTime = 11;
2231
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002232# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002233 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002234 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002235# endif
2236# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002237 // When waiting very briefly don't trigger timers.
2238 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002239 {
2240 long due_time;
2241
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002242 // Trigger timers and then get the time in msec until the next
2243 // one is due. Wait up to that time.
2244 due_time = check_due_timer();
2245 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002246 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002247 // timer may have used feedkeys().
2248 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002249 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002250 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
2251 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002252 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002253# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002254 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002255# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002256 // Wait for either an event on the console input or a
2257 // message in the client-server window.
2258 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
2259 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002260# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002261 wait_for_single_object(g_hConIn, dwWaitTime)
2262 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002263# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002264 )
2265 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002266 }
2267
2268 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002269 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002270
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002271# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02002272 // May have to redraw if the cursor ends up in the wrong place.
2273 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01002274 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002275 {
2276 CONSOLE_SCREEN_BUFFER_INFO csbi;
2277
2278 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2279 {
2280 if (csbi.dwCursorPosition.Y != msg_row)
2281 {
matveyte08795e2021-05-07 15:00:17 +02002282 // The screen is now messed up, must redraw the command
2283 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002284 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02002285 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002286 redrawcmd();
2287 }
2288 }
2289 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002290# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002291
2292 if (cRecords > 0)
2293 {
2294 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
2295 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002296# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01002297 // Windows IME sends two '\n's with only one 'ENTER'. First:
2298 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00002299 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002300 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
2301 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002302 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002303 continue;
2304 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002305# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002306 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
2307 NULL, FALSE))
2308 return TRUE;
2309 }
2310
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002311 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002312
2313 if (ir.EventType == FOCUS_EVENT)
2314 handle_focus_event(ir);
2315 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002316 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002317 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
2318
Bram Moolenaar36698e32019-12-11 22:57:40 +01002319 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002320 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002321 if (dwSize.X != Columns || dwSize.Y != Rows)
2322 {
2323 CONSOLE_SCREEN_BUFFER_INFO csbi;
2324 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01002325 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002326 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01002327 if (dwSize.X != Columns || dwSize.Y != Rows)
2328 {
2329 ResizeConBuf(g_hConOut, dwSize);
2330 shell_resized();
2331 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002332 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002333 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002334 else if (ir.EventType == MOUSE_EVENT
2335 && decode_mouse_event(&ir.Event.MouseEvent))
2336 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002337 }
2338 else if (msec == 0)
2339 break;
2340 }
2341
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002342# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01002343 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002344 if (input_available())
2345 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002346# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002347
Bram Moolenaar071d4272004-06-13 20:20:40 +00002348 return FALSE;
2349}
2350
Bram Moolenaar071d4272004-06-13 20:20:40 +00002351/*
2352 * return non-zero if a character is available
2353 */
2354 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002355mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002356{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002357# ifdef VIMDLL
2358 if (gui.in_use)
2359 return TRUE;
2360# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002361 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002362}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002363
2364# if defined(FEAT_TERMINAL) || defined(PROTO)
2365/*
2366 * Check for any pending input or messages.
2367 */
2368 int
2369mch_check_messages(void)
2370{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002371# ifdef VIMDLL
2372 if (gui.in_use)
2373 return TRUE;
2374# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002375 return WaitForChar(0L, TRUE);
2376}
2377# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002378
2379/*
2380 * Create the console input. Used when reading stdin doesn't work.
2381 */
2382 static void
2383create_conin(void)
2384{
2385 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
2386 FILE_SHARE_READ|FILE_SHARE_WRITE,
2387 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002388 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002389 did_create_conin = TRUE;
2390}
2391
2392/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002393 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002394 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002395 static WCHAR
2396tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002397{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002398 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002399
2400 for (;;)
2401 {
2402 INPUT_RECORD ir;
2403 DWORD cRecords = 0;
2404
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002405# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002406 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002407 if (input_available())
2408 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002409 if (g_nMouseClick != -1)
2410 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002411# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002412 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002413 {
2414 if (did_create_conin)
2415 read_error_exit();
2416 create_conin();
2417 continue;
2418 }
2419
2420 if (ir.EventType == KEY_EVENT)
2421 {
2422 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
2423 pmodifiers, TRUE))
2424 return ch;
2425 }
2426 else if (ir.EventType == FOCUS_EVENT)
2427 handle_focus_event(ir);
2428 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
2429 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002430 else if (ir.EventType == MOUSE_EVENT)
2431 {
2432 if (decode_mouse_event(&ir.Event.MouseEvent))
2433 return 0;
2434 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002435 }
2436}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002437#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002438
2439
2440/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02002441 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002442 * Get one or more characters from the keyboard or the mouse.
2443 * If time == 0, do not wait for characters.
2444 * If time == n, wait a short time for characters.
2445 * If time == -1, wait forever for characters.
2446 * Returns the number of characters read into buf.
2447 */
2448 int
2449mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002450 char_u *buf UNUSED,
2451 int maxlen UNUSED,
2452 long time UNUSED,
2453 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002454{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002455#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002456
2457 int len;
2458 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002459# ifdef VIMDLL
2460// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
2461# define TYPEAHEADSPACE 6
2462# else
2463# define TYPEAHEADSPACE 0
2464# endif
2465# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002466 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002467 static int typeaheadlen = 0;
2468
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002469# ifdef VIMDLL
2470 if (gui.in_use)
2471 return 0;
2472# endif
2473
Bram Moolenaar0f873732019-12-05 20:28:46 +01002474 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002475 if (typeaheadlen > 0)
2476 goto theend;
2477
Bram Moolenaar071d4272004-06-13 20:20:40 +00002478 if (time >= 0)
2479 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002480 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00002481 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002482 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01002483 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00002484 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002485 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00002486
Bram Moolenaar3918c952005-03-15 22:34:55 +00002487 /*
2488 * If there is no character available within 2 seconds (default)
2489 * write the autoscript file to disk. Or cause the CursorHold event
2490 * to be triggered.
2491 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002492 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00002494 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002495 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00002496 buf[0] = K_SPECIAL;
2497 buf[1] = KS_EXTRA;
2498 buf[2] = (int)KE_CURSORHOLD;
2499 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002500 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00002501 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002502 }
2503 }
2504
2505 /*
2506 * Try to read as many characters as there are, until the buffer is full.
2507 */
2508
Bram Moolenaar0f873732019-12-05 20:28:46 +01002509 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002510 g_fCBrkPressed = FALSE;
2511
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002512# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002513 if (fdDump)
2514 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002515# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002516
Bram Moolenaar0f873732019-12-05 20:28:46 +01002517 // Keep looping until there is something in the typeahead buffer and more
2518 // to get and still room in the buffer (up to two bytes for a char and
2519 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002520 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01002521 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002522 {
2523 if (typebuf_changed(tb_change_cnt))
2524 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002525 // "buf" may be invalid now if a client put something in the
2526 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002527 typeaheadlen = 0;
2528 break;
2529 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002530 if (g_nMouseClick != -1)
2531 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002532# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002533 if (fdDump)
2534 fprintf(fdDump, "{%02x @ %d, %d}",
2535 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002536# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01002537 char_u modifiers = ((char_u *)(&g_nMouseClick))[0];
2538 char_u scroll_dir = ((char_u *)(&g_nMouseClick))[1];
2539
2540 if (scroll_dir == KE_MOUSEDOWN
2541 || scroll_dir == KE_MOUSEUP
2542 || scroll_dir == KE_MOUSELEFT
2543 || scroll_dir == KE_MOUSERIGHT)
2544 {
2545 if (modifiers > 0)
2546 {
Christopher Plewright03193062022-11-22 12:58:27 +00002547 // use K_SPECIAL instead of CSI to make mappings work
2548 typeahead[typeaheadlen++] = K_SPECIAL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002549 typeahead[typeaheadlen++] = KS_MODIFIER;
2550 typeahead[typeaheadlen++] = modifiers;
2551 }
2552 typeahead[typeaheadlen++] = CSI;
2553 typeahead[typeaheadlen++] = KS_EXTRA;
2554 typeahead[typeaheadlen++] = scroll_dir;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002555 }
2556 else
2557 {
2558 typeahead[typeaheadlen++] = ESC + 128;
2559 typeahead[typeaheadlen++] = 'M';
2560 typeahead[typeaheadlen++] = g_nMouseClick;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002561 }
Christopher Plewright36446bb2022-11-23 22:28:08 +00002562
2563 // Pass the pointer coordinates of the mouse event in 2 bytes,
2564 // allowing for > 223 columns. Both for click and scroll events.
2565 // This is the same as what is used for the GUI.
2566 typeahead[typeaheadlen++] = (char_u)(g_xMouse / 128 + ' ' + 1);
2567 typeahead[typeaheadlen++] = (char_u)(g_xMouse % 128 + ' ' + 1);
2568 typeahead[typeaheadlen++] = (char_u)(g_yMouse / 128 + ' ' + 1);
2569 typeahead[typeaheadlen++] = (char_u)(g_yMouse % 128 + ' ' + 1);
2570
2571 g_nMouseClick = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002572 }
2573 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002574 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002575 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002576 int modifiers = 0;
2577
2578 c = tgetch(&modifiers, &ch2);
2579
Christopher Plewrightc8b20492023-01-04 18:06:00 +00002580 c = simplify_key(c, &modifiers);
2581
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002582 // Some chars need adjustment when the Ctrl modifier is used.
2583 ++no_reduce_keys;
2584 c = may_adjust_key_for_ctrl(modifiers, c);
2585 --no_reduce_keys;
2586
2587 // remove the SHIFT modifier for keys where it's already included,
2588 // e.g., '(' and '*'
2589 modifiers = may_remove_shift_modifier(modifiers, c);
2590
Bram Moolenaar071d4272004-06-13 20:20:40 +00002591 if (typebuf_changed(tb_change_cnt))
2592 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002593 // "buf" may be invalid now if a client put something in the
2594 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002595 typeaheadlen = 0;
2596 break;
2597 }
2598
2599 if (c == Ctrl_C && ctrl_c_interrupts)
2600 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002601# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002602 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002603# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002604 got_int = TRUE;
2605 }
2606
Bram Moolenaar071d4272004-06-13 20:20:40 +00002607 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002608 {
2609 int n = 1;
2610
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002611 if (ch2 == NUL)
2612 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002613 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002614 char_u *p;
2615 WCHAR ch[2];
2616
2617 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002618 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002619 {
2620 ch[1] = tgetch(&modifiers, &ch2);
2621 n++;
2622 }
2623 p = utf16_to_enc(ch, &n);
2624 if (p != NULL)
2625 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002626 for (i = 0, j = 0; i < n; i++)
2627 {
2628 typeahead[typeaheadlen + j++] = p[i];
2629# ifdef VIMDLL
2630 if (p[i] == CSI)
2631 {
2632 typeahead[typeaheadlen + j++] = KS_EXTRA;
2633 typeahead[typeaheadlen + j++] = KE_CSI;
2634 }
2635# endif
2636 }
2637 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002638 vim_free(p);
2639 }
2640 }
2641 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002642 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002643 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002644# ifdef VIMDLL
2645 if (c == CSI)
2646 {
2647 typeahead[typeaheadlen + 1] = KS_EXTRA;
2648 typeahead[typeaheadlen + 2] = KE_CSI;
2649 n = 3;
2650 }
2651# endif
2652 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002653 if (ch2 != NUL)
2654 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002655 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002656 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002657 switch (ch2)
2658 {
2659 case (WCHAR)'\324': // SHIFT+Insert
2660 case (WCHAR)'\325': // CTRL+Insert
2661 case (WCHAR)'\327': // SHIFT+Delete
2662 case (WCHAR)'\330': // CTRL+Delete
2663 typeahead[typeaheadlen + n] = (char_u)ch2;
2664 n++;
2665 break;
2666
2667 default:
2668 typeahead[typeaheadlen + n] = 3;
2669 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2670 n += 2;
2671 break;
2672 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002673 }
2674 else
2675 {
2676 typeahead[typeaheadlen + n] = 3;
2677 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2678 n += 2;
2679 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002680 }
2681
Bram Moolenaar0f873732019-12-05 20:28:46 +01002682 // Use the ALT key to set the 8th bit of the character
2683 // when it's one byte, the 8th bit isn't set yet and not
2684 // using a double-byte encoding (would become a lead
2685 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002686 if ((modifiers & MOD_MASK_ALT)
2687 && n == 1
2688 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002689 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002690 )
2691 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002692 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2693 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002694 modifiers &= ~MOD_MASK_ALT;
2695 }
2696
2697 if (modifiers != 0)
2698 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002699 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002700 mch_memmove(typeahead + typeaheadlen + 3,
2701 typeahead + typeaheadlen, n);
2702 typeahead[typeaheadlen++] = K_SPECIAL;
2703 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2704 typeahead[typeaheadlen++] = modifiers;
2705 }
2706
2707 typeaheadlen += n;
2708
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002709# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002710 if (fdDump)
2711 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002712# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002713 }
2714 }
2715 }
2716
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002717# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002718 if (fdDump)
2719 {
2720 fputs("]\n", fdDump);
2721 fflush(fdDump);
2722 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002723# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002724
Bram Moolenaar071d4272004-06-13 20:20:40 +00002725theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002726 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002727 len = 0;
2728 while (len < maxlen && typeaheadlen > 0)
2729 {
2730 buf[len++] = typeahead[0];
2731 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2732 }
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00002733# ifdef FEAT_EVAL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002734 if (len > 0)
2735 {
2736 buf[len] = NUL;
2737 ch_log(NULL, "raw key input: \"%s\"", buf);
2738 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002739# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002740 return len;
2741
Bram Moolenaar0f873732019-12-05 20:28:46 +01002742#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002743 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002744#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002745}
2746
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002747/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002748 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002749 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2750 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002751 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002752 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002753 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002754executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002755{
LemonBoy40fd7e62022-05-05 20:18:16 +01002756 int attrs = win32_getattrs((char_u *)name);
2757
2758 // The file doesn't exist or is a folder.
2759 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2760 return FALSE;
2761 // Check if the file is an AppExecLink, a special alias used by Windows
2762 // Store for its apps.
2763 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002764 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002765 char_u *res = resolve_appexeclink((char_u *)name);
2766 if (res == NULL)
AmberArrf5d0f542023-08-20 20:03:45 +02002767 res = resolve_reparse_point((char_u *)name);
2768 if (res == NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002769 return FALSE;
2770 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002771 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002772 *path = res;
2773 else
2774 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002775 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002776 else if (path != NULL)
2777 *path = FullName_save((char_u *)name, FALSE);
2778 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002779}
2780
2781/*
2782 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2783 * If "use_path" is FALSE: Return TRUE if "name" exists.
2784 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2785 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2786 * the allocated memory.
2787 */
2788 static int
2789executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2790{
2791 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2792 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2793 // UTF-8.
2794 char_u buf[_MAX_PATH * 3];
2795 size_t len = STRLEN(name);
2796 size_t tmplen;
2797 char_u *p, *e, *e2;
2798 char_u *pathbuf = NULL;
2799 char_u *pathext = NULL;
2800 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002801 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002802 int noext = FALSE;
2803 int retval = FALSE;
2804
2805 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002806 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002807
2808 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002809 shname = gettail(p_sh);
2810 if (strstr((char *)shname, "sh") != NULL &&
2811 !(strstr((char *)shname, "powershell") != NULL
2812 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002813 noext = TRUE;
2814
2815 if (use_pathext)
2816 {
2817 pathext = mch_getenv("PATHEXT");
2818 if (pathext == NULL)
2819 pathext = (char_u *)".com;.exe;.bat;.cmd";
2820
2821 if (noext == FALSE)
2822 {
2823 /*
2824 * Loop over all extensions in $PATHEXT.
2825 * Check "name" ends with extension.
2826 */
2827 p = pathext;
2828 while (*p)
2829 {
2830 if (p[0] == ';'
2831 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2832 {
2833 // Skip empty or single ".".
2834 ++p;
2835 continue;
2836 }
2837 e = vim_strchr(p, ';');
2838 if (e == NULL)
2839 e = p + STRLEN(p);
2840 tmplen = e - p;
2841
2842 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2843 {
2844 noext = TRUE;
2845 break;
2846 }
2847
2848 p = e;
2849 }
2850 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002851 }
2852
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002853 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002854 if (pathext == NULL)
2855 pathext = (char_u *)".";
2856 else if (noext == TRUE)
2857 {
2858 if (pathextbuf == NULL)
2859 pathextbuf = alloc(STRLEN(pathext) + 3);
2860 if (pathextbuf == NULL)
2861 {
2862 retval = FALSE;
2863 goto theend;
2864 }
2865 STRCPY(pathextbuf, ".;");
2866 STRCAT(pathextbuf, pathext);
2867 pathext = pathextbuf;
2868 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002869
Bram Moolenaar95da1362020-05-30 18:37:55 +02002870 // Use $PATH when "use_path" is TRUE and "name" is basename.
2871 if (use_path && gettail((char_u *)name) == (char_u *)name)
2872 {
2873 p = mch_getenv("PATH");
2874 if (p != NULL)
2875 {
2876 pathbuf = alloc(STRLEN(p) + 3);
2877 if (pathbuf == NULL)
2878 {
2879 retval = FALSE;
2880 goto theend;
2881 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002882
2883 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2884 STRCPY(pathbuf, ".;");
2885 else
2886 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002887 STRCAT(pathbuf, p);
2888 }
2889 }
2890
2891 /*
2892 * Walk through all entries in $PATH to check if "name" exists there and
2893 * is an executable file.
2894 */
2895 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2896 while (*p)
2897 {
2898 if (*p == ';') // Skip empty entry
2899 {
2900 ++p;
2901 continue;
2902 }
2903 e = vim_strchr(p, ';');
2904 if (e == NULL)
2905 e = p + STRLEN(p);
2906
2907 if (e - p + len + 2 > sizeof(buf))
2908 {
2909 retval = FALSE;
2910 goto theend;
2911 }
2912 // A single "." that means current dir.
2913 if (e - p == 1 && *p == '.')
2914 STRCPY(buf, name);
2915 else
2916 {
2917 vim_strncpy(buf, p, e - p);
2918 add_pathsep(buf);
2919 STRCAT(buf, name);
2920 }
2921 tmplen = STRLEN(buf);
2922
2923 /*
2924 * Loop over all extensions in $PATHEXT.
2925 * Check "name" with extension added.
2926 */
2927 p = pathext;
2928 while (*p)
2929 {
2930 if (*p == ';')
2931 {
2932 // Skip empty entry
2933 ++p;
2934 continue;
2935 }
2936 e2 = vim_strchr(p, (int)';');
2937 if (e2 == NULL)
2938 e2 = p + STRLEN(p);
2939
2940 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2941 {
2942 // Not a single "." that means no extension is added.
2943 if (e2 - p + tmplen + 1 > sizeof(buf))
2944 {
2945 retval = FALSE;
2946 goto theend;
2947 }
2948 vim_strncpy(buf + tmplen, p, e2 - p);
2949 }
2950 if (executable_file((char *)buf, path))
2951 {
2952 retval = TRUE;
2953 goto theend;
2954 }
2955
2956 p = e2;
2957 }
2958
2959 p = e;
2960 }
2961
2962theend:
2963 free(pathextbuf);
2964 free(pathbuf);
2965 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002966}
2967
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002968#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2969 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002970/*
2971 * Bad parameter handler.
2972 *
2973 * Certain MS CRT functions will intentionally crash when passed invalid
2974 * parameters to highlight possible security holes. Setting this function as
2975 * the bad parameter handler will prevent the crash.
2976 *
2977 * In debug builds the parameters contain CRT information that might help track
2978 * down the source of a problem, but in non-debug builds the arguments are all
2979 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2980 * worth allowing these to make debugging of issues easier.
2981 */
2982 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002983bad_param_handler(const wchar_t *expression UNUSED,
2984 const wchar_t *function UNUSED,
2985 const wchar_t *file UNUSED,
2986 unsigned int line UNUSED,
2987 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002988{
2989}
2990
2991# define SET_INVALID_PARAM_HANDLER \
2992 ((void)_set_invalid_parameter_handler(bad_param_handler))
2993#else
2994# define SET_INVALID_PARAM_HANDLER
2995#endif
2996
Bram Moolenaar4f974752019-02-17 17:44:42 +01002997#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002998
2999/*
3000 * GUI version of mch_init().
3001 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003002 static void
3003mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003004{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003005# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00003006 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003007# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003008
Bram Moolenaar0f873732019-12-05 20:28:46 +01003009 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02003010 SET_INVALID_PARAM_HANDLER;
3011
Bram Moolenaar0f873732019-12-05 20:28:46 +01003012 // Let critical errors result in a failure, not in a dialog box. Required
3013 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003014 SetErrorMode(SEM_FAILCRITICALERRORS);
3015
Bram Moolenaar0f873732019-12-05 20:28:46 +01003016 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00003017
Bram Moolenaar0f873732019-12-05 20:28:46 +01003018 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00003019 Rows = 25;
3020 Columns = 80;
3021
Bram Moolenaar0f873732019-12-05 20:28:46 +01003022 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00003023 {
3024 char_u vimrun_location[_MAX_PATH + 4];
3025
Bram Moolenaar0f873732019-12-05 20:28:46 +01003026 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00003027 STRCPY(vimrun_location, exe_name);
3028 STRCPY(gettail(vimrun_location), "vimrun.exe");
3029 if (mch_getperm(vimrun_location) >= 0)
3030 {
John Marriott738df382025-06-05 20:49:39 +02003031 char *p;
3032
Bram Moolenaar071d4272004-06-13 20:20:40 +00003033 if (*skiptowhite(vimrun_location) != NUL)
3034 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01003035 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003036 mch_memmove(vimrun_location + 1, vimrun_location,
3037 STRLEN(vimrun_location) + 1);
3038 *vimrun_location = '"';
3039 STRCPY(gettail(vimrun_location), "vimrun\" ");
3040 }
3041 else
3042 STRCPY(gettail(vimrun_location), "vimrun ");
3043
John Marriott738df382025-06-05 20:49:39 +02003044 p = (char *)vim_strsave(vimrun_location);
3045 if (p != NULL)
3046 {
3047 vimrun_path = p;
3048 s_dont_use_vimrun = FALSE;
3049 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003050 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02003051 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003052 s_dont_use_vimrun = FALSE;
3053
Bram Moolenaar0f873732019-12-05 20:28:46 +01003054 // Don't give the warning for a missing vimrun.exe right now, but only
3055 // when vimrun was supposed to be used. Don't bother people that do
3056 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003057 if (s_dont_use_vimrun)
3058 need_vimrun_warning = TRUE;
3059 }
3060
3061 /*
3062 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
3063 * Otherwise the default "findstr /n" is used.
3064 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02003065 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01003066 set_option_value_give_err((char_u *)"grepprg",
3067 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003068
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003069# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003070 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003071# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003072
3073 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003074}
3075
3076
Bram Moolenaar0f873732019-12-05 20:28:46 +01003077#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003078
3079#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003080
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003081# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
3082# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003083
3084/*
3085 * ClearConsoleBuffer()
3086 * Description:
3087 * Clears the entire contents of the console screen buffer, using the
3088 * specified attribute.
3089 * Returns:
3090 * TRUE on success
3091 */
3092 static BOOL
3093ClearConsoleBuffer(WORD wAttribute)
3094{
3095 CONSOLE_SCREEN_BUFFER_INFO csbi;
3096 COORD coord;
3097 DWORD NumCells, dummy;
3098
3099 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3100 return FALSE;
3101
3102 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
3103 coord.X = 0;
3104 coord.Y = 0;
3105 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
3106 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003107 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003108 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
3109 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003110 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003111
3112 return TRUE;
3113}
3114
3115/*
3116 * FitConsoleWindow()
3117 * Description:
3118 * Checks if the console window will fit within given buffer dimensions.
3119 * Also, if requested, will shrink the window to fit.
3120 * Returns:
3121 * TRUE on success
3122 */
3123 static BOOL
3124FitConsoleWindow(
3125 COORD dwBufferSize,
3126 BOOL WantAdjust)
3127{
3128 CONSOLE_SCREEN_BUFFER_INFO csbi;
3129 COORD dwWindowSize;
3130 BOOL NeedAdjust = FALSE;
3131
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003132 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3133 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003134
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003135 /*
3136 * A buffer resize will fail if the current console window does
3137 * not lie completely within that buffer. To avoid this, we might
3138 * have to move and possibly shrink the window.
3139 */
3140 if (csbi.srWindow.Right >= dwBufferSize.X)
3141 {
3142 dwWindowSize.X = SRWIDTH(csbi.srWindow);
3143 if (dwWindowSize.X > dwBufferSize.X)
3144 dwWindowSize.X = dwBufferSize.X;
3145 csbi.srWindow.Right = dwBufferSize.X - 1;
3146 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
3147 NeedAdjust = TRUE;
3148 }
3149 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
3150 {
3151 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
3152 if (dwWindowSize.Y > dwBufferSize.Y)
3153 dwWindowSize.Y = dwBufferSize.Y;
3154 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
3155 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
3156 NeedAdjust = TRUE;
3157 }
3158 if (NeedAdjust && WantAdjust)
3159 {
3160 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
3161 return FALSE;
3162 }
3163 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003164}
3165
3166typedef struct ConsoleBufferStruct
3167{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003168 BOOL IsValid;
3169 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003170 PCHAR_INFO Buffer;
3171 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003172 PSMALL_RECT Regions;
3173 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003174} ConsoleBuffer;
3175
3176/*
3177 * SaveConsoleBuffer()
3178 * Description:
3179 * Saves important information about the console buffer, including the
3180 * actual buffer contents. The saved information is suitable for later
3181 * restoration by RestoreConsoleBuffer().
3182 * Returns:
3183 * TRUE if all information was saved; FALSE otherwise
3184 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
3185 */
3186 static BOOL
3187SaveConsoleBuffer(
3188 ConsoleBuffer *cb)
3189{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003190 DWORD NumCells;
3191 COORD BufferCoord;
3192 SMALL_RECT ReadRegion;
3193 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003194 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003195
Bram Moolenaar071d4272004-06-13 20:20:40 +00003196 if (cb == NULL)
3197 return FALSE;
3198
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003199 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003200 {
3201 cb->IsValid = FALSE;
3202 return FALSE;
3203 }
3204 cb->IsValid = TRUE;
3205
Christopher Plewright1140b512022-11-12 18:46:05 +00003206 // VTP uses alternate screen buffer.
3207 // No need to save buffer contents for restoration.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003208 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003209 return TRUE;
3210
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003211 /*
3212 * Allocate a buffer large enough to hold the entire console screen
3213 * buffer. If this ConsoleBuffer structure has already been initialized
3214 * with a buffer of the correct size, then just use that one.
3215 */
3216 if (!cb->IsValid || cb->Buffer == NULL ||
3217 cb->BufferSize.X != cb->Info.dwSize.X ||
3218 cb->BufferSize.Y != cb->Info.dwSize.Y)
3219 {
3220 cb->BufferSize.X = cb->Info.dwSize.X;
3221 cb->BufferSize.Y = cb->Info.dwSize.Y;
3222 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
3223 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003224 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003225 if (cb->Buffer == NULL)
3226 return FALSE;
3227 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003228
3229 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003230 * We will now copy the console screen buffer into our buffer.
3231 * ReadConsoleOutput() seems to be limited as far as how much you
3232 * can read at a time. Empirically, this number seems to be about
3233 * 12000 cells (rows * columns). Start at position (0, 0) and copy
3234 * in chunks until it is all copied. The chunks will all have the
3235 * same horizontal characteristics, so initialize them now. The
3236 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003237 */
Bram Moolenaar61594242015-09-01 20:23:37 +02003238 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003239 ReadRegion.Left = 0;
3240 ReadRegion.Right = cb->Info.dwSize.X - 1;
3241 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003242
3243 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
3244 if (cb->Regions == NULL || numregions != cb->NumRegions)
3245 {
3246 cb->NumRegions = numregions;
3247 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003248 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003249 if (cb->Regions == NULL)
3250 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003251 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003252 return FALSE;
3253 }
3254 }
3255
3256 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003257 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003258 /*
3259 * Read into position (0, Y) in our buffer.
3260 */
3261 BufferCoord.Y = Y;
3262 /*
3263 * Read the region whose top left corner is (0, Y) and whose bottom
3264 * right corner is (width - 1, Y + Y_incr - 1). This should define
3265 * a region of size width by Y_incr. Don't worry if this region is
3266 * too large for the remaining buffer; it will be cropped.
3267 */
3268 ReadRegion.Top = Y;
3269 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003270 if (!ReadConsoleOutputW(g_hConOut, // output handle
3271 cb->Buffer, // our buffer
3272 cb->BufferSize, // dimensions of our buffer
3273 BufferCoord, // offset in our buffer
3274 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003275 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003276 VIM_CLEAR(cb->Buffer);
3277 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003278 return FALSE;
3279 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02003280 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003281 }
3282
3283 return TRUE;
3284}
3285
3286/*
3287 * RestoreConsoleBuffer()
3288 * Description:
3289 * Restores important information about the console buffer, including the
3290 * actual buffer contents, if desired. The information to restore is in
3291 * the same format used by SaveConsoleBuffer().
3292 * Returns:
3293 * TRUE on success
3294 */
3295 static BOOL
3296RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003297 ConsoleBuffer *cb,
3298 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003299{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003300 COORD BufferCoord;
3301 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003302 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003303
Christopher Plewright1140b512022-11-12 18:46:05 +00003304
Bram Moolenaar071d4272004-06-13 20:20:40 +00003305 if (cb == NULL || !cb->IsValid)
3306 return FALSE;
3307
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003308 /*
3309 * Before restoring the buffer contents, clear the current buffer, and
3310 * restore the cursor position and window information. Doing this now
3311 * prevents old buffer contents from "flashing" onto the screen.
3312 */
3313 if (RestoreScreen)
3314 ClearConsoleBuffer(cb->Info.wAttributes);
3315
3316 FitConsoleWindow(cb->Info.dwSize, TRUE);
3317 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
3318 return FALSE;
3319 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
3320 return FALSE;
3321
3322 if (!RestoreScreen)
3323 {
3324 /*
3325 * No need to restore the screen buffer contents, so we're done.
3326 */
3327 return TRUE;
3328 }
3329
3330 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
3331 return FALSE;
3332 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
3333 return FALSE;
3334
Christopher Plewrightab281f82025-03-16 19:14:31 +01003335 // VTP uses alternate screen buffer.
3336 // No need to restore buffer contents.
3337 if (use_alternate_screen_buffer)
3338 return TRUE;
3339
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003340 /*
3341 * Restore the screen buffer contents.
3342 */
3343 if (cb->Buffer != NULL)
3344 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003345 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003346 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003347 BufferCoord.X = cb->Regions[i].Left;
3348 BufferCoord.Y = cb->Regions[i].Top;
3349 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01003350 if (!WriteConsoleOutputW(g_hConOut, // output handle
3351 cb->Buffer, // our buffer
3352 cb->BufferSize, // dimensions of our buffer
3353 BufferCoord, // offset in our buffer
3354 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02003355 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003356 }
3357 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003358
3359 return TRUE;
3360}
3361
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003362# define FEAT_RESTORE_ORIG_SCREEN
3363# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003364static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003365# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003366static ConsoleBuffer g_cbNonTermcap = { 0 };
3367static ConsoleBuffer g_cbTermcap = { 0 };
3368
Bram Moolenaar071d4272004-06-13 20:20:40 +00003369char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01003370HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00003371static HICON g_hOrigIconSmall = NULL;
3372static HICON g_hOrigIcon = NULL;
3373static HICON g_hVimIcon = NULL;
3374static BOOL g_fCanChangeIcon = FALSE;
3375
Bram Moolenaar071d4272004-06-13 20:20:40 +00003376/*
3377 * GetConsoleIcon()
3378 * Description:
3379 * Attempts to retrieve the small icon and/or the big icon currently in
3380 * use by a given window.
3381 * Returns:
3382 * TRUE on success
3383 */
3384 static BOOL
3385GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003386 HWND hWnd,
3387 HICON *phIconSmall,
3388 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003389{
3390 if (hWnd == NULL)
3391 return FALSE;
3392
3393 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003394 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
3395 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003396 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003397 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
3398 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003399 return TRUE;
3400}
3401
3402/*
3403 * SetConsoleIcon()
3404 * Description:
3405 * Attempts to change the small icon and/or the big icon currently in
3406 * use by a given window.
3407 * Returns:
3408 * TRUE on success
3409 */
3410 static BOOL
3411SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003412 HWND hWnd,
3413 HICON hIconSmall,
3414 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003415{
Bram Moolenaar071d4272004-06-13 20:20:40 +00003416 if (hWnd == NULL)
3417 return FALSE;
3418
3419 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003420 SendMessage(hWnd, WM_SETICON,
3421 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003422 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003423 SendMessage(hWnd, WM_SETICON,
3424 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003425 return TRUE;
3426}
3427
3428/*
3429 * SaveConsoleTitleAndIcon()
3430 * Description:
3431 * Saves the current console window title in g_szOrigTitle, for later
3432 * restoration. Also, attempts to obtain a handle to the console window,
3433 * and use it to save the small and big icons currently in use by the
3434 * console window. This is not always possible on some versions of Windows;
3435 * nor is it possible when running Vim remotely using Telnet (since the
3436 * console window the user sees is owned by a remote process).
3437 */
3438 static void
3439SaveConsoleTitleAndIcon(void)
3440{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003441 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003442 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
3443 return;
3444
3445 /*
3446 * Obtain a handle to the console window using GetConsoleWindow() from
3447 * KERNEL32.DLL; we need to handle in order to change the window icon.
3448 * This function only exists on NT-based Windows, starting with Windows
3449 * 2000. On older operating systems, we can't change the window icon
3450 * anyway.
3451 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003452 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003453 if (g_hWnd == NULL)
3454 return;
3455
Bram Moolenaar0f873732019-12-05 20:28:46 +01003456 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003457 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
3458 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
3459 return;
3460
Bram Moolenaar0f873732019-12-05 20:28:46 +01003461 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01003462 if (
3463# ifdef FEAT_LIBCALL
3464 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
3465# endif
3466 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003467 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003468 if (g_hVimIcon != NULL)
3469 g_fCanChangeIcon = TRUE;
3470}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003471
3472static int g_fWindInitCalled = FALSE;
3473static int g_fTermcapMode = FALSE;
3474static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003475
3476/*
3477 * non-GUI version of mch_init().
3478 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003479 static void
3480mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003481{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003482# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003483 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003484# endif
3485# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00003486 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003487# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003488
Bram Moolenaar0f873732019-12-05 20:28:46 +01003489 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02003490 SET_INVALID_PARAM_HANDLER;
3491
Bram Moolenaar0f873732019-12-05 20:28:46 +01003492 // Let critical errors result in a failure, not in a dialog box. Required
3493 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003494 SetErrorMode(SEM_FAILCRITICALERRORS);
3495
Bram Moolenaar0f873732019-12-05 20:28:46 +01003496 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00003497 out_flush();
3498
Bram Moolenaar0f873732019-12-05 20:28:46 +01003499 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00003500 if (read_cmd_fd == 0)
3501 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
3502 else
3503 create_conin();
3504 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
3505
Christopher Plewright38804d62022-11-09 23:55:52 +00003506 wt_init();
3507 vtp_flag_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003508# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01003509 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003510 SaveConsoleBuffer(&g_cbOrig);
3511 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003512# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01003513 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003514 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
3515 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003516# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003517 if (cterm_normal_fg_color == 0)
3518 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
3519 if (cterm_normal_bg_color == 0)
3520 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
3521
Bram Moolenaarbdace832019-03-02 10:13:42 +01003522 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02003523 g_color_index_fg = g_attrDefault & 0xf;
3524 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
3525
Bram Moolenaar0f873732019-12-05 20:28:46 +01003526 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00003527 update_tcap(g_attrCurrent);
3528
3529 GetConsoleCursorInfo(g_hConOut, &g_cci);
3530 GetConsoleMode(g_hConIn, &g_cmodein);
3531 GetConsoleMode(g_hConOut, &g_cmodeout);
3532
Bram Moolenaar071d4272004-06-13 20:20:40 +00003533 SaveConsoleTitleAndIcon();
3534 /*
3535 * Set both the small and big icons of the console window to Vim's icon.
3536 * Note that Vim presently only has one size of icon (32x32), but it
3537 * automatically gets scaled down to 16x16 when setting the small icon.
3538 */
3539 if (g_fCanChangeIcon)
3540 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003541
3542 ui_get_shellsize();
3543
Christopher Plewrightd343c602023-01-22 18:58:30 +00003544 vtp_init();
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00003545 // Switch to a new alternate screen buffer.
3546 if (use_alternate_screen_buffer)
3547 vtp_printf("\033[?1049h");
Christopher Plewrightd343c602023-01-22 18:58:30 +00003548
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003549# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003550 fdDump = fopen("dump", "wt");
3551
3552 if (fdDump)
3553 {
3554 time_t t;
3555
3556 time(&t);
3557 fputs(ctime(&t), fdDump);
3558 fflush(fdDump);
3559 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003560# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003561
3562 g_fWindInitCalled = TRUE;
3563
Bram Moolenaar071d4272004-06-13 20:20:40 +00003564 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003565
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003566# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003567 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003568# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003569}
3570
3571/*
3572 * non-GUI version of mch_exit().
3573 * Shut down and exit with status `r'
3574 * Careful: mch_exit() may be called before mch_init()!
3575 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003576 static void
3577mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003578{
William Breslerded59132024-10-08 21:30:48 +02003579 // Copy flag since stoptermcap() will clear the flag.
3580 int fTermcapMode = g_fTermcapMode;
3581
Bram Moolenaar955f1982017-02-05 15:10:51 +01003582 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003583
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003584 vtp_exit();
3585
Bram Moolenaar955f1982017-02-05 15:10:51 +01003586 stoptermcap();
William Breslerded59132024-10-08 21:30:48 +02003587 // Switch back to main screen buffer if TermcapMode was not active.
3588 if (!fTermcapMode && use_alternate_screen_buffer)
Ken Takata568cbc92024-08-07 21:18:24 +02003589 vtp_printf("\033[?1049l");
3590
Bram Moolenaar071d4272004-06-13 20:20:40 +00003591 if (g_fWindInitCalled)
3592 settmode(TMODE_COOK);
3593
Bram Moolenaar0f873732019-12-05 20:28:46 +01003594 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00003595
3596 if (g_fWindInitCalled)
3597 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02003598 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003599 /*
3600 * Restore both the small and big icons of the console window to
3601 * what they were at startup. Don't do this when the window is
3602 * closed, Vim would hang here.
3603 */
3604 if (g_fCanChangeIcon && !g_fForceExit)
3605 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003606
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003607# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003608 if (fdDump)
3609 {
3610 time_t t;
3611
3612 time(&t);
3613 fputs(ctime(&t), fdDump);
3614 fclose(fdDump);
3615 }
3616 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003617# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003618 }
3619
3620 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003621 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003622 SetConsoleMode(g_hConOut, g_cmodeout);
3623
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003624# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003625 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003626# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003627
3628 exit(r);
3629}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003630#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003631
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003632 void
3633mch_init(void)
3634{
3635#ifdef VIMDLL
3636 if (gui.starting)
3637 mch_init_g();
3638 else
3639 mch_init_c();
3640#elif defined(FEAT_GUI_MSWIN)
3641 mch_init_g();
3642#else
3643 mch_init_c();
3644#endif
3645}
3646
3647 void
3648mch_exit(int r)
3649{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003650#ifdef FEAT_NETBEANS_INTG
3651 netbeans_send_disconnect();
3652#endif
3653
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003654#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003655 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003656 mch_exit_g(r);
3657 else
3658 mch_exit_c(r);
3659#elif defined(FEAT_GUI_MSWIN)
3660 mch_exit_g(r);
3661#else
3662 mch_exit_c(r);
3663#endif
3664}
3665
Bram Moolenaar071d4272004-06-13 20:20:40 +00003666/*
3667 * Do we have an interactive window?
3668 */
3669 int
3670mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003671 int argc UNUSED,
3672 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003673{
K.Takatace3189d2023-02-15 19:13:43 +00003674 mch_get_exe_name();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003675
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003676#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003677 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003678#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003679# ifdef VIMDLL
3680 if (gui.in_use)
3681 return OK;
3682# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003683 if (isatty(1))
3684 return OK;
3685 return FAIL;
3686#endif
3687}
3688
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003689/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003690 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003691 * When "len" is > 0, also expand short to long filenames.
3692 */
3693 void
3694fname_case(
3695 char_u *name,
3696 int len)
3697{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003698 int flen;
3699 WCHAR *p;
3700 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003701
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003702 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003703 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003704 return;
3705
3706 slash_adjust(name);
3707
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003708 p = enc_to_utf16(name, NULL);
3709 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003710 return;
3711
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003712 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003713 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003714 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003715
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003716 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003717 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003718 if (len > 0 || flen >= (int)STRLEN(q))
3719 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3720 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003721 }
3722 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003723 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003724}
3725
3726
3727/*
3728 * Insert user name in s[len].
3729 */
3730 int
3731mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003732 char_u *s,
3733 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003734{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003735 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003736 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003737
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003738 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003739 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003740 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003741
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003742 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003743 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003744 vim_strncpy(s, p, len - 1);
3745 vim_free(p);
3746 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003747 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003748 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003749 s[0] = NUL;
3750 return FAIL;
3751}
3752
3753
3754/*
3755 * Insert host name in s[len].
3756 */
3757 void
3758mch_get_host_name(
3759 char_u *s,
3760 int len)
3761{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003762 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003763 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003764
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003765 if (!GetComputerNameW(wszHostName, &wcch))
3766 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003767
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003768 char_u *p = utf16_to_enc(wszHostName, NULL);
3769 if (p == NULL)
3770 return;
3771
3772 vim_strncpy(s, p, len - 1);
3773 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003774}
3775
3776
3777/*
3778 * return process ID
3779 */
3780 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003781mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003782{
3783 return (long)GetCurrentProcessId();
3784}
3785
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003786/*
3787 * return TRUE if process "pid" is still running
3788 */
3789 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003790mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003791{
3792 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3793 DWORD status = 0;
3794 int ret = FALSE;
3795
3796 if (hProcess == NULL)
3797 return FALSE; // might not have access
3798 if (GetExitCodeProcess(hProcess, &status) )
3799 ret = status == STILL_ACTIVE;
3800 CloseHandle(hProcess);
3801 return ret;
3802}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003803
3804/*
3805 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3806 * Return OK for success, FAIL for failure.
3807 */
3808 int
3809mch_dirname(
3810 char_u *buf,
3811 int len)
3812{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003813 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003814
Bram Moolenaar071d4272004-06-13 20:20:40 +00003815 /*
3816 * Originally this was:
3817 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3818 * But the Win32s known bug list says that getcwd() doesn't work
3819 * so use the Win32 system call instead. <Negri>
3820 */
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003821 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) == 0)
3822 return FAIL;
3823
3824 WCHAR wcbuf[_MAX_PATH + 1];
3825 char_u *p = NULL;
3826
3827 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003828 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003829 p = utf16_to_enc(wcbuf, NULL);
John Marriott031f2272025-04-23 20:56:08 +02003830 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003831 {
John Marriott031f2272025-04-23 20:56:08 +02003832 if (STRLEN(p) >= (size_t)len)
3833 {
3834 // long path name is too long, fall back to short one
3835 VIM_CLEAR(p);
3836 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003837 }
3838 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003839 if (p == NULL)
3840 p = utf16_to_enc(wbuf, NULL);
3841
3842 if (p == NULL)
3843 return FAIL;
3844
3845 vim_strncpy(buf, p, len - 1);
3846 vim_free(p);
3847 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003848}
3849
3850/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003851 * Get file permissions for "name".
3852 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003853 */
3854 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003855mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003856{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003857 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003858 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003859
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003860 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003861 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003862}
3863
3864
3865/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003866 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003867 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003868 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003869 */
3870 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003871mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003872{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003873 long n;
3874 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003875
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003876 p = enc_to_utf16(name, NULL);
3877 if (p == NULL)
3878 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003879
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003880 n = _wchmod(p, perm);
3881 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003882 if (n == -1)
3883 return FAIL;
3884
3885 win32_set_archive(name);
3886
3887 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003888}
3889
3890/*
3891 * Set hidden flag for "name".
3892 */
3893 void
3894mch_hide(char_u *name)
3895{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003896 int attrs = win32_getattrs(name);
3897 if (attrs == -1)
3898 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003899
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003900 attrs |= FILE_ATTRIBUTE_HIDDEN;
3901 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003902}
3903
3904/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003905 * Return TRUE if file "name" exists and is hidden.
3906 */
3907 int
3908mch_ishidden(char_u *name)
3909{
3910 int f = win32_getattrs(name);
3911
3912 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003913 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003914
3915 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3916}
3917
3918/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003919 * return TRUE if "name" is a directory
3920 * return FALSE if "name" is not a directory or upon error
3921 */
3922 int
3923mch_isdir(char_u *name)
3924{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003925 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003926
3927 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003928 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003929
3930 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3931}
3932
3933/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003934 * return TRUE if "name" is a directory, NOT a symlink to a directory
3935 * return FALSE if "name" is not a directory
3936 * return FALSE for error
3937 */
3938 int
3939mch_isrealdir(char_u *name)
3940{
3941 return mch_isdir(name) && !mch_is_symbolic_link(name);
3942}
3943
3944/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003945 * Create directory "name".
3946 * Return 0 on success, -1 on error.
3947 */
3948 int
3949mch_mkdir(char_u *name)
3950{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003951 WCHAR *p;
3952 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003953
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003954 p = enc_to_utf16(name, NULL);
3955 if (p == NULL)
3956 return -1;
3957 retval = _wmkdir(p);
3958 vim_free(p);
3959 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003960}
3961
3962/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003963 * Delete directory "name".
3964 * Return 0 on success, -1 on error.
3965 */
3966 int
3967mch_rmdir(char_u *name)
3968{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003969 WCHAR *p;
3970 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003971
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003972 p = enc_to_utf16(name, NULL);
3973 if (p == NULL)
3974 return -1;
3975 retval = _wrmdir(p);
3976 vim_free(p);
3977 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003978}
3979
3980/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003981 * Return TRUE if file "fname" has more than one link.
3982 */
3983 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003984mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003985{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003986 BY_HANDLE_FILE_INFORMATION info;
3987
3988 return win32_fileinfo(fname, &info) == FILEINFO_OK
3989 && info.nNumberOfLinks > 1;
3990}
3991
3992/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003993 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003994 */
3995 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003996mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003997{
3998 HANDLE hFind;
3999 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004000 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004001 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004002 WIN32_FIND_DATAW findDataW;
4003
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004004 wn = enc_to_utf16(name, NULL);
4005 if (wn == NULL)
4006 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004007
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004008 hFind = FindFirstFileW(wn, &findDataW);
4009 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004010 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004011 {
4012 fileFlags = findDataW.dwFileAttributes;
4013 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004014 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004015 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004016
4017 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01004018 && (reparseTag == IO_REPARSE_TAG_SYMLINK
4019 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004020 res = TRUE;
4021
4022 return res;
4023}
4024
4025/*
4026 * Return TRUE if file "fname" has more than one link or if it is a symbolic
4027 * link.
4028 */
4029 int
4030mch_is_linked(char_u *fname)
4031{
4032 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
4033 return TRUE;
4034 return FALSE;
4035}
4036
4037/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02004038 * Get the by-handle-file-information for "fname".
4039 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004040 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02004041 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
4042 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
4043 */
4044 int
4045win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
4046{
Bram Moolenaar03f48552006-02-28 23:52:23 +00004047 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02004048 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004049 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00004050
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004051 wn = enc_to_utf16(fname, NULL);
4052 if (wn == NULL)
4053 return FILEINFO_ENC_FAIL;
4054
4055 hFile = CreateFileW(wn, // file name
4056 GENERIC_READ, // access mode
4057 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
4058 NULL, // security descriptor
4059 OPEN_EXISTING, // creation disposition
4060 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
4061 NULL); // handle to template file
4062 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00004063
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00004064 if (hFile == INVALID_HANDLE_VALUE)
4065 return FILEINFO_READ_FAIL;
4066
4067 if (GetFileInformationByHandle(hFile, info) != 0)
4068 res = FILEINFO_OK;
4069 else
4070 res = FILEINFO_INFO_FAIL;
4071 CloseHandle(hFile);
Bram Moolenaar03f48552006-02-28 23:52:23 +00004072
Bram Moolenaar03f48552006-02-28 23:52:23 +00004073 return res;
4074}
4075
4076/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004077 * get file attributes for `name'
4078 * -1 : error
4079 * else FILE_ATTRIBUTE_* defined in winnt.h
4080 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01004081 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004082win32_getattrs(char_u *name)
4083{
4084 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004085 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004086
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004087 p = enc_to_utf16(name, NULL);
4088 if (p == NULL)
4089 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004090
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004091 attr = GetFileAttributesW(p);
4092 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004093
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004094 return attr;
4095}
4096
4097/*
4098 * set file attributes for `name' to `attrs'
4099 *
4100 * return -1 for failure, 0 otherwise
4101 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004102 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004103win32_setattrs(char_u *name, int attrs)
4104{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004105 int res;
4106 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004107
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004108 p = enc_to_utf16(name, NULL);
4109 if (p == NULL)
4110 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004111
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004112 res = SetFileAttributesW(p, attrs);
4113 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004114
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004115 return res ? 0 : -1;
4116}
4117
4118/*
4119 * Set archive flag for "name".
4120 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004121 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004122win32_set_archive(char_u *name)
4123{
4124 int attrs = win32_getattrs(name);
4125 if (attrs == -1)
4126 return -1;
4127
4128 attrs |= FILE_ATTRIBUTE_ARCHIVE;
4129 return win32_setattrs(name, attrs);
4130}
4131
4132/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004133 * Return TRUE if file or directory "name" is writable (not readonly).
4134 * Strange semantics of Win32: a readonly directory is writable, but you can't
4135 * delete a file. Let's say this means it is writable.
4136 */
4137 int
4138mch_writable(char_u *name)
4139{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004140 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004141
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004142 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
4143 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004144}
4145
Bram Moolenaar071d4272004-06-13 20:20:40 +00004146/*
Bram Moolenaar43663192017-03-05 14:29:12 +01004147 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01004148 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01004149 * When returning TRUE and "path" is not NULL save the path and set "*path" to
4150 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004151 */
4152 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01004153mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004154{
Bram Moolenaar95da1362020-05-30 18:37:55 +02004155 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004156}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004157
4158/*
4159 * Check what "name" is:
4160 * NODE_NORMAL: file or directory (or doesn't exist)
4161 * NODE_WRITABLE: writable device, socket, fifo, etc.
4162 * NODE_OTHER: non-writable things
4163 */
4164 int
4165mch_nodetype(char_u *name)
4166{
4167 HANDLE hFile;
4168 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004169 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004170
Bram Moolenaar0f873732019-12-05 20:28:46 +01004171 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
4172 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
4173 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00004174 if (STRNCMP(name, "\\\\.\\", 4) == 0)
4175 return NODE_WRITABLE;
4176
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004177 wn = enc_to_utf16(name, NULL);
4178 if (wn == NULL)
4179 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004180
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004181 hFile = CreateFileW(wn, // file name
4182 GENERIC_WRITE, // access mode
4183 0, // share mode
4184 NULL, // security descriptor
4185 OPEN_EXISTING, // creation disposition
4186 0, // file attributes
4187 NULL); // handle to template file
4188 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004189 if (hFile == INVALID_HANDLE_VALUE)
4190 return NODE_NORMAL;
4191
4192 type = GetFileType(hFile);
4193 CloseHandle(hFile);
4194 if (type == FILE_TYPE_CHAR)
4195 return NODE_WRITABLE;
4196 if (type == FILE_TYPE_DISK)
4197 return NODE_NORMAL;
4198 return NODE_OTHER;
4199}
4200
4201#ifdef HAVE_ACL
4202struct my_acl
4203{
4204 PSECURITY_DESCRIPTOR pSecurityDescriptor;
4205 PSID pSidOwner;
4206 PSID pSidGroup;
4207 PACL pDacl;
4208 PACL pSacl;
4209};
4210#endif
4211
4212/*
4213 * Return a pointer to the ACL of file "fname" in allocated memory.
4214 * Return NULL if the ACL is not available for whatever reason.
4215 */
4216 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004217mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004218{
4219#ifndef HAVE_ACL
4220 return (vim_acl_T)NULL;
4221#else
4222 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02004223 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004224
Bram Moolenaarc799fe22019-05-28 23:08:19 +02004225 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004226 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004227 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004228 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02004229
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004230 wn = enc_to_utf16(fname, NULL);
4231 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004232 {
4233 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004234 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004235 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004236
4237 // Try to retrieve the entire security descriptor.
4238 err = GetNamedSecurityInfoW(
4239 wn, // Abstract filename
4240 SE_FILE_OBJECT, // File Object
4241 OWNER_SECURITY_INFORMATION |
4242 GROUP_SECURITY_INFORMATION |
4243 DACL_SECURITY_INFORMATION |
4244 SACL_SECURITY_INFORMATION,
4245 &p->pSidOwner, // Ownership information.
4246 &p->pSidGroup, // Group membership.
4247 &p->pDacl, // Discretionary information.
4248 &p->pSacl, // For auditing purposes.
4249 &p->pSecurityDescriptor);
4250 if (err == ERROR_ACCESS_DENIED ||
4251 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004252 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004253 // Retrieve only DACL.
4254 (void)GetNamedSecurityInfoW(
4255 wn,
4256 SE_FILE_OBJECT,
4257 DACL_SECURITY_INFORMATION,
4258 NULL,
4259 NULL,
4260 &p->pDacl,
4261 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004262 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004263 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004264 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004265 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004266 mch_free_acl((vim_acl_T)p);
4267 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004268 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004269 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004270 }
4271
4272 return (vim_acl_T)p;
4273#endif
4274}
4275
Bram Moolenaar27515922013-06-29 15:36:26 +02004276#ifdef HAVE_ACL
4277/*
4278 * Check if "acl" contains inherited ACE.
4279 */
4280 static BOOL
4281is_acl_inherited(PACL acl)
4282{
4283 DWORD i;
4284 ACL_SIZE_INFORMATION acl_info;
4285 PACCESS_ALLOWED_ACE ace;
4286
4287 acl_info.AceCount = 0;
4288 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
4289 for (i = 0; i < acl_info.AceCount; i++)
4290 {
4291 GetAce(acl, i, (LPVOID *)&ace);
4292 if (ace->Header.AceFlags & INHERITED_ACE)
4293 return TRUE;
4294 }
4295 return FALSE;
4296}
4297#endif
4298
Bram Moolenaar071d4272004-06-13 20:20:40 +00004299/*
4300 * Set the ACL of file "fname" to "acl" (unless it's NULL).
4301 * Errors are ignored.
4302 * This must only be called with "acl" equal to what mch_get_acl() returned.
4303 */
4304 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004305mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004306{
4307#ifdef HAVE_ACL
4308 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02004309 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004310 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004311
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004312 if (p == NULL)
4313 return;
4314
4315 wn = enc_to_utf16(fname, NULL);
4316 if (wn == NULL)
4317 return;
4318
4319 // Set security flags
4320 if (p->pSidOwner)
4321 sec_info |= OWNER_SECURITY_INFORMATION;
4322 if (p->pSidGroup)
4323 sec_info |= GROUP_SECURITY_INFORMATION;
4324 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02004325 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004326 sec_info |= DACL_SECURITY_INFORMATION;
4327 // Do not inherit its parent's DACL.
4328 // If the DACL is inherited, Cygwin permissions would be changed.
4329 if (!is_acl_inherited(p->pDacl))
4330 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02004331 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004332 if (p->pSacl)
4333 sec_info |= SACL_SECURITY_INFORMATION;
4334
4335 (void)SetNamedSecurityInfoW(
4336 wn, // Abstract filename
4337 SE_FILE_OBJECT, // File Object
4338 sec_info,
4339 p->pSidOwner, // Ownership information.
4340 p->pSidGroup, // Group membership.
4341 p->pDacl, // Discretionary information.
4342 p->pSacl // For auditing purposes.
4343 );
4344 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004345#endif
4346}
4347
4348 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004349mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004350{
4351#ifdef HAVE_ACL
4352 struct my_acl *p = (struct my_acl *)acl;
4353
4354 if (p != NULL)
4355 {
4356 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
4357 vim_free(p);
4358 }
4359#endif
4360}
4361
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004362#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004363
4364/*
4365 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
4366 */
4367 static BOOL WINAPI
4368handler_routine(
4369 DWORD dwCtrlType)
4370{
Bram Moolenaar589b1102017-08-12 16:39:05 +02004371 INPUT_RECORD ir;
4372 DWORD out;
4373
Bram Moolenaar071d4272004-06-13 20:20:40 +00004374 switch (dwCtrlType)
4375 {
4376 case CTRL_C_EVENT:
4377 if (ctrl_c_interrupts)
4378 g_fCtrlCPressed = TRUE;
4379 return TRUE;
4380
4381 case CTRL_BREAK_EVENT:
4382 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02004383 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004384 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02004385 ir.EventType = KEY_EVENT;
4386 ir.Event.KeyEvent.bKeyDown = TRUE;
4387 ir.Event.KeyEvent.wRepeatCount = 1;
4388 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
4389 ir.Event.KeyEvent.wVirtualScanCode = 0;
4390 ir.Event.KeyEvent.dwControlKeyState = 0;
4391 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
4392 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004393 return TRUE;
4394
Bram Moolenaar0f873732019-12-05 20:28:46 +01004395 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00004396 case CTRL_CLOSE_EVENT:
4397 case CTRL_LOGOFF_EVENT:
4398 case CTRL_SHUTDOWN_EVENT:
4399 windgoto((int)Rows - 1, 0);
4400 g_fForceExit = TRUE;
4401
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004402 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004403 (dwCtrlType == CTRL_CLOSE_EVENT
4404 ? _("close")
4405 : dwCtrlType == CTRL_LOGOFF_EVENT
4406 ? _("logoff")
4407 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004408# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00004409 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004410# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004411
Bram Moolenaar0f873732019-12-05 20:28:46 +01004412 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00004413
Bram Moolenaar0f873732019-12-05 20:28:46 +01004414 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00004415
4416 default:
4417 return FALSE;
4418 }
4419}
4420
4421
4422/*
4423 * set the tty in (raw) ? "raw" : "cooked" mode
4424 */
4425 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02004426mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004427{
4428 DWORD cmodein;
4429 DWORD cmodeout;
4430 BOOL bEnableHandler;
4431
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004432# ifdef VIMDLL
4433 if (gui.in_use)
4434 return;
4435# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004436 GetConsoleMode(g_hConIn, &cmodein);
4437 GetConsoleMode(g_hConOut, &cmodeout);
4438 if (tmode == TMODE_RAW)
4439 {
4440 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4441 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004442 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004443 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004444 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004445 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
4446 }
4447 else
4448 {
4449 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
4450 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004451 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004452# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01004453 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
4454 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004455 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004456# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004457 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004458# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004459 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004460 bEnableHandler = TRUE;
4461 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004462 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00004463 {
4464 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4465 ENABLE_ECHO_INPUT);
4466 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
4467 bEnableHandler = FALSE;
4468 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004469 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004470 SetConsoleMode(g_hConOut, cmodeout);
4471 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
4472
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004473# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004474 if (fdDump)
4475 {
4476 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
4477 tmode == TMODE_RAW ? "raw" :
4478 tmode == TMODE_COOK ? "cooked" : "normal",
4479 cmodein, cmodeout);
4480 fflush(fdDump);
4481 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004482# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004483}
4484
4485
4486/*
4487 * Get the size of the current window in `Rows' and `Columns'
4488 * Return OK when size could be determined, FAIL otherwise.
4489 */
4490 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004491mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004492{
4493 CONSOLE_SCREEN_BUFFER_INFO csbi;
4494
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004495# ifdef VIMDLL
4496 if (gui.in_use)
4497 return OK;
4498# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004499 if (!g_fTermcapMode && g_cbTermcap.IsValid)
4500 {
4501 /*
4502 * For some reason, we are trying to get the screen dimensions
4503 * even though we are not in termcap mode. The 'Rows' and 'Columns'
4504 * variables are really intended to mean the size of Vim screen
4505 * while in termcap mode.
4506 */
4507 Rows = g_cbTermcap.Info.dwSize.Y;
4508 Columns = g_cbTermcap.Info.dwSize.X;
4509 }
4510 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4511 {
4512 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4513 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4514 }
4515 else
4516 {
4517 Rows = 25;
4518 Columns = 80;
4519 }
4520 return OK;
4521}
4522
4523/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004524 * Resize console buffer to 'COORD'
4525 */
4526 static void
4527ResizeConBuf(
4528 HANDLE hConsole,
4529 COORD coordScreen)
4530{
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00004531 if (use_alternate_screen_buffer)
4532 return;
4533
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004534 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4535 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004536# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004537 if (fdDump)
4538 {
4539 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4540 GetLastError());
4541 fflush(fdDump);
4542 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004543# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004544 }
4545}
4546
4547/*
4548 * Resize console window size to 'srWindowRect'
4549 */
4550 static void
4551ResizeWindow(
4552 HANDLE hConsole,
4553 SMALL_RECT srWindowRect)
4554{
4555 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4556 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004557# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004558 if (fdDump)
4559 {
4560 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4561 GetLastError());
4562 fflush(fdDump);
4563 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004564# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004565 }
4566}
4567
4568/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004569 * Set a console window to `xSize' * `ySize'
4570 */
4571 static void
4572ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004573 HANDLE hConsole,
4574 int xSize,
4575 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004576{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004577 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
4578 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004579 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004580 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004581 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004582
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004583# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004584 if (fdDump)
4585 {
4586 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4587 fflush(fdDump);
4588 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004589# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004590
Bram Moolenaar0f873732019-12-05 20:28:46 +01004591 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00004592 coordScreen = GetLargestConsoleWindowSize(hConsole);
4593
Bram Moolenaar0f873732019-12-05 20:28:46 +01004594 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00004595 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4596 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4597 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4598
4599 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4600 {
4601 int sx, sy;
4602
4603 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4604 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4605 if (sy < ySize || sx < xSize)
4606 {
4607 /*
4608 * Increasing number of lines/columns, do buffer first.
4609 * Use the maximal size in x and y direction.
4610 */
4611 if (sy < ySize)
4612 coordScreen.Y = ySize;
4613 else
4614 coordScreen.Y = sy;
4615 if (sx < xSize)
4616 coordScreen.X = xSize;
4617 else
4618 coordScreen.X = sx;
4619 SetConsoleScreenBufferSize(hConsole, coordScreen);
4620 }
4621 }
4622
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004623 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004624 coordScreen.X = xSize;
4625 coordScreen.Y = ySize;
4626
Bram Moolenaar2551c032018-08-23 22:38:31 +02004627 // In the new console call API, only the first time in reverse order
4628 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004629 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004630 ResizeWindow(hConsole, srWindowRect);
4631 ResizeConBuf(hConsole, coordScreen);
4632 }
4633 else
4634 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004635 // Workaround for a Windows 10 bug
4636 cursor.X = srWindowRect.Left;
4637 cursor.Y = srWindowRect.Top;
4638 SetConsoleCursorPosition(hConsole, cursor);
4639
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004640 ResizeConBuf(hConsole, coordScreen);
4641 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004642 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004643 }
4644}
4645
4646
4647/*
4648 * Set the console window to `Rows' * `Columns'
4649 */
4650 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004651mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004652{
4653 COORD coordScreen;
4654
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004655# ifdef VIMDLL
4656 if (gui.in_use)
4657 return;
4658# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004659 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004660 if (suppress_winsize != 0)
4661 {
4662 suppress_winsize = 2;
4663 return;
4664 }
4665
4666 if (term_console)
4667 {
4668 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4669
Bram Moolenaar0f873732019-12-05 20:28:46 +01004670 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004671 if (Rows > coordScreen.Y)
4672 Rows = coordScreen.Y;
4673 if (Columns > coordScreen.X)
4674 Columns = coordScreen.X;
4675
4676 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4677 }
4678}
4679
4680/*
4681 * Rows and/or Columns has changed.
4682 */
4683 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004684mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004685{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004686# ifdef VIMDLL
4687 if (gui.in_use)
4688 return;
4689# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004690 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4691}
4692
4693
4694/*
4695 * Called when started up, to set the winsize that was delayed.
4696 */
4697 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004698mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004699{
4700 if (suppress_winsize == 2)
4701 {
4702 suppress_winsize = 0;
4703 mch_set_shellsize();
4704 shell_resized();
4705 }
4706 suppress_winsize = 0;
4707}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004708#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004709
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004710 static BOOL
4711vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004712 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004713 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004714 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004715 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004716 PROCESS_INFORMATION *pi,
4717 LPVOID *env,
4718 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004719{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004720 BOOL ret = FALSE;
4721 WCHAR *wcmd, *wcwd = NULL;
4722
4723 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4724 if (wcmd == NULL)
4725 return FALSE;
4726 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004727 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004728 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4729 if (wcwd == NULL)
4730 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004731 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004732
4733 ret = CreateProcessW(
4734 NULL, // Executable name
4735 wcmd, // Command to execute
4736 NULL, // Process security attributes
4737 NULL, // Thread security attributes
4738 inherit_handles, // Inherit handles
4739 flags, // Creation flags
4740 env, // Environment
4741 wcwd, // Current directory
4742 (LPSTARTUPINFOW)si, // Startup information
4743 pi); // Process information
4744theend:
4745 vim_free(wcmd);
4746 vim_free(wcwd);
4747 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004748}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004749
4750
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004751 static HINSTANCE
4752vim_shell_execute(
4753 char *cmd,
4754 INT n_show_cmd)
4755{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004756 HINSTANCE ret;
4757 WCHAR *wcmd;
4758
4759 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4760 if (wcmd == NULL)
4761 return (HINSTANCE) 0;
4762
4763 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4764 vim_free(wcmd);
4765 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004766}
4767
4768
Bram Moolenaar4f974752019-02-17 17:44:42 +01004769#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004770
4771/*
4772 * Specialised version of system() for Win32 GUI mode.
4773 * This version proceeds as follows:
4774 * 1. Create a console window for use by the subprocess
4775 * 2. Run the subprocess (it gets the allocated console by default)
4776 * 3. Wait for the subprocess to terminate and get its exit code
4777 * 4. Prompt the user to press a key to close the console window
4778 */
4779 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004780mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004781{
4782 STARTUPINFO si;
4783 PROCESS_INFORMATION pi;
4784 DWORD ret = 0;
4785 HWND hwnd = GetFocus();
4786
4787 si.cb = sizeof(si);
4788 si.lpReserved = NULL;
4789 si.lpDesktop = NULL;
4790 si.lpTitle = NULL;
4791 si.dwFlags = STARTF_USESHOWWINDOW;
4792 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004793 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004794 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004795 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004796 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004797 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004798 else
4799 si.wShowWindow = SW_SHOWNORMAL;
4800 si.cbReserved2 = 0;
4801 si.lpReserved2 = NULL;
4802
Bram Moolenaar0f873732019-12-05 20:28:46 +01004803 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004804 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004805 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4806 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004807
Bram Moolenaar0f873732019-12-05 20:28:46 +01004808 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004809 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004810# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004811 int delay = 1;
4812
Bram Moolenaar0f873732019-12-05 20:28:46 +01004813 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004814 for (;;)
4815 {
4816 MSG msg;
4817
K.Takatab7057bd2022-01-21 11:37:07 +00004818 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004819 {
4820 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004821 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004822 delay = 1;
4823 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004824 }
4825 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4826 break;
4827
Bram Moolenaar0f873732019-12-05 20:28:46 +01004828 // We start waiting for a very short time and then increase it, so
4829 // that we respond quickly when the process is quick, and don't
4830 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004831 if (delay < 50)
4832 delay += 10;
4833 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004834# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004835 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004836# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004837
Bram Moolenaar0f873732019-12-05 20:28:46 +01004838 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004839 GetExitCodeProcess(pi.hProcess, &ret);
4840 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004841
Bram Moolenaar0f873732019-12-05 20:28:46 +01004842 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004843 CloseHandle(pi.hThread);
4844 CloseHandle(pi.hProcess);
4845
Bram Moolenaar0f873732019-12-05 20:28:46 +01004846 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004847 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4848
4849 return ret;
4850}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004851
4852/*
4853 * Thread launched by the gui to send the current buffer data to the
4854 * process. This way avoid to hang up vim totally if the children
4855 * process take a long time to process the lines.
4856 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004857 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004858sub_process_writer(LPVOID param)
4859{
4860 HANDLE g_hChildStd_IN_Wr = param;
4861 linenr_T lnum = curbuf->b_op_start.lnum;
4862 DWORD len = 0;
4863 DWORD l;
4864 char_u *lp = ml_get(lnum);
4865 char_u *s;
4866 int written = 0;
4867
4868 for (;;)
4869 {
4870 l = (DWORD)STRLEN(lp + written);
4871 if (l == 0)
4872 len = 0;
4873 else if (lp[written] == NL)
4874 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004875 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004876 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4877 }
4878 else
4879 {
4880 s = vim_strchr(lp + written, NL);
4881 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4882 s == NULL ? l : (DWORD)(s - (lp + written)),
4883 &len, NULL);
4884 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004885 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004886 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004887 // Finished a line, add a NL, unless this line should not have
4888 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004889 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004890 || (!curbuf->b_p_bin
4891 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004892 || (lnum != curbuf->b_no_eol_lnum
4893 && (lnum != curbuf->b_ml.ml_line_count
4894 || curbuf->b_p_eol)))
4895 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004896 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4897 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004898 }
4899
4900 ++lnum;
4901 if (lnum > curbuf->b_op_end.lnum)
4902 break;
4903
4904 lp = ml_get(lnum);
4905 written = 0;
4906 }
4907 else if (len > 0)
4908 written += len;
4909 }
4910
Bram Moolenaar0f873732019-12-05 20:28:46 +01004911 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004912 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004913 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004914}
4915
4916
Bram Moolenaar0f873732019-12-05 20:28:46 +01004917# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004918
4919/*
4920 * This function read from the children's stdout and write the
4921 * data on screen or in the buffer accordingly.
4922 */
4923 static void
4924dump_pipe(int options,
4925 HANDLE g_hChildStd_OUT_Rd,
4926 garray_T *ga,
4927 char_u buffer[],
4928 DWORD *buffer_off)
4929{
4930 DWORD availableBytes = 0;
4931 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004932 int ret;
4933 DWORD len;
4934 DWORD toRead;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004935
Bram Moolenaar0f873732019-12-05 20:28:46 +01004936 // we query the pipe to see if there is any data to read
4937 // to avoid to perform a blocking read
4938 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4939 NULL, // optional buffer
4940 0, // buffer size
4941 NULL, // number of read bytes
4942 &availableBytes, // available bytes total
4943 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004944
Bram Moolenaar0f873732019-12-05 20:28:46 +01004945 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004946 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004947 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01004948 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004949 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004950 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004951
Bram Moolenaar0f873732019-12-05 20:28:46 +01004952 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004953 if (len == 0)
4954 break;
4955
4956 availableBytes -= len;
4957
4958 if (options & SHELL_READ)
4959 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004960 // Do NUL -> NL translation, append NL separated
4961 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004962 for (i = 0; i < len; ++i)
4963 {
4964 if (buffer[i] == NL)
4965 append_ga_line(ga);
4966 else if (buffer[i] == NUL)
4967 ga_append(ga, NL);
4968 else
4969 ga_append(ga, buffer[i]);
4970 }
4971 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004972 else if (has_mbyte)
4973 {
4974 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004975 int c;
4976 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004977
4978 len += *buffer_off;
4979 buffer[len] = NUL;
4980
Bram Moolenaar0f873732019-12-05 20:28:46 +01004981 // Check if the last character in buffer[] is
4982 // incomplete, keep these bytes for the next
4983 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004984 for (p = buffer; p < buffer + len; p += l)
4985 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004986 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004987 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004988 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004989 else if (MB_BYTE2LEN(*p) != l)
4990 break;
4991 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004992 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004993 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004994 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004995 if (len >= 12)
4996 ++p;
4997 else
4998 {
4999 *buffer_off = len;
5000 return;
5001 }
5002 }
5003 c = *p;
5004 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01005005 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005006 if (p < buffer + len)
5007 {
5008 *p = c;
5009 *buffer_off = (DWORD)((buffer + len) - p);
5010 mch_memmove(buffer, p, *buffer_off);
5011 return;
5012 }
5013 *buffer_off = 0;
5014 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005015 else
5016 {
5017 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01005018 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005019 }
5020
5021 windgoto(msg_row, msg_col);
5022 cursor_on();
5023 out_flush();
5024 }
5025}
5026
5027/*
5028 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
5029 * for communication and doesn't open any new window.
5030 */
5031 static int
5032mch_system_piped(char *cmd, int options)
5033{
5034 STARTUPINFO si;
5035 PROCESS_INFORMATION pi;
5036 DWORD ret = 0;
5037
5038 HANDLE g_hChildStd_IN_Rd = NULL;
5039 HANDLE g_hChildStd_IN_Wr = NULL;
5040 HANDLE g_hChildStd_OUT_Rd = NULL;
5041 HANDLE g_hChildStd_OUT_Wr = NULL;
5042
Bram Moolenaar0f873732019-12-05 20:28:46 +01005043 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005044 DWORD len;
5045
Bram Moolenaar0f873732019-12-05 20:28:46 +01005046 // buffer used to receive keys
5047 char_u ta_buf[BUFLEN + 1]; // TypeAHead
5048 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005049
5050 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005051 int noread_cnt = 0;
5052 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005053 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005054 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005055 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005056
5057 SECURITY_ATTRIBUTES saAttr;
5058
Bram Moolenaar0f873732019-12-05 20:28:46 +01005059 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005060 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5061 saAttr.bInheritHandle = TRUE;
5062 saAttr.lpSecurityDescriptor = NULL;
5063
5064 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005065 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005066 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005067 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005068 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005069 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005070 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005071 {
5072 CloseHandle(g_hChildStd_IN_Rd);
5073 CloseHandle(g_hChildStd_IN_Wr);
5074 CloseHandle(g_hChildStd_OUT_Rd);
5075 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01005076 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005077 }
5078
5079 si.cb = sizeof(si);
5080 si.lpReserved = NULL;
5081 si.lpDesktop = NULL;
5082 si.lpTitle = NULL;
5083 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
5084
Bram Moolenaar0f873732019-12-05 20:28:46 +01005085 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005086 si.hStdError = g_hChildStd_OUT_Wr;
5087 si.hStdOutput = g_hChildStd_OUT_Wr;
5088 si.hStdInput = g_hChildStd_IN_Rd;
5089 si.wShowWindow = SW_HIDE;
5090 si.cbReserved2 = 0;
5091 si.lpReserved2 = NULL;
5092
5093 if (options & SHELL_READ)
5094 ga_init2(&ga, 1, BUFLEN);
5095
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005096 if (cmd != NULL)
5097 {
5098 p = (char *)vim_strsave((char_u *)cmd);
5099 if (p != NULL)
5100 unescape_shellxquote((char_u *)p, p_sxe);
5101 else
5102 p = cmd;
5103 }
5104
Bram Moolenaar0f873732019-12-05 20:28:46 +01005105 // Now, run the command.
5106 // About "Inherit handles" being TRUE: this command can be litigious,
5107 // handle inheritance was deactivated for pending temp file, but, if we
5108 // deactivate it, the pipes don't work for some reason.
Yegappan Lakshmanane89aef32025-05-14 20:31:55 +02005109 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
5110 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005111
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005112 if (p != cmd)
5113 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005114
Bram Moolenaar0f873732019-12-05 20:28:46 +01005115 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005116 CloseHandle(g_hChildStd_IN_Rd);
5117 CloseHandle(g_hChildStd_OUT_Wr);
5118
5119 if (options & SHELL_WRITE)
5120 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02005121 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005122 _beginthreadex(NULL, // security attributes
5123 0, // default stack size
5124 sub_process_writer, // function to be executed
5125 g_hChildStd_IN_Wr, // parameter
5126 0, // creation flag, start immediately
5127 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005128 CloseHandle(thread);
5129 g_hChildStd_IN_Wr = NULL;
5130 }
5131
Bram Moolenaar0f873732019-12-05 20:28:46 +01005132 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005133 for (;;)
5134 {
5135 MSG msg;
5136
K.Takatab7057bd2022-01-21 11:37:07 +00005137 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005138 {
5139 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00005140 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005141 }
5142
Bram Moolenaar0f873732019-12-05 20:28:46 +01005143 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005144 if ((options & (SHELL_READ|SHELL_WRITE))
5145# ifdef FEAT_GUI
5146 || gui.in_use
5147# endif
5148 )
5149 {
5150 len = 0;
GuyBrush52ecc762024-02-21 20:16:38 +01005151 if (((options &
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005152 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
5153 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
5154# ifdef FEAT_GUI
5155 || gui.in_use
5156# endif
5157 )
5158 && (ta_len > 0 || noread_cnt > 4))
5159 {
5160 if (ta_len == 0)
5161 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005162 // Get extra characters when we don't have any. Reset the
5163 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005164 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005165 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
5166 }
5167 if (ta_len > 0 || len > 0)
5168 {
5169 /*
5170 * For pipes: Check for CTRL-C: send interrupt signal to
GuyBrush1f13fcc2024-01-14 20:08:40 +01005171 * child.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005172 */
5173 if (len == 1 && cmd != NULL)
5174 {
5175 if (ta_buf[ta_len] == Ctrl_C)
5176 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005177 // Learn what exit code is expected, for
5178 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005179 TerminateProcess(pi.hProcess, 9);
5180 }
GuyBrush1f13fcc2024-01-14 20:08:40 +01005181 }
5182
5183 /*
5184 * Check for CTRL-D: EOF, close pipe to child.
5185 * Ctrl_D may be decorated by _OnChar()
5186 */
5187 if ((len == 1 || len == 4 ) && cmd != NULL)
5188 {
5189 if (ta_buf[0] == Ctrl_D
5190 || (ta_buf[0] == CSI
5191 && ta_buf[1] == KS_MODIFIER
5192 && ta_buf[3] == Ctrl_D))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005193 {
5194 CloseHandle(g_hChildStd_IN_Wr);
5195 g_hChildStd_IN_Wr = NULL;
GuyBrush1f13fcc2024-01-14 20:08:40 +01005196 len = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005197 }
5198 }
5199
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01005200 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005201
5202 /*
5203 * For pipes: echo the typed characters. For a pty this
5204 * does not seem to work.
5205 */
5206 for (i = ta_len; i < ta_len + len; ++i)
5207 {
5208 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
5209 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005210 else if (has_mbyte)
5211 {
5212 int l = (*mb_ptr2len)(ta_buf + i);
5213
5214 msg_outtrans_len(ta_buf + i, l);
5215 i += l - 1;
5216 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005217 else
5218 msg_outtrans_len(ta_buf + i, 1);
5219 }
5220 windgoto(msg_row, msg_col);
5221 out_flush();
5222
5223 ta_len += len;
5224
5225 /*
5226 * Write the characters to the child, unless EOF has been
5227 * typed for pipes. Write one character at a time, to
5228 * avoid losing too much typeahead. When writing buffer
5229 * lines, drop the typed characters (only check for
5230 * CTRL-C).
5231 */
5232 if (options & SHELL_WRITE)
5233 ta_len = 0;
5234 else if (g_hChildStd_IN_Wr != NULL)
5235 {
5236 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
5237 1, &len, NULL);
5238 // if we are typing in, we want to keep things reactive
5239 delay = 1;
5240 if (len > 0)
5241 {
5242 ta_len -= len;
5243 mch_memmove(ta_buf, ta_buf + len, ta_len);
5244 }
5245 }
5246 }
5247 }
5248 }
5249
5250 if (ta_len)
5251 ui_inchar_undo(ta_buf, ta_len);
5252
5253 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
5254 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005255 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005256 break;
5257 }
5258
5259 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005260 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005261
Bram Moolenaar0f873732019-12-05 20:28:46 +01005262 // We start waiting for a very short time and then increase it, so
5263 // that we respond quickly when the process is quick, and don't
5264 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005265 if (delay < 50)
5266 delay += 10;
5267 }
5268
Bram Moolenaar0f873732019-12-05 20:28:46 +01005269 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005270 CloseHandle(g_hChildStd_OUT_Rd);
5271 if (g_hChildStd_IN_Wr != NULL)
5272 CloseHandle(g_hChildStd_IN_Wr);
5273
5274 WaitForSingleObject(pi.hProcess, INFINITE);
5275
Bram Moolenaar0f873732019-12-05 20:28:46 +01005276 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005277 GetExitCodeProcess(pi.hProcess, &ret);
5278
5279 if (options & SHELL_READ)
5280 {
5281 if (ga.ga_len > 0)
5282 {
5283 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01005284 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005285 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
5286 }
5287 else
5288 curbuf->b_no_eol_lnum = 0;
5289 ga_clear(&ga);
5290 }
5291
Bram Moolenaar0f873732019-12-05 20:28:46 +01005292 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005293 CloseHandle(pi.hThread);
5294 CloseHandle(pi.hProcess);
5295
5296 return ret;
5297}
5298
5299 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005300mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005301{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005302 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005303 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005304 return mch_system_piped(cmd, options);
5305 else
5306 return mch_system_classic(cmd, options);
5307}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005308#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005309
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005310#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005311 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02005312mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005313{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005314 int ret;
5315 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005316 char_u *buf;
5317 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005318
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005319 // If the command starts and ends with double quotes, enclose the command
5320 // in parentheses.
5321 len = STRLEN(cmd);
5322 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
5323 {
5324 len += 3;
5325 buf = alloc(len);
5326 if (buf == NULL)
5327 return -1;
5328 vim_snprintf((char *)buf, len, "(%s)", cmd);
5329 wcmd = enc_to_utf16(buf, NULL);
5330 free(buf);
5331 }
5332 else
5333 wcmd = enc_to_utf16((char_u *)cmd, NULL);
5334
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005335 if (wcmd == NULL)
5336 return -1;
5337
5338 ret = _wsystem(wcmd);
5339 vim_free(wcmd);
5340 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005341}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005342
5343#endif
5344
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005345 static int
5346mch_system(char *cmd, int options)
5347{
5348#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005349 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005350 return mch_system_g(cmd, options);
5351 else
5352 return mch_system_c(cmd, options);
5353#elif defined(FEAT_GUI_MSWIN)
5354 return mch_system_g(cmd, options);
5355#else
5356 return mch_system_c(cmd, options);
5357#endif
5358}
5359
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005360#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
5361/*
5362 * Use a terminal window to run a shell command in.
5363 */
5364 static int
5365mch_call_shell_terminal(
5366 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005367 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005368{
5369 jobopt_T opt;
5370 char_u *newcmd = NULL;
5371 typval_T argvar[2];
5372 long_u cmdlen;
5373 int retval = -1;
5374 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005375 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005376 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005377 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005378
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005379 if (cmd == NULL)
5380 cmdlen = STRLEN(p_sh) + 1;
5381 else
5382 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005383 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005384 if (newcmd == NULL)
5385 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005386 if (cmd == NULL)
5387 {
5388 STRCPY(newcmd, p_sh);
5389 ch_log(NULL, "starting terminal to run a shell");
5390 }
5391 else
5392 {
5393 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
5394 ch_log(NULL, "starting terminal for system command '%s'", cmd);
5395 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005396
5397 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005398
5399 argvar[0].v_type = VAR_STRING;
5400 argvar[0].vval.v_string = newcmd;
5401 argvar[1].v_type = VAR_UNKNOWN;
5402 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005403 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01005404 {
5405 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005406 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01005407 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005408
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005409 job = term_getjob(buf->b_term);
5410 ++job->jv_refcount;
5411
Bram Moolenaar0f873732019-12-05 20:28:46 +01005412 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005413 aucmd_prepbuf(&aco, buf);
Bram Moolenaare76062c2022-11-28 18:51:43 +00005414 if (curbuf == buf)
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005415 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005416 // Only do this when a window was found for "buf".
5417 clear_oparg(&oa);
5418 while (term_use_loop())
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005419 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005420 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
5421 {
5422 // If terminal_loop() returns OK we got a key that is handled
5423 // in Normal model. We don't do redrawing anyway.
5424 if (terminal_loop(TRUE) == OK)
5425 normal_cmd(&oa, TRUE);
5426 }
5427 else
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005428 normal_cmd(&oa, TRUE);
5429 }
Bram Moolenaare76062c2022-11-28 18:51:43 +00005430 retval = job->jv_exitval;
5431 ch_log(NULL, "system command finished");
5432
5433 job_unref(job);
5434
5435 // restore curwin/curbuf and a few other things
5436 aucmd_restbuf(&aco);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005437 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005438
5439 wait_return(TRUE);
5440 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
5441
5442 vim_free(newcmd);
5443 return retval;
5444}
5445#endif
5446
Bram Moolenaar071d4272004-06-13 20:20:40 +00005447/*
5448 * Either execute a command by calling the shell or start a new shell
5449 */
5450 int
5451mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005452 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005453 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00005454{
5455 int x = 0;
5456 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005457 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02005458
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00005459#ifdef FEAT_EVAL
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01005460 ch_log(NULL, "executing shell command: %s", cmd);
5461#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01005462 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02005463 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005464 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005465 if (cmd == NULL)
5466 wcscat(szShellTitle, L" :sh");
5467 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005468 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005469 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005470
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005471 if (wn != NULL)
5472 {
5473 wcscat(szShellTitle, L" - !");
5474 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02005475 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005476 wcscat(szShellTitle, wn);
5477 SetConsoleTitleW(szShellTitle);
5478 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005479 }
5480 }
5481 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005482
5483 out_flush();
5484
5485#ifdef MCH_WRITE_DUMP
5486 if (fdDump)
5487 {
5488 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
5489 fflush(fdDump);
5490 }
5491#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005492#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005493 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005494 if (
5495# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005496 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005497# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005498 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005499 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
5500 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005501 char_u *cmdbase = cmd;
5502
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02005503 if (cmdbase != NULL)
5504 // Skip a leading quote and (.
5505 while (*cmdbase == '"' || *cmdbase == '(')
5506 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005507
5508 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01005509 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
5510 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005511 {
5512 // Use a terminal window to run the command in.
5513 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005514 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005515 return x;
5516 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005517 }
5518#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005519
5520 /*
5521 * Catch all deadly signals while running the external command, because a
5522 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5523 */
ichizok378447f2023-05-11 22:25:42 +01005524 mch_signal(SIGINT, SIG_IGN);
ichizok378447f2023-05-11 22:25:42 +01005525 mch_signal(SIGBREAK, SIG_IGN);
ichizok378447f2023-05-11 22:25:42 +01005526 mch_signal(SIGILL, SIG_IGN);
5527 mch_signal(SIGFPE, SIG_IGN);
5528 mch_signal(SIGSEGV, SIG_IGN);
5529 mch_signal(SIGTERM, SIG_IGN);
5530 mch_signal(SIGABRT, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005531
5532 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005533 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00005534
5535 if (cmd == NULL)
5536 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005537 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005538 }
5539 else
5540 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005541 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005542 char_u *newcmd = NULL;
5543 char_u *cmdbase = cmd;
5544 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005545
Bram Moolenaar0f873732019-12-05 20:28:46 +01005546 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005547 if (*cmdbase == '"' )
5548 ++cmdbase;
5549 if (*cmdbase == '(')
5550 ++cmdbase;
5551
Bram Moolenaar1c465442017-03-12 20:10:05 +01005552 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005553 {
5554 STARTUPINFO si;
5555 PROCESS_INFORMATION pi;
5556 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005557 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005558 char_u *p;
5559
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005560 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005561 si.cb = sizeof(si);
5562 si.lpReserved = NULL;
5563 si.lpDesktop = NULL;
5564 si.lpTitle = NULL;
5565 si.dwFlags = 0;
5566 si.cbReserved2 = 0;
5567 si.lpReserved2 = NULL;
5568
5569 cmdbase = skipwhite(cmdbase + 5);
5570 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005571 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005572 {
5573 cmdbase = skipwhite(cmdbase + 4);
5574 si.dwFlags = STARTF_USESHOWWINDOW;
5575 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005576 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005577 }
5578 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005579 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005580 {
5581 cmdbase = skipwhite(cmdbase + 2);
5582 flags = CREATE_NO_WINDOW;
5583 si.dwFlags = STARTF_USESTDHANDLES;
5584 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005585 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005586 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005587 NULL, // Security att.
5588 OPEN_EXISTING, // Open flags
5589 FILE_ATTRIBUTE_NORMAL, // File att.
5590 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005591 si.hStdOutput = si.hStdInput;
5592 si.hStdError = si.hStdInput;
5593 }
5594
Bram Moolenaar0f873732019-12-05 20:28:46 +01005595 // Remove a trailing ", ) and )" if they have a match
5596 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005597 if (cmdbase > cmd)
5598 {
5599 p = cmdbase + STRLEN(cmdbase);
5600 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5601 *--p = NUL;
5602 if (p > cmdbase && p[-1] == ')'
5603 && (*cmd =='(' || cmd[1] == '('))
5604 *--p = NUL;
5605 }
5606
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005607 newcmd = cmdbase;
5608 unescape_shellxquote(cmdbase, p_sxe);
5609
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005610 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005611 * If creating new console, arguments are passed to the
5612 * 'cmd.exe' as-is. If it's not, arguments are not treated
5613 * correctly for current 'cmd.exe'. So unescape characters in
5614 * shellxescape except '|' for avoiding to be treated as
5615 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005616 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005617 if (flags != CREATE_NEW_CONSOLE)
5618 {
5619 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005620 char_u *cmd_shell = mch_getenv("COMSPEC");
5621
5622 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005623 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005624
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005625 subcmd = vim_strsave_escaped_ext(cmdbase,
5626 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005627 if (subcmd != NULL)
5628 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005629 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005630 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005631 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005632 if (newcmd != NULL)
5633 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005634 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005635 else
5636 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005637 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005638 }
5639 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005640
5641 /*
5642 * Now, start the command as a process, so that it doesn't
5643 * inherit our handles which causes unpleasant dangling swap
5644 * files if we exit before the spawned process
5645 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005646 if (vim_create_process((char *)newcmd, FALSE, flags,
5647 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005648 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005649 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5650 > (HINSTANCE)32)
5651 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005652 else
5653 {
5654 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005655#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005656# ifdef VIMDLL
5657 if (gui.in_use)
5658# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005659 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005660#endif
5661 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005662
5663 if (newcmd != cmdbase)
5664 vim_free(newcmd);
5665
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005666 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005667 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005668 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005669 CloseHandle(si.hStdInput);
5670 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005671 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005672 CloseHandle(pi.hThread);
5673 CloseHandle(pi.hProcess);
5674 }
5675 else
5676 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005677 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005678#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005679 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005680 (!s_dont_use_vimrun && p_stmp ?
5681 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5682 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005683#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005684 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005685
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005686 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005687 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005688 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005689#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005690 if (
5691# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005692 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005693# endif
5694 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005695 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005696 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5697 "External commands will not pause after completion.\n"
5698 "See :help win32-vimrun for more information.");
5699 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005700 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5701 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005702
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005703 if (wmsg != NULL && wtitle != NULL)
5704 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5705 vim_free(wmsg);
5706 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005707 need_vimrun_warning = FALSE;
5708 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005709 if (
5710# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005711 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005712# endif
5713 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005714 // Use vimrun to execute the command. It opens a console
5715 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005716 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005717 vimrun_path,
5718 (msg_silent != 0 || (options & SHELL_DOOUT))
5719 ? "-s " : "",
5720 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005721 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005722# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005723 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005724# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005725 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005726 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005727 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5728 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005729 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005730#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005731 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005732 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005733 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005734 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005735 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005736 }
5737 }
5738
5739 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005740 {
5741 // The shell may have messed with the mode, always set it.
5742 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005743 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005744 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005745
Bram Moolenaar0f873732019-12-05 20:28:46 +01005746 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005747 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005748#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005749 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005750 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005751#endif
5752 )
5753 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005754 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005755 msg_putchar('\n');
5756 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005757 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005758
ichizok378447f2023-05-11 22:25:42 +01005759 mch_signal(SIGINT, SIG_DFL);
ichizok378447f2023-05-11 22:25:42 +01005760 mch_signal(SIGBREAK, SIG_DFL);
ichizok378447f2023-05-11 22:25:42 +01005761 mch_signal(SIGILL, SIG_DFL);
5762 mch_signal(SIGFPE, SIG_DFL);
5763 mch_signal(SIGSEGV, SIG_DFL);
5764 mch_signal(SIGTERM, SIG_DFL);
5765 mch_signal(SIGABRT, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005766
5767 return x;
5768}
5769
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005770#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005771 static HANDLE
5772job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005773 char_u *fname,
5774 DWORD dwDesiredAccess,
5775 DWORD dwShareMode,
5776 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5777 DWORD dwCreationDisposition,
5778 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005779{
5780 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005781 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005782
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005783 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005784 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005785 return INVALID_HANDLE_VALUE;
5786
5787 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5788 lpSecurityAttributes, dwCreationDisposition,
5789 dwFlagsAndAttributes, NULL);
5790 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005791 return h;
5792}
5793
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005794/*
5795 * Turn the dictionary "env" into a NUL separated list that can be used as the
5796 * environment argument of vim_create_process().
5797 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005798 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005799win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005800{
5801 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005802 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005803 LPVOID base = GetEnvironmentStringsW();
5804
Bram Moolenaar0f873732019-12-05 20:28:46 +01005805 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005806 if (ga_grow(gap, 1) == FAIL)
5807 return;
5808
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005809 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005810 {
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00005811 FOR_ALL_HASHTAB_ITEMS(&env->dv_hashtab, hi, todo)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005812 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005813 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005814 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005815 typval_T *item = &dict_lookup(hi)->di_tv;
5816 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005817 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005818 --todo;
5819 if (wkey != NULL && wval != NULL)
5820 {
5821 size_t n;
5822 size_t lkey = wcslen(wkey);
5823 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005824
Yegappan Lakshmananfadc02a2023-01-27 21:03:12 +00005825 if (ga_grow(gap, (int)(lkey + lval + 2)) == FAIL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005826 continue;
5827 for (n = 0; n < lkey; n++)
5828 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5829 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5830 for (n = 0; n < lval; n++)
5831 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5832 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5833 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005834 vim_free(wkey);
5835 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005836 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005837 }
5838 }
5839
Bram Moolenaar355757a2020-02-10 22:06:32 +01005840 if (base)
5841 {
5842 WCHAR *p = (WCHAR*) base;
5843
5844 // for last \0
5845 if (ga_grow(gap, 1) == FAIL)
5846 return;
5847
5848 while (*p != 0 || *(p + 1) != 0)
5849 {
5850 if (ga_grow(gap, 1) == OK)
5851 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5852 p++;
5853 }
Ken Takataad29f6a2023-09-16 13:56:02 +02005854 FreeEnvironmentStringsW(base);
Bram Moolenaar355757a2020-02-10 22:06:32 +01005855 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5856 }
5857
Bram Moolenaar493359e2018-06-12 20:25:52 +02005858# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005859 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005860# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005861 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005862 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005863# endif
5864# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005865 char_u *version = get_vim_var_str(VV_VERSION);
5866 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005867# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005868 // size of "VIM_SERVERNAME=" and value,
5869 // plus "VIM_TERMINAL=" and value,
5870 // plus two terminating NULs
5871 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005872# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005873 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005874# endif
5875# ifdef FEAT_TERMINAL
5876 + 13 + version_len + 2
5877# endif
5878 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005879
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005880 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005881 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005882# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005883 for (n = 0; n < 15; n++)
5884 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5885 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005886 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005887 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5888 (WCHAR)servername[n];
5889 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005890# endif
5891# ifdef FEAT_TERMINAL
5892 if (is_terminal)
5893 {
5894 for (n = 0; n < 13; n++)
5895 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5896 (WCHAR)"VIM_TERMINAL="[n];
5897 for (n = 0; n < version_len; n++)
5898 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5899 (WCHAR)version[n];
5900 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5901 }
5902# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005903 }
5904 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005905# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005906}
5907
Bram Moolenaarb091f302019-01-19 14:37:00 +01005908/*
5909 * Create a pair of pipes.
5910 * Return TRUE for success, FALSE for failure.
5911 */
5912 static BOOL
5913create_pipe_pair(HANDLE handles[2])
5914{
5915 static LONG s;
5916 char name[64];
5917 SECURITY_ATTRIBUTES sa;
5918
5919 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5920 GetCurrentProcessId(),
5921 InterlockedIncrement(&s));
5922
5923 // Create named pipe. Max size of named pipe is 65535.
5924 handles[1] = CreateNamedPipe(
5925 name,
5926 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5927 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005928 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005929
5930 if (handles[1] == INVALID_HANDLE_VALUE)
5931 return FALSE;
5932
5933 sa.nLength = sizeof(sa);
5934 sa.bInheritHandle = TRUE;
5935 sa.lpSecurityDescriptor = NULL;
5936
5937 handles[0] = CreateFile(name,
5938 FILE_GENERIC_READ,
5939 FILE_SHARE_READ, &sa,
5940 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5941
5942 if (handles[0] == INVALID_HANDLE_VALUE)
5943 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005944 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005945 return FALSE;
5946 }
5947
5948 return TRUE;
5949}
5950
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005951 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005952mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005953{
5954 STARTUPINFO si;
5955 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005956 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005957 SECURITY_ATTRIBUTES saAttr;
5958 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005959 HANDLE ifd[2];
5960 HANDLE ofd[2];
5961 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005962 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005963
5964 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5965 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5966 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5967 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5968 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5969 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5970 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5971
5972 if (use_out_for_err && use_null_for_out)
5973 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005974
5975 ifd[0] = INVALID_HANDLE_VALUE;
5976 ifd[1] = INVALID_HANDLE_VALUE;
5977 ofd[0] = INVALID_HANDLE_VALUE;
5978 ofd[1] = INVALID_HANDLE_VALUE;
5979 efd[0] = INVALID_HANDLE_VALUE;
5980 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005981 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005982
Bram Moolenaar14207f42016-10-27 21:13:10 +02005983 jo = CreateJobObject(NULL, NULL);
5984 if (jo == NULL)
5985 {
5986 job->jv_status = JOB_FAILED;
5987 goto failed;
5988 }
5989
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005990 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005991 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005992
Bram Moolenaar76467df2016-02-12 19:30:26 +01005993 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005994 ZeroMemory(&si, sizeof(si));
5995 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005996 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005997 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005998
Bram Moolenaard8070362016-02-15 21:56:54 +01005999 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
6000 saAttr.bInheritHandle = TRUE;
6001 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006002
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006003 if (use_file_for_in)
6004 {
6005 char_u *fname = options->jo_io_name[PART_IN];
6006
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01006007 ifd[0] = job_io_file_open(fname, GENERIC_READ,
6008 FILE_SHARE_READ | FILE_SHARE_WRITE,
6009 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
6010 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01006011 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006012 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01006013 goto failed;
6014 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006015 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01006016 else if (!use_null_for_in
6017 && (!create_pipe_pair(ifd)
6018 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006019 goto failed;
6020
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006021 if (use_file_for_out)
6022 {
6023 char_u *fname = options->jo_io_name[PART_OUT];
6024
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01006025 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
6026 FILE_SHARE_READ | FILE_SHARE_WRITE,
6027 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
6028 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006029 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006030 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006031 goto failed;
6032 }
6033 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006034 else if (!use_null_for_out &&
6035 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006036 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006037 goto failed;
6038
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006039 if (use_file_for_err)
6040 {
6041 char_u *fname = options->jo_io_name[PART_ERR];
6042
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01006043 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
6044 FILE_SHARE_READ | FILE_SHARE_WRITE,
6045 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
6046 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006047 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006048 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006049 goto failed;
6050 }
6051 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006052 else if (!use_out_for_err && !use_null_for_err &&
6053 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006054 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01006055 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006056
Bram Moolenaard8070362016-02-15 21:56:54 +01006057 si.dwFlags |= STARTF_USESTDHANDLES;
6058 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006059 si.hStdOutput = ofd[1];
6060 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
6061
6062 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
6063 {
Bram Moolenaarde279892016-03-11 22:19:44 +01006064 if (options->jo_set & JO_CHANNEL)
6065 {
6066 channel = options->jo_channel;
6067 if (channel != NULL)
6068 ++channel->ch_refcount;
6069 }
6070 else
6071 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006072 if (channel == NULL)
6073 goto failed;
6074 }
Bram Moolenaard8070362016-02-15 21:56:54 +01006075
6076 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02006077 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006078 CREATE_DEFAULT_ERROR_MODE |
6079 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006080 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01006081 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006082 &si, &pi,
6083 ga.ga_data,
6084 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01006085 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02006086 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006087 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006088 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006089 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006090
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006091 ga_clear(&ga);
6092
Bram Moolenaar14207f42016-10-27 21:13:10 +02006093 if (!AssignProcessToJobObject(jo, pi.hProcess))
6094 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006095 // if failing, switch the way to terminate
6096 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02006097 CloseHandle(jo);
6098 jo = NULL;
6099 }
6100 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01006101 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006102 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02006103 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006104 job->jv_status = JOB_STARTED;
6105
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02006106 CloseHandle(ifd[0]);
6107 CloseHandle(ofd[1]);
6108 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01006109 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01006110
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006111 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006112 if (channel != NULL)
6113 {
6114 channel_set_pipes(channel,
6115 use_file_for_in || use_null_for_in
6116 ? INVALID_FD : (sock_T)ifd[1],
6117 use_file_for_out || use_null_for_out
6118 ? INVALID_FD : (sock_T)ofd[0],
6119 use_out_for_err || use_file_for_err || use_null_for_err
6120 ? INVALID_FD : (sock_T)efd[0]);
6121 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006122 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006123 return;
6124
6125failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01006126 CloseHandle(ifd[0]);
6127 CloseHandle(ofd[0]);
6128 CloseHandle(efd[0]);
6129 CloseHandle(ifd[1]);
6130 CloseHandle(ofd[1]);
6131 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01006132 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006133 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006134}
6135
6136 char *
6137mch_job_status(job_T *job)
6138{
6139 DWORD dwExitCode = 0;
6140
Bram Moolenaar76467df2016-02-12 19:30:26 +01006141 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
6142 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006143 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01006144 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01006145 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02006146 {
6147 ch_log(job->jv_channel, "Job ended");
6148 job->jv_status = JOB_ENDED;
6149 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006150 return "dead";
6151 }
6152 return "run";
6153}
6154
Bram Moolenaar97792de2016-10-15 18:36:49 +02006155 job_T *
6156mch_detect_ended_job(job_T *job_list)
6157{
6158 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
6159 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
6160 job_T *job = job_list;
6161
6162 while (job != NULL)
6163 {
6164 DWORD n;
6165 DWORD result;
6166
6167 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
6168 && job != NULL; job = job->jv_next)
6169 {
6170 if (job->jv_status == JOB_STARTED)
6171 {
6172 jobHandles[n] = job->jv_proc_info.hProcess;
6173 jobArray[n] = job;
6174 ++n;
6175 }
6176 }
6177 if (n == 0)
6178 continue;
6179 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
6180 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
6181 {
6182 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
6183
6184 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
6185 return wait_job;
6186 }
6187 }
6188 return NULL;
6189}
6190
Bram Moolenaarfb630902016-10-29 14:55:00 +02006191 static BOOL
6192terminate_all(HANDLE process, int code)
6193{
6194 PROCESSENTRY32 pe;
6195 HANDLE h = INVALID_HANDLE_VALUE;
6196 DWORD pid = GetProcessId(process);
6197
6198 if (pid != 0)
6199 {
6200 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
6201 if (h != INVALID_HANDLE_VALUE)
6202 {
6203 pe.dwSize = sizeof(PROCESSENTRY32);
6204 if (!Process32First(h, &pe))
6205 goto theend;
6206
6207 do
6208 {
6209 if (pe.th32ParentProcessID == pid)
6210 {
6211 HANDLE ph = OpenProcess(
6212 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
6213 if (ph != NULL)
6214 {
6215 terminate_all(ph, code);
6216 CloseHandle(ph);
6217 }
6218 }
6219 } while (Process32Next(h, &pe));
6220
6221 CloseHandle(h);
6222 }
6223 }
6224
6225theend:
6226 return TerminateProcess(process, code);
6227}
6228
6229/*
6230 * Send a (deadly) signal to "job".
6231 * Return FAIL if it didn't work.
6232 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006233 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02006234mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006235{
Bram Moolenaar923d9262016-02-25 20:56:01 +01006236 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006237
Bram Moolenaar923d9262016-02-25 20:56:01 +01006238 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01006239 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006240 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02006241 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006242 {
6243 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
6244 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00006245 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006246 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01006247 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006248 }
6249
6250 if (!AttachConsole(job->jv_proc_info.dwProcessId))
6251 return FAIL;
6252 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01006253 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
6254 job->jv_proc_info.dwProcessId)
6255 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006256 FreeConsole();
6257 return ret;
6258}
6259
6260/*
6261 * Clear the data related to "job".
6262 */
6263 void
6264mch_clear_job(job_T *job)
6265{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00006266 if (job->jv_status == JOB_FAILED)
6267 return;
6268
6269 if (job->jv_job_object != NULL)
6270 CloseHandle(job->jv_job_object);
6271 CloseHandle(job->jv_proc_info.hProcess);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006272}
6273#endif
6274
Bram Moolenaar071d4272004-06-13 20:20:40 +00006275
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006276#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006277
6278/*
6279 * Start termcap mode
6280 */
6281 static void
6282termcap_mode_start(void)
6283{
6284 DWORD cmodein;
6285
6286 if (g_fTermcapMode)
6287 return;
6288
6289 SaveConsoleBuffer(&g_cbNonTermcap);
6290
6291 if (g_cbTermcap.IsValid)
6292 {
6293 /*
6294 * We've been in termcap mode before. Restore certain screen
6295 * characteristics, including the buffer size and the window
6296 * size. Since we will be redrawing the screen, we don't need
6297 * to restore the actual contents of the buffer.
6298 */
6299 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006300 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006301 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
6302 Rows = g_cbTermcap.Info.dwSize.Y;
6303 Columns = g_cbTermcap.Info.dwSize.X;
6304 }
6305 else
6306 {
6307 /*
6308 * This is our first time entering termcap mode. Clear the console
6309 * screen buffer, and resize the buffer to match the current window
6310 * size. We will use this as the size of our editing environment.
6311 */
6312 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006313 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006314 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
6315 }
6316
Bram Moolenaar071d4272004-06-13 20:20:40 +00006317 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006318
6319 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006320 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006321 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006322 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006323 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
6324 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006325 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006326 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006327 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006328 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6329 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006330 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006331 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006332
6333 redraw_later_clear();
6334 g_fTermcapMode = TRUE;
6335}
6336
6337
6338/*
6339 * End termcap mode
6340 */
6341 static void
6342termcap_mode_end(void)
6343{
6344 DWORD cmodein;
6345 ConsoleBuffer *cb;
6346 COORD coord;
6347 DWORD dwDummy;
6348
6349 if (!g_fTermcapMode)
6350 return;
6351
6352 SaveConsoleBuffer(&g_cbTermcap);
6353
6354 GetConsoleMode(g_hConIn, &cmodein);
6355 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006356 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6357 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006358
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006359# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01006360 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006361# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006362 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006363# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006364 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01006365 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006366
William Breslerded59132024-10-08 21:30:48 +02006367 // Switch back to main screen buffer.
6368 if (exiting && use_alternate_screen_buffer)
Naruhiko Nishinoc2a90002025-05-04 20:05:47 +02006369 vtp_printf("\033[?1049l");
William Breslerded59132024-10-08 21:30:48 +02006370
Christopher Plewright1140b512022-11-12 18:46:05 +00006371 if (!USE_WT && (p_rs || exiting))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006372 {
6373 /*
6374 * Clear anything that happens to be on the current line.
6375 */
6376 coord.X = 0;
6377 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006378 FillConsoleOutputCharacter(g_hConOut, ' ',
6379 cb->Info.dwSize.X, coord, &dwDummy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006380 /*
6381 * The following is just for aesthetics. If we are exiting without
6382 * restoring the screen, then we want to have a prompt string
6383 * appear at the bottom line. However, the command interpreter
6384 * seems to always advance the cursor one line before displaying
6385 * the prompt string, which causes the screen to scroll. To
6386 * counter this, move the cursor up one line before exiting.
6387 */
6388 if (exiting && !p_rs)
6389 coord.Y--;
6390 /*
6391 * Position the cursor at the leftmost column of the desired row.
6392 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006393 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006394 }
Christopher Plewright1140b512022-11-12 18:46:05 +00006395 SetConsoleCursorInfo(g_hConOut, &g_cci);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006396 g_fTermcapMode = FALSE;
6397}
Christopher Plewright38804d62022-11-09 23:55:52 +00006398#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006399
6400
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006401#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006402 void
6403mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01006404 char_u *s UNUSED,
6405 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006406{
Bram Moolenaar0f873732019-12-05 20:28:46 +01006407 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00006408}
6409
6410#else
6411
6412/*
6413 * clear `n' chars, starting from `coord'
6414 */
6415 static void
6416clear_chars(
6417 COORD coord,
6418 DWORD n)
6419{
Christopher Plewright38804d62022-11-09 23:55:52 +00006420 if (!vtp_working)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006421 {
6422 DWORD dwDummy;
6423
6424 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
6425 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
6426 &dwDummy);
6427 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006428 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02006429 {
6430 set_console_color_rgb();
6431 gotoxy(coord.X + 1, coord.Y + 1);
6432 vtp_printf("\033[%dX", n);
6433 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006434}
6435
6436
6437/*
6438 * Clear the screen
6439 */
6440 static void
6441clear_screen(void)
6442{
6443 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006444
Christopher Plewright38804d62022-11-09 23:55:52 +00006445 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006446 clear_chars(g_coord, Rows * Columns);
6447 else
6448 {
6449 set_console_color_rgb();
6450 gotoxy(1, 1);
6451 vtp_printf("\033[2J");
6452 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006453}
6454
6455
6456/*
6457 * Clear to end of display
6458 */
6459 static void
6460clear_to_end_of_display(void)
6461{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006462 COORD save = g_coord;
6463
Christopher Plewright38804d62022-11-09 23:55:52 +00006464 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006465 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006466 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006467 else
6468 {
6469 set_console_color_rgb();
6470 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6471 vtp_printf("\033[0J");
6472
6473 gotoxy(save.X + 1, save.Y + 1);
6474 g_coord = save;
6475 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006476}
6477
6478
6479/*
6480 * Clear to end of line
6481 */
6482 static void
6483clear_to_end_of_line(void)
6484{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006485 COORD save = g_coord;
6486
Christopher Plewright38804d62022-11-09 23:55:52 +00006487 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006488 clear_chars(g_coord, Columns - g_coord.X);
6489 else
6490 {
6491 set_console_color_rgb();
6492 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6493 vtp_printf("\033[0K");
6494
6495 gotoxy(save.X + 1, save.Y + 1);
6496 g_coord = save;
6497 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006498}
6499
6500
6501/*
6502 * Scroll the scroll region up by `cLines' lines
6503 */
6504 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006505scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006506{
6507 COORD oldcoord = g_coord;
6508
6509 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6510 delete_lines(cLines);
6511
6512 g_coord = oldcoord;
6513}
6514
6515
6516/*
6517 * Set the scroll region
6518 */
6519 static void
6520set_scroll_region(
6521 unsigned left,
6522 unsigned top,
6523 unsigned right,
6524 unsigned bottom)
6525{
6526 if (left >= right
6527 || top >= bottom
6528 || right > (unsigned) Columns - 1
6529 || bottom > (unsigned) Rows - 1)
6530 return;
6531
6532 g_srScrollRegion.Left = left;
6533 g_srScrollRegion.Top = top;
6534 g_srScrollRegion.Right = right;
6535 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006536}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006537
Bram Moolenaar6982f422019-02-16 16:48:01 +01006538 static void
6539set_scroll_region_tb(
6540 unsigned top,
6541 unsigned bottom)
6542{
6543 if (top >= bottom || bottom > (unsigned)Rows - 1)
6544 return;
6545
6546 g_srScrollRegion.Top = top;
6547 g_srScrollRegion.Bottom = bottom;
6548}
6549
6550 static void
6551set_scroll_region_lr(
6552 unsigned left,
6553 unsigned right)
6554{
6555 if (left >= right || right > (unsigned)Columns - 1)
6556 return;
6557
6558 g_srScrollRegion.Left = left;
6559 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006560}
6561
6562
6563/*
6564 * Insert `cLines' lines at the current cursor position
6565 */
6566 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006567insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006568{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006569 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006570 COORD dest;
6571 CHAR_INFO fill;
6572
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006573 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6574
Bram Moolenaar6982f422019-02-16 16:48:01 +01006575 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006576 dest.Y = g_coord.Y + cLines;
6577
Bram Moolenaar6982f422019-02-16 16:48:01 +01006578 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006579 source.Top = g_coord.Y;
6580 source.Right = g_srScrollRegion.Right;
6581 source.Bottom = g_srScrollRegion.Bottom - cLines;
6582
Bram Moolenaar6982f422019-02-16 16:48:01 +01006583 clip.Left = g_srScrollRegion.Left;
6584 clip.Top = g_coord.Y;
6585 clip.Right = g_srScrollRegion.Right;
6586 clip.Bottom = g_srScrollRegion.Bottom;
6587
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006588 fill.Char.AsciiChar = ' ';
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006589 if (!USE_VTP)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006590 fill.Attributes = g_attrCurrent;
6591 else
6592 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006593
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006594 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006595
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006596 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6597
Bram Moolenaar6982f422019-02-16 16:48:01 +01006598 // Here we have to deal with a win32 console flake: If the scroll
6599 // region looks like abc and we scroll c to a and fill with d we get
6600 // cbd... if we scroll block c one line at a time to a, we get cdd...
6601 // vim expects cdd consistently... So we have to deal with that
6602 // here... (this also occurs scrolling the same way in the other
6603 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006604
6605 if (source.Bottom < dest.Y)
6606 {
6607 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006608 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006609
Bram Moolenaar6982f422019-02-16 16:48:01 +01006610 coord.X = source.Left;
6611 for (i = clip.Top; i < dest.Y; ++i)
6612 {
6613 coord.Y = i;
6614 clear_chars(coord, source.Right - source.Left + 1);
6615 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006616 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006617
Christopher Plewright38804d62022-11-09 23:55:52 +00006618 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006619 {
6620 COORD coord;
6621 int i;
6622
6623 coord.X = source.Left;
6624 for (i = source.Top; i < dest.Y; ++i)
6625 {
6626 coord.Y = i;
6627 clear_chars(coord, source.Right - source.Left + 1);
6628 }
6629 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006630}
6631
6632
6633/*
6634 * Delete `cLines' lines at the current cursor position
6635 */
6636 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006637delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006638{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006639 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006640 COORD dest;
6641 CHAR_INFO fill;
6642 int nb;
6643
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006644 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6645
Bram Moolenaar6982f422019-02-16 16:48:01 +01006646 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006647 dest.Y = g_coord.Y;
6648
Bram Moolenaar6982f422019-02-16 16:48:01 +01006649 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006650 source.Top = g_coord.Y + cLines;
6651 source.Right = g_srScrollRegion.Right;
6652 source.Bottom = g_srScrollRegion.Bottom;
6653
Bram Moolenaar6982f422019-02-16 16:48:01 +01006654 clip.Left = g_srScrollRegion.Left;
6655 clip.Top = g_coord.Y;
6656 clip.Right = g_srScrollRegion.Right;
6657 clip.Bottom = g_srScrollRegion.Bottom;
6658
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006659 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006660 if (!vtp_working)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006661 fill.Attributes = g_attrCurrent;
6662 else
6663 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006664
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006665 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006666
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006667 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6668
Bram Moolenaar6982f422019-02-16 16:48:01 +01006669 // Here we have to deal with a win32 console flake; See insert_lines()
6670 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006671
6672 nb = dest.Y + (source.Bottom - source.Top) + 1;
6673
6674 if (nb < source.Top)
6675 {
6676 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006677 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006678
Bram Moolenaar6982f422019-02-16 16:48:01 +01006679 coord.X = source.Left;
6680 for (i = nb; i < clip.Bottom; ++i)
6681 {
6682 coord.Y = i;
6683 clear_chars(coord, source.Right - source.Left + 1);
6684 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006685 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006686
Christopher Plewright38804d62022-11-09 23:55:52 +00006687 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006688 {
6689 COORD coord;
6690 int i;
6691
6692 coord.X = source.Left;
6693 for (i = nb; i <= source.Bottom; ++i)
6694 {
6695 coord.Y = i;
6696 clear_chars(coord, source.Right - source.Left + 1);
6697 }
6698 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006699}
6700
6701
6702/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006703 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006704 */
6705 static void
6706gotoxy(
6707 unsigned x,
6708 unsigned y)
6709{
6710 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6711 return;
6712
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006713 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006714 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006715 // There are reports of double-width characters not displayed
6716 // correctly. This workaround should fix it, similar to how it's done
6717 // for VTP.
6718 g_coord.X = 0;
6719 SetConsoleCursorPosition(g_hConOut, g_coord);
6720
Bram Moolenaar2313b612019-09-27 14:14:32 +02006721 // external cursor coords are 1-based; internal are 0-based
6722 g_coord.X = x - 1;
6723 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006724 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006725 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006726 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006727 {
6728 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006729 // destruction. Insider build bug. Always enabled because it's cheap
6730 // and avoids mistakes with recognizing the build.
6731 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006732
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006733 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006734
6735 g_coord.X = x - 1;
6736 g_coord.Y = y - 1;
6737 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006738}
6739
6740
6741/*
6742 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006743 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006744 */
6745 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006746textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006747{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006748 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006749
6750 SetConsoleTextAttribute(g_hConOut, wAttr);
6751}
6752
6753
6754 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006755textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006756{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006757 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006758
Christopher Plewright38804d62022-11-09 23:55:52 +00006759 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006760 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6761 else
6762 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006763}
6764
6765
6766 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006767textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006768{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006769 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006770
Christopher Plewright38804d62022-11-09 23:55:52 +00006771 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006772 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6773 else
6774 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006775}
6776
6777
6778/*
6779 * restore the default text attribute (whatever we started with)
6780 */
6781 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006782normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006783{
Christopher Plewright38804d62022-11-09 23:55:52 +00006784 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006785 textattr(g_attrDefault);
6786 else
6787 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006788}
6789
6790
6791static WORD g_attrPreStandout = 0;
6792
6793/*
6794 * Make the text standout, by brightening it
6795 */
6796 static void
6797standout(void)
6798{
6799 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006800
Bram Moolenaar071d4272004-06-13 20:20:40 +00006801 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6802}
6803
6804
6805/*
6806 * Turn off standout mode
6807 */
6808 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006809standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006810{
6811 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006812 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006813
6814 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006815}
6816
6817
6818/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006819 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006820 */
6821 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006822mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006823{
6824 char_u *p;
6825 int n;
6826
6827 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6828 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006829 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006830# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006831 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006832# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006833 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006834 {
6835 p = T_ME + 2;
6836 n = getdigits(&p);
6837 if (*p == 'm' && n > 0)
6838 {
6839 cterm_normal_fg_color = (n & 0xf) + 1;
6840 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6841 }
6842 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006843# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006844 cterm_normal_fg_gui_color = INVALCOLOR;
6845 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006846# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006847}
6848
6849
6850/*
6851 * visual bell: flash the screen
6852 */
6853 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006854visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006855{
6856 COORD coordOrigin = {0, 0};
6857 WORD attrFlash = ~g_attrCurrent & 0xff;
6858
6859 DWORD dwDummy;
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006860 LPWORD oldattrs = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006861
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006862# ifdef FEAT_TERMGUICOLORS
6863 if (!(p_tgc || t_colors >= 256))
6864# endif
6865 {
6866 oldattrs = ALLOC_MULT(WORD, Rows * Columns);
6867 if (oldattrs == NULL)
6868 return;
6869 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006870 coordOrigin, &dwDummy);
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006871 }
6872
Bram Moolenaar071d4272004-06-13 20:20:40 +00006873 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6874 coordOrigin, &dwDummy);
6875
Bram Moolenaar0f873732019-12-05 20:28:46 +01006876 Sleep(15); // wait for 15 msec
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006877
6878 if (oldattrs != NULL)
6879 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006880 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006881 coordOrigin, &dwDummy);
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006882 vim_free(oldattrs);
6883 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006884}
6885
6886
6887/*
6888 * Make the cursor visible or invisible
6889 */
6890 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006891cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006892{
6893 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006894
Christopher Plewright38804d62022-11-09 23:55:52 +00006895 if (vtp_working)
Bram Moolenaar2695de62020-04-17 21:13:01 +02006896 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6897
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006898# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006899 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006900# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006901}
6902
6903
6904/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006905 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006906 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006907 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006908 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006909write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006910 char_u *pchBuf,
6911 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006912{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006913 COORD coord = g_coord;
6914 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006915 DWORD n, cchwritten;
6916 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006917 static WCHAR *unicodebuf = NULL;
6918 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006919 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006920 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006921 static WCHAR *utf8spbuf = NULL;
6922 static int utf8splength;
6923 static DWORD utf8spcells;
6924 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006925
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006926 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006927 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006928 utf8usingbuf = &unicodebuf;
6929 do
6930 {
6931 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6932 unicodebuf, unibuflen);
6933 if (length && length <= unibuflen)
6934 break;
6935 vim_free(unicodebuf);
6936 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6937 unibuflen = unibuflen ? 0 : length;
Bram Moolenaarc9471b12023-05-09 15:00:00 +01006938 } while (TRUE);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006939 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006940 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006941 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6942 {
6943 if (utf8usingbuf != &utf8spbuf)
6944 {
6945 if (utf8spbuf == NULL)
6946 {
6947 cells = mb_string2cells((char_u *)" ", 1);
6948 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6949 utf8spbuf = LALLOC_MULT(WCHAR, length);
6950 if (utf8spbuf != NULL)
6951 {
6952 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6953 utf8usingbuf = &utf8spbuf;
6954 utf8splength = length;
6955 utf8spcells = cells;
6956 }
6957 }
6958 else
6959 {
6960 utf8usingbuf = &utf8spbuf;
6961 length = utf8splength;
6962 cells = utf8spcells;
6963 }
6964 }
6965 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006966
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006967 if (!USE_VTP)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006968 {
6969 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6970 coord, &written);
6971 // When writing fails or didn't write a single character, pretend one
6972 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006973 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006974 coord, &cchwritten) == 0
6975 || cchwritten == 0 || cchwritten == (DWORD)-1)
6976 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006977 }
6978 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006979 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006980 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006981 NULL) == 0 || cchwritten == 0)
6982 cchwritten = 1;
6983 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006984
K.Takata135e1522022-01-29 15:27:58 +00006985 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006986 {
6987 written = cbToWrite;
6988 g_coord.X += (SHORT)cells;
6989 }
6990 else
6991 {
6992 char_u *p = pchBuf;
6993 for (n = 0; n < cchwritten; n++)
6994 MB_CPTR_ADV(p);
6995 written = p - pchBuf;
6996 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006997 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006998
6999 while (g_coord.X > g_srScrollRegion.Right)
7000 {
7001 g_coord.X -= (SHORT) Columns;
7002 if (g_coord.Y < g_srScrollRegion.Bottom)
7003 g_coord.Y++;
7004 }
7005
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007006 // Cursor under VTP is always in the correct position, no need to reset.
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00007007 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007008 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007009
7010 return written;
7011}
7012
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007013 static char_u *
7014get_seq(
7015 int *args,
7016 int *count,
7017 char_u *head)
7018{
7019 int argc;
7020 char_u *p;
7021
7022 if (head == NULL || *head != '\033')
7023 return NULL;
7024
7025 argc = 0;
7026 p = head;
7027 ++p;
7028 do
7029 {
7030 ++p;
7031 args[argc] = getdigits(&p);
7032 argc += (argc < 15) ? 1 : 0;
7033 } while (*p == ';');
7034 *count = argc;
7035
7036 return p;
7037}
7038
7039 static char_u *
7040get_sgr(
7041 int *args,
7042 int *count,
7043 char_u *head)
7044{
7045 char_u *p = get_seq(args, count, head);
7046
7047 return (p && *p == 'm') ? ++p : NULL;
7048}
7049
7050/*
7051 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
7052 */
7053 static char_u *
7054sgrn2(
7055 char_u *head,
7056 int n)
7057{
7058 int argc;
7059 int args[16];
7060 char_u *p = get_sgr(args, &argc, head);
7061
7062 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
7063}
7064
7065/*
7066 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
7067 */
7068 static char_u *
7069sgrnc(
7070 char_u *head,
7071 int n)
7072{
7073 int argc;
7074 int args[16];
7075 char_u *p = get_sgr(args, &argc, head);
7076
7077 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
7078 ? p : NULL;
7079}
7080
7081 static char_u *
7082skipblank(char_u *q)
7083{
7084 char_u *p = q;
7085
7086 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
7087 ++p;
7088 return p;
7089}
7090
7091/*
7092 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
7093 * NULL.
7094 */
7095 static char_u *
7096sgrn2c(
7097 char_u *head,
7098 int n)
7099{
7100 char_u *p = sgrn2(head, n);
7101
7102 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
7103}
7104
7105/*
7106 * If there is only a newline between the sequence immediately following it,
7107 * a pointer to the character following the newline is returned.
7108 * Otherwise NULL.
7109 */
7110 static char_u *
7111sgrn2cn(
7112 char_u *head,
7113 int n)
7114{
7115 char_u *p = sgrn2(head, n);
7116
7117 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
7118}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007119
7120/*
7121 * mch_write(): write the output buffer to the screen, translating ESC
7122 * sequences into calls to console output routines.
7123 */
7124 void
7125mch_write(
7126 char_u *s,
7127 int len)
7128{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007129 char_u *end = s + len;
7130
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007131# ifdef VIMDLL
7132 if (gui.in_use)
7133 return;
7134# endif
7135
Bram Moolenaar071d4272004-06-13 20:20:40 +00007136 if (!term_console)
7137 {
7138 write(1, s, (unsigned)len);
7139 return;
7140 }
7141
Bram Moolenaar0f873732019-12-05 20:28:46 +01007142 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00007143 while (len--)
7144 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007145 int prefix = -1;
7146 char_u ch;
7147
7148 // While processing a sequence, on rare occasions it seems that another
7149 // sequence may be inserted asynchronously.
7150 if (len < 0)
7151 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01007152 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007153 return;
7154 }
7155
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007156 while (s + ++prefix < end)
7157 {
7158 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007159 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
7160 && ch != '\a' && ch != '\033'))
7161 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007162 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007163
7164 if (p_wd)
7165 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007166 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007167 if (prefix != 0)
7168 prefix = 1;
7169 }
7170
7171 if (prefix != 0)
7172 {
7173 DWORD nWritten;
7174
7175 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007176# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007177 if (fdDump)
7178 {
7179 fputc('>', fdDump);
7180 fwrite(s, sizeof(char_u), nWritten, fdDump);
7181 fputs("<\n", fdDump);
7182 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007183# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007184 len -= (nWritten - 1);
7185 s += nWritten;
7186 }
7187 else if (s[0] == '\n')
7188 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007189 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00007190 if (g_coord.Y == g_srScrollRegion.Bottom)
7191 {
7192 scroll(1);
7193 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
7194 }
7195 else
7196 {
7197 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
7198 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007199# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007200 if (fdDump)
7201 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007202# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007203 s++;
7204 }
7205 else if (s[0] == '\r')
7206 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007207 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00007208 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007209# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007210 if (fdDump)
7211 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007212# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007213 s++;
7214 }
7215 else if (s[0] == '\b')
7216 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007217 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00007218 if (g_coord.X > g_srScrollRegion.Left)
7219 g_coord.X--;
7220 else if (g_coord.Y > g_srScrollRegion.Top)
7221 {
7222 g_coord.X = g_srScrollRegion.Right;
7223 g_coord.Y--;
7224 }
7225 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007226# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007227 if (fdDump)
7228 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007229# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007230 s++;
7231 }
7232 else if (s[0] == '\a')
7233 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007234 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00007235 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007236# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007237 if (fdDump)
7238 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007239# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007240 s++;
7241 }
7242 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
7243 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007244# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007245 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007246# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007247 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007248 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007249 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007250
7251 switch (s[2])
7252 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007253 case '0': case '1': case '2': case '3': case '4':
7254 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007255 if (*(p = get_seq(args, &argc, s)) != 'm')
7256 goto notsgr;
7257
7258 p = s;
7259
7260 // Handling frequent optional sequences. Output to the screen
7261 // takes too long, so do not output as much as possible.
7262
7263 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
7264 // resetFG,FG,BG are omitted.
7265 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007266 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007267 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
7268 len = len + 1 - (int)(p - s);
7269 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007270 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007271 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007272
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007273 // If FG,BG,BG,FG of SGR are connected, the first FG can be
7274 // omitted.
7275 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
7276 p = sp;
7277
7278 // If FG,BG,FG,BG of SGR are connected, the first FG can be
7279 // omitted.
7280 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
7281 p = sp;
7282
7283 // If BG,BG of SGR are connected, the first BG can be omitted.
7284 if (sgrn2((sp = sgrn2(p, 48)), 48))
7285 p = sp;
7286
7287 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007288 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007289 if (sgrn2((sp = sgrnc(p, 39)), 38))
7290 p = sp;
7291
7292 p = get_seq(args, &argc, p);
7293
7294notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007295 arg1 = args[0];
7296 arg2 = args[1];
7297 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007298 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007299 if (argc == 1 && args[0] == 0)
7300 normvideo();
7301 else if (argc == 1)
7302 {
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00007303 if (USE_VTP)
Christopher Plewright38804d62022-11-09 23:55:52 +00007304 textcolor((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007305 else
Christopher Plewright38804d62022-11-09 23:55:52 +00007306 textattr((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007307 }
Christopher Plewright38804d62022-11-09 23:55:52 +00007308 else if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007309 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007310 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007311 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007312 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007313 gotoxy(arg2, arg1);
7314 }
7315 else if (argc == 2 && *p == 'r')
7316 {
7317 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
7318 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01007319 else if (argc == 2 && *p == 'R')
7320 {
7321 set_scroll_region_tb(arg1, arg2);
7322 }
7323 else if (argc == 2 && *p == 'V')
7324 {
7325 set_scroll_region_lr(arg1, arg2);
7326 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007327 else if (argc == 1 && *p == 'A')
7328 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007329 gotoxy(g_coord.X + 1,
7330 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
7331 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007332 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007333 {
7334 textbackground((WORD) arg1);
7335 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007336 else if (argc == 1 && *p == 'C')
7337 {
7338 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
7339 g_coord.Y + 1);
7340 }
7341 else if (argc == 1 && *p == 'f')
7342 {
7343 textcolor((WORD) arg1);
7344 }
7345 else if (argc == 1 && *p == 'H')
7346 {
7347 gotoxy(1, arg1);
7348 }
7349 else if (argc == 1 && *p == 'L')
7350 {
7351 insert_lines(arg1);
7352 }
7353 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007354 {
7355 delete_lines(arg1);
7356 }
7357
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007358 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007359 s = p + 1;
7360 break;
7361
Bram Moolenaar071d4272004-06-13 20:20:40 +00007362 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007363 gotoxy(g_coord.X + 1,
7364 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
7365 goto got3;
7366
7367 case 'B':
7368 visual_bell();
7369 goto got3;
7370
7371 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007372 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
7373 g_coord.Y + 1);
7374 goto got3;
7375
7376 case 'E':
7377 termcap_mode_end();
7378 goto got3;
7379
7380 case 'F':
7381 standout();
7382 goto got3;
7383
7384 case 'f':
7385 standend();
7386 goto got3;
7387
7388 case 'H':
7389 gotoxy(1, 1);
7390 goto got3;
7391
7392 case 'j':
7393 clear_to_end_of_display();
7394 goto got3;
7395
7396 case 'J':
7397 clear_screen();
7398 goto got3;
7399
7400 case 'K':
7401 clear_to_end_of_line();
7402 goto got3;
7403
7404 case 'L':
7405 insert_lines(1);
7406 goto got3;
7407
7408 case 'M':
7409 delete_lines(1);
7410 goto got3;
7411
7412 case 'S':
7413 termcap_mode_start();
7414 goto got3;
7415
7416 case 'V':
7417 cursor_visible(TRUE);
7418 goto got3;
7419
7420 case 'v':
7421 cursor_visible(FALSE);
7422 goto got3;
7423
7424 got3:
7425 s += 3;
7426 len -= 2;
7427 }
7428
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007429# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007430 if (fdDump)
7431 {
7432 fputs("ESC | ", fdDump);
7433 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
7434 fputc('\n', fdDump);
7435 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007436# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007437 }
K.Takatadf5320c2022-09-01 13:20:16 +01007438 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
7439 {
7440 int l = 2;
7441
Keith Thompson184f71c2024-01-04 21:19:04 +01007442 if (SAFE_isdigit(s[l]))
K.Takatadf5320c2022-09-01 13:20:16 +01007443 l++;
7444 if (s[l] == ' ' && s[l + 1] == 'q')
7445 {
7446 // DECSCUSR (cursor style) sequences
Christopher Plewright38804d62022-11-09 23:55:52 +00007447 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01007448 vtp_printf("%.*s", l + 2, s); // Pass through
7449 s += l + 2;
7450 len -= l + 1;
7451 }
7452 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007453 else
7454 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007455 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00007456 DWORD nWritten;
7457
7458 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007459# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007460 if (fdDump)
7461 {
7462 fputc('>', fdDump);
7463 fwrite(s, sizeof(char_u), nWritten, fdDump);
7464 fputs("<\n", fdDump);
7465 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007466# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007467
7468 len -= (nWritten - 1);
7469 s += nWritten;
7470 }
7471 }
7472
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007473# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007474 if (fdDump)
7475 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007476# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007477}
7478
Bram Moolenaar0f873732019-12-05 20:28:46 +01007479#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00007480
7481
7482/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01007483 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007484 */
7485 void
7486mch_delay(
7487 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02007488 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007489{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007490#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007491 Sleep((int)msec); // never wait for input
7492#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007493# ifdef VIMDLL
7494 if (gui.in_use)
7495 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007496 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007497 return;
7498 }
7499# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02007500 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007501# ifdef FEAT_MZSCHEME
7502 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
7503 {
7504 int towait = p_mzq;
7505
Bram Moolenaar0f873732019-12-05 20:28:46 +01007506 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007507 while (msec > 0)
7508 {
7509 mzvim_check_threads();
7510 if (msec < towait)
7511 towait = msec;
7512 Sleep(towait);
7513 msec -= towait;
7514 }
7515 }
7516 else
7517# endif
7518 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007519 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007520 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007521#endif
7522}
7523
7524
7525/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01007526 * This version of remove is not scared by a readonly (backup) file.
7527 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007528 * Return 0 for success, -1 for failure.
7529 */
7530 int
7531mch_remove(char_u *name)
7532{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007533 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007534 int n;
7535
Bram Moolenaar203258c2016-01-17 22:15:16 +01007536 /*
7537 * On Windows, deleting a directory's symbolic link is done by
7538 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
7539 */
7540 if (mch_isdir(name) && mch_is_symbolic_link(name))
7541 return mch_rmdir(name);
7542
Bram Moolenaar12b559e2013-06-12 22:41:37 +02007543 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
7544
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007545 wn = enc_to_utf16(name, NULL);
7546 if (wn == NULL)
7547 return -1;
7548
7549 n = DeleteFileW(wn) ? 0 : -1;
7550 vim_free(wn);
7551 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007552}
7553
7554
7555/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007556 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007557 */
7558 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007559mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007560{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007561#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7562# ifdef VIMDLL
7563 if (!gui.in_use)
7564# endif
7565 if (g_fCtrlCPressed || g_fCBrkPressed)
7566 {
7567 ctrl_break_was_pressed = g_fCBrkPressed;
7568 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7569 got_int = TRUE;
7570 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007571#endif
7572}
7573
Bram Moolenaar0f873732019-12-05 20:28:46 +01007574// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007575#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007576
7577/*
7578 * How much main memory in KiB that can be used by VIM.
7579 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007580 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007581mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007582{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007583 MEMORYSTATUSEX ms;
7584
Bram Moolenaar0f873732019-12-05 20:28:46 +01007585 // Need to use GlobalMemoryStatusEx() when there is more memory than
7586 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007587 ms.dwLength = sizeof(MEMORYSTATUSEX);
7588 GlobalMemoryStatusEx(&ms);
7589 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007590 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007591 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007592 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007593 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007594 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007595 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007596 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007597 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007598 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007599 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007600 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007601}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007602
Bram Moolenaar071d4272004-06-13 20:20:40 +00007603/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007604 * mch_wrename() works around a bug in rename (aka MoveFile) in
Nir Lichtman563e8ec2024-09-30 19:42:28 +02007605 * Windows, the bug can be demonstrated with the following scenario:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007606 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
Nir Lichtman563e8ec2024-09-30 19:42:28 +02007607 * "abcdef~1.txt" again.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007608 *
7609 * Like rename(), returns 0 upon success, non-zero upon failure.
7610 * Should probably set errno appropriately when errors occur.
7611 */
7612 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007613mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007614{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007615 WCHAR *p;
7616 int i;
7617 WCHAR szTempFile[_MAX_PATH + 1];
7618 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007619 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007620
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007621 // No need to play tricks unless the file name contains a "~" as the
7622 // seventh character.
7623 p = wold;
7624 for (i = 0; wold[i] != NUL; ++i)
7625 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
7626 && wold[i + 1] != 0)
7627 p = wold + i + 1;
7628 if ((int)(wold + i - p) < 8 || p[6] != '~')
7629 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007630
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007631 // Get base path of new file name. Undocumented feature: If pszNewFile is
7632 // a directory, no error is returned and pszFilePart will be NULL.
7633 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007634 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007635 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007636
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007637 // Get (and create) a unique temporary file name in directory of new file
7638 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007639 return -2;
7640
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007641 // blow the temp file away
7642 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007643 return -3;
7644
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007645 // rename old file to the temp file
7646 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007647 return -4;
7648
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007649 // now create an empty file called pszOldFile; this prevents the operating
7650 // system using pszOldFile as an alias (SFN) if we're renaming within the
7651 // same directory. For example, we're editing a file called
7652 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7653 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7654 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7655 // cause all sorts of problems later in buf_write(). So, we create an
7656 // empty file called filena~1.txt and the system will have to find some
7657 // other SFN for filena~1.txt~, such as filena~2.txt
7658 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007659 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7660 return -5;
7661 if (!CloseHandle(hf))
7662 return -6;
7663
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007664 // rename the temp file to the new file
7665 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007666 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007667 // Renaming failed. Rename the file back to its old name, so that it
7668 // looks like nothing happened.
7669 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007670 return -7;
7671 }
7672
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007673 // Seems to be left around on Novell filesystems
7674 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007675
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007676 // finally, remove the empty old file
7677 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007678 return -8;
7679
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007680 return 0;
7681}
7682
7683
7684/*
7685 * Converts the filenames to UTF-16, then call mch_wrename().
7686 * Like rename(), returns 0 upon success, non-zero upon failure.
7687 */
7688 int
7689mch_rename(
7690 const char *pszOldFile,
7691 const char *pszNewFile)
7692{
7693 WCHAR *wold = NULL;
7694 WCHAR *wnew = NULL;
7695 int retval = -1;
7696
7697 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7698 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7699 if (wold != NULL && wnew != NULL)
7700 retval = mch_wrename(wold, wnew);
7701 vim_free(wold);
7702 vim_free(wnew);
7703 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007704}
7705
7706/*
7707 * Get the default shell for the current hardware platform
7708 */
7709 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007710default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007711{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007712 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007713}
7714
7715/*
7716 * mch_access() extends access() to do more detailed check on network drives.
7717 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7718 */
7719 int
7720mch_access(char *n, int p)
7721{
7722 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007723 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007724 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007725
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007726 wn = enc_to_utf16((char_u *)n, NULL);
7727 if (wn == NULL)
7728 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007729
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007730 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007731 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007732 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007733
7734 if (p & R_OK)
7735 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007736 // Read check is performed by seeing if we can do a find file on
7737 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007738 int i;
7739 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007740
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007741 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7742 TempNameW[i] = wn[i];
7743 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7744 TempNameW[i++] = '\\';
7745 TempNameW[i++] = '*';
7746 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007747
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007748 hFile = FindFirstFileW(TempNameW, &d);
7749 if (hFile == INVALID_HANDLE_VALUE)
7750 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007751 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007752 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007753 }
7754
7755 if (p & W_OK)
7756 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007757 // Trying to create a temporary file in the directory should catch
7758 // directories on read-only network shares. However, in
7759 // directories whose ACL allows writes but denies deletes will end
7760 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007761 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7762 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007763 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007764 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007765 }
7766 }
7767 else
7768 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007769 // Don't consider a file read-only if another process has opened it.
7770 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7771
Bram Moolenaar0f873732019-12-05 20:28:46 +01007772 // Trying to open the file for the required access does ACL, read-only
7773 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007774 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7775 | ((p & R_OK) ? GENERIC_READ : 0);
7776
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007777 hFile = CreateFileW(wn, access_mode, share_mode,
7778 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007779 if (hFile == INVALID_HANDLE_VALUE)
7780 goto getout;
7781 CloseHandle(hFile);
7782 }
7783
Bram Moolenaar0f873732019-12-05 20:28:46 +01007784 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007785getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007786 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007787 return retval;
7788}
7789
Bram Moolenaar071d4272004-06-13 20:20:40 +00007790/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007791 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007792 */
7793 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007794mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007795{
7796 WCHAR *wn;
7797 int f;
7798
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007799 wn = enc_to_utf16((char_u *)name, NULL);
7800 if (wn == NULL)
7801 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007802
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007803 f = _wopen(wn, flags, mode);
7804 vim_free(wn);
7805 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007806}
7807
7808/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007809 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007810 */
7811 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007812mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007813{
7814 WCHAR *wn, *wm;
7815 FILE *f = NULL;
7816
Bram Moolenaara12a1612019-01-24 16:39:02 +01007817#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007818 // Work around an annoying assertion in the Microsoft debug CRT
7819 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007820 char newMode = mode[strlen(mode) - 1];
7821 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007822
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007823 _get_fmode(&oldMode);
7824 if (newMode == 't')
7825 _set_fmode(_O_TEXT);
7826 else if (newMode == 'b')
7827 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007828#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007829 wn = enc_to_utf16((char_u *)name, NULL);
7830 wm = enc_to_utf16((char_u *)mode, NULL);
7831 if (wn != NULL && wm != NULL)
7832 f = _wfopen(wn, wm);
7833 vim_free(wn);
7834 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007835
Bram Moolenaara12a1612019-01-24 16:39:02 +01007836#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007837 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007838#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007839 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007840}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007841
Bram Moolenaar071d4272004-06-13 20:20:40 +00007842/*
7843 * SUB STREAM (aka info stream) handling:
7844 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007845 * NTFS can have sub streams for each file. The normal contents of a file is
7846 * stored in the main stream, and extra contents (author information, title and
7847 * so on) can be stored in a sub stream. After Windows 2000, the user can
7848 * access and store this information in sub streams via an explorer's property
7849 * menu item in the right click menu. This information in sub streams was lost
7850 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007851 *
7852 * Incomplete explanation:
7853 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7854 * More useful info and an example:
7855 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7856 */
7857
7858/*
7859 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7860 * and write to stream "substream" of file "to".
7861 * Errors are ignored.
7862 */
7863 static void
7864copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7865{
7866 HANDLE hTo;
7867 WCHAR *to_name;
7868
John Marriott738df382025-06-05 20:49:39 +02007869 to_name = alloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7870 if (to_name == NULL)
7871 return;
7872
Bram Moolenaar071d4272004-06-13 20:20:40 +00007873 wcscpy(to_name, to);
7874 wcscat(to_name, substream);
7875
7876 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7877 FILE_ATTRIBUTE_NORMAL, NULL);
7878 if (hTo != INVALID_HANDLE_VALUE)
7879 {
7880 long done;
7881 DWORD todo;
7882 DWORD readcnt, written;
7883 char buf[4096];
7884
Bram Moolenaar0f873732019-12-05 20:28:46 +01007885 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007886 for (done = 0; done < len; done += written)
7887 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007888 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007889 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7890 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007891 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7892 FALSE, FALSE, context)
7893 || readcnt != todo
7894 || !WriteFile(hTo, buf, todo, &written, NULL)
7895 || written != todo)
7896 break;
7897 }
7898 CloseHandle(hTo);
7899 }
7900
7901 free(to_name);
7902}
7903
7904/*
7905 * Copy info streams from file "from" to file "to".
7906 */
7907 static void
7908copy_infostreams(char_u *from, char_u *to)
7909{
7910 WCHAR *fromw;
7911 WCHAR *tow;
7912 HANDLE sh;
7913 WIN32_STREAM_ID sid;
7914 int headersize;
7915 WCHAR streamname[_MAX_PATH];
7916 DWORD readcount;
7917 void *context = NULL;
7918 DWORD lo, hi;
7919 int len;
7920
Bram Moolenaar0f873732019-12-05 20:28:46 +01007921 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007922 fromw = enc_to_utf16(from, NULL);
7923 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007924 if (fromw != NULL && tow != NULL)
7925 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007926 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007927 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7928 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7929 if (sh != INVALID_HANDLE_VALUE)
7930 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007931 // Use BackupRead() to find the info streams. Repeat until we
7932 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007933 for (;;)
7934 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007935 // Get the header to find the length of the stream name. If
7936 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007937 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007938 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007939 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7940 &readcount, FALSE, FALSE, &context)
7941 || readcount == 0)
7942 break;
7943
Bram Moolenaar0f873732019-12-05 20:28:46 +01007944 // We only deal with streams that have a name. The normal
7945 // file data appears to be without a name, even though docs
7946 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007947 if (sid.dwStreamNameSize > 0)
7948 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007949 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007950 if (!BackupRead(sh, (LPBYTE)streamname,
7951 sid.dwStreamNameSize,
7952 &readcount, FALSE, FALSE, &context))
7953 break;
7954
Bram Moolenaar0f873732019-12-05 20:28:46 +01007955 // Copy an info stream with a name ":anything:$DATA".
7956 // Skip "::$DATA", it has no stream name (examples suggest
7957 // it might be used for the normal file contents).
7958 // Note that BackupRead() counts bytes, but the name is in
7959 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007960 len = readcount / sizeof(WCHAR);
7961 streamname[len] = 0;
7962 if (len > 7 && wcsicmp(streamname + len - 6,
7963 L":$DATA") == 0)
7964 {
7965 streamname[len - 6] = 0;
7966 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007967 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007968 }
7969 }
7970
Bram Moolenaar0f873732019-12-05 20:28:46 +01007971 // Advance to the next stream. We might try seeking too far,
7972 // but BackupSeek() doesn't skip over stream borders, thus
7973 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007974 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007975 &lo, &hi, &context);
7976 }
7977
Bram Moolenaar0f873732019-12-05 20:28:46 +01007978 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007979 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7980
7981 CloseHandle(sh);
7982 }
7983 }
7984 vim_free(fromw);
7985 vim_free(tow);
7986}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007987
7988/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007989 * ntdll.dll definitions
7990 */
7991#define FileEaInformation 7
7992#ifndef STATUS_SUCCESS
7993# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7994#endif
7995
7996typedef struct _FILE_FULL_EA_INFORMATION_ {
7997 ULONG NextEntryOffset;
7998 UCHAR Flags;
7999 UCHAR EaNameLength;
8000 USHORT EaValueLength;
8001 CHAR EaName[1];
8002} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
8003
8004typedef struct _FILE_EA_INFORMATION_ {
8005 ULONG EaSize;
8006} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
8007
Paul Ollis65745772022-06-05 16:55:54 +01008008#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008009typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
8010 PHANDLE FileHandle,
8011 ACCESS_MASK DesiredAccess,
8012 POBJECT_ATTRIBUTES ObjectAttributes,
8013 PIO_STATUS_BLOCK IoStatusBlock,
8014 ULONG ShareAccess,
8015 ULONG OpenOptions);
8016typedef NTSTATUS (NTAPI *PfnNtClose)(
8017 HANDLE Handle);
8018typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01008019 HANDLE FileHandle,
8020 PIO_STATUS_BLOCK IoStatusBlock,
8021 PVOID Buffer,
8022 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008023typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
8024 HANDLE FileHandle,
8025 PIO_STATUS_BLOCK IoStatusBlock,
8026 PVOID Buffer,
8027 ULONG Length,
8028 BOOLEAN ReturnSingleEntry,
8029 PVOID EaList,
8030 ULONG EaListLength,
8031 PULONG EaIndex,
8032 BOOLEAN RestartScan);
8033typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01008034 HANDLE FileHandle,
8035 PIO_STATUS_BLOCK IoStatusBlock,
8036 PVOID FileInformation,
8037 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008038 FILE_INFORMATION_CLASS FileInformationClass);
8039typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
8040 PUNICODE_STRING DestinationString,
8041 PCWSTR SourceString);
8042
8043PfnNtOpenFile pNtOpenFile = NULL;
8044PfnNtClose pNtClose = NULL;
8045PfnNtSetEaFile pNtSetEaFile = NULL;
8046PfnNtQueryEaFile pNtQueryEaFile = NULL;
8047PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
8048PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01008049#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008050
8051/*
8052 * Load ntdll.dll functions.
8053 */
8054 static BOOL
8055load_ntdll(void)
8056{
8057 static int loaded = -1;
8058
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008059 if (loaded != -1)
8060 return (BOOL) loaded;
8061
8062 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
8063 if (hNtdll != NULL)
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008064 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008065 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
8066 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
8067 pNtSetEaFile = (PfnNtSetEaFile)
8068 GetProcAddress(hNtdll, "NtSetEaFile");
8069 pNtQueryEaFile = (PfnNtQueryEaFile)
8070 GetProcAddress(hNtdll, "NtQueryEaFile");
8071 pNtQueryInformationFile = (PfnNtQueryInformationFile)
8072 GetProcAddress(hNtdll, "NtQueryInformationFile");
8073 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
8074 GetProcAddress(hNtdll, "RtlInitUnicodeString");
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008075 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008076 if (pNtOpenFile == NULL
8077 || pNtClose == NULL
8078 || pNtSetEaFile == NULL
8079 || pNtQueryEaFile == NULL
8080 || pNtQueryInformationFile == NULL
8081 || pRtlInitUnicodeString == NULL)
8082 loaded = FALSE;
8083 else
8084 loaded = TRUE;
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008085 return (BOOL) loaded;
8086}
8087
8088/*
8089 * Copy extended attributes (EA) from file "from" to file "to".
8090 */
8091 static void
8092copy_extattr(char_u *from, char_u *to)
8093{
8094 char_u *fromf = NULL;
8095 char_u *tof = NULL;
8096 WCHAR *fromw = NULL;
8097 WCHAR *tow = NULL;
8098 UNICODE_STRING u;
8099 HANDLE h;
8100 OBJECT_ATTRIBUTES oa;
8101 IO_STATUS_BLOCK iosb;
8102 FILE_EA_INFORMATION_ eainfo = {0};
8103 void *ea = NULL;
8104
8105 if (!load_ntdll())
8106 return;
8107
8108 // Convert the file names to the fully qualified object names.
8109 fromf = alloc(STRLEN(from) + 5);
8110 tof = alloc(STRLEN(to) + 5);
8111 if (fromf == NULL || tof == NULL)
8112 goto theend;
8113 STRCPY(fromf, "\\??\\");
8114 STRCAT(fromf, from);
8115 STRCPY(tof, "\\??\\");
8116 STRCAT(tof, to);
8117
8118 // Convert the names to wide characters.
8119 fromw = enc_to_utf16(fromf, NULL);
8120 tow = enc_to_utf16(tof, NULL);
8121 if (fromw == NULL || tow == NULL)
8122 goto theend;
8123
8124 // Get the EA.
8125 pRtlInitUnicodeString(&u, fromw);
8126 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8127 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
8128 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8129 goto theend;
8130 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
8131 FileEaInformation);
8132 if (eainfo.EaSize != 0)
8133 {
8134 ea = alloc(eainfo.EaSize);
8135 if (ea != NULL)
8136 {
8137 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
8138 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
8139 {
Yegappan Lakshmanan960dcbd2023-03-07 17:45:11 +00008140 VIM_CLEAR(ea);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008141 }
8142 }
8143 }
8144 pNtClose(h);
8145
8146 // Set the EA.
8147 if (ea != NULL)
8148 {
8149 pRtlInitUnicodeString(&u, tow);
8150 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8151 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
8152 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8153 goto theend;
8154
8155 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
8156 pNtClose(h);
8157 }
8158
8159theend:
8160 vim_free(fromf);
8161 vim_free(tof);
8162 vim_free(fromw);
8163 vim_free(tow);
8164 vim_free(ea);
8165}
8166
8167/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008168 * Copy file attributes from file "from" to file "to".
8169 * For Windows NT and later we copy info streams.
8170 * Always returns zero, errors are ignored.
8171 */
8172 int
8173mch_copy_file_attribute(char_u *from, char_u *to)
8174{
Bram Moolenaar0f873732019-12-05 20:28:46 +01008175 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02008176 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008177 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008178 return 0;
8179}
8180
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008181
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008182/*
K.Takatadc73b4b2021-06-08 18:32:36 +02008183 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008184 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008185static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008186static LPWSTR *ArglistW = NULL;
8187static int global_argc = 0;
8188static char **global_argv;
8189
Bram Moolenaar0f873732019-12-05 20:28:46 +01008190static int used_file_argc = 0; // last argument in global_argv[] used
8191 // for the argument list.
8192static int *used_file_indexes = NULL; // indexes in global_argv[] for
8193 // command line arguments added to
8194 // the argument list
8195static int used_file_count = 0; // nr of entries in used_file_indexes
8196static int used_file_literal = FALSE; // take file names literally
8197static int used_file_full_path = FALSE; // file name was full path
8198static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008199static int used_alist_count = 0;
8200
8201
8202/*
8203 * Get the command line arguments. Unicode version.
8204 * Returns argc. Zero when something fails.
8205 */
8206 int
8207get_cmd_argsW(char ***argvp)
8208{
8209 char **argv = NULL;
8210 int argc = 0;
8211 int i;
8212
Bram Moolenaar14993322014-09-09 12:25:33 +02008213 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008214 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
8215 if (ArglistW != NULL)
8216 {
John Marriott738df382025-06-05 20:49:39 +02008217 argv = alloc((nArgsW + 1) * sizeof(char *));
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008218 if (argv != NULL)
8219 {
8220 argc = nArgsW;
8221 argv[argc] = NULL;
8222 for (i = 0; i < argc; ++i)
8223 {
8224 int len;
8225
K.Takatadc73b4b2021-06-08 18:32:36 +02008226 // Convert each Unicode argument to UTF-8.
8227 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008228 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008229 (LPSTR *)&argv[i], &len, 0, 0);
8230 if (argv[i] == NULL)
8231 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008232 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008233 while (i > 0)
8234 free(argv[--i]);
8235 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01008236 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008237 argc = 0;
8238 }
8239 }
8240 }
8241 }
8242
8243 global_argc = argc;
8244 global_argv = argv;
8245 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02008246 {
8247 if (used_file_indexes != NULL)
8248 free(used_file_indexes);
John Marriott738df382025-06-05 20:49:39 +02008249 used_file_indexes = alloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02008250 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008251
8252 if (argvp != NULL)
8253 *argvp = argv;
8254 return argc;
8255}
8256
8257 void
8258free_cmd_argsW(void)
8259{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008260 if (ArglistW == NULL)
8261 return;
8262
8263 GlobalFree(ArglistW);
8264 ArglistW = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008265}
8266
8267/*
8268 * Remember "name" is an argument that was added to the argument list.
8269 * This avoids that we have to re-parse the argument list when fix_arg_enc()
8270 * is called.
8271 */
8272 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008273used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008274{
8275 int i;
8276
8277 if (used_file_indexes == NULL)
8278 return;
8279 for (i = used_file_argc + 1; i < global_argc; ++i)
8280 if (STRCMP(global_argv[i], name) == 0)
8281 {
8282 used_file_argc = i;
8283 used_file_indexes[used_file_count++] = i;
8284 break;
8285 }
8286 used_file_literal = literal;
8287 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008288 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008289}
8290
8291/*
8292 * Remember the length of the argument list as it was. If it changes then we
8293 * leave it alone when 'encoding' is set.
8294 */
8295 void
8296set_alist_count(void)
8297{
8298 used_alist_count = GARGCOUNT;
8299}
8300
8301/*
8302 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02008303 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008304 * and convert them to 'encoding'.
8305 */
8306 void
8307fix_arg_enc(void)
8308{
8309 int i;
8310 int idx;
8311 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00008312 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008313
Bram Moolenaar0f873732019-12-05 20:28:46 +01008314 // Safety checks:
8315 // - if argument count differs between the wide and non-wide argument
8316 // list, something must be wrong.
8317 // - the file name arguments must have been located.
8318 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008319 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008320 || ArglistW == NULL
8321 || used_file_indexes == NULL
8322 || used_file_count == 0
8323 || used_alist_count != GARGCOUNT)
8324 return;
8325
Bram Moolenaar0f873732019-12-05 20:28:46 +01008326 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02008327 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008328 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008329 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00008330 for (i = 0; i < GARGCOUNT; ++i)
8331 fnum_list[i] = GARGLIST[i].ae_fnum;
8332
Bram Moolenaar0f873732019-12-05 20:28:46 +01008333 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008334 alist_clear(&global_alist);
8335 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008336 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008337
8338 for (i = 0; i < used_file_count; ++i)
8339 {
8340 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008341 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008342 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00008343 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008344 int literal = used_file_literal;
8345
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008346#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01008347 // When using diff mode may need to concatenate file name to
8348 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008349 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
8350 && !mch_isdir(alist_name(&GARGLIST[0])))
8351 {
8352 char_u *r;
8353
8354 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
8355 if (r != NULL)
8356 {
8357 vim_free(str);
8358 str = r;
8359 }
8360 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008361#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01008362 // Re-use the old buffer by renaming it. When not using literal
8363 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00008364 if (used_file_literal)
8365 buf_set_name(fnum_list[i], str);
8366
Bram Moolenaar0f873732019-12-05 20:28:46 +01008367 // Check backtick literal. backtick literal is already expanded in
8368 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008369 if (literal == FALSE)
8370 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02008371 size_t len = STRLEN(str);
8372
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008373 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
8374 literal = TRUE;
8375 }
8376 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008377 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008378 }
8379
8380 if (!used_file_literal)
8381 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008382 // Now expand wildcards in the arguments.
8383 // Temporarily add '(' and ')' to 'isfname'. These are valid
8384 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00008385 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01008386 // Also, unset wildignore to not be influenced by this option.
8387 // The arguments specified in command-line should be kept even if
8388 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00008389 // Use :legacy so that it also works when in Vim9 script.
8390 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
8391 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00008392 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00008393 do_cmdline_cmd(
8394 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
8395 do_cmdline_cmd(
8396 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008397 }
8398
Bram Moolenaar0f873732019-12-05 20:28:46 +01008399 // If wildcard expansion failed, we are editing the first file of the
8400 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008401 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
8402 {
8403 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00008404 if (GARGCOUNT == 1 && used_file_full_path
8405 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
8406 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008407 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00008408
8409 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008410}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008411
8412 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02008413mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008414{
8415 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008416 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008417
Bram Moolenaar964b3742019-05-24 18:54:09 +02008418 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008419 if (envbuf == NULL)
8420 return -1;
8421
8422 sprintf((char *)envbuf, "%s=%s", var, value);
8423
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008424 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008425
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008426 vim_free(envbuf);
8427 if (p == NULL)
8428 return -1;
8429 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008430#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008431 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008432#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008433 // Unlike Un*x systems, we can free the string for _wputenv().
8434 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008435
8436 return 0;
8437}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008438
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008439/*
8440 * Support for 256 colors and 24-bit colors was added in Windows 10
8441 * version 1703 (Creators update).
8442 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008443#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
8444
8445/*
8446 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02008447 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008448 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008449#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008450
8451/*
8452 * ConPTY differences between versions, need different logic.
8453 * version 1903 (May 2019 update).
8454 */
8455#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
8456
8457/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008458 * version 1909 (November 2019 update).
8459 */
8460#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
8461
8462/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008463 * Stay ahead of the next update, and when it's done, fix this.
8464 * version ? (2020 update, temporarily use the build number of insider preview)
8465 */
8466#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
8467
8468/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02008469 * Confirm until this version. Also the logic changes.
8470 * insider preview.
8471 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02008472#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008473
8474/*
8475 * Not stable now.
8476 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008477#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Christopher Plewright1140b512022-11-12 18:46:05 +00008478// Notes:
8479// Win 10 22H2 Final is build 19045, it's conpty is widely used.
8480// Strangely, 19045 is newer but is a lower build number than the 2020 insider
8481// preview which had a build 19587. And, not sure how stable that was?
8482// Win Server 2022 (May 10, 2022) is build 20348, its conpty is widely used.
8483// Win 11 starts from build 22000, even though the major version says 10!
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008484
8485 static void
8486vtp_flag_init(void)
8487{
8488 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008489#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008490 DWORD mode;
8491 HANDLE out;
8492
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008493# ifdef VIMDLL
8494 if (!gui.in_use)
8495# endif
8496 {
8497 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008498
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008499 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
8500 GetConsoleMode(out, &mode);
8501 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
8502 if (SetConsoleMode(out, mode) == 0)
8503 vtp_working = 0;
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008504
8505 // VTP uses alternate screen buffer.
8506 // But, not if running in a nested terminal
8507 use_alternate_screen_buffer = win10_22H2_or_later && p_rs && vtp_working
8508 && !mch_getenv("VIM_TERMINAL");
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008509 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008510#endif
8511
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008512 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008513 conpty_working = 1;
8514 if (ver >= CONPTY_STABLE_BUILD)
8515 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008516
Bram Moolenaar57da6982019-09-13 22:30:11 +02008517 if (ver <= CONPTY_INSIDER_BUILD)
8518 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008519 if (ver <= CONPTY_1909_BUILD)
8520 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02008521 if (ver <= CONPTY_1903_BUILD)
8522 conpty_type = 2;
8523 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
8524 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008525
8526 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
8527 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008528}
8529
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008530#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008531
8532 static void
8533vtp_init(void)
8534{
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008535# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightd343c602023-01-22 18:58:30 +00008536 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8537 csbi.cbSize = sizeof(csbi);
8538 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8539 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
8540 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
8541 store_console_bg_rgb = save_console_bg_rgb;
8542 store_console_fg_rgb = save_console_fg_rgb;
Christopher Plewright38804d62022-11-09 23:55:52 +00008543
Christopher Plewrightd343c602023-01-22 18:58:30 +00008544 COLORREF bg;
8545 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
8546 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8547 default_console_color_bg = bg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008548
Christopher Plewrightd343c602023-01-22 18:58:30 +00008549 COLORREF fg;
8550 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
8551 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8552 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008553# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008554 set_console_color_rgb();
8555}
8556
8557 static void
8558vtp_exit(void)
8559{
Bram Moolenaardf543822020-01-30 11:53:59 +01008560 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008561}
8562
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008563 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008564vtp_printf(
8565 char *format,
8566 ...)
8567{
8568 char_u buf[100];
8569 va_list list;
8570 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008571 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008572
Nir Lichtman6cd2d1d2023-11-11 11:27:41 +01008573 if (silent_mode)
8574 return 0;
8575
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008576 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008577 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008578 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008579 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008580 return (int)result;
8581}
8582
8583 static void
8584vtp_sgr_bulk(
8585 int arg)
8586{
8587 int args[1];
8588
8589 args[0] = arg;
8590 vtp_sgr_bulks(1, args);
8591}
8592
K.Takata6e1d31e2022-02-03 13:05:32 +00008593# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008594 if ((*p-- = "0123456789"[(n = x % 10)]) \
8595 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8596 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8597
K.Takata6e1d31e2022-02-03 13:05:32 +00008598# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008599 case x: \
8600 FAST256(newargs[x - 1]);
8601
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008602 static void
8603vtp_sgr_bulks(
8604 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008605 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008606{
K.Takata6e1d31e2022-02-03 13:05:32 +00008607# define MAXSGR 16
8608# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008609 char_u buf[SGRBUFSIZE];
8610 char_u *p;
8611 int in, out;
8612 int newargs[16];
8613 static int sgrfgr = -1, sgrfgg, sgrfgb;
8614 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008615
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008616 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008617 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008618 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008619 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008620 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008621 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008622
8623 in = out = 0;
8624 while (in < argc)
8625 {
8626 int s = args[in];
8627 int copylen = 1;
8628
8629 if (s == 38)
8630 {
8631 if (argc - in >= 5 && args[in + 1] == 2)
8632 {
8633 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8634 && sgrfgb == args[in + 4])
8635 {
8636 in += 5;
8637 copylen = 0;
8638 }
8639 else
8640 {
8641 sgrfgr = args[in + 2];
8642 sgrfgg = args[in + 3];
8643 sgrfgb = args[in + 4];
8644 copylen = 5;
8645 }
8646 }
8647 else if (argc - in >= 3 && args[in + 1] == 5)
8648 {
8649 sgrfgr = -1;
8650 copylen = 3;
8651 }
8652 }
8653 else if (s == 48)
8654 {
8655 if (argc - in >= 5 && args[in + 1] == 2)
8656 {
8657 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8658 && sgrbgb == args[in + 4])
8659 {
8660 in += 5;
8661 copylen = 0;
8662 }
8663 else
8664 {
8665 sgrbgr = args[in + 2];
8666 sgrbgg = args[in + 3];
8667 sgrbgb = args[in + 4];
8668 copylen = 5;
8669 }
8670 }
8671 else if (argc - in >= 3 && args[in + 1] == 5)
8672 {
8673 sgrbgr = -1;
8674 copylen = 3;
8675 }
8676 }
8677 else if (30 <= s && s <= 39)
8678 sgrfgr = -1;
8679 else if (90 <= s && s <= 97)
8680 sgrfgr = -1;
8681 else if (40 <= s && s <= 49)
8682 sgrbgr = -1;
8683 else if (100 <= s && s <= 107)
8684 sgrbgr = -1;
8685 else if (s == 0)
8686 sgrfgr = sgrbgr = -1;
8687
8688 while (copylen--)
8689 newargs[out++] = args[in++];
8690 }
8691
8692 p = &buf[sizeof(buf) - 1];
8693 *p-- = 'm';
8694
8695 switch (out)
8696 {
8697 int n, m;
8698 DWORD r;
8699
8700 FAST256CASE(16);
8701 *p-- = ';';
8702 FAST256CASE(15);
8703 *p-- = ';';
8704 FAST256CASE(14);
8705 *p-- = ';';
8706 FAST256CASE(13);
8707 *p-- = ';';
8708 FAST256CASE(12);
8709 *p-- = ';';
8710 FAST256CASE(11);
8711 *p-- = ';';
8712 FAST256CASE(10);
8713 *p-- = ';';
8714 FAST256CASE(9);
8715 *p-- = ';';
8716 FAST256CASE(8);
8717 *p-- = ';';
8718 FAST256CASE(7);
8719 *p-- = ';';
8720 FAST256CASE(6);
8721 *p-- = ';';
8722 FAST256CASE(5);
8723 *p-- = ';';
8724 FAST256CASE(4);
8725 *p-- = ';';
8726 FAST256CASE(3);
8727 *p-- = ';';
8728 FAST256CASE(2);
8729 *p-- = ';';
8730 FAST256CASE(1);
8731 *p-- = '[';
8732 *p = '\033';
8733 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8734 default:
8735 break;
8736 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008737}
8738
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008739 static void
8740wt_init(void)
8741{
Christopher Plewright1140b512022-11-12 18:46:05 +00008742 wt_working = mch_getenv("WT_SESSION") != NULL;
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008743}
8744
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008745# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008746 static int
8747ctermtoxterm(
8748 int cterm)
8749{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008750 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008751
8752 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8753 return (((int)r << 16) | ((int)g << 8) | (int)b);
8754}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008755# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008756
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008757 static void
8758set_console_color_rgb(void)
8759{
8760# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008761 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008762 guicolor_T fg, bg;
8763 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008764
Christopher Plewright38804d62022-11-09 23:55:52 +00008765 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008766 return;
8767
Bram Moolenaara050b942019-12-02 21:35:31 +01008768 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8769
Christopher Plewright38804d62022-11-09 23:55:52 +00008770 if (p_tgc || t_colors >= 256)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008771 {
8772 term_fg_rgb_color(fg);
8773 term_bg_rgb_color(bg);
8774 return;
8775 }
8776
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008777 if (use_alternate_screen_buffer)
8778 return;
8779
Christopher Plewrightd343c602023-01-22 18:58:30 +00008780 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8781 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008782
Christopher Plewrightd343c602023-01-22 18:58:30 +00008783 csbi.cbSize = sizeof(csbi);
8784 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008785
Christopher Plewrightd343c602023-01-22 18:58:30 +00008786 csbi.cbSize = sizeof(csbi);
8787 csbi.srWindow.Right += 1;
8788 csbi.srWindow.Bottom += 1;
8789 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8790 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
8791 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8792 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
8793 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008794# endif
8795}
8796
Bram Moolenaara050b942019-12-02 21:35:31 +01008797# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8798 void
8799get_default_console_color(
8800 int *cterm_fg,
8801 int *cterm_bg,
8802 guicolor_T *gui_fg,
8803 guicolor_T *gui_bg)
8804{
8805 int id;
8806 guicolor_T guifg = INVALCOLOR;
8807 guicolor_T guibg = INVALCOLOR;
8808 int ctermfg = 0;
8809 int ctermbg = 0;
Christopher Plewright38804d62022-11-09 23:55:52 +00008810 int dummynull = 0;
Bram Moolenaara050b942019-12-02 21:35:31 +01008811
8812 id = syn_name2id((char_u *)"Normal");
8813 if (id > 0 && p_tgc)
8814 syn_id2colors(id, &guifg, &guibg);
8815 if (guifg == INVALCOLOR)
8816 {
8817 ctermfg = -1;
8818 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008819 syn_id2cterm_bg(id, &ctermfg, &dummynull);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008820 if (ctermfg != -1)
8821 guifg = ctermtoxterm(ctermfg);
Christopher Plewright38804d62022-11-09 23:55:52 +00008822 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008823 guifg = USE_WT ? INVALCOLOR : default_console_color_fg;
8824 cterm_normal_fg_gui_color = guifg;
8825 ctermfg = ctermfg < 0 ? 0 : ctermfg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008826 }
8827 if (guibg == INVALCOLOR)
8828 {
8829 ctermbg = -1;
8830 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008831 syn_id2cterm_bg(id, &dummynull, &ctermbg);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008832 if (ctermbg != -1)
8833 guibg = ctermtoxterm(ctermbg);
K.Takatae53a0d42022-09-05 21:45:11 +01008834 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008835 guibg = USE_WT ? INVALCOLOR : default_console_color_bg;
8836 cterm_normal_bg_gui_color = guibg;
8837 ctermbg = ctermbg < 0 ? 0 : ctermbg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008838 }
8839
8840 *cterm_fg = ctermfg;
8841 *cterm_bg = ctermbg;
8842 *gui_fg = guifg;
8843 *gui_bg = guibg;
8844}
8845# endif
8846
Bram Moolenaardf543822020-01-30 11:53:59 +01008847/*
8848 * Set the console colors to the original colors or the last set colors.
8849 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008850 static void
8851reset_console_color_rgb(void)
8852{
8853# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008854 if (use_alternate_screen_buffer)
8855 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008856
Christopher Plewright38804d62022-11-09 23:55:52 +00008857 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8858
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008859 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008860 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008861
8862 csbi.cbSize = sizeof(csbi);
8863 csbi.srWindow.Right += 1;
8864 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008865 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8866 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008867 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008868# endif
8869}
8870
8871/*
8872 * Set the console colors to the original colors.
8873 */
8874 static void
8875restore_console_color_rgb(void)
8876{
8877# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008878 if (use_alternate_screen_buffer)
8879 return;
Christopher Plewright38804d62022-11-09 23:55:52 +00008880
K.Takata27b53be2022-09-18 12:25:49 +01008881 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008882
8883 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008884 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008885
8886 csbi.cbSize = sizeof(csbi);
8887 csbi.srWindow.Right += 1;
8888 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008889 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8890 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008891 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008892# endif
8893}
8894
8895 void
8896control_console_color_rgb(void)
8897{
Christopher Plewright38804d62022-11-09 23:55:52 +00008898 if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008899 set_console_color_rgb();
8900 else
8901 reset_console_color_rgb();
8902}
8903
8904 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008905use_vtp(void)
8906{
8907 return USE_VTP;
8908}
8909
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008910 int
8911is_term_win32(void)
8912{
8913 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8914}
8915
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008916 int
8917has_vtp_working(void)
8918{
8919 return vtp_working;
8920}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008921
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008922#endif
8923
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008924 int
8925has_conpty_working(void)
8926{
8927 return conpty_working;
8928}
8929
8930 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008931get_conpty_type(void)
8932{
8933 return conpty_type;
8934}
8935
8936 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008937is_conpty_stable(void)
8938{
8939 return conpty_stable;
8940}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008941
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008942 int
8943get_conpty_fix_type(void)
8944{
8945 return conpty_fix_type;
8946}
8947
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008948#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008949 void
8950resize_console_buf(void)
8951{
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008952 if (use_alternate_screen_buffer)
8953 return;
8954
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008955 CONSOLE_SCREEN_BUFFER_INFO csbi;
8956 COORD coord;
8957 SMALL_RECT newsize;
8958
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008959 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8960 return;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008961
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008962 coord.X = SRWIDTH(csbi.srWindow);
8963 coord.Y = SRHEIGHT(csbi.srWindow);
8964 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008965
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008966 newsize.Left = 0;
8967 newsize.Top = 0;
8968 newsize.Right = coord.X - 1;
8969 newsize.Bottom = coord.Y - 1;
8970 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8971
8972 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008973}
8974#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008975
8976 char *
8977GetWin32Error(void)
8978{
K.Takatad68b2fc2022-02-12 11:18:37 +00008979 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008980 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008981
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008982 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8983 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008984 if (oldmsg != NULL)
8985 LocalFree(oldmsg);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008986 if (msg == NULL)
8987 return NULL;
8988
8989 // remove trailing \r\n
8990 char *pcrlf = strstr(msg, "\r\n");
8991 if (pcrlf != NULL)
8992 *pcrlf = '\0';
8993 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008994 return msg;
8995}
Paul Ollis65745772022-06-05 16:55:54 +01008996
8997#if defined(FEAT_RELTIME) || defined(PROTO)
8998static HANDLE timer_handle;
8999static int timer_active = FALSE;
9000
9001/*
9002 * Calls to start_timeout alternate the return value pointer between the two
9003 * entries in timeout_flags. If the previously active timeout is very close to
9004 * expiring when start_timeout() is called then a race condition means that the
9005 * set_flag() function may still be invoked after the previous timer is
9006 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
9007 * timeouts.
9008 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01009009static sig_atomic_t timeout_flags[2];
9010static int timeout_flag_idx = 0;
9011static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01009012
9013
9014 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01009015set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01009016{
John Marriott2c7ccaa2025-05-26 20:25:38 +02009017 *(sig_atomic_t *)param = TRUE;
Paul Ollis65745772022-06-05 16:55:54 +01009018}
9019
9020/*
9021 * Stop any active timeout.
9022 */
9023 void
9024stop_timeout(void)
9025{
9026 if (timer_active)
9027 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01009028 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01009029 timer_active = FALSE;
9030 if (!ret && GetLastError() != ERROR_IO_PENDING)
9031 {
9032 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
9033 }
9034 }
9035 *timeout_flag = FALSE;
9036}
9037
9038/*
9039 * Start the timeout timer.
9040 *
9041 * The period is defined in milliseconds.
9042 *
9043 * The return value is a pointer to a flag that is initialised to 0. If the
9044 * timeout expires, the flag is set to 1. This will only return pointers to
9045 * static memory; i.e. any pointer returned by this function may always be
9046 * safely dereferenced.
9047 *
9048 * This function is not expected to fail, but if it does it still returns a
9049 * valid flag pointer; the flag will remain stuck at zero.
9050 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01009051 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01009052start_timeout(long msec)
9053{
Paul Ollis65745772022-06-05 16:55:54 +01009054 BOOL ret;
9055
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01009056 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01009057
9058 stop_timeout();
9059 ret = CreateTimerQueueTimer(
9060 &timer_handle, NULL, set_flag, timeout_flag,
9061 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
9062 if (!ret)
9063 {
9064 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
9065 }
9066 else
9067 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01009068 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01009069 timer_active = TRUE;
9070 *timeout_flag = FALSE;
9071 }
9072 return timeout_flag;
9073}
9074#endif