blob: 799ec578d1f02bd817355d1651152170b9ffe919 [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
12 * Used for both the console version and the Win32 GUI. A lot of code is for
Bram Moolenaar4f974752019-02-17 17:44:42 +010013 * the console version only, so there is a lot of "#ifndef FEAT_GUI_MSWIN".
Bram Moolenaar071d4272004-06-13 20:20:40 +000014 *
Nir Lichtman563e8ec2024-09-30 19:42:28 +020015 * Win32 system-dependent routines.
Bram Moolenaar071d4272004-06-13 20:20:40 +000016 * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17 * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18 *
19 * George V. Reilly <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
Bram Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010032
Bram Moolenaar0f873732019-12-05 20:28:46 +010033// cproto fails on missing include files
Bram Moolenaar82881492012-11-20 16:53:39 +010034#ifndef PROTO
35# include <process.h>
Bram Moolenaare7bebc42021-02-01 20:50:37 +010036# include <winternl.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000037# include <direct.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000038
Bram Moolenaar651fca82021-11-29 20:39:38 +000039# if !defined(FEAT_GUI_MSWIN)
Bram Moolenaar82881492012-11-20 16:53:39 +010040# include <shellapi.h>
41# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000042
K.Takata56f587b2024-06-19 19:56:03 +020043# ifdef FEAT_JOB_CHANNEL
44# include <tlhelp32.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000045# endif
46#endif
47
Bram Moolenaar0f873732019-12-05 20:28:46 +010048// Record all output and all keyboard & mouse input
49// #define MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +000050
51#ifdef MCH_WRITE_DUMP
52FILE* fdDump = NULL;
53#endif
54
55/*
56 * When generating prototypes for Win32 on Unix, these lines make the syntax
57 * errors disappear. They do not need to be correct.
58 */
59#ifdef PROTO
Bram Moolenaar912bc4a2019-12-01 18:58:11 +010060# define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000061typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000062typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +000063typedef int ACCESS_MASK;
64typedef int BOOL;
Paul Ollis65745772022-06-05 16:55:54 +010065typedef int BOOLEAN;
66typedef int CALLBACK;
Bram Moolenaar071d4272004-06-13 20:20:40 +000067typedef int COLORREF;
68typedef int CONSOLE_CURSOR_INFO;
69typedef int COORD;
70typedef int DWORD;
71typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +010072typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000073typedef int HDC;
74typedef int HFONT;
75typedef int HICON;
76typedef int HINSTANCE;
77typedef int HWND;
78typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +020079typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +000080typedef int KEY_EVENT_RECORD;
81typedef int LOGFONT;
82typedef int LPBOOL;
83typedef int LPCTSTR;
84typedef int LPDWORD;
85typedef int LPSTR;
86typedef int LPTSTR;
87typedef int LPVOID;
88typedef int MOUSE_EVENT_RECORD;
89typedef int PACL;
90typedef int PDWORD;
91typedef int PHANDLE;
92typedef int PRINTDLG;
93typedef int PSECURITY_DESCRIPTOR;
94typedef int PSID;
95typedef int SECURITY_INFORMATION;
96typedef int SHORT;
97typedef int SMALL_RECT;
98typedef int TEXTMETRIC;
99typedef int TOKEN_INFORMATION_CLASS;
100typedef int TRUSTEE;
101typedef int WORD;
102typedef int WCHAR;
103typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100104typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200105typedef int SE_OBJECT_TYPE;
106typedef int PSNSECINFO;
107typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100108typedef int STARTUPINFO;
109typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200110typedef int LPSECURITY_ATTRIBUTES;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100111# define __stdcall // empty
Bram Moolenaar071d4272004-06-13 20:20:40 +0000112#endif
113
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200114#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100115// Win32 Console handles for input and output
Bram Moolenaar071d4272004-06-13 20:20:40 +0000116static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
117static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
118
Bram Moolenaar0f873732019-12-05 20:28:46 +0100119// Win32 Screen buffer,coordinate,console I/O information
Bram Moolenaar071d4272004-06-13 20:20:40 +0000120static SMALL_RECT g_srScrollRegion;
Saleem Abdulrasool38bea302023-12-27 18:57:12 +0100121// This is explicitly initialised to work around a LTCG issue on Windows ARM64
122// (at least of 19.39.33321). This pushes this into the `.data` rather than
123// `.bss` which corrects code generation in `write_chars` (#13453).
124static COORD g_coord = {0, 0}; // 0-based, but external coords are 1-based
Bram Moolenaar071d4272004-06-13 20:20:40 +0000125
Bram Moolenaar0f873732019-12-05 20:28:46 +0100126// The attribute of the screen when the editor was started
127static WORD g_attrDefault = 7; // lightgray text on black background
Bram Moolenaar071d4272004-06-13 20:20:40 +0000128static WORD g_attrCurrent;
129
Bram Moolenaar0f873732019-12-05 20:28:46 +0100130static int g_fCBrkPressed = FALSE; // set by ctrl-break interrupt
131static int g_fCtrlCPressed = FALSE; // set when ctrl-C or ctrl-break detected
132static int g_fForceExit = FALSE; // set when forcefully exiting
Bram Moolenaar071d4272004-06-13 20:20:40 +0000133
Bram Moolenaar071d4272004-06-13 20:20:40 +0000134static void scroll(unsigned cLines);
135static void set_scroll_region(unsigned left, unsigned top,
136 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100137static void set_scroll_region_tb(unsigned top, unsigned bottom);
138static void set_scroll_region_lr(unsigned left, unsigned right);
139static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000140static void delete_lines(unsigned cLines);
141static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000142static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000143static int s_cursor_visible = TRUE;
144static int did_create_conin = FALSE;
Christopher Plewright20b795e2022-12-20 20:01:58 +0000145// The 'input_record_buffer' is an internal dynamic fifo queue of MS-Windows
146// console INPUT_RECORD events that are normally read from the console input
147// buffer. This provides an injection point for testing the low-level handling
148// of INPUT_RECORDs.
149typedef struct input_record_buffer_node_S
150{
151 INPUT_RECORD ir;
152 struct input_record_buffer_node_S *next;
153} input_record_buffer_node_T;
154typedef struct input_record_buffer_S
155{
156 input_record_buffer_node_T *head;
157 input_record_buffer_node_T *tail;
158 int length;
159} input_record_buffer_T;
160static input_record_buffer_T input_record_buffer;
Christopher Plewright20b795e2022-12-20 20:01:58 +0000161static int read_input_record_buffer(INPUT_RECORD* irEvents, int nMaxLength);
162static int write_input_record_buffer(INPUT_RECORD* irEvents, int nLength);
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200163#endif
164#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000165static int s_dont_use_vimrun = TRUE;
166static int need_vimrun_warning = FALSE;
167static char *vimrun_path = "vimrun ";
168#endif
169
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200170static int win32_getattrs(char_u *name);
171static int win32_setattrs(char_u *name, int attrs);
172static int win32_set_archive(char_u *name);
173
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100174static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200175static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100176static int conpty_stable = 0;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +0200177static int conpty_fix_type = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100178static void vtp_flag_init();
179
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200180#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100181static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100182static void vtp_init();
183static void vtp_exit();
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100184static void vtp_sgr_bulk(int arg);
185static void vtp_sgr_bulks(int argc, int *argv);
186
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200187static int wt_working = 0;
Christopher Plewright1140b512022-11-12 18:46:05 +0000188static void wt_init(void);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200189
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200190static int g_color_index_bg = 0;
191static int g_color_index_fg = 7;
192
193# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +0000194static guicolor_T save_console_bg_rgb;
195static guicolor_T save_console_fg_rgb;
196static guicolor_T store_console_bg_rgb;
197static guicolor_T store_console_fg_rgb;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +0100198static int default_console_color_bg = 0x000000; // black
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200199static int default_console_color_fg = 0xc0c0c0; // white
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +0000200# define USE_VTP (vtp_working && is_term_win32() \
201 && (p_tgc || t_colors >= 256))
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200202# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100203# else
204# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200205# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100206# endif
207
208static void set_console_color_rgb(void);
209static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100210static void restore_console_color_rgb(void);
Christopher Plewright20b795e2022-12-20 20:01:58 +0000211#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100212
Bram Moolenaar0f873732019-12-05 20:28:46 +0100213// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100214#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
215# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
216#endif
217
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200218#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100219static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000220#endif
221
K.Takatace3189d2023-02-15 19:13:43 +0000222static WCHAR *exe_pathw = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200223
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100224static BOOL win8_or_later = FALSE;
Christopher Plewrightc8b126d2022-12-22 13:45:23 +0000225static BOOL win10_22H2_or_later = FALSE;
Bram Moolenaar9fca1332022-12-22 21:06:41 +0000226#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Christopher Plewrightc8b126d2022-12-22 13:45:23 +0000227static BOOL use_alternate_screen_buffer = FALSE;
Bram Moolenaar9fca1332022-12-22 21:06:41 +0000228#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100229
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100230/*
231 * Get version number including build number
232 */
233typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100234#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100235 (((major) << 24) | ((minor) << 16) | (build))
236
237 static DWORD
238get_build_number(void)
239{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100240 OSVERSIONINFOW osver;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100241 HMODULE hNtdll;
242 PfnRtlGetVersion pRtlGetVersion;
243 DWORD ver = MAKE_VER(0, 0, 0);
244
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100245 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100246 hNtdll = GetModuleHandle("ntdll.dll");
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000247 if (hNtdll == NULL)
248 return ver;
249
250 pRtlGetVersion =
251 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
252 pRtlGetVersion(&osver);
253 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
254 min(osver.dwMinorVersion, 255),
255 min(osver.dwBuildNumber, 32767));
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100256 return ver;
257}
258
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200259#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200260 static BOOL
261is_ambiwidth_event(
262 INPUT_RECORD *ir)
263{
264 return ir->EventType == KEY_EVENT
265 && ir->Event.KeyEvent.bKeyDown
266 && ir->Event.KeyEvent.wRepeatCount == 1
267 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
268 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000269 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200270 && ir->Event.KeyEvent.dwControlKeyState == 2;
271}
272
273 static void
274make_ambiwidth_event(
275 INPUT_RECORD *down,
276 INPUT_RECORD *up)
277{
278 down->Event.KeyEvent.wVirtualKeyCode = 0;
279 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000280 down->Event.KeyEvent.uChar.UnicodeChar
281 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200282 down->Event.KeyEvent.dwControlKeyState = 0;
283}
284
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100285/*
286 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100287 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100288 */
289 static BOOL
290read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100291 HANDLE hInput,
292 INPUT_RECORD *lpBuffer,
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100293 int nLength,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100294 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100295{
296 enum
297 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100298 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100299 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100300 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100301 static DWORD s_dwIndex = 0;
302 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100303 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100304 int head;
305 int tail;
306 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200307 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100308
Christopher Plewright20b795e2022-12-20 20:01:58 +0000309 if (s_dwMax == 0 && input_record_buffer.length > 0)
310 {
311 dwEvents = read_input_record_buffer(s_irCache, IRSIZE);
312 s_dwIndex = 0;
313 s_dwMax = dwEvents;
314 }
315
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200316 if (nLength == -2)
317 return (s_dwMax > 0) ? TRUE : FALSE;
318
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100319 if (!win8_or_later)
320 {
321 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200322 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
323 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100324 }
325
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100326 if (s_dwMax == 0)
327 {
Christopher Plewright38804d62022-11-09 23:55:52 +0000328 if (!vtp_working && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200329 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200330 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
331 if (dwEvents == 0 && nLength == -1)
332 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
333 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100334 s_dwIndex = 0;
335 s_dwMax = dwEvents;
336 if (dwEvents == 0)
337 {
338 *lpEvents = 0;
339 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100340 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100341
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200342 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
343 if (is_ambiwidth_event(&s_irCache[i]))
344 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
345
Bram Moolenaardd415a62014-02-05 14:02:27 +0100346 if (s_dwMax > 1)
347 {
348 head = 0;
349 tail = s_dwMax - 1;
350 while (head != tail)
351 {
352 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
353 && s_irCache[head + 1].EventType
354 == WINDOW_BUFFER_SIZE_EVENT)
355 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100356 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100357 for (i = head; i < tail; ++i)
358 s_irCache[i] = s_irCache[i + 1];
359 --tail;
360 continue;
361 }
362 head++;
363 }
364 s_dwMax = tail + 1;
365 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100366 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100367
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200368 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
369 {
370 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
371 {
372 s_irPseudo = s_irCache[s_dwIndex];
373 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
374 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
375 *lpBuffer = s_irPseudo;
376 *lpEvents = 1;
377 return TRUE;
378 }
379 }
380
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100381 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200382 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100383 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100384 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100385 return TRUE;
386}
387
388/*
389 * Version of PeekConsoleInput() that works with IME.
390 */
391 static BOOL
392peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100393 HANDLE hInput,
394 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200395 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100396 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100397{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100398 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100399}
400
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100401# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200402 static DWORD
403msg_wait_for_multiple_objects(
404 DWORD nCount,
405 LPHANDLE pHandles,
406 BOOL fWaitAll,
407 DWORD dwMilliseconds,
408 DWORD dwWakeMask)
409{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100410 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200411 return WAIT_OBJECT_0;
412 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
413 dwMilliseconds, dwWakeMask);
414}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100415# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200416
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100417# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200418 static DWORD
419wait_for_single_object(
420 HANDLE hHandle,
421 DWORD dwMilliseconds)
422{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100423 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200424 return WAIT_OBJECT_0;
425 return WaitForSingleObject(hHandle, dwMilliseconds);
426}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100427# endif
Christopher Plewright20b795e2022-12-20 20:01:58 +0000428#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200429
K.Takatace3189d2023-02-15 19:13:43 +0000430 void
431mch_get_exe_name(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000432{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100433 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
K.Takataf741e3e2023-05-15 16:41:40 +0100434 // as the maximum length that works. Add 1 for a NUL byte and 5 for
435 // "PATH=".
436#define MAX_ENV_PATH_LEN (8191 + 1 + 5)
437 WCHAR temp[MAX_ENV_PATH_LEN];
K.Takatace3189d2023-02-15 19:13:43 +0000438 WCHAR buf[MAX_PATH];
439 int updated = FALSE;
440 static int enc_prev = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000441
K.Takatace3189d2023-02-15 19:13:43 +0000442 if (exe_name == NULL || exe_pathw == NULL || enc_prev != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000443 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100444 // store the name of the executable, may be used for $VIM
K.Takatace3189d2023-02-15 19:13:43 +0000445 GetModuleFileNameW(NULL, buf, MAX_PATH);
446 if (*buf != NUL)
447 {
448 if (enc_codepage == -1)
449 enc_codepage = GetACP();
K.Takataf741e3e2023-05-15 16:41:40 +0100450 vim_free(exe_name);
K.Takatace3189d2023-02-15 19:13:43 +0000451 exe_name = utf16_to_enc(buf, NULL);
452 enc_prev = enc_codepage;
453
454 WCHAR *wp = wcsrchr(buf, '\\');
455 if (wp != NULL)
456 *wp = NUL;
K.Takataf741e3e2023-05-15 16:41:40 +0100457 vim_free(exe_pathw);
K.Takatace3189d2023-02-15 19:13:43 +0000458 exe_pathw = _wcsdup(buf);
459 updated = TRUE;
460 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000461 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000462
K.Takatace3189d2023-02-15 19:13:43 +0000463 if (exe_pathw == NULL || !updated)
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000464 return;
465
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000466 // Append our starting directory to $PATH, so that when doing
467 // "!xxd" it's found in our starting directory. Needed because
468 // SearchPath() also looks there.
K.Takataf741e3e2023-05-15 16:41:40 +0100469 WCHAR *p = _wgetenv(L"PATH");
470 if (p == NULL || wcslen(p) + wcslen(exe_pathw) + 2 + 5 < MAX_ENV_PATH_LEN)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000471 {
K.Takataf741e3e2023-05-15 16:41:40 +0100472 wcscpy(temp, L"PATH=");
473
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000474 if (p == NULL || *p == NUL)
K.Takataf741e3e2023-05-15 16:41:40 +0100475 wcscat(temp, exe_pathw);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000476 else
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000477 {
K.Takataf741e3e2023-05-15 16:41:40 +0100478 wcscat(temp, p);
479
480 // Check if exe_path is already included in $PATH.
481 if (wcsstr(temp, exe_pathw) == NULL)
482 {
483 // Append ';' if $PATH doesn't end with it.
484 size_t len = wcslen(temp);
485 if (temp[len - 1] != L';')
486 wcscat(temp, L";");
487
488 wcscat(temp, exe_pathw);
489 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000490 }
K.Takataf741e3e2023-05-15 16:41:40 +0100491 _wputenv(temp);
492#ifdef libintl_wputenv
493 libintl_wputenv(temp);
494#endif
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000495 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000496}
497
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200498/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100499 * Unescape characters in "p" that appear in "escaped".
500 */
501 static void
502unescape_shellxquote(char_u *p, char_u *escaped)
503{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100504 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100505 int n;
506
507 while (*p != NUL)
508 {
509 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
510 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100511 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100512 p += n;
513 l -= n;
514 }
515}
516
517/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200518 * Load library "name".
519 */
520 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000521vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200522{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200523 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200524
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200525 // No need to load any library when registering OLE.
526 if (found_register_arg)
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000527 return NULL;
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200528
Bram Moolenaar0f873732019-12-05 20:28:46 +0100529 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
530 // vimLoadLib() recursively, which causes a stack overflow.
K.Takatace3189d2023-02-15 19:13:43 +0000531 if (exe_pathw == NULL)
K.Takataf741e3e2023-05-15 16:41:40 +0100532 {
K.Takatace3189d2023-02-15 19:13:43 +0000533 mch_get_exe_name();
K.Takataf741e3e2023-05-15 16:41:40 +0100534 if (exe_pathw == NULL)
535 return NULL;
536 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000537
538 WCHAR old_dirw[MAXPATHL];
539
540 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) == 0)
541 return NULL;
542
543 // Change directory to where the executable is, both to make
544 // sure we find a .dll there and to avoid looking for a .dll
545 // in the current directory.
K.Takatace3189d2023-02-15 19:13:43 +0000546 SetCurrentDirectoryW(exe_pathw);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000547 dll = LoadLibrary(name);
548 SetCurrentDirectoryW(old_dirw);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200549 return dll;
550}
551
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200552#if defined(VIMDLL) || defined(PROTO)
553/*
554 * Check if the current executable file is for the GUI subsystem.
555 */
556 int
557mch_is_gui_executable(void)
558{
559 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
560 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
561 PIMAGE_NT_HEADERS pPE;
562
563 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
564 return FALSE;
565 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
566 if (pPE->Signature != IMAGE_NT_SIGNATURE)
567 return FALSE;
568 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
569 return TRUE;
570 return FALSE;
571}
572#endif
573
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000574#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
575 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100576/*
577 * Get related information about 'funcname' which is imported by 'hInst'.
578 * If 'info' is 0, return the function address.
579 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000580 * If 'info' is 2, hook the function with 'ptr', and return the original
581 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100582 */
583 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000584get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
585 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100586{
587 PBYTE pImage = (PBYTE)hInst;
588 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
589 PIMAGE_NT_HEADERS pPE;
590 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100591 PIMAGE_THUNK_DATA pIAT; // Import Address Table
592 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100593 PIMAGE_IMPORT_BY_NAME pImpName;
Ken Takata119fdd92023-10-04 20:05:05 +0200594 DWORD ImpVA;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100595
596 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
597 return NULL;
598 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
599 if (pPE->Signature != IMAGE_NT_SIGNATURE)
600 return NULL;
Ken Takata119fdd92023-10-04 20:05:05 +0200601
602 ImpVA = pPE->OptionalHeader
603 .DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
604 if (ImpVA == 0)
605 return NULL; // No Import Table
606 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage + ImpVA);
607
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100608 for (; pImpDesc->FirstThunk; ++pImpDesc)
609 {
610 if (!pImpDesc->OriginalFirstThunk)
611 continue;
612 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
613 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
614 for (; pIAT->u1.Function; ++pIAT, ++pINT)
615 {
616 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
617 continue;
618 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
619 + (UINT_PTR)(pINT->u1.AddressOfData));
620 if (strcmp((char *)pImpName->Name, funcname) == 0)
621 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000622 void *original;
623 DWORD old, new = PAGE_READWRITE;
624
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100625 switch (info)
626 {
627 case 0:
628 return (void *)pIAT->u1.Function;
629 case 1:
630 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000631 case 2:
632 original = (void *)pIAT->u1.Function;
633 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
634 new, &old);
635 pIAT->u1.Function = (UINT_PTR)ptr;
636 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
637 old, &new);
638 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100639 default:
640 return NULL;
641 }
642 }
643 }
644 }
645 return NULL;
646}
647
648/*
649 * Get the module handle which 'funcname' in 'hInst' is imported from.
650 */
651 HINSTANCE
652find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
653{
654 char *modulename;
655
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000656 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100657 if (modulename != NULL)
658 return GetModuleHandleA(modulename);
659 return NULL;
660}
661
662/*
663 * Get the address of 'funcname' which is imported by 'hInst' DLL.
664 */
665 void *
666get_dll_import_func(HINSTANCE hInst, const char *funcname)
667{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000668 return get_imported_func_info(hInst, funcname, 0, NULL);
669}
670
671/*
672 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
673 * and return the original function address.
674 */
675 void *
676hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
677{
678 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100679}
680#endif
681
Ken Takata119fdd92023-10-04 20:05:05 +0200682#if defined(FEAT_PYTHON3) || defined(PROTO)
683/*
684 * Check if the specified DLL is a function forwarder.
685 * If yes, return the instance of the forwarded DLL.
686 * If no, return the specified DLL.
687 * If error, return NULL.
688 * This assumes that the DLL forwards all the function to a single DLL.
689 */
690 HINSTANCE
691get_forwarded_dll(HINSTANCE hInst)
692{
693 PBYTE pImage = (PBYTE)hInst;
694 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
695 PIMAGE_NT_HEADERS pPE;
696 PIMAGE_EXPORT_DIRECTORY pExpDir;
697 DWORD ExpVA;
698 DWORD ExpSize;
699 LPDWORD pFunctionTable;
700
701 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
702 return NULL;
703 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
704 if (pPE->Signature != IMAGE_NT_SIGNATURE)
705 return NULL;
706
707 ExpVA = pPE->OptionalHeader
708 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
709 ExpSize = pPE->OptionalHeader
710 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
711 if (ExpVA == 0)
712 return hInst; // No Export Directory
713 pExpDir = (PIMAGE_EXPORT_DIRECTORY)(pImage + ExpVA);
714 pFunctionTable = (LPDWORD)(pImage + pExpDir->AddressOfFunctions);
715
716 if (pExpDir->NumberOfNames == 0)
717 return hInst; // No export names.
718
719 // Check only the first entry.
720 if ((pFunctionTable[0] < ExpVA) || (pFunctionTable[0] >= ExpVA + ExpSize))
721 // The first entry is not a function forwarder.
722 return hInst;
723
724 // The first entry is a function forwarder.
725 // The name is represented as "DllName.FunctionName".
726 const char *name = (const char *)(pImage + pFunctionTable[0]);
727 const char *p = strchr(name, '.');
728 if (p == NULL)
729 return hInst;
730
731 // Extract DllName.
732 char buf[MAX_PATH];
733 if (p - name + 1 > sizeof(buf))
734 return NULL;
735 strncpy(buf, name, p - name);
736 buf[p - name] = '\0';
737 return GetModuleHandleA(buf);
738}
739#endif
740
Bram Moolenaar071d4272004-06-13 20:20:40 +0000741#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
742# ifndef GETTEXT_DLL
743# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200744# define GETTEXT_DLL_ALT1 "libintl-8.dll"
745# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000746# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100747// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000748static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200749static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000750static char *null_libintl_textdomain(const char *);
751static char *null_libintl_bindtextdomain(const char *, const char *);
752static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100753static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000754
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200755static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000756char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200757char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
758 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000759char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
760char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000761 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000762char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
763 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100764int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000765
766 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100767dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000768{
769 int i;
770 static struct
771 {
772 char *name;
773 FARPROC *ptr;
774 } libintl_entry[] =
775 {
776 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200777 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000778 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
779 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
780 {NULL, NULL}
781 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100782 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000783
Bram Moolenaar7554c542018-10-06 15:03:15 +0200784 // No need to initialize twice.
785 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000786 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200787 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100788 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100789# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100790 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200791 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100792# endif
793# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200794 if (!hLibintlDLL)
795 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100796# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100797 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000798 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200799 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000800 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200801 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000802 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200803 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000804 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200805 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000806 }
807 for (i = 0; libintl_entry[i].name != NULL
808 && libintl_entry[i].ptr != NULL; ++i)
809 {
K.Takata54119102022-02-03 13:33:03 +0000810 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000811 libintl_entry[i].name)) == NULL)
812 {
813 dyn_libintl_end();
814 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000815 {
816 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000817 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000818 verbose_leave();
819 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000820 return 0;
821 }
822 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000823
Bram Moolenaar0f873732019-12-05 20:28:46 +0100824 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100825 dyn_libintl_bind_textdomain_codeset = (char *(*)(const char *, const char *))
826 GetProcAddress(hLibintlDLL, "bind_textdomain_codeset");
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000827 if (dyn_libintl_bind_textdomain_codeset == NULL)
828 dyn_libintl_bind_textdomain_codeset =
829 null_libintl_bind_textdomain_codeset;
830
Bram Moolenaar0f873732019-12-05 20:28:46 +0100831 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100832 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
833 if (hmsvcrt != NULL)
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100834 dyn_libintl_wputenv = (int (*)(const wchar_t *))
835 GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100836 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
837 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100838
Bram Moolenaar071d4272004-06-13 20:20:40 +0000839 return 1;
840}
841
842 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100843dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000844{
845 if (hLibintlDLL)
846 FreeLibrary(hLibintlDLL);
847 hLibintlDLL = NULL;
848 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200849 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000850 dyn_libintl_textdomain = null_libintl_textdomain;
851 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000852 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100853 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000854}
855
856 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000857null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000858{
859 return (char*)msgid;
860}
861
862 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200863null_libintl_ngettext(
864 const char *msgid,
865 const char *msgid_plural,
866 unsigned long n)
867{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200868 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200869}
870
Bram Moolenaaree695f72016-08-03 22:08:45 +0200871 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100872null_libintl_bindtextdomain(
873 const char *domainname UNUSED,
874 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000875{
876 return NULL;
877}
878
879 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100880null_libintl_bind_textdomain_codeset(
881 const char *domainname UNUSED,
882 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000883{
884 return NULL;
885}
886
887 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100888null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000889{
890 return NULL;
891}
892
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200893 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100894null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100895{
896 return 0;
897}
898
Bram Moolenaar0f873732019-12-05 20:28:46 +0100899#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000900
Bram Moolenaar0f873732019-12-05 20:28:46 +0100901// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000902
903#ifndef VER_PLATFORM_WIN32_WINDOWS
904# define VER_PLATFORM_WIN32_WINDOWS 1
905#endif
906
Bram Moolenaar071d4272004-06-13 20:20:40 +0000907#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100908# ifndef PROTO
909# include <aclapi.h>
910# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200911# ifndef PROTECTED_DACL_SECURITY_INFORMATION
912# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
913# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000914#endif
915
Bram Moolenaar27515922013-06-29 15:36:26 +0200916#ifdef HAVE_ACL
917/*
918 * Enables or disables the specified privilege.
919 */
920 static BOOL
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))
974 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))
991 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{
1965 int nCount = 0;
1966 while (nCount < nLength)
1967 {
1968 input_record_buffer.length++;
1969 input_record_buffer_node_T *event_node =
1970 malloc(sizeof(input_record_buffer_node_T));
1971 event_node->ir = irEvents[nCount++];
1972 event_node->next = NULL;
1973 if (input_record_buffer.tail == NULL)
1974 {
1975 input_record_buffer.head = event_node;
1976 input_record_buffer.tail = event_node;
1977 }
1978 else
1979 {
1980 input_record_buffer.tail->next = event_node;
1981 input_record_buffer.tail = input_record_buffer.tail->next;
1982 }
1983 }
1984 return nCount;
1985}
1986
1987 static int
1988read_input_record_buffer(INPUT_RECORD* irEvents, int nMaxLength)
1989{
1990 int nCount = 0;
1991 while (nCount < nMaxLength && input_record_buffer.head != NULL)
1992 {
1993 input_record_buffer.length--;
1994 input_record_buffer_node_T *pop_head = input_record_buffer.head;
1995 irEvents[nCount++] = pop_head->ir;
1996 input_record_buffer.head = pop_head->next;
1997 vim_free(pop_head);
1998 if (input_record_buffer.length == 0)
1999 input_record_buffer.tail = NULL;
2000 }
2001 return nCount;
2002}
Christopher Plewright20b795e2022-12-20 20:01:58 +00002003#endif // !FEAT_GUI_MSWIN || VIMDLL
2004
2005#ifdef FEAT_EVAL
2006/*
2007 * The 'test_mswin_event' function is for testing Vim's low-level handling of
2008 * user input events. ie, this manages the encoding of INPUT_RECORD events
2009 * so that we have a way to test how Vim decodes INPUT_RECORD events in Windows
2010 * consoles.
2011 *
2012 * The 'test_mswin_event' function is based on 'test_gui_event'. In fact, when
2013 * the Windows GUI is running, the arguments; 'event' and 'args', are the same.
2014 * So, it acts as an alias for 'test_gui_event' for the Windows GUI.
2015 *
2016 * When the Windows console is running, the arguments; 'event' and 'args', are
2017 * a subset of what 'test_gui_event' handles, ie, only "key" and "mouse"
2018 * events are encoded as INPUT_RECORD events.
2019 *
2020 * Note: INPUT_RECORDs are only used by the Windows console, not the GUI. The
2021 * GUI sends MSG structs instead.
2022 */
2023 int
2024test_mswin_event(char_u *event, dict_T *args)
2025{
2026 int lpEventsWritten = 0;
2027
2028# if defined(VIMDLL) || defined(FEAT_GUI_MSWIN)
2029 if (gui.in_use)
2030 return test_gui_w32_sendevent(event, args);
2031# endif
2032
2033# if defined(VIMDLL) || !defined(FEAT_GUI_MSWIN)
2034
2035// Currently implemented event record types are; KEY_EVENT and MOUSE_EVENT
2036// Potentially could also implement: FOCUS_EVENT and WINDOW_BUFFER_SIZE_EVENT
2037// Maybe also: MENU_EVENT
2038
2039 INPUT_RECORD ir;
2040 BOOL input_encoded = FALSE;
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002041 BOOL execute = FALSE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00002042 if (STRCMP(event, "key") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002043 {
2044 execute = dict_get_bool(args, "execute", FALSE);
2045 if (dict_has_key(args, "event"))
2046 input_encoded = encode_key_event(args, &ir);
2047 else if (!execute)
2048 {
2049 semsg(_(e_missing_argument_str), "event");
2050 return FALSE;
2051 }
2052 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002053 else if (STRCMP(event, "mouse") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002054 {
2055 execute = TRUE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00002056 input_encoded = encode_mouse_event(args, &ir);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002057 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002058 else
2059 {
2060 semsg(_(e_invalid_value_for_argument_str_str), "event", event);
2061 return FALSE;
2062 }
2063
2064 // Ideally, WriteConsoleInput would be used to inject these low-level
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00002065 // events. But, this doesn't work well in the CI test environment. So
Christopher Plewright20b795e2022-12-20 20:01:58 +00002066 // implementing an input_record_buffer instead.
2067 if (input_encoded)
2068 lpEventsWritten = write_input_record_buffer(&ir, 1);
2069
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002070 // Set flags to execute the event, ie. like feedkeys mode X.
2071 if (execute)
2072 {
2073 int save_msg_scroll = msg_scroll;
2074 // Avoid a 1 second delay when the keys start Insert mode.
2075 msg_scroll = FALSE;
2076 ch_log(NULL, "test_mswin_event() executing");
Christopher Plewright20b795e2022-12-20 20:01:58 +00002077 exec_normal(TRUE, TRUE, TRUE);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002078 msg_scroll |= save_msg_scroll;
2079 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002080
2081# endif
2082 return lpEventsWritten;
2083}
2084#endif // FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002085
2086#ifdef MCH_CURSOR_SHAPE
2087/*
2088 * Set the shape of the cursor.
2089 * 'thickness' can be from 1 (thin) to 99 (block)
2090 */
2091 static void
2092mch_set_cursor_shape(int thickness)
2093{
Christopher Plewright38804d62022-11-09 23:55:52 +00002094 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01002095 {
2096 if (*T_CSI == NUL)
2097 {
2098 // If 't_SI' is not set, use the default cursor styles.
2099 if (thickness < 50)
2100 vtp_printf("\033[3 q"); // underline
2101 else
2102 vtp_printf("\033[0 q"); // default
2103 }
2104 }
2105 else
2106 {
2107 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
2108 ConsoleCursorInfo.dwSize = thickness;
2109 ConsoleCursorInfo.bVisible = s_cursor_visible;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002110
K.Takatadf5320c2022-09-01 13:20:16 +01002111 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
2112 if (s_cursor_visible)
2113 SetConsoleCursorPosition(g_hConOut, g_coord);
2114 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002115}
2116
2117 void
2118mch_update_cursor(void)
2119{
2120 int idx;
2121 int thickness;
2122
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002123# ifdef VIMDLL
2124 if (gui.in_use)
2125 return;
2126# endif
2127
Bram Moolenaar071d4272004-06-13 20:20:40 +00002128 /*
2129 * How the cursor is drawn depends on the current mode.
2130 */
2131 idx = get_shape_idx(FALSE);
2132
2133 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002134 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00002135 else
2136 thickness = shape_table[idx].percentage;
2137 mch_set_cursor_shape(thickness);
2138}
2139#endif
2140
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002141#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002142/*
2143 * Handle FOCUS_EVENT.
2144 */
2145 static void
2146handle_focus_event(INPUT_RECORD ir)
2147{
2148 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
2149 ui_focus_change((int)g_fJustGotFocus);
2150}
2151
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002152static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
2153
Bram Moolenaar071d4272004-06-13 20:20:40 +00002154/*
2155 * Wait until console input from keyboard or mouse is available,
2156 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002157 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002158 * Return TRUE if something is available FALSE if not.
2159 */
2160 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002161WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002162{
2163 DWORD dwNow = 0, dwEndTime = 0;
2164 INPUT_RECORD ir;
2165 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002166 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002167# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02002168 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002169# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002170
2171 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002172 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002173 dwEndTime = GetTickCount() + msec;
2174 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002175 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002176 dwEndTime = INFINITE;
2177
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002178 // We need to loop until the end of the time period, because
2179 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002180 for (;;)
2181 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002182 // Only process messages when waiting.
2183 if (msec != 0)
2184 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002185# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002186 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002187# endif
2188# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002189 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002190# endif
2191# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002192 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002193# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002194 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002195
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02002196 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002197# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002198 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002199# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002200 )
2201 return TRUE;
2202
2203 if (msec > 0)
2204 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002205 // If the specified wait time has passed, return. Beware that
2206 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002207 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02002208 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002209 break;
2210 }
2211 if (msec != 0)
2212 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00002213 DWORD dwWaitTime = dwEndTime - dwNow;
2214
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002215 // Don't wait for more than 11 msec to avoid dropping characters,
2216 // check channel while waiting for input and handle a callback from
2217 // 'balloonexpr'.
2218 if (dwWaitTime > 11)
2219 dwWaitTime = 11;
2220
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002221# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002222 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002223 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002224# endif
2225# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002226 // When waiting very briefly don't trigger timers.
2227 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002228 {
2229 long due_time;
2230
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002231 // Trigger timers and then get the time in msec until the next
2232 // one is due. Wait up to that time.
2233 due_time = check_due_timer();
2234 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002235 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002236 // timer may have used feedkeys().
2237 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002238 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002239 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
2240 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002241 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002242# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002243 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002244# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002245 // Wait for either an event on the console input or a
2246 // message in the client-server window.
2247 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
2248 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002249# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002250 wait_for_single_object(g_hConIn, dwWaitTime)
2251 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002252# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002253 )
2254 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002255 }
2256
2257 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002258 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002259
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002260# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02002261 // May have to redraw if the cursor ends up in the wrong place.
2262 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01002263 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002264 {
2265 CONSOLE_SCREEN_BUFFER_INFO csbi;
2266
2267 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2268 {
2269 if (csbi.dwCursorPosition.Y != msg_row)
2270 {
matveyte08795e2021-05-07 15:00:17 +02002271 // The screen is now messed up, must redraw the command
2272 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002273 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02002274 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002275 redrawcmd();
2276 }
2277 }
2278 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002279# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002280
2281 if (cRecords > 0)
2282 {
2283 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
2284 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002285# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01002286 // Windows IME sends two '\n's with only one 'ENTER'. First:
2287 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00002288 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002289 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
2290 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002291 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002292 continue;
2293 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002294# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002295 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
2296 NULL, FALSE))
2297 return TRUE;
2298 }
2299
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002300 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002301
2302 if (ir.EventType == FOCUS_EVENT)
2303 handle_focus_event(ir);
2304 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002305 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002306 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
2307
Bram Moolenaar36698e32019-12-11 22:57:40 +01002308 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002309 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002310 if (dwSize.X != Columns || dwSize.Y != Rows)
2311 {
2312 CONSOLE_SCREEN_BUFFER_INFO csbi;
2313 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01002314 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002315 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01002316 if (dwSize.X != Columns || dwSize.Y != Rows)
2317 {
2318 ResizeConBuf(g_hConOut, dwSize);
2319 shell_resized();
2320 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002321 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002322 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002323 else if (ir.EventType == MOUSE_EVENT
2324 && decode_mouse_event(&ir.Event.MouseEvent))
2325 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002326 }
2327 else if (msec == 0)
2328 break;
2329 }
2330
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002331# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01002332 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002333 if (input_available())
2334 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002335# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002336
Bram Moolenaar071d4272004-06-13 20:20:40 +00002337 return FALSE;
2338}
2339
Bram Moolenaar071d4272004-06-13 20:20:40 +00002340/*
2341 * return non-zero if a character is available
2342 */
2343 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002344mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002345{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002346# ifdef VIMDLL
2347 if (gui.in_use)
2348 return TRUE;
2349# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002350 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002351}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002352
2353# if defined(FEAT_TERMINAL) || defined(PROTO)
2354/*
2355 * Check for any pending input or messages.
2356 */
2357 int
2358mch_check_messages(void)
2359{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002360# ifdef VIMDLL
2361 if (gui.in_use)
2362 return TRUE;
2363# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002364 return WaitForChar(0L, TRUE);
2365}
2366# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002367
2368/*
2369 * Create the console input. Used when reading stdin doesn't work.
2370 */
2371 static void
2372create_conin(void)
2373{
2374 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
2375 FILE_SHARE_READ|FILE_SHARE_WRITE,
2376 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002377 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002378 did_create_conin = TRUE;
2379}
2380
2381/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002382 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002383 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002384 static WCHAR
2385tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002386{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002387 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002388
2389 for (;;)
2390 {
2391 INPUT_RECORD ir;
2392 DWORD cRecords = 0;
2393
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002394# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002395 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002396 if (input_available())
2397 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002398 if (g_nMouseClick != -1)
2399 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002400# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002401 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002402 {
2403 if (did_create_conin)
2404 read_error_exit();
2405 create_conin();
2406 continue;
2407 }
2408
2409 if (ir.EventType == KEY_EVENT)
2410 {
2411 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
2412 pmodifiers, TRUE))
2413 return ch;
2414 }
2415 else if (ir.EventType == FOCUS_EVENT)
2416 handle_focus_event(ir);
2417 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
2418 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002419 else if (ir.EventType == MOUSE_EVENT)
2420 {
2421 if (decode_mouse_event(&ir.Event.MouseEvent))
2422 return 0;
2423 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002424 }
2425}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002426#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002427
2428
2429/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02002430 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002431 * Get one or more characters from the keyboard or the mouse.
2432 * If time == 0, do not wait for characters.
2433 * If time == n, wait a short time for characters.
2434 * If time == -1, wait forever for characters.
2435 * Returns the number of characters read into buf.
2436 */
2437 int
2438mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002439 char_u *buf UNUSED,
2440 int maxlen UNUSED,
2441 long time UNUSED,
2442 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002443{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002444#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002445
2446 int len;
2447 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002448# ifdef VIMDLL
2449// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
2450# define TYPEAHEADSPACE 6
2451# else
2452# define TYPEAHEADSPACE 0
2453# endif
2454# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002455 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002456 static int typeaheadlen = 0;
2457
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002458# ifdef VIMDLL
2459 if (gui.in_use)
2460 return 0;
2461# endif
2462
Bram Moolenaar0f873732019-12-05 20:28:46 +01002463 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002464 if (typeaheadlen > 0)
2465 goto theend;
2466
Bram Moolenaar071d4272004-06-13 20:20:40 +00002467 if (time >= 0)
2468 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002469 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00002470 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002471 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01002472 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00002473 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002474 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00002475
Bram Moolenaar3918c952005-03-15 22:34:55 +00002476 /*
2477 * If there is no character available within 2 seconds (default)
2478 * write the autoscript file to disk. Or cause the CursorHold event
2479 * to be triggered.
2480 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002481 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002482 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00002483 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002484 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00002485 buf[0] = K_SPECIAL;
2486 buf[1] = KS_EXTRA;
2487 buf[2] = (int)KE_CURSORHOLD;
2488 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002489 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00002490 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002491 }
2492 }
2493
2494 /*
2495 * Try to read as many characters as there are, until the buffer is full.
2496 */
2497
Bram Moolenaar0f873732019-12-05 20:28:46 +01002498 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002499 g_fCBrkPressed = FALSE;
2500
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002501# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002502 if (fdDump)
2503 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002504# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002505
Bram Moolenaar0f873732019-12-05 20:28:46 +01002506 // Keep looping until there is something in the typeahead buffer and more
2507 // to get and still room in the buffer (up to two bytes for a char and
2508 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002509 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01002510 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002511 {
2512 if (typebuf_changed(tb_change_cnt))
2513 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002514 // "buf" may be invalid now if a client put something in the
2515 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002516 typeaheadlen = 0;
2517 break;
2518 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519 if (g_nMouseClick != -1)
2520 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002521# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002522 if (fdDump)
2523 fprintf(fdDump, "{%02x @ %d, %d}",
2524 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002525# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01002526 char_u modifiers = ((char_u *)(&g_nMouseClick))[0];
2527 char_u scroll_dir = ((char_u *)(&g_nMouseClick))[1];
2528
2529 if (scroll_dir == KE_MOUSEDOWN
2530 || scroll_dir == KE_MOUSEUP
2531 || scroll_dir == KE_MOUSELEFT
2532 || scroll_dir == KE_MOUSERIGHT)
2533 {
2534 if (modifiers > 0)
2535 {
Christopher Plewright03193062022-11-22 12:58:27 +00002536 // use K_SPECIAL instead of CSI to make mappings work
2537 typeahead[typeaheadlen++] = K_SPECIAL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002538 typeahead[typeaheadlen++] = KS_MODIFIER;
2539 typeahead[typeaheadlen++] = modifiers;
2540 }
2541 typeahead[typeaheadlen++] = CSI;
2542 typeahead[typeaheadlen++] = KS_EXTRA;
2543 typeahead[typeaheadlen++] = scroll_dir;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002544 }
2545 else
2546 {
2547 typeahead[typeaheadlen++] = ESC + 128;
2548 typeahead[typeaheadlen++] = 'M';
2549 typeahead[typeaheadlen++] = g_nMouseClick;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002550 }
Christopher Plewright36446bb2022-11-23 22:28:08 +00002551
2552 // Pass the pointer coordinates of the mouse event in 2 bytes,
2553 // allowing for > 223 columns. Both for click and scroll events.
2554 // This is the same as what is used for the GUI.
2555 typeahead[typeaheadlen++] = (char_u)(g_xMouse / 128 + ' ' + 1);
2556 typeahead[typeaheadlen++] = (char_u)(g_xMouse % 128 + ' ' + 1);
2557 typeahead[typeaheadlen++] = (char_u)(g_yMouse / 128 + ' ' + 1);
2558 typeahead[typeaheadlen++] = (char_u)(g_yMouse % 128 + ' ' + 1);
2559
2560 g_nMouseClick = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002561 }
2562 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002563 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002564 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002565 int modifiers = 0;
2566
2567 c = tgetch(&modifiers, &ch2);
2568
Christopher Plewrightc8b20492023-01-04 18:06:00 +00002569 c = simplify_key(c, &modifiers);
2570
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002571 // Some chars need adjustment when the Ctrl modifier is used.
2572 ++no_reduce_keys;
2573 c = may_adjust_key_for_ctrl(modifiers, c);
2574 --no_reduce_keys;
2575
2576 // remove the SHIFT modifier for keys where it's already included,
2577 // e.g., '(' and '*'
2578 modifiers = may_remove_shift_modifier(modifiers, c);
2579
Bram Moolenaar071d4272004-06-13 20:20:40 +00002580 if (typebuf_changed(tb_change_cnt))
2581 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002582 // "buf" may be invalid now if a client put something in the
2583 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002584 typeaheadlen = 0;
2585 break;
2586 }
2587
2588 if (c == Ctrl_C && ctrl_c_interrupts)
2589 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002590# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002591 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002592# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002593 got_int = TRUE;
2594 }
2595
Bram Moolenaar071d4272004-06-13 20:20:40 +00002596 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002597 {
2598 int n = 1;
2599
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002600 if (ch2 == NUL)
2601 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002602 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002603 char_u *p;
2604 WCHAR ch[2];
2605
2606 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002607 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002608 {
2609 ch[1] = tgetch(&modifiers, &ch2);
2610 n++;
2611 }
2612 p = utf16_to_enc(ch, &n);
2613 if (p != NULL)
2614 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002615 for (i = 0, j = 0; i < n; i++)
2616 {
2617 typeahead[typeaheadlen + j++] = p[i];
2618# ifdef VIMDLL
2619 if (p[i] == CSI)
2620 {
2621 typeahead[typeaheadlen + j++] = KS_EXTRA;
2622 typeahead[typeaheadlen + j++] = KE_CSI;
2623 }
2624# endif
2625 }
2626 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002627 vim_free(p);
2628 }
2629 }
2630 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002631 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002632 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002633# ifdef VIMDLL
2634 if (c == CSI)
2635 {
2636 typeahead[typeaheadlen + 1] = KS_EXTRA;
2637 typeahead[typeaheadlen + 2] = KE_CSI;
2638 n = 3;
2639 }
2640# endif
2641 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002642 if (ch2 != NUL)
2643 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002644 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002645 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002646 switch (ch2)
2647 {
2648 case (WCHAR)'\324': // SHIFT+Insert
2649 case (WCHAR)'\325': // CTRL+Insert
2650 case (WCHAR)'\327': // SHIFT+Delete
2651 case (WCHAR)'\330': // CTRL+Delete
2652 typeahead[typeaheadlen + n] = (char_u)ch2;
2653 n++;
2654 break;
2655
2656 default:
2657 typeahead[typeaheadlen + n] = 3;
2658 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2659 n += 2;
2660 break;
2661 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002662 }
2663 else
2664 {
2665 typeahead[typeaheadlen + n] = 3;
2666 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2667 n += 2;
2668 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002669 }
2670
Bram Moolenaar0f873732019-12-05 20:28:46 +01002671 // Use the ALT key to set the 8th bit of the character
2672 // when it's one byte, the 8th bit isn't set yet and not
2673 // using a double-byte encoding (would become a lead
2674 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002675 if ((modifiers & MOD_MASK_ALT)
2676 && n == 1
2677 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002678 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002679 )
2680 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002681 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2682 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002683 modifiers &= ~MOD_MASK_ALT;
2684 }
2685
2686 if (modifiers != 0)
2687 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002688 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002689 mch_memmove(typeahead + typeaheadlen + 3,
2690 typeahead + typeaheadlen, n);
2691 typeahead[typeaheadlen++] = K_SPECIAL;
2692 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2693 typeahead[typeaheadlen++] = modifiers;
2694 }
2695
2696 typeaheadlen += n;
2697
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002698# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002699 if (fdDump)
2700 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002701# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002702 }
2703 }
2704 }
2705
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002706# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002707 if (fdDump)
2708 {
2709 fputs("]\n", fdDump);
2710 fflush(fdDump);
2711 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002712# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002713
Bram Moolenaar071d4272004-06-13 20:20:40 +00002714theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002715 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002716 len = 0;
2717 while (len < maxlen && typeaheadlen > 0)
2718 {
2719 buf[len++] = typeahead[0];
2720 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2721 }
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00002722# ifdef FEAT_EVAL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002723 if (len > 0)
2724 {
2725 buf[len] = NUL;
2726 ch_log(NULL, "raw key input: \"%s\"", buf);
2727 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002728# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002729 return len;
2730
Bram Moolenaar0f873732019-12-05 20:28:46 +01002731#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002732 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002733#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002734}
2735
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002736/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002737 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002738 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2739 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002740 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002741 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002742 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002743executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002744{
LemonBoy40fd7e62022-05-05 20:18:16 +01002745 int attrs = win32_getattrs((char_u *)name);
2746
2747 // The file doesn't exist or is a folder.
2748 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2749 return FALSE;
2750 // Check if the file is an AppExecLink, a special alias used by Windows
2751 // Store for its apps.
2752 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002753 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002754 char_u *res = resolve_appexeclink((char_u *)name);
2755 if (res == NULL)
AmberArrf5d0f542023-08-20 20:03:45 +02002756 res = resolve_reparse_point((char_u *)name);
2757 if (res == NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002758 return FALSE;
2759 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002760 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002761 *path = res;
2762 else
2763 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002764 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002765 else if (path != NULL)
2766 *path = FullName_save((char_u *)name, FALSE);
2767 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002768}
2769
2770/*
2771 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2772 * If "use_path" is FALSE: Return TRUE if "name" exists.
2773 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2774 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2775 * the allocated memory.
2776 */
2777 static int
2778executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2779{
2780 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2781 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2782 // UTF-8.
2783 char_u buf[_MAX_PATH * 3];
2784 size_t len = STRLEN(name);
2785 size_t tmplen;
2786 char_u *p, *e, *e2;
2787 char_u *pathbuf = NULL;
2788 char_u *pathext = NULL;
2789 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002790 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002791 int noext = FALSE;
2792 int retval = FALSE;
2793
2794 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002795 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002796
2797 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002798 shname = gettail(p_sh);
2799 if (strstr((char *)shname, "sh") != NULL &&
2800 !(strstr((char *)shname, "powershell") != NULL
2801 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002802 noext = TRUE;
2803
2804 if (use_pathext)
2805 {
2806 pathext = mch_getenv("PATHEXT");
2807 if (pathext == NULL)
2808 pathext = (char_u *)".com;.exe;.bat;.cmd";
2809
2810 if (noext == FALSE)
2811 {
2812 /*
2813 * Loop over all extensions in $PATHEXT.
2814 * Check "name" ends with extension.
2815 */
2816 p = pathext;
2817 while (*p)
2818 {
2819 if (p[0] == ';'
2820 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2821 {
2822 // Skip empty or single ".".
2823 ++p;
2824 continue;
2825 }
2826 e = vim_strchr(p, ';');
2827 if (e == NULL)
2828 e = p + STRLEN(p);
2829 tmplen = e - p;
2830
2831 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2832 {
2833 noext = TRUE;
2834 break;
2835 }
2836
2837 p = e;
2838 }
2839 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002840 }
2841
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002842 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002843 if (pathext == NULL)
2844 pathext = (char_u *)".";
2845 else if (noext == TRUE)
2846 {
2847 if (pathextbuf == NULL)
2848 pathextbuf = alloc(STRLEN(pathext) + 3);
2849 if (pathextbuf == NULL)
2850 {
2851 retval = FALSE;
2852 goto theend;
2853 }
2854 STRCPY(pathextbuf, ".;");
2855 STRCAT(pathextbuf, pathext);
2856 pathext = pathextbuf;
2857 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002858
Bram Moolenaar95da1362020-05-30 18:37:55 +02002859 // Use $PATH when "use_path" is TRUE and "name" is basename.
2860 if (use_path && gettail((char_u *)name) == (char_u *)name)
2861 {
2862 p = mch_getenv("PATH");
2863 if (p != NULL)
2864 {
2865 pathbuf = alloc(STRLEN(p) + 3);
2866 if (pathbuf == NULL)
2867 {
2868 retval = FALSE;
2869 goto theend;
2870 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002871
2872 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2873 STRCPY(pathbuf, ".;");
2874 else
2875 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002876 STRCAT(pathbuf, p);
2877 }
2878 }
2879
2880 /*
2881 * Walk through all entries in $PATH to check if "name" exists there and
2882 * is an executable file.
2883 */
2884 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2885 while (*p)
2886 {
2887 if (*p == ';') // Skip empty entry
2888 {
2889 ++p;
2890 continue;
2891 }
2892 e = vim_strchr(p, ';');
2893 if (e == NULL)
2894 e = p + STRLEN(p);
2895
2896 if (e - p + len + 2 > sizeof(buf))
2897 {
2898 retval = FALSE;
2899 goto theend;
2900 }
2901 // A single "." that means current dir.
2902 if (e - p == 1 && *p == '.')
2903 STRCPY(buf, name);
2904 else
2905 {
2906 vim_strncpy(buf, p, e - p);
2907 add_pathsep(buf);
2908 STRCAT(buf, name);
2909 }
2910 tmplen = STRLEN(buf);
2911
2912 /*
2913 * Loop over all extensions in $PATHEXT.
2914 * Check "name" with extension added.
2915 */
2916 p = pathext;
2917 while (*p)
2918 {
2919 if (*p == ';')
2920 {
2921 // Skip empty entry
2922 ++p;
2923 continue;
2924 }
2925 e2 = vim_strchr(p, (int)';');
2926 if (e2 == NULL)
2927 e2 = p + STRLEN(p);
2928
2929 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2930 {
2931 // Not a single "." that means no extension is added.
2932 if (e2 - p + tmplen + 1 > sizeof(buf))
2933 {
2934 retval = FALSE;
2935 goto theend;
2936 }
2937 vim_strncpy(buf + tmplen, p, e2 - p);
2938 }
2939 if (executable_file((char *)buf, path))
2940 {
2941 retval = TRUE;
2942 goto theend;
2943 }
2944
2945 p = e2;
2946 }
2947
2948 p = e;
2949 }
2950
2951theend:
2952 free(pathextbuf);
2953 free(pathbuf);
2954 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002955}
2956
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002957#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2958 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002959/*
2960 * Bad parameter handler.
2961 *
2962 * Certain MS CRT functions will intentionally crash when passed invalid
2963 * parameters to highlight possible security holes. Setting this function as
2964 * the bad parameter handler will prevent the crash.
2965 *
2966 * In debug builds the parameters contain CRT information that might help track
2967 * down the source of a problem, but in non-debug builds the arguments are all
2968 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2969 * worth allowing these to make debugging of issues easier.
2970 */
2971 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002972bad_param_handler(const wchar_t *expression UNUSED,
2973 const wchar_t *function UNUSED,
2974 const wchar_t *file UNUSED,
2975 unsigned int line UNUSED,
2976 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002977{
2978}
2979
2980# define SET_INVALID_PARAM_HANDLER \
2981 ((void)_set_invalid_parameter_handler(bad_param_handler))
2982#else
2983# define SET_INVALID_PARAM_HANDLER
2984#endif
2985
Bram Moolenaar4f974752019-02-17 17:44:42 +01002986#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002987
2988/*
2989 * GUI version of mch_init().
2990 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002991 static void
2992mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002993{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002994# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002995 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002996# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002997
Bram Moolenaar0f873732019-12-05 20:28:46 +01002998 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002999 SET_INVALID_PARAM_HANDLER;
3000
Bram Moolenaar0f873732019-12-05 20:28:46 +01003001 // Let critical errors result in a failure, not in a dialog box. Required
3002 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003003 SetErrorMode(SEM_FAILCRITICALERRORS);
3004
Bram Moolenaar0f873732019-12-05 20:28:46 +01003005 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00003006
Bram Moolenaar0f873732019-12-05 20:28:46 +01003007 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00003008 Rows = 25;
3009 Columns = 80;
3010
Bram Moolenaar0f873732019-12-05 20:28:46 +01003011 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00003012 {
3013 char_u vimrun_location[_MAX_PATH + 4];
3014
Bram Moolenaar0f873732019-12-05 20:28:46 +01003015 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00003016 STRCPY(vimrun_location, exe_name);
3017 STRCPY(gettail(vimrun_location), "vimrun.exe");
3018 if (mch_getperm(vimrun_location) >= 0)
3019 {
3020 if (*skiptowhite(vimrun_location) != NUL)
3021 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01003022 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003023 mch_memmove(vimrun_location + 1, vimrun_location,
3024 STRLEN(vimrun_location) + 1);
3025 *vimrun_location = '"';
3026 STRCPY(gettail(vimrun_location), "vimrun\" ");
3027 }
3028 else
3029 STRCPY(gettail(vimrun_location), "vimrun ");
3030
3031 vimrun_path = (char *)vim_strsave(vimrun_location);
3032 s_dont_use_vimrun = FALSE;
3033 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02003034 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003035 s_dont_use_vimrun = FALSE;
3036
Bram Moolenaar0f873732019-12-05 20:28:46 +01003037 // Don't give the warning for a missing vimrun.exe right now, but only
3038 // when vimrun was supposed to be used. Don't bother people that do
3039 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003040 if (s_dont_use_vimrun)
3041 need_vimrun_warning = TRUE;
3042 }
3043
3044 /*
3045 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
3046 * Otherwise the default "findstr /n" is used.
3047 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02003048 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01003049 set_option_value_give_err((char_u *)"grepprg",
3050 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003051
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003052# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003053 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003054# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003055
3056 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003057}
3058
3059
Bram Moolenaar0f873732019-12-05 20:28:46 +01003060#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003061
3062#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003063
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003064# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
3065# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003066
3067/*
3068 * ClearConsoleBuffer()
3069 * Description:
3070 * Clears the entire contents of the console screen buffer, using the
3071 * specified attribute.
3072 * Returns:
3073 * TRUE on success
3074 */
3075 static BOOL
3076ClearConsoleBuffer(WORD wAttribute)
3077{
3078 CONSOLE_SCREEN_BUFFER_INFO csbi;
3079 COORD coord;
3080 DWORD NumCells, dummy;
3081
3082 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3083 return FALSE;
3084
3085 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
3086 coord.X = 0;
3087 coord.Y = 0;
3088 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
3089 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003090 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003091 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
3092 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003093 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003094
3095 return TRUE;
3096}
3097
3098/*
3099 * FitConsoleWindow()
3100 * Description:
3101 * Checks if the console window will fit within given buffer dimensions.
3102 * Also, if requested, will shrink the window to fit.
3103 * Returns:
3104 * TRUE on success
3105 */
3106 static BOOL
3107FitConsoleWindow(
3108 COORD dwBufferSize,
3109 BOOL WantAdjust)
3110{
3111 CONSOLE_SCREEN_BUFFER_INFO csbi;
3112 COORD dwWindowSize;
3113 BOOL NeedAdjust = FALSE;
3114
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003115 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3116 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003117
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003118 /*
3119 * A buffer resize will fail if the current console window does
3120 * not lie completely within that buffer. To avoid this, we might
3121 * have to move and possibly shrink the window.
3122 */
3123 if (csbi.srWindow.Right >= dwBufferSize.X)
3124 {
3125 dwWindowSize.X = SRWIDTH(csbi.srWindow);
3126 if (dwWindowSize.X > dwBufferSize.X)
3127 dwWindowSize.X = dwBufferSize.X;
3128 csbi.srWindow.Right = dwBufferSize.X - 1;
3129 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
3130 NeedAdjust = TRUE;
3131 }
3132 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
3133 {
3134 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
3135 if (dwWindowSize.Y > dwBufferSize.Y)
3136 dwWindowSize.Y = dwBufferSize.Y;
3137 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
3138 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
3139 NeedAdjust = TRUE;
3140 }
3141 if (NeedAdjust && WantAdjust)
3142 {
3143 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
3144 return FALSE;
3145 }
3146 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003147}
3148
3149typedef struct ConsoleBufferStruct
3150{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003151 BOOL IsValid;
3152 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003153 PCHAR_INFO Buffer;
3154 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003155 PSMALL_RECT Regions;
3156 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003157} ConsoleBuffer;
3158
3159/*
3160 * SaveConsoleBuffer()
3161 * Description:
3162 * Saves important information about the console buffer, including the
3163 * actual buffer contents. The saved information is suitable for later
3164 * restoration by RestoreConsoleBuffer().
3165 * Returns:
3166 * TRUE if all information was saved; FALSE otherwise
3167 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
3168 */
3169 static BOOL
3170SaveConsoleBuffer(
3171 ConsoleBuffer *cb)
3172{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003173 DWORD NumCells;
3174 COORD BufferCoord;
3175 SMALL_RECT ReadRegion;
3176 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003177 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003178
Bram Moolenaar071d4272004-06-13 20:20:40 +00003179 if (cb == NULL)
3180 return FALSE;
3181
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003182 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003183 {
3184 cb->IsValid = FALSE;
3185 return FALSE;
3186 }
3187 cb->IsValid = TRUE;
3188
Christopher Plewright1140b512022-11-12 18:46:05 +00003189 // VTP uses alternate screen buffer.
3190 // No need to save buffer contents for restoration.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003191 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003192 return TRUE;
3193
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003194 /*
3195 * Allocate a buffer large enough to hold the entire console screen
3196 * buffer. If this ConsoleBuffer structure has already been initialized
3197 * with a buffer of the correct size, then just use that one.
3198 */
3199 if (!cb->IsValid || cb->Buffer == NULL ||
3200 cb->BufferSize.X != cb->Info.dwSize.X ||
3201 cb->BufferSize.Y != cb->Info.dwSize.Y)
3202 {
3203 cb->BufferSize.X = cb->Info.dwSize.X;
3204 cb->BufferSize.Y = cb->Info.dwSize.Y;
3205 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
3206 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003207 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003208 if (cb->Buffer == NULL)
3209 return FALSE;
3210 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003211
3212 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003213 * We will now copy the console screen buffer into our buffer.
3214 * ReadConsoleOutput() seems to be limited as far as how much you
3215 * can read at a time. Empirically, this number seems to be about
3216 * 12000 cells (rows * columns). Start at position (0, 0) and copy
3217 * in chunks until it is all copied. The chunks will all have the
3218 * same horizontal characteristics, so initialize them now. The
3219 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003220 */
Bram Moolenaar61594242015-09-01 20:23:37 +02003221 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003222 ReadRegion.Left = 0;
3223 ReadRegion.Right = cb->Info.dwSize.X - 1;
3224 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003225
3226 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
3227 if (cb->Regions == NULL || numregions != cb->NumRegions)
3228 {
3229 cb->NumRegions = numregions;
3230 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003231 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003232 if (cb->Regions == NULL)
3233 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003234 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003235 return FALSE;
3236 }
3237 }
3238
3239 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003240 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003241 /*
3242 * Read into position (0, Y) in our buffer.
3243 */
3244 BufferCoord.Y = Y;
3245 /*
3246 * Read the region whose top left corner is (0, Y) and whose bottom
3247 * right corner is (width - 1, Y + Y_incr - 1). This should define
3248 * a region of size width by Y_incr. Don't worry if this region is
3249 * too large for the remaining buffer; it will be cropped.
3250 */
3251 ReadRegion.Top = Y;
3252 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003253 if (!ReadConsoleOutputW(g_hConOut, // output handle
3254 cb->Buffer, // our buffer
3255 cb->BufferSize, // dimensions of our buffer
3256 BufferCoord, // offset in our buffer
3257 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003258 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003259 VIM_CLEAR(cb->Buffer);
3260 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003261 return FALSE;
3262 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02003263 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003264 }
3265
3266 return TRUE;
3267}
3268
3269/*
3270 * RestoreConsoleBuffer()
3271 * Description:
3272 * Restores important information about the console buffer, including the
3273 * actual buffer contents, if desired. The information to restore is in
3274 * the same format used by SaveConsoleBuffer().
3275 * Returns:
3276 * TRUE on success
3277 */
3278 static BOOL
3279RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003280 ConsoleBuffer *cb,
3281 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003282{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003283 COORD BufferCoord;
3284 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003285 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003286
Christopher Plewright1140b512022-11-12 18:46:05 +00003287
Bram Moolenaar071d4272004-06-13 20:20:40 +00003288 if (cb == NULL || !cb->IsValid)
3289 return FALSE;
3290
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003291 /*
3292 * Before restoring the buffer contents, clear the current buffer, and
3293 * restore the cursor position and window information. Doing this now
3294 * prevents old buffer contents from "flashing" onto the screen.
3295 */
3296 if (RestoreScreen)
3297 ClearConsoleBuffer(cb->Info.wAttributes);
3298
3299 FitConsoleWindow(cb->Info.dwSize, TRUE);
3300 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
3301 return FALSE;
3302 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
3303 return FALSE;
3304
3305 if (!RestoreScreen)
3306 {
3307 /*
3308 * No need to restore the screen buffer contents, so we're done.
3309 */
3310 return TRUE;
3311 }
3312
3313 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
3314 return FALSE;
3315 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
3316 return FALSE;
3317
Christopher Plewrightab281f82025-03-16 19:14:31 +01003318 // VTP uses alternate screen buffer.
3319 // No need to restore buffer contents.
3320 if (use_alternate_screen_buffer)
3321 return TRUE;
3322
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003323 /*
3324 * Restore the screen buffer contents.
3325 */
3326 if (cb->Buffer != NULL)
3327 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003328 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003329 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003330 BufferCoord.X = cb->Regions[i].Left;
3331 BufferCoord.Y = cb->Regions[i].Top;
3332 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01003333 if (!WriteConsoleOutputW(g_hConOut, // output handle
3334 cb->Buffer, // our buffer
3335 cb->BufferSize, // dimensions of our buffer
3336 BufferCoord, // offset in our buffer
3337 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02003338 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003339 }
3340 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003341
3342 return TRUE;
3343}
3344
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003345# define FEAT_RESTORE_ORIG_SCREEN
3346# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003347static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003348# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003349static ConsoleBuffer g_cbNonTermcap = { 0 };
3350static ConsoleBuffer g_cbTermcap = { 0 };
3351
Bram Moolenaar071d4272004-06-13 20:20:40 +00003352char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01003353HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00003354static HICON g_hOrigIconSmall = NULL;
3355static HICON g_hOrigIcon = NULL;
3356static HICON g_hVimIcon = NULL;
3357static BOOL g_fCanChangeIcon = FALSE;
3358
Bram Moolenaar071d4272004-06-13 20:20:40 +00003359/*
3360 * GetConsoleIcon()
3361 * Description:
3362 * Attempts to retrieve the small icon and/or the big icon currently in
3363 * use by a given window.
3364 * Returns:
3365 * TRUE on success
3366 */
3367 static BOOL
3368GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003369 HWND hWnd,
3370 HICON *phIconSmall,
3371 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003372{
3373 if (hWnd == NULL)
3374 return FALSE;
3375
3376 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003377 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
3378 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003379 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003380 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
3381 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003382 return TRUE;
3383}
3384
3385/*
3386 * SetConsoleIcon()
3387 * Description:
3388 * Attempts to change the small icon and/or the big icon currently in
3389 * use by a given window.
3390 * Returns:
3391 * TRUE on success
3392 */
3393 static BOOL
3394SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003395 HWND hWnd,
3396 HICON hIconSmall,
3397 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003398{
Bram Moolenaar071d4272004-06-13 20:20:40 +00003399 if (hWnd == NULL)
3400 return FALSE;
3401
3402 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003403 SendMessage(hWnd, WM_SETICON,
3404 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003405 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003406 SendMessage(hWnd, WM_SETICON,
3407 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003408 return TRUE;
3409}
3410
3411/*
3412 * SaveConsoleTitleAndIcon()
3413 * Description:
3414 * Saves the current console window title in g_szOrigTitle, for later
3415 * restoration. Also, attempts to obtain a handle to the console window,
3416 * and use it to save the small and big icons currently in use by the
3417 * console window. This is not always possible on some versions of Windows;
3418 * nor is it possible when running Vim remotely using Telnet (since the
3419 * console window the user sees is owned by a remote process).
3420 */
3421 static void
3422SaveConsoleTitleAndIcon(void)
3423{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003424 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003425 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
3426 return;
3427
3428 /*
3429 * Obtain a handle to the console window using GetConsoleWindow() from
3430 * KERNEL32.DLL; we need to handle in order to change the window icon.
3431 * This function only exists on NT-based Windows, starting with Windows
3432 * 2000. On older operating systems, we can't change the window icon
3433 * anyway.
3434 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003435 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003436 if (g_hWnd == NULL)
3437 return;
3438
Bram Moolenaar0f873732019-12-05 20:28:46 +01003439 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003440 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
3441 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
3442 return;
3443
Bram Moolenaar0f873732019-12-05 20:28:46 +01003444 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01003445 if (
3446# ifdef FEAT_LIBCALL
3447 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
3448# endif
3449 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003450 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003451 if (g_hVimIcon != NULL)
3452 g_fCanChangeIcon = TRUE;
3453}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003454
3455static int g_fWindInitCalled = FALSE;
3456static int g_fTermcapMode = FALSE;
3457static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003458
3459/*
3460 * non-GUI version of mch_init().
3461 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003462 static void
3463mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003464{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003465# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003466 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003467# endif
3468# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00003469 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003470# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003471
Bram Moolenaar0f873732019-12-05 20:28:46 +01003472 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02003473 SET_INVALID_PARAM_HANDLER;
3474
Bram Moolenaar0f873732019-12-05 20:28:46 +01003475 // Let critical errors result in a failure, not in a dialog box. Required
3476 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003477 SetErrorMode(SEM_FAILCRITICALERRORS);
3478
Bram Moolenaar0f873732019-12-05 20:28:46 +01003479 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00003480 out_flush();
3481
Bram Moolenaar0f873732019-12-05 20:28:46 +01003482 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00003483 if (read_cmd_fd == 0)
3484 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
3485 else
3486 create_conin();
3487 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
3488
Christopher Plewright38804d62022-11-09 23:55:52 +00003489 wt_init();
3490 vtp_flag_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003491# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01003492 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003493 SaveConsoleBuffer(&g_cbOrig);
3494 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003495# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01003496 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003497 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
3498 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003499# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003500 if (cterm_normal_fg_color == 0)
3501 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
3502 if (cterm_normal_bg_color == 0)
3503 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
3504
Bram Moolenaarbdace832019-03-02 10:13:42 +01003505 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02003506 g_color_index_fg = g_attrDefault & 0xf;
3507 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
3508
Bram Moolenaar0f873732019-12-05 20:28:46 +01003509 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00003510 update_tcap(g_attrCurrent);
3511
3512 GetConsoleCursorInfo(g_hConOut, &g_cci);
3513 GetConsoleMode(g_hConIn, &g_cmodein);
3514 GetConsoleMode(g_hConOut, &g_cmodeout);
3515
Bram Moolenaar071d4272004-06-13 20:20:40 +00003516 SaveConsoleTitleAndIcon();
3517 /*
3518 * Set both the small and big icons of the console window to Vim's icon.
3519 * Note that Vim presently only has one size of icon (32x32), but it
3520 * automatically gets scaled down to 16x16 when setting the small icon.
3521 */
3522 if (g_fCanChangeIcon)
3523 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003524
3525 ui_get_shellsize();
3526
Christopher Plewrightd343c602023-01-22 18:58:30 +00003527 vtp_init();
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00003528 // Switch to a new alternate screen buffer.
3529 if (use_alternate_screen_buffer)
3530 vtp_printf("\033[?1049h");
Christopher Plewrightd343c602023-01-22 18:58:30 +00003531
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003532# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003533 fdDump = fopen("dump", "wt");
3534
3535 if (fdDump)
3536 {
3537 time_t t;
3538
3539 time(&t);
3540 fputs(ctime(&t), fdDump);
3541 fflush(fdDump);
3542 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003543# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003544
3545 g_fWindInitCalled = TRUE;
3546
Bram Moolenaar071d4272004-06-13 20:20:40 +00003547 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003548
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003549# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003550 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003551# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003552}
3553
3554/*
3555 * non-GUI version of mch_exit().
3556 * Shut down and exit with status `r'
3557 * Careful: mch_exit() may be called before mch_init()!
3558 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003559 static void
3560mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003561{
William Breslerded59132024-10-08 21:30:48 +02003562 // Copy flag since stoptermcap() will clear the flag.
3563 int fTermcapMode = g_fTermcapMode;
3564
Bram Moolenaar955f1982017-02-05 15:10:51 +01003565 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003566
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003567 vtp_exit();
3568
Bram Moolenaar955f1982017-02-05 15:10:51 +01003569 stoptermcap();
William Breslerded59132024-10-08 21:30:48 +02003570 // Switch back to main screen buffer if TermcapMode was not active.
3571 if (!fTermcapMode && use_alternate_screen_buffer)
Ken Takata568cbc92024-08-07 21:18:24 +02003572 vtp_printf("\033[?1049l");
3573
Bram Moolenaar071d4272004-06-13 20:20:40 +00003574 if (g_fWindInitCalled)
3575 settmode(TMODE_COOK);
3576
Bram Moolenaar0f873732019-12-05 20:28:46 +01003577 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00003578
3579 if (g_fWindInitCalled)
3580 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02003581 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003582 /*
3583 * Restore both the small and big icons of the console window to
3584 * what they were at startup. Don't do this when the window is
3585 * closed, Vim would hang here.
3586 */
3587 if (g_fCanChangeIcon && !g_fForceExit)
3588 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003589
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003590# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003591 if (fdDump)
3592 {
3593 time_t t;
3594
3595 time(&t);
3596 fputs(ctime(&t), fdDump);
3597 fclose(fdDump);
3598 }
3599 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003600# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003601 }
3602
3603 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003604 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003605 SetConsoleMode(g_hConOut, g_cmodeout);
3606
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003607# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003608 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003609# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003610
3611 exit(r);
3612}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003613#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003614
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003615 void
3616mch_init(void)
3617{
3618#ifdef VIMDLL
3619 if (gui.starting)
3620 mch_init_g();
3621 else
3622 mch_init_c();
3623#elif defined(FEAT_GUI_MSWIN)
3624 mch_init_g();
3625#else
3626 mch_init_c();
3627#endif
3628}
3629
3630 void
3631mch_exit(int r)
3632{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003633#ifdef FEAT_NETBEANS_INTG
3634 netbeans_send_disconnect();
3635#endif
3636
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003637#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003638 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003639 mch_exit_g(r);
3640 else
3641 mch_exit_c(r);
3642#elif defined(FEAT_GUI_MSWIN)
3643 mch_exit_g(r);
3644#else
3645 mch_exit_c(r);
3646#endif
3647}
3648
Bram Moolenaar071d4272004-06-13 20:20:40 +00003649/*
3650 * Do we have an interactive window?
3651 */
3652 int
3653mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003654 int argc UNUSED,
3655 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003656{
K.Takatace3189d2023-02-15 19:13:43 +00003657 mch_get_exe_name();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003658
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003659#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003660 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003661#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003662# ifdef VIMDLL
3663 if (gui.in_use)
3664 return OK;
3665# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003666 if (isatty(1))
3667 return OK;
3668 return FAIL;
3669#endif
3670}
3671
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003672/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003673 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003674 * When "len" is > 0, also expand short to long filenames.
3675 */
3676 void
3677fname_case(
3678 char_u *name,
3679 int len)
3680{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003681 int flen;
3682 WCHAR *p;
3683 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003684
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003685 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003686 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003687 return;
3688
3689 slash_adjust(name);
3690
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003691 p = enc_to_utf16(name, NULL);
3692 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003693 return;
3694
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003695 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003696 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003697 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003698
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003699 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003700 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003701 if (len > 0 || flen >= (int)STRLEN(q))
3702 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3703 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003704 }
3705 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003706 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003707}
3708
3709
3710/*
3711 * Insert user name in s[len].
3712 */
3713 int
3714mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003715 char_u *s,
3716 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003717{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003718 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003719 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003720
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003721 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003722 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003723 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003724
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003725 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003726 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003727 vim_strncpy(s, p, len - 1);
3728 vim_free(p);
3729 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003730 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003731 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003732 s[0] = NUL;
3733 return FAIL;
3734}
3735
3736
3737/*
3738 * Insert host name in s[len].
3739 */
3740 void
3741mch_get_host_name(
3742 char_u *s,
3743 int len)
3744{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003745 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003746 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003747
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003748 if (!GetComputerNameW(wszHostName, &wcch))
3749 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003750
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003751 char_u *p = utf16_to_enc(wszHostName, NULL);
3752 if (p == NULL)
3753 return;
3754
3755 vim_strncpy(s, p, len - 1);
3756 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003757}
3758
3759
3760/*
3761 * return process ID
3762 */
3763 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003764mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003765{
3766 return (long)GetCurrentProcessId();
3767}
3768
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003769/*
3770 * return TRUE if process "pid" is still running
3771 */
3772 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003773mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003774{
3775 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3776 DWORD status = 0;
3777 int ret = FALSE;
3778
3779 if (hProcess == NULL)
3780 return FALSE; // might not have access
3781 if (GetExitCodeProcess(hProcess, &status) )
3782 ret = status == STILL_ACTIVE;
3783 CloseHandle(hProcess);
3784 return ret;
3785}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003786
3787/*
3788 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3789 * Return OK for success, FAIL for failure.
3790 */
3791 int
3792mch_dirname(
3793 char_u *buf,
3794 int len)
3795{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003796 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003797
Bram Moolenaar071d4272004-06-13 20:20:40 +00003798 /*
3799 * Originally this was:
3800 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3801 * But the Win32s known bug list says that getcwd() doesn't work
3802 * so use the Win32 system call instead. <Negri>
3803 */
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003804 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) == 0)
3805 return FAIL;
3806
3807 WCHAR wcbuf[_MAX_PATH + 1];
3808 char_u *p = NULL;
3809
3810 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003811 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003812 p = utf16_to_enc(wcbuf, NULL);
John Marriott031f2272025-04-23 20:56:08 +02003813 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003814 {
John Marriott031f2272025-04-23 20:56:08 +02003815 if (STRLEN(p) >= (size_t)len)
3816 {
3817 // long path name is too long, fall back to short one
3818 VIM_CLEAR(p);
3819 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003820 }
3821 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003822 if (p == NULL)
3823 p = utf16_to_enc(wbuf, NULL);
3824
3825 if (p == NULL)
3826 return FAIL;
3827
3828 vim_strncpy(buf, p, len - 1);
3829 vim_free(p);
3830 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003831}
3832
3833/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003834 * Get file permissions for "name".
3835 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003836 */
3837 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003838mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003839{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003840 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003841 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003842
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003843 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003844 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003845}
3846
3847
3848/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003849 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003850 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003851 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003852 */
3853 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003854mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003855{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003856 long n;
3857 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003858
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003859 p = enc_to_utf16(name, NULL);
3860 if (p == NULL)
3861 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003862
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003863 n = _wchmod(p, perm);
3864 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003865 if (n == -1)
3866 return FAIL;
3867
3868 win32_set_archive(name);
3869
3870 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003871}
3872
3873/*
3874 * Set hidden flag for "name".
3875 */
3876 void
3877mch_hide(char_u *name)
3878{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003879 int attrs = win32_getattrs(name);
3880 if (attrs == -1)
3881 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003882
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003883 attrs |= FILE_ATTRIBUTE_HIDDEN;
3884 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003885}
3886
3887/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003888 * Return TRUE if file "name" exists and is hidden.
3889 */
3890 int
3891mch_ishidden(char_u *name)
3892{
3893 int f = win32_getattrs(name);
3894
3895 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003896 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003897
3898 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3899}
3900
3901/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003902 * return TRUE if "name" is a directory
3903 * return FALSE if "name" is not a directory or upon error
3904 */
3905 int
3906mch_isdir(char_u *name)
3907{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003908 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003909
3910 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003911 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003912
3913 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3914}
3915
3916/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003917 * return TRUE if "name" is a directory, NOT a symlink to a directory
3918 * return FALSE if "name" is not a directory
3919 * return FALSE for error
3920 */
3921 int
3922mch_isrealdir(char_u *name)
3923{
3924 return mch_isdir(name) && !mch_is_symbolic_link(name);
3925}
3926
3927/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003928 * Create directory "name".
3929 * Return 0 on success, -1 on error.
3930 */
3931 int
3932mch_mkdir(char_u *name)
3933{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003934 WCHAR *p;
3935 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003936
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003937 p = enc_to_utf16(name, NULL);
3938 if (p == NULL)
3939 return -1;
3940 retval = _wmkdir(p);
3941 vim_free(p);
3942 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003943}
3944
3945/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003946 * Delete directory "name".
3947 * Return 0 on success, -1 on error.
3948 */
3949 int
3950mch_rmdir(char_u *name)
3951{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003952 WCHAR *p;
3953 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003954
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003955 p = enc_to_utf16(name, NULL);
3956 if (p == NULL)
3957 return -1;
3958 retval = _wrmdir(p);
3959 vim_free(p);
3960 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003961}
3962
3963/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003964 * Return TRUE if file "fname" has more than one link.
3965 */
3966 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003967mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003968{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003969 BY_HANDLE_FILE_INFORMATION info;
3970
3971 return win32_fileinfo(fname, &info) == FILEINFO_OK
3972 && info.nNumberOfLinks > 1;
3973}
3974
3975/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003976 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003977 */
3978 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003979mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003980{
3981 HANDLE hFind;
3982 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003983 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003984 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003985 WIN32_FIND_DATAW findDataW;
3986
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003987 wn = enc_to_utf16(name, NULL);
3988 if (wn == NULL)
3989 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003990
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003991 hFind = FindFirstFileW(wn, &findDataW);
3992 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003993 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003994 {
3995 fileFlags = findDataW.dwFileAttributes;
3996 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003997 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003998 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003999
4000 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01004001 && (reparseTag == IO_REPARSE_TAG_SYMLINK
4002 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004003 res = TRUE;
4004
4005 return res;
4006}
4007
4008/*
4009 * Return TRUE if file "fname" has more than one link or if it is a symbolic
4010 * link.
4011 */
4012 int
4013mch_is_linked(char_u *fname)
4014{
4015 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
4016 return TRUE;
4017 return FALSE;
4018}
4019
4020/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02004021 * Get the by-handle-file-information for "fname".
4022 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004023 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02004024 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
4025 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
4026 */
4027 int
4028win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
4029{
Bram Moolenaar03f48552006-02-28 23:52:23 +00004030 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02004031 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004032 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00004033
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004034 wn = enc_to_utf16(fname, NULL);
4035 if (wn == NULL)
4036 return FILEINFO_ENC_FAIL;
4037
4038 hFile = CreateFileW(wn, // file name
4039 GENERIC_READ, // access mode
4040 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
4041 NULL, // security descriptor
4042 OPEN_EXISTING, // creation disposition
4043 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
4044 NULL); // handle to template file
4045 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00004046
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00004047 if (hFile == INVALID_HANDLE_VALUE)
4048 return FILEINFO_READ_FAIL;
4049
4050 if (GetFileInformationByHandle(hFile, info) != 0)
4051 res = FILEINFO_OK;
4052 else
4053 res = FILEINFO_INFO_FAIL;
4054 CloseHandle(hFile);
Bram Moolenaar03f48552006-02-28 23:52:23 +00004055
Bram Moolenaar03f48552006-02-28 23:52:23 +00004056 return res;
4057}
4058
4059/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004060 * get file attributes for `name'
4061 * -1 : error
4062 * else FILE_ATTRIBUTE_* defined in winnt.h
4063 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01004064 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004065win32_getattrs(char_u *name)
4066{
4067 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004068 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004069
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004070 p = enc_to_utf16(name, NULL);
4071 if (p == NULL)
4072 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004073
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004074 attr = GetFileAttributesW(p);
4075 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004076
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004077 return attr;
4078}
4079
4080/*
4081 * set file attributes for `name' to `attrs'
4082 *
4083 * return -1 for failure, 0 otherwise
4084 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004085 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004086win32_setattrs(char_u *name, int attrs)
4087{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004088 int res;
4089 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004090
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004091 p = enc_to_utf16(name, NULL);
4092 if (p == NULL)
4093 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004094
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004095 res = SetFileAttributesW(p, attrs);
4096 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004097
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004098 return res ? 0 : -1;
4099}
4100
4101/*
4102 * Set archive flag for "name".
4103 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004104 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004105win32_set_archive(char_u *name)
4106{
4107 int attrs = win32_getattrs(name);
4108 if (attrs == -1)
4109 return -1;
4110
4111 attrs |= FILE_ATTRIBUTE_ARCHIVE;
4112 return win32_setattrs(name, attrs);
4113}
4114
4115/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004116 * Return TRUE if file or directory "name" is writable (not readonly).
4117 * Strange semantics of Win32: a readonly directory is writable, but you can't
4118 * delete a file. Let's say this means it is writable.
4119 */
4120 int
4121mch_writable(char_u *name)
4122{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004123 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004124
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004125 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
4126 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004127}
4128
Bram Moolenaar071d4272004-06-13 20:20:40 +00004129/*
Bram Moolenaar43663192017-03-05 14:29:12 +01004130 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01004131 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01004132 * When returning TRUE and "path" is not NULL save the path and set "*path" to
4133 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004134 */
4135 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01004136mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004137{
Bram Moolenaar95da1362020-05-30 18:37:55 +02004138 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004139}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004140
4141/*
4142 * Check what "name" is:
4143 * NODE_NORMAL: file or directory (or doesn't exist)
4144 * NODE_WRITABLE: writable device, socket, fifo, etc.
4145 * NODE_OTHER: non-writable things
4146 */
4147 int
4148mch_nodetype(char_u *name)
4149{
4150 HANDLE hFile;
4151 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004152 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004153
Bram Moolenaar0f873732019-12-05 20:28:46 +01004154 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
4155 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
4156 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00004157 if (STRNCMP(name, "\\\\.\\", 4) == 0)
4158 return NODE_WRITABLE;
4159
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004160 wn = enc_to_utf16(name, NULL);
4161 if (wn == NULL)
4162 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004163
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004164 hFile = CreateFileW(wn, // file name
4165 GENERIC_WRITE, // access mode
4166 0, // share mode
4167 NULL, // security descriptor
4168 OPEN_EXISTING, // creation disposition
4169 0, // file attributes
4170 NULL); // handle to template file
4171 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004172 if (hFile == INVALID_HANDLE_VALUE)
4173 return NODE_NORMAL;
4174
4175 type = GetFileType(hFile);
4176 CloseHandle(hFile);
4177 if (type == FILE_TYPE_CHAR)
4178 return NODE_WRITABLE;
4179 if (type == FILE_TYPE_DISK)
4180 return NODE_NORMAL;
4181 return NODE_OTHER;
4182}
4183
4184#ifdef HAVE_ACL
4185struct my_acl
4186{
4187 PSECURITY_DESCRIPTOR pSecurityDescriptor;
4188 PSID pSidOwner;
4189 PSID pSidGroup;
4190 PACL pDacl;
4191 PACL pSacl;
4192};
4193#endif
4194
4195/*
4196 * Return a pointer to the ACL of file "fname" in allocated memory.
4197 * Return NULL if the ACL is not available for whatever reason.
4198 */
4199 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004200mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004201{
4202#ifndef HAVE_ACL
4203 return (vim_acl_T)NULL;
4204#else
4205 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02004206 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004207
Bram Moolenaarc799fe22019-05-28 23:08:19 +02004208 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004209 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004210 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004211 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02004212
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004213 wn = enc_to_utf16(fname, NULL);
4214 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004215 {
4216 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004217 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004218 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004219
4220 // Try to retrieve the entire security descriptor.
4221 err = GetNamedSecurityInfoW(
4222 wn, // Abstract filename
4223 SE_FILE_OBJECT, // File Object
4224 OWNER_SECURITY_INFORMATION |
4225 GROUP_SECURITY_INFORMATION |
4226 DACL_SECURITY_INFORMATION |
4227 SACL_SECURITY_INFORMATION,
4228 &p->pSidOwner, // Ownership information.
4229 &p->pSidGroup, // Group membership.
4230 &p->pDacl, // Discretionary information.
4231 &p->pSacl, // For auditing purposes.
4232 &p->pSecurityDescriptor);
4233 if (err == ERROR_ACCESS_DENIED ||
4234 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004235 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004236 // Retrieve only DACL.
4237 (void)GetNamedSecurityInfoW(
4238 wn,
4239 SE_FILE_OBJECT,
4240 DACL_SECURITY_INFORMATION,
4241 NULL,
4242 NULL,
4243 &p->pDacl,
4244 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004245 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004246 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004247 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004248 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004249 mch_free_acl((vim_acl_T)p);
4250 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004251 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004252 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004253 }
4254
4255 return (vim_acl_T)p;
4256#endif
4257}
4258
Bram Moolenaar27515922013-06-29 15:36:26 +02004259#ifdef HAVE_ACL
4260/*
4261 * Check if "acl" contains inherited ACE.
4262 */
4263 static BOOL
4264is_acl_inherited(PACL acl)
4265{
4266 DWORD i;
4267 ACL_SIZE_INFORMATION acl_info;
4268 PACCESS_ALLOWED_ACE ace;
4269
4270 acl_info.AceCount = 0;
4271 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
4272 for (i = 0; i < acl_info.AceCount; i++)
4273 {
4274 GetAce(acl, i, (LPVOID *)&ace);
4275 if (ace->Header.AceFlags & INHERITED_ACE)
4276 return TRUE;
4277 }
4278 return FALSE;
4279}
4280#endif
4281
Bram Moolenaar071d4272004-06-13 20:20:40 +00004282/*
4283 * Set the ACL of file "fname" to "acl" (unless it's NULL).
4284 * Errors are ignored.
4285 * This must only be called with "acl" equal to what mch_get_acl() returned.
4286 */
4287 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004288mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004289{
4290#ifdef HAVE_ACL
4291 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02004292 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004293 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004294
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004295 if (p == NULL)
4296 return;
4297
4298 wn = enc_to_utf16(fname, NULL);
4299 if (wn == NULL)
4300 return;
4301
4302 // Set security flags
4303 if (p->pSidOwner)
4304 sec_info |= OWNER_SECURITY_INFORMATION;
4305 if (p->pSidGroup)
4306 sec_info |= GROUP_SECURITY_INFORMATION;
4307 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02004308 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004309 sec_info |= DACL_SECURITY_INFORMATION;
4310 // Do not inherit its parent's DACL.
4311 // If the DACL is inherited, Cygwin permissions would be changed.
4312 if (!is_acl_inherited(p->pDacl))
4313 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02004314 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004315 if (p->pSacl)
4316 sec_info |= SACL_SECURITY_INFORMATION;
4317
4318 (void)SetNamedSecurityInfoW(
4319 wn, // Abstract filename
4320 SE_FILE_OBJECT, // File Object
4321 sec_info,
4322 p->pSidOwner, // Ownership information.
4323 p->pSidGroup, // Group membership.
4324 p->pDacl, // Discretionary information.
4325 p->pSacl // For auditing purposes.
4326 );
4327 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004328#endif
4329}
4330
4331 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004332mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004333{
4334#ifdef HAVE_ACL
4335 struct my_acl *p = (struct my_acl *)acl;
4336
4337 if (p != NULL)
4338 {
4339 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
4340 vim_free(p);
4341 }
4342#endif
4343}
4344
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004345#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004346
4347/*
4348 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
4349 */
4350 static BOOL WINAPI
4351handler_routine(
4352 DWORD dwCtrlType)
4353{
Bram Moolenaar589b1102017-08-12 16:39:05 +02004354 INPUT_RECORD ir;
4355 DWORD out;
4356
Bram Moolenaar071d4272004-06-13 20:20:40 +00004357 switch (dwCtrlType)
4358 {
4359 case CTRL_C_EVENT:
4360 if (ctrl_c_interrupts)
4361 g_fCtrlCPressed = TRUE;
4362 return TRUE;
4363
4364 case CTRL_BREAK_EVENT:
4365 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02004366 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004367 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02004368 ir.EventType = KEY_EVENT;
4369 ir.Event.KeyEvent.bKeyDown = TRUE;
4370 ir.Event.KeyEvent.wRepeatCount = 1;
4371 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
4372 ir.Event.KeyEvent.wVirtualScanCode = 0;
4373 ir.Event.KeyEvent.dwControlKeyState = 0;
4374 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
4375 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004376 return TRUE;
4377
Bram Moolenaar0f873732019-12-05 20:28:46 +01004378 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00004379 case CTRL_CLOSE_EVENT:
4380 case CTRL_LOGOFF_EVENT:
4381 case CTRL_SHUTDOWN_EVENT:
4382 windgoto((int)Rows - 1, 0);
4383 g_fForceExit = TRUE;
4384
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004385 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004386 (dwCtrlType == CTRL_CLOSE_EVENT
4387 ? _("close")
4388 : dwCtrlType == CTRL_LOGOFF_EVENT
4389 ? _("logoff")
4390 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004391# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00004392 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004393# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004394
Bram Moolenaar0f873732019-12-05 20:28:46 +01004395 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00004396
Bram Moolenaar0f873732019-12-05 20:28:46 +01004397 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00004398
4399 default:
4400 return FALSE;
4401 }
4402}
4403
4404
4405/*
4406 * set the tty in (raw) ? "raw" : "cooked" mode
4407 */
4408 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02004409mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004410{
4411 DWORD cmodein;
4412 DWORD cmodeout;
4413 BOOL bEnableHandler;
4414
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004415# ifdef VIMDLL
4416 if (gui.in_use)
4417 return;
4418# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004419 GetConsoleMode(g_hConIn, &cmodein);
4420 GetConsoleMode(g_hConOut, &cmodeout);
4421 if (tmode == TMODE_RAW)
4422 {
4423 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4424 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004425 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004426 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004427 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004428 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
4429 }
4430 else
4431 {
4432 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
4433 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004434 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004435# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01004436 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
4437 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004438 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004439# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004440 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004441# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004442 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004443 bEnableHandler = TRUE;
4444 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004445 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00004446 {
4447 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4448 ENABLE_ECHO_INPUT);
4449 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
4450 bEnableHandler = FALSE;
4451 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004452 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004453 SetConsoleMode(g_hConOut, cmodeout);
4454 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
4455
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004456# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004457 if (fdDump)
4458 {
4459 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
4460 tmode == TMODE_RAW ? "raw" :
4461 tmode == TMODE_COOK ? "cooked" : "normal",
4462 cmodein, cmodeout);
4463 fflush(fdDump);
4464 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004465# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004466}
4467
4468
4469/*
4470 * Get the size of the current window in `Rows' and `Columns'
4471 * Return OK when size could be determined, FAIL otherwise.
4472 */
4473 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004474mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004475{
4476 CONSOLE_SCREEN_BUFFER_INFO csbi;
4477
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004478# ifdef VIMDLL
4479 if (gui.in_use)
4480 return OK;
4481# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004482 if (!g_fTermcapMode && g_cbTermcap.IsValid)
4483 {
4484 /*
4485 * For some reason, we are trying to get the screen dimensions
4486 * even though we are not in termcap mode. The 'Rows' and 'Columns'
4487 * variables are really intended to mean the size of Vim screen
4488 * while in termcap mode.
4489 */
4490 Rows = g_cbTermcap.Info.dwSize.Y;
4491 Columns = g_cbTermcap.Info.dwSize.X;
4492 }
4493 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4494 {
4495 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4496 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4497 }
4498 else
4499 {
4500 Rows = 25;
4501 Columns = 80;
4502 }
4503 return OK;
4504}
4505
4506/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004507 * Resize console buffer to 'COORD'
4508 */
4509 static void
4510ResizeConBuf(
4511 HANDLE hConsole,
4512 COORD coordScreen)
4513{
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00004514 if (use_alternate_screen_buffer)
4515 return;
4516
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004517 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4518 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004519# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004520 if (fdDump)
4521 {
4522 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4523 GetLastError());
4524 fflush(fdDump);
4525 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004526# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004527 }
4528}
4529
4530/*
4531 * Resize console window size to 'srWindowRect'
4532 */
4533 static void
4534ResizeWindow(
4535 HANDLE hConsole,
4536 SMALL_RECT srWindowRect)
4537{
4538 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4539 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004540# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004541 if (fdDump)
4542 {
4543 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4544 GetLastError());
4545 fflush(fdDump);
4546 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004547# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004548 }
4549}
4550
4551/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004552 * Set a console window to `xSize' * `ySize'
4553 */
4554 static void
4555ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004556 HANDLE hConsole,
4557 int xSize,
4558 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004559{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004560 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
4561 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004562 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004563 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004564 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004565
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004566# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004567 if (fdDump)
4568 {
4569 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4570 fflush(fdDump);
4571 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004572# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004573
Bram Moolenaar0f873732019-12-05 20:28:46 +01004574 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00004575 coordScreen = GetLargestConsoleWindowSize(hConsole);
4576
Bram Moolenaar0f873732019-12-05 20:28:46 +01004577 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00004578 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4579 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4580 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4581
4582 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4583 {
4584 int sx, sy;
4585
4586 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4587 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4588 if (sy < ySize || sx < xSize)
4589 {
4590 /*
4591 * Increasing number of lines/columns, do buffer first.
4592 * Use the maximal size in x and y direction.
4593 */
4594 if (sy < ySize)
4595 coordScreen.Y = ySize;
4596 else
4597 coordScreen.Y = sy;
4598 if (sx < xSize)
4599 coordScreen.X = xSize;
4600 else
4601 coordScreen.X = sx;
4602 SetConsoleScreenBufferSize(hConsole, coordScreen);
4603 }
4604 }
4605
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004606 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004607 coordScreen.X = xSize;
4608 coordScreen.Y = ySize;
4609
Bram Moolenaar2551c032018-08-23 22:38:31 +02004610 // In the new console call API, only the first time in reverse order
4611 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004612 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004613 ResizeWindow(hConsole, srWindowRect);
4614 ResizeConBuf(hConsole, coordScreen);
4615 }
4616 else
4617 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004618 // Workaround for a Windows 10 bug
4619 cursor.X = srWindowRect.Left;
4620 cursor.Y = srWindowRect.Top;
4621 SetConsoleCursorPosition(hConsole, cursor);
4622
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004623 ResizeConBuf(hConsole, coordScreen);
4624 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004625 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004626 }
4627}
4628
4629
4630/*
4631 * Set the console window to `Rows' * `Columns'
4632 */
4633 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004634mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004635{
4636 COORD coordScreen;
4637
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004638# ifdef VIMDLL
4639 if (gui.in_use)
4640 return;
4641# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004642 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004643 if (suppress_winsize != 0)
4644 {
4645 suppress_winsize = 2;
4646 return;
4647 }
4648
4649 if (term_console)
4650 {
4651 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4652
Bram Moolenaar0f873732019-12-05 20:28:46 +01004653 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004654 if (Rows > coordScreen.Y)
4655 Rows = coordScreen.Y;
4656 if (Columns > coordScreen.X)
4657 Columns = coordScreen.X;
4658
4659 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4660 }
4661}
4662
4663/*
4664 * Rows and/or Columns has changed.
4665 */
4666 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004667mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004668{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004669# ifdef VIMDLL
4670 if (gui.in_use)
4671 return;
4672# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004673 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4674}
4675
4676
4677/*
4678 * Called when started up, to set the winsize that was delayed.
4679 */
4680 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004681mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004682{
4683 if (suppress_winsize == 2)
4684 {
4685 suppress_winsize = 0;
4686 mch_set_shellsize();
4687 shell_resized();
4688 }
4689 suppress_winsize = 0;
4690}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004691#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004692
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004693 static BOOL
4694vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004695 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004696 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004697 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004698 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004699 PROCESS_INFORMATION *pi,
4700 LPVOID *env,
4701 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004702{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004703 BOOL ret = FALSE;
4704 WCHAR *wcmd, *wcwd = NULL;
4705
4706 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4707 if (wcmd == NULL)
4708 return FALSE;
4709 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004710 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004711 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4712 if (wcwd == NULL)
4713 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004714 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004715
4716 ret = CreateProcessW(
4717 NULL, // Executable name
4718 wcmd, // Command to execute
4719 NULL, // Process security attributes
4720 NULL, // Thread security attributes
4721 inherit_handles, // Inherit handles
4722 flags, // Creation flags
4723 env, // Environment
4724 wcwd, // Current directory
4725 (LPSTARTUPINFOW)si, // Startup information
4726 pi); // Process information
4727theend:
4728 vim_free(wcmd);
4729 vim_free(wcwd);
4730 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004731}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004732
4733
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004734 static HINSTANCE
4735vim_shell_execute(
4736 char *cmd,
4737 INT n_show_cmd)
4738{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004739 HINSTANCE ret;
4740 WCHAR *wcmd;
4741
4742 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4743 if (wcmd == NULL)
4744 return (HINSTANCE) 0;
4745
4746 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4747 vim_free(wcmd);
4748 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004749}
4750
4751
Bram Moolenaar4f974752019-02-17 17:44:42 +01004752#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004753
4754/*
4755 * Specialised version of system() for Win32 GUI mode.
4756 * This version proceeds as follows:
4757 * 1. Create a console window for use by the subprocess
4758 * 2. Run the subprocess (it gets the allocated console by default)
4759 * 3. Wait for the subprocess to terminate and get its exit code
4760 * 4. Prompt the user to press a key to close the console window
4761 */
4762 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004763mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004764{
4765 STARTUPINFO si;
4766 PROCESS_INFORMATION pi;
4767 DWORD ret = 0;
4768 HWND hwnd = GetFocus();
4769
4770 si.cb = sizeof(si);
4771 si.lpReserved = NULL;
4772 si.lpDesktop = NULL;
4773 si.lpTitle = NULL;
4774 si.dwFlags = STARTF_USESHOWWINDOW;
4775 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004776 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004777 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004778 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004779 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004780 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004781 else
4782 si.wShowWindow = SW_SHOWNORMAL;
4783 si.cbReserved2 = 0;
4784 si.lpReserved2 = NULL;
4785
Bram Moolenaar0f873732019-12-05 20:28:46 +01004786 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004787 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004788 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4789 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004790
Bram Moolenaar0f873732019-12-05 20:28:46 +01004791 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004792 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004793# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004794 int delay = 1;
4795
Bram Moolenaar0f873732019-12-05 20:28:46 +01004796 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004797 for (;;)
4798 {
4799 MSG msg;
4800
K.Takatab7057bd2022-01-21 11:37:07 +00004801 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004802 {
4803 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004804 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004805 delay = 1;
4806 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004807 }
4808 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4809 break;
4810
Bram Moolenaar0f873732019-12-05 20:28:46 +01004811 // We start waiting for a very short time and then increase it, so
4812 // that we respond quickly when the process is quick, and don't
4813 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004814 if (delay < 50)
4815 delay += 10;
4816 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004817# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004818 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004819# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004820
Bram Moolenaar0f873732019-12-05 20:28:46 +01004821 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004822 GetExitCodeProcess(pi.hProcess, &ret);
4823 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004824
Bram Moolenaar0f873732019-12-05 20:28:46 +01004825 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004826 CloseHandle(pi.hThread);
4827 CloseHandle(pi.hProcess);
4828
Bram Moolenaar0f873732019-12-05 20:28:46 +01004829 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004830 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4831
4832 return ret;
4833}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004834
4835/*
4836 * Thread launched by the gui to send the current buffer data to the
4837 * process. This way avoid to hang up vim totally if the children
4838 * process take a long time to process the lines.
4839 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004840 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004841sub_process_writer(LPVOID param)
4842{
4843 HANDLE g_hChildStd_IN_Wr = param;
4844 linenr_T lnum = curbuf->b_op_start.lnum;
4845 DWORD len = 0;
4846 DWORD l;
4847 char_u *lp = ml_get(lnum);
4848 char_u *s;
4849 int written = 0;
4850
4851 for (;;)
4852 {
4853 l = (DWORD)STRLEN(lp + written);
4854 if (l == 0)
4855 len = 0;
4856 else if (lp[written] == NL)
4857 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004858 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004859 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4860 }
4861 else
4862 {
4863 s = vim_strchr(lp + written, NL);
4864 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4865 s == NULL ? l : (DWORD)(s - (lp + written)),
4866 &len, NULL);
4867 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004868 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004869 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004870 // Finished a line, add a NL, unless this line should not have
4871 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004872 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004873 || (!curbuf->b_p_bin
4874 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004875 || (lnum != curbuf->b_no_eol_lnum
4876 && (lnum != curbuf->b_ml.ml_line_count
4877 || curbuf->b_p_eol)))
4878 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004879 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4880 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004881 }
4882
4883 ++lnum;
4884 if (lnum > curbuf->b_op_end.lnum)
4885 break;
4886
4887 lp = ml_get(lnum);
4888 written = 0;
4889 }
4890 else if (len > 0)
4891 written += len;
4892 }
4893
Bram Moolenaar0f873732019-12-05 20:28:46 +01004894 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004895 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004896 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004897}
4898
4899
Bram Moolenaar0f873732019-12-05 20:28:46 +01004900# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004901
4902/*
4903 * This function read from the children's stdout and write the
4904 * data on screen or in the buffer accordingly.
4905 */
4906 static void
4907dump_pipe(int options,
4908 HANDLE g_hChildStd_OUT_Rd,
4909 garray_T *ga,
4910 char_u buffer[],
4911 DWORD *buffer_off)
4912{
4913 DWORD availableBytes = 0;
4914 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004915 int ret;
4916 DWORD len;
4917 DWORD toRead;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004918
Bram Moolenaar0f873732019-12-05 20:28:46 +01004919 // we query the pipe to see if there is any data to read
4920 // to avoid to perform a blocking read
4921 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4922 NULL, // optional buffer
4923 0, // buffer size
4924 NULL, // number of read bytes
4925 &availableBytes, // available bytes total
4926 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004927
Bram Moolenaar0f873732019-12-05 20:28:46 +01004928 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004929 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004930 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01004931 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004932 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004933 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004934
Bram Moolenaar0f873732019-12-05 20:28:46 +01004935 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004936 if (len == 0)
4937 break;
4938
4939 availableBytes -= len;
4940
4941 if (options & SHELL_READ)
4942 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004943 // Do NUL -> NL translation, append NL separated
4944 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004945 for (i = 0; i < len; ++i)
4946 {
4947 if (buffer[i] == NL)
4948 append_ga_line(ga);
4949 else if (buffer[i] == NUL)
4950 ga_append(ga, NL);
4951 else
4952 ga_append(ga, buffer[i]);
4953 }
4954 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004955 else if (has_mbyte)
4956 {
4957 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004958 int c;
4959 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004960
4961 len += *buffer_off;
4962 buffer[len] = NUL;
4963
Bram Moolenaar0f873732019-12-05 20:28:46 +01004964 // Check if the last character in buffer[] is
4965 // incomplete, keep these bytes for the next
4966 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004967 for (p = buffer; p < buffer + len; p += l)
4968 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004969 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004970 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004971 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004972 else if (MB_BYTE2LEN(*p) != l)
4973 break;
4974 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004975 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004976 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004977 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004978 if (len >= 12)
4979 ++p;
4980 else
4981 {
4982 *buffer_off = len;
4983 return;
4984 }
4985 }
4986 c = *p;
4987 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004988 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004989 if (p < buffer + len)
4990 {
4991 *p = c;
4992 *buffer_off = (DWORD)((buffer + len) - p);
4993 mch_memmove(buffer, p, *buffer_off);
4994 return;
4995 }
4996 *buffer_off = 0;
4997 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004998 else
4999 {
5000 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01005001 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005002 }
5003
5004 windgoto(msg_row, msg_col);
5005 cursor_on();
5006 out_flush();
5007 }
5008}
5009
5010/*
5011 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
5012 * for communication and doesn't open any new window.
5013 */
5014 static int
5015mch_system_piped(char *cmd, int options)
5016{
5017 STARTUPINFO si;
5018 PROCESS_INFORMATION pi;
5019 DWORD ret = 0;
5020
5021 HANDLE g_hChildStd_IN_Rd = NULL;
5022 HANDLE g_hChildStd_IN_Wr = NULL;
5023 HANDLE g_hChildStd_OUT_Rd = NULL;
5024 HANDLE g_hChildStd_OUT_Wr = NULL;
5025
Bram Moolenaar0f873732019-12-05 20:28:46 +01005026 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005027 DWORD len;
5028
Bram Moolenaar0f873732019-12-05 20:28:46 +01005029 // buffer used to receive keys
5030 char_u ta_buf[BUFLEN + 1]; // TypeAHead
5031 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005032
5033 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005034 int noread_cnt = 0;
5035 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005036 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005037 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005038 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005039
5040 SECURITY_ATTRIBUTES saAttr;
5041
Bram Moolenaar0f873732019-12-05 20:28:46 +01005042 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005043 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5044 saAttr.bInheritHandle = TRUE;
5045 saAttr.lpSecurityDescriptor = NULL;
5046
5047 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005048 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005049 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005050 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005051 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005052 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005053 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005054 {
5055 CloseHandle(g_hChildStd_IN_Rd);
5056 CloseHandle(g_hChildStd_IN_Wr);
5057 CloseHandle(g_hChildStd_OUT_Rd);
5058 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01005059 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005060 }
5061
5062 si.cb = sizeof(si);
5063 si.lpReserved = NULL;
5064 si.lpDesktop = NULL;
5065 si.lpTitle = NULL;
5066 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
5067
Bram Moolenaar0f873732019-12-05 20:28:46 +01005068 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005069 si.hStdError = g_hChildStd_OUT_Wr;
5070 si.hStdOutput = g_hChildStd_OUT_Wr;
5071 si.hStdInput = g_hChildStd_IN_Rd;
5072 si.wShowWindow = SW_HIDE;
5073 si.cbReserved2 = 0;
5074 si.lpReserved2 = NULL;
5075
5076 if (options & SHELL_READ)
5077 ga_init2(&ga, 1, BUFLEN);
5078
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005079 if (cmd != NULL)
5080 {
5081 p = (char *)vim_strsave((char_u *)cmd);
5082 if (p != NULL)
5083 unescape_shellxquote((char_u *)p, p_sxe);
5084 else
5085 p = cmd;
5086 }
5087
Bram Moolenaar0f873732019-12-05 20:28:46 +01005088 // Now, run the command.
5089 // About "Inherit handles" being TRUE: this command can be litigious,
5090 // handle inheritance was deactivated for pending temp file, but, if we
5091 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005092 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
5093 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005094
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005095 if (p != cmd)
5096 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005097
Bram Moolenaar0f873732019-12-05 20:28:46 +01005098 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005099 CloseHandle(g_hChildStd_IN_Rd);
5100 CloseHandle(g_hChildStd_OUT_Wr);
5101
5102 if (options & SHELL_WRITE)
5103 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02005104 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005105 _beginthreadex(NULL, // security attributes
5106 0, // default stack size
5107 sub_process_writer, // function to be executed
5108 g_hChildStd_IN_Wr, // parameter
5109 0, // creation flag, start immediately
5110 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005111 CloseHandle(thread);
5112 g_hChildStd_IN_Wr = NULL;
5113 }
5114
Bram Moolenaar0f873732019-12-05 20:28:46 +01005115 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005116 for (;;)
5117 {
5118 MSG msg;
5119
K.Takatab7057bd2022-01-21 11:37:07 +00005120 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005121 {
5122 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00005123 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005124 }
5125
Bram Moolenaar0f873732019-12-05 20:28:46 +01005126 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005127 if ((options & (SHELL_READ|SHELL_WRITE))
5128# ifdef FEAT_GUI
5129 || gui.in_use
5130# endif
5131 )
5132 {
5133 len = 0;
GuyBrush52ecc762024-02-21 20:16:38 +01005134 if (((options &
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005135 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
5136 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
5137# ifdef FEAT_GUI
5138 || gui.in_use
5139# endif
5140 )
5141 && (ta_len > 0 || noread_cnt > 4))
5142 {
5143 if (ta_len == 0)
5144 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005145 // Get extra characters when we don't have any. Reset the
5146 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005147 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005148 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
5149 }
5150 if (ta_len > 0 || len > 0)
5151 {
5152 /*
5153 * For pipes: Check for CTRL-C: send interrupt signal to
GuyBrush1f13fcc2024-01-14 20:08:40 +01005154 * child.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005155 */
5156 if (len == 1 && cmd != NULL)
5157 {
5158 if (ta_buf[ta_len] == Ctrl_C)
5159 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005160 // Learn what exit code is expected, for
5161 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005162 TerminateProcess(pi.hProcess, 9);
5163 }
GuyBrush1f13fcc2024-01-14 20:08:40 +01005164 }
5165
5166 /*
5167 * Check for CTRL-D: EOF, close pipe to child.
5168 * Ctrl_D may be decorated by _OnChar()
5169 */
5170 if ((len == 1 || len == 4 ) && cmd != NULL)
5171 {
5172 if (ta_buf[0] == Ctrl_D
5173 || (ta_buf[0] == CSI
5174 && ta_buf[1] == KS_MODIFIER
5175 && ta_buf[3] == Ctrl_D))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005176 {
5177 CloseHandle(g_hChildStd_IN_Wr);
5178 g_hChildStd_IN_Wr = NULL;
GuyBrush1f13fcc2024-01-14 20:08:40 +01005179 len = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005180 }
5181 }
5182
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01005183 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005184
5185 /*
5186 * For pipes: echo the typed characters. For a pty this
5187 * does not seem to work.
5188 */
5189 for (i = ta_len; i < ta_len + len; ++i)
5190 {
5191 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
5192 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005193 else if (has_mbyte)
5194 {
5195 int l = (*mb_ptr2len)(ta_buf + i);
5196
5197 msg_outtrans_len(ta_buf + i, l);
5198 i += l - 1;
5199 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005200 else
5201 msg_outtrans_len(ta_buf + i, 1);
5202 }
5203 windgoto(msg_row, msg_col);
5204 out_flush();
5205
5206 ta_len += len;
5207
5208 /*
5209 * Write the characters to the child, unless EOF has been
5210 * typed for pipes. Write one character at a time, to
5211 * avoid losing too much typeahead. When writing buffer
5212 * lines, drop the typed characters (only check for
5213 * CTRL-C).
5214 */
5215 if (options & SHELL_WRITE)
5216 ta_len = 0;
5217 else if (g_hChildStd_IN_Wr != NULL)
5218 {
5219 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
5220 1, &len, NULL);
5221 // if we are typing in, we want to keep things reactive
5222 delay = 1;
5223 if (len > 0)
5224 {
5225 ta_len -= len;
5226 mch_memmove(ta_buf, ta_buf + len, ta_len);
5227 }
5228 }
5229 }
5230 }
5231 }
5232
5233 if (ta_len)
5234 ui_inchar_undo(ta_buf, ta_len);
5235
5236 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
5237 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005238 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005239 break;
5240 }
5241
5242 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005243 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005244
Bram Moolenaar0f873732019-12-05 20:28:46 +01005245 // We start waiting for a very short time and then increase it, so
5246 // that we respond quickly when the process is quick, and don't
5247 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005248 if (delay < 50)
5249 delay += 10;
5250 }
5251
Bram Moolenaar0f873732019-12-05 20:28:46 +01005252 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005253 CloseHandle(g_hChildStd_OUT_Rd);
5254 if (g_hChildStd_IN_Wr != NULL)
5255 CloseHandle(g_hChildStd_IN_Wr);
5256
5257 WaitForSingleObject(pi.hProcess, INFINITE);
5258
Bram Moolenaar0f873732019-12-05 20:28:46 +01005259 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005260 GetExitCodeProcess(pi.hProcess, &ret);
5261
5262 if (options & SHELL_READ)
5263 {
5264 if (ga.ga_len > 0)
5265 {
5266 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01005267 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005268 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
5269 }
5270 else
5271 curbuf->b_no_eol_lnum = 0;
5272 ga_clear(&ga);
5273 }
5274
Bram Moolenaar0f873732019-12-05 20:28:46 +01005275 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005276 CloseHandle(pi.hThread);
5277 CloseHandle(pi.hProcess);
5278
5279 return ret;
5280}
5281
5282 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005283mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005284{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005285 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005286 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005287 return mch_system_piped(cmd, options);
5288 else
5289 return mch_system_classic(cmd, options);
5290}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005291#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005292
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005293#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005294 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02005295mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005296{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005297 int ret;
5298 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005299 char_u *buf;
5300 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005301
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005302 // If the command starts and ends with double quotes, enclose the command
5303 // in parentheses.
5304 len = STRLEN(cmd);
5305 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
5306 {
5307 len += 3;
5308 buf = alloc(len);
5309 if (buf == NULL)
5310 return -1;
5311 vim_snprintf((char *)buf, len, "(%s)", cmd);
5312 wcmd = enc_to_utf16(buf, NULL);
5313 free(buf);
5314 }
5315 else
5316 wcmd = enc_to_utf16((char_u *)cmd, NULL);
5317
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005318 if (wcmd == NULL)
5319 return -1;
5320
5321 ret = _wsystem(wcmd);
5322 vim_free(wcmd);
5323 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005324}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005325
5326#endif
5327
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005328 static int
5329mch_system(char *cmd, int options)
5330{
5331#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005332 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005333 return mch_system_g(cmd, options);
5334 else
5335 return mch_system_c(cmd, options);
5336#elif defined(FEAT_GUI_MSWIN)
5337 return mch_system_g(cmd, options);
5338#else
5339 return mch_system_c(cmd, options);
5340#endif
5341}
5342
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005343#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
5344/*
5345 * Use a terminal window to run a shell command in.
5346 */
5347 static int
5348mch_call_shell_terminal(
5349 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005350 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005351{
5352 jobopt_T opt;
5353 char_u *newcmd = NULL;
5354 typval_T argvar[2];
5355 long_u cmdlen;
5356 int retval = -1;
5357 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005358 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005359 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005360 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005361
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005362 if (cmd == NULL)
5363 cmdlen = STRLEN(p_sh) + 1;
5364 else
5365 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005366 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005367 if (newcmd == NULL)
5368 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005369 if (cmd == NULL)
5370 {
5371 STRCPY(newcmd, p_sh);
5372 ch_log(NULL, "starting terminal to run a shell");
5373 }
5374 else
5375 {
5376 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
5377 ch_log(NULL, "starting terminal for system command '%s'", cmd);
5378 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005379
5380 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005381
5382 argvar[0].v_type = VAR_STRING;
5383 argvar[0].vval.v_string = newcmd;
5384 argvar[1].v_type = VAR_UNKNOWN;
5385 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005386 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01005387 {
5388 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005389 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01005390 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005391
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005392 job = term_getjob(buf->b_term);
5393 ++job->jv_refcount;
5394
Bram Moolenaar0f873732019-12-05 20:28:46 +01005395 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005396 aucmd_prepbuf(&aco, buf);
Bram Moolenaare76062c2022-11-28 18:51:43 +00005397 if (curbuf == buf)
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005398 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005399 // Only do this when a window was found for "buf".
5400 clear_oparg(&oa);
5401 while (term_use_loop())
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005402 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005403 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
5404 {
5405 // If terminal_loop() returns OK we got a key that is handled
5406 // in Normal model. We don't do redrawing anyway.
5407 if (terminal_loop(TRUE) == OK)
5408 normal_cmd(&oa, TRUE);
5409 }
5410 else
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005411 normal_cmd(&oa, TRUE);
5412 }
Bram Moolenaare76062c2022-11-28 18:51:43 +00005413 retval = job->jv_exitval;
5414 ch_log(NULL, "system command finished");
5415
5416 job_unref(job);
5417
5418 // restore curwin/curbuf and a few other things
5419 aucmd_restbuf(&aco);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005420 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005421
5422 wait_return(TRUE);
5423 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
5424
5425 vim_free(newcmd);
5426 return retval;
5427}
5428#endif
5429
Bram Moolenaar071d4272004-06-13 20:20:40 +00005430/*
5431 * Either execute a command by calling the shell or start a new shell
5432 */
5433 int
5434mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005435 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005436 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00005437{
5438 int x = 0;
5439 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005440 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02005441
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00005442#ifdef FEAT_EVAL
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01005443 ch_log(NULL, "executing shell command: %s", cmd);
5444#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01005445 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02005446 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005447 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005448 if (cmd == NULL)
5449 wcscat(szShellTitle, L" :sh");
5450 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005451 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005452 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005453
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005454 if (wn != NULL)
5455 {
5456 wcscat(szShellTitle, L" - !");
5457 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02005458 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005459 wcscat(szShellTitle, wn);
5460 SetConsoleTitleW(szShellTitle);
5461 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005462 }
5463 }
5464 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005465
5466 out_flush();
5467
5468#ifdef MCH_WRITE_DUMP
5469 if (fdDump)
5470 {
5471 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
5472 fflush(fdDump);
5473 }
5474#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005475#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005476 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005477 if (
5478# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005479 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005480# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005481 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005482 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
5483 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005484 char_u *cmdbase = cmd;
5485
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02005486 if (cmdbase != NULL)
5487 // Skip a leading quote and (.
5488 while (*cmdbase == '"' || *cmdbase == '(')
5489 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005490
5491 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01005492 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
5493 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005494 {
5495 // Use a terminal window to run the command in.
5496 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005497 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005498 return x;
5499 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005500 }
5501#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005502
5503 /*
5504 * Catch all deadly signals while running the external command, because a
5505 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5506 */
ichizok378447f2023-05-11 22:25:42 +01005507 mch_signal(SIGINT, SIG_IGN);
ichizok378447f2023-05-11 22:25:42 +01005508 mch_signal(SIGBREAK, SIG_IGN);
ichizok378447f2023-05-11 22:25:42 +01005509 mch_signal(SIGILL, SIG_IGN);
5510 mch_signal(SIGFPE, SIG_IGN);
5511 mch_signal(SIGSEGV, SIG_IGN);
5512 mch_signal(SIGTERM, SIG_IGN);
5513 mch_signal(SIGABRT, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005514
5515 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005516 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00005517
5518 if (cmd == NULL)
5519 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005520 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005521 }
5522 else
5523 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005524 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005525 char_u *newcmd = NULL;
5526 char_u *cmdbase = cmd;
5527 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005528
Bram Moolenaar0f873732019-12-05 20:28:46 +01005529 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005530 if (*cmdbase == '"' )
5531 ++cmdbase;
5532 if (*cmdbase == '(')
5533 ++cmdbase;
5534
Bram Moolenaar1c465442017-03-12 20:10:05 +01005535 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005536 {
5537 STARTUPINFO si;
5538 PROCESS_INFORMATION pi;
5539 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005540 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005541 char_u *p;
5542
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005543 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005544 si.cb = sizeof(si);
5545 si.lpReserved = NULL;
5546 si.lpDesktop = NULL;
5547 si.lpTitle = NULL;
5548 si.dwFlags = 0;
5549 si.cbReserved2 = 0;
5550 si.lpReserved2 = NULL;
5551
5552 cmdbase = skipwhite(cmdbase + 5);
5553 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005554 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005555 {
5556 cmdbase = skipwhite(cmdbase + 4);
5557 si.dwFlags = STARTF_USESHOWWINDOW;
5558 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005559 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005560 }
5561 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005562 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005563 {
5564 cmdbase = skipwhite(cmdbase + 2);
5565 flags = CREATE_NO_WINDOW;
5566 si.dwFlags = STARTF_USESTDHANDLES;
5567 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005568 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005569 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005570 NULL, // Security att.
5571 OPEN_EXISTING, // Open flags
5572 FILE_ATTRIBUTE_NORMAL, // File att.
5573 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005574 si.hStdOutput = si.hStdInput;
5575 si.hStdError = si.hStdInput;
5576 }
5577
Bram Moolenaar0f873732019-12-05 20:28:46 +01005578 // Remove a trailing ", ) and )" if they have a match
5579 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005580 if (cmdbase > cmd)
5581 {
5582 p = cmdbase + STRLEN(cmdbase);
5583 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5584 *--p = NUL;
5585 if (p > cmdbase && p[-1] == ')'
5586 && (*cmd =='(' || cmd[1] == '('))
5587 *--p = NUL;
5588 }
5589
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005590 newcmd = cmdbase;
5591 unescape_shellxquote(cmdbase, p_sxe);
5592
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005593 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005594 * If creating new console, arguments are passed to the
5595 * 'cmd.exe' as-is. If it's not, arguments are not treated
5596 * correctly for current 'cmd.exe'. So unescape characters in
5597 * shellxescape except '|' for avoiding to be treated as
5598 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005599 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005600 if (flags != CREATE_NEW_CONSOLE)
5601 {
5602 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005603 char_u *cmd_shell = mch_getenv("COMSPEC");
5604
5605 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005606 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005607
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005608 subcmd = vim_strsave_escaped_ext(cmdbase,
5609 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005610 if (subcmd != NULL)
5611 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005612 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005613 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005614 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005615 if (newcmd != NULL)
5616 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005617 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005618 else
5619 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005620 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005621 }
5622 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005623
5624 /*
5625 * Now, start the command as a process, so that it doesn't
5626 * inherit our handles which causes unpleasant dangling swap
5627 * files if we exit before the spawned process
5628 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005629 if (vim_create_process((char *)newcmd, FALSE, flags,
5630 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005631 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005632 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5633 > (HINSTANCE)32)
5634 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005635 else
5636 {
5637 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005638#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005639# ifdef VIMDLL
5640 if (gui.in_use)
5641# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005642 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005643#endif
5644 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005645
5646 if (newcmd != cmdbase)
5647 vim_free(newcmd);
5648
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005649 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005650 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005651 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005652 CloseHandle(si.hStdInput);
5653 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005654 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005655 CloseHandle(pi.hThread);
5656 CloseHandle(pi.hProcess);
5657 }
5658 else
5659 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005660 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005661#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005662 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005663 (!s_dont_use_vimrun && p_stmp ?
5664 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5665 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005666#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005667 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005668
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005669 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005670 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005671 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005672#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005673 if (
5674# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005675 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005676# endif
5677 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005678 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005679 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5680 "External commands will not pause after completion.\n"
5681 "See :help win32-vimrun for more information.");
5682 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005683 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5684 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005685
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005686 if (wmsg != NULL && wtitle != NULL)
5687 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5688 vim_free(wmsg);
5689 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005690 need_vimrun_warning = FALSE;
5691 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005692 if (
5693# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005694 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005695# endif
5696 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005697 // Use vimrun to execute the command. It opens a console
5698 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005699 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005700 vimrun_path,
5701 (msg_silent != 0 || (options & SHELL_DOOUT))
5702 ? "-s " : "",
5703 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005704 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005705# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005706 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005707# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005708 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005709 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005710 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5711 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005712 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005713#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005714 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005715 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005716 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005717 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005718 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005719 }
5720 }
5721
5722 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005723 {
5724 // The shell may have messed with the mode, always set it.
5725 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005726 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005727 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005728
Bram Moolenaar0f873732019-12-05 20:28:46 +01005729 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005730 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005731#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005732 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005733 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005734#endif
5735 )
5736 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005737 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005738 msg_putchar('\n');
5739 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005740 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005741
ichizok378447f2023-05-11 22:25:42 +01005742 mch_signal(SIGINT, SIG_DFL);
ichizok378447f2023-05-11 22:25:42 +01005743 mch_signal(SIGBREAK, SIG_DFL);
ichizok378447f2023-05-11 22:25:42 +01005744 mch_signal(SIGILL, SIG_DFL);
5745 mch_signal(SIGFPE, SIG_DFL);
5746 mch_signal(SIGSEGV, SIG_DFL);
5747 mch_signal(SIGTERM, SIG_DFL);
5748 mch_signal(SIGABRT, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005749
5750 return x;
5751}
5752
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005753#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005754 static HANDLE
5755job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005756 char_u *fname,
5757 DWORD dwDesiredAccess,
5758 DWORD dwShareMode,
5759 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5760 DWORD dwCreationDisposition,
5761 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005762{
5763 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005764 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005765
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005766 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005767 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005768 return INVALID_HANDLE_VALUE;
5769
5770 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5771 lpSecurityAttributes, dwCreationDisposition,
5772 dwFlagsAndAttributes, NULL);
5773 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005774 return h;
5775}
5776
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005777/*
5778 * Turn the dictionary "env" into a NUL separated list that can be used as the
5779 * environment argument of vim_create_process().
5780 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005781 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005782win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005783{
5784 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005785 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005786 LPVOID base = GetEnvironmentStringsW();
5787
Bram Moolenaar0f873732019-12-05 20:28:46 +01005788 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005789 if (ga_grow(gap, 1) == FAIL)
5790 return;
5791
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005792 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005793 {
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00005794 FOR_ALL_HASHTAB_ITEMS(&env->dv_hashtab, hi, todo)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005795 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005796 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005797 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005798 typval_T *item = &dict_lookup(hi)->di_tv;
5799 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005800 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005801 --todo;
5802 if (wkey != NULL && wval != NULL)
5803 {
5804 size_t n;
5805 size_t lkey = wcslen(wkey);
5806 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005807
Yegappan Lakshmananfadc02a2023-01-27 21:03:12 +00005808 if (ga_grow(gap, (int)(lkey + lval + 2)) == FAIL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005809 continue;
5810 for (n = 0; n < lkey; n++)
5811 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5812 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5813 for (n = 0; n < lval; n++)
5814 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5815 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5816 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005817 vim_free(wkey);
5818 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005819 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005820 }
5821 }
5822
Bram Moolenaar355757a2020-02-10 22:06:32 +01005823 if (base)
5824 {
5825 WCHAR *p = (WCHAR*) base;
5826
5827 // for last \0
5828 if (ga_grow(gap, 1) == FAIL)
5829 return;
5830
5831 while (*p != 0 || *(p + 1) != 0)
5832 {
5833 if (ga_grow(gap, 1) == OK)
5834 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5835 p++;
5836 }
Ken Takataad29f6a2023-09-16 13:56:02 +02005837 FreeEnvironmentStringsW(base);
Bram Moolenaar355757a2020-02-10 22:06:32 +01005838 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5839 }
5840
Bram Moolenaar493359e2018-06-12 20:25:52 +02005841# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005842 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005843# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005844 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005845 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005846# endif
5847# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005848 char_u *version = get_vim_var_str(VV_VERSION);
5849 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005850# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005851 // size of "VIM_SERVERNAME=" and value,
5852 // plus "VIM_TERMINAL=" and value,
5853 // plus two terminating NULs
5854 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005855# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005856 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005857# endif
5858# ifdef FEAT_TERMINAL
5859 + 13 + version_len + 2
5860# endif
5861 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005862
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005863 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005864 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005865# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005866 for (n = 0; n < 15; n++)
5867 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5868 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005869 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005870 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5871 (WCHAR)servername[n];
5872 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005873# endif
5874# ifdef FEAT_TERMINAL
5875 if (is_terminal)
5876 {
5877 for (n = 0; n < 13; n++)
5878 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5879 (WCHAR)"VIM_TERMINAL="[n];
5880 for (n = 0; n < version_len; n++)
5881 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5882 (WCHAR)version[n];
5883 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5884 }
5885# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005886 }
5887 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005888# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005889}
5890
Bram Moolenaarb091f302019-01-19 14:37:00 +01005891/*
5892 * Create a pair of pipes.
5893 * Return TRUE for success, FALSE for failure.
5894 */
5895 static BOOL
5896create_pipe_pair(HANDLE handles[2])
5897{
5898 static LONG s;
5899 char name[64];
5900 SECURITY_ATTRIBUTES sa;
5901
5902 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5903 GetCurrentProcessId(),
5904 InterlockedIncrement(&s));
5905
5906 // Create named pipe. Max size of named pipe is 65535.
5907 handles[1] = CreateNamedPipe(
5908 name,
5909 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5910 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005911 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005912
5913 if (handles[1] == INVALID_HANDLE_VALUE)
5914 return FALSE;
5915
5916 sa.nLength = sizeof(sa);
5917 sa.bInheritHandle = TRUE;
5918 sa.lpSecurityDescriptor = NULL;
5919
5920 handles[0] = CreateFile(name,
5921 FILE_GENERIC_READ,
5922 FILE_SHARE_READ, &sa,
5923 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5924
5925 if (handles[0] == INVALID_HANDLE_VALUE)
5926 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005927 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005928 return FALSE;
5929 }
5930
5931 return TRUE;
5932}
5933
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005934 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005935mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005936{
5937 STARTUPINFO si;
5938 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005939 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005940 SECURITY_ATTRIBUTES saAttr;
5941 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005942 HANDLE ifd[2];
5943 HANDLE ofd[2];
5944 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005945 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005946
5947 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5948 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5949 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5950 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5951 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5952 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5953 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5954
5955 if (use_out_for_err && use_null_for_out)
5956 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005957
5958 ifd[0] = INVALID_HANDLE_VALUE;
5959 ifd[1] = INVALID_HANDLE_VALUE;
5960 ofd[0] = INVALID_HANDLE_VALUE;
5961 ofd[1] = INVALID_HANDLE_VALUE;
5962 efd[0] = INVALID_HANDLE_VALUE;
5963 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005964 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005965
Bram Moolenaar14207f42016-10-27 21:13:10 +02005966 jo = CreateJobObject(NULL, NULL);
5967 if (jo == NULL)
5968 {
5969 job->jv_status = JOB_FAILED;
5970 goto failed;
5971 }
5972
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005973 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005974 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005975
Bram Moolenaar76467df2016-02-12 19:30:26 +01005976 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005977 ZeroMemory(&si, sizeof(si));
5978 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005979 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005980 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005981
Bram Moolenaard8070362016-02-15 21:56:54 +01005982 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5983 saAttr.bInheritHandle = TRUE;
5984 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005985
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005986 if (use_file_for_in)
5987 {
5988 char_u *fname = options->jo_io_name[PART_IN];
5989
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005990 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5991 FILE_SHARE_READ | FILE_SHARE_WRITE,
5992 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5993 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005994 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005995 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005996 goto failed;
5997 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005998 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005999 else if (!use_null_for_in
6000 && (!create_pipe_pair(ifd)
6001 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006002 goto failed;
6003
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006004 if (use_file_for_out)
6005 {
6006 char_u *fname = options->jo_io_name[PART_OUT];
6007
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01006008 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
6009 FILE_SHARE_READ | FILE_SHARE_WRITE,
6010 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
6011 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006012 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006013 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006014 goto failed;
6015 }
6016 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006017 else if (!use_null_for_out &&
6018 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006019 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006020 goto failed;
6021
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006022 if (use_file_for_err)
6023 {
6024 char_u *fname = options->jo_io_name[PART_ERR];
6025
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01006026 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
6027 FILE_SHARE_READ | FILE_SHARE_WRITE,
6028 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
6029 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006030 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006031 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006032 goto failed;
6033 }
6034 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006035 else if (!use_out_for_err && !use_null_for_err &&
6036 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006037 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01006038 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006039
Bram Moolenaard8070362016-02-15 21:56:54 +01006040 si.dwFlags |= STARTF_USESTDHANDLES;
6041 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006042 si.hStdOutput = ofd[1];
6043 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
6044
6045 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
6046 {
Bram Moolenaarde279892016-03-11 22:19:44 +01006047 if (options->jo_set & JO_CHANNEL)
6048 {
6049 channel = options->jo_channel;
6050 if (channel != NULL)
6051 ++channel->ch_refcount;
6052 }
6053 else
6054 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006055 if (channel == NULL)
6056 goto failed;
6057 }
Bram Moolenaard8070362016-02-15 21:56:54 +01006058
6059 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02006060 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006061 CREATE_DEFAULT_ERROR_MODE |
6062 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006063 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01006064 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006065 &si, &pi,
6066 ga.ga_data,
6067 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01006068 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02006069 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006070 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006071 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006072 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006073
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006074 ga_clear(&ga);
6075
Bram Moolenaar14207f42016-10-27 21:13:10 +02006076 if (!AssignProcessToJobObject(jo, pi.hProcess))
6077 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006078 // if failing, switch the way to terminate
6079 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02006080 CloseHandle(jo);
6081 jo = NULL;
6082 }
6083 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01006084 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006085 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02006086 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006087 job->jv_status = JOB_STARTED;
6088
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02006089 CloseHandle(ifd[0]);
6090 CloseHandle(ofd[1]);
6091 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01006092 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01006093
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006094 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006095 if (channel != NULL)
6096 {
6097 channel_set_pipes(channel,
6098 use_file_for_in || use_null_for_in
6099 ? INVALID_FD : (sock_T)ifd[1],
6100 use_file_for_out || use_null_for_out
6101 ? INVALID_FD : (sock_T)ofd[0],
6102 use_out_for_err || use_file_for_err || use_null_for_err
6103 ? INVALID_FD : (sock_T)efd[0]);
6104 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006105 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006106 return;
6107
6108failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01006109 CloseHandle(ifd[0]);
6110 CloseHandle(ofd[0]);
6111 CloseHandle(efd[0]);
6112 CloseHandle(ifd[1]);
6113 CloseHandle(ofd[1]);
6114 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01006115 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006116 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006117}
6118
6119 char *
6120mch_job_status(job_T *job)
6121{
6122 DWORD dwExitCode = 0;
6123
Bram Moolenaar76467df2016-02-12 19:30:26 +01006124 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
6125 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006126 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01006127 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01006128 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02006129 {
6130 ch_log(job->jv_channel, "Job ended");
6131 job->jv_status = JOB_ENDED;
6132 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006133 return "dead";
6134 }
6135 return "run";
6136}
6137
Bram Moolenaar97792de2016-10-15 18:36:49 +02006138 job_T *
6139mch_detect_ended_job(job_T *job_list)
6140{
6141 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
6142 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
6143 job_T *job = job_list;
6144
6145 while (job != NULL)
6146 {
6147 DWORD n;
6148 DWORD result;
6149
6150 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
6151 && job != NULL; job = job->jv_next)
6152 {
6153 if (job->jv_status == JOB_STARTED)
6154 {
6155 jobHandles[n] = job->jv_proc_info.hProcess;
6156 jobArray[n] = job;
6157 ++n;
6158 }
6159 }
6160 if (n == 0)
6161 continue;
6162 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
6163 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
6164 {
6165 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
6166
6167 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
6168 return wait_job;
6169 }
6170 }
6171 return NULL;
6172}
6173
Bram Moolenaarfb630902016-10-29 14:55:00 +02006174 static BOOL
6175terminate_all(HANDLE process, int code)
6176{
6177 PROCESSENTRY32 pe;
6178 HANDLE h = INVALID_HANDLE_VALUE;
6179 DWORD pid = GetProcessId(process);
6180
6181 if (pid != 0)
6182 {
6183 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
6184 if (h != INVALID_HANDLE_VALUE)
6185 {
6186 pe.dwSize = sizeof(PROCESSENTRY32);
6187 if (!Process32First(h, &pe))
6188 goto theend;
6189
6190 do
6191 {
6192 if (pe.th32ParentProcessID == pid)
6193 {
6194 HANDLE ph = OpenProcess(
6195 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
6196 if (ph != NULL)
6197 {
6198 terminate_all(ph, code);
6199 CloseHandle(ph);
6200 }
6201 }
6202 } while (Process32Next(h, &pe));
6203
6204 CloseHandle(h);
6205 }
6206 }
6207
6208theend:
6209 return TerminateProcess(process, code);
6210}
6211
6212/*
6213 * Send a (deadly) signal to "job".
6214 * Return FAIL if it didn't work.
6215 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006216 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02006217mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006218{
Bram Moolenaar923d9262016-02-25 20:56:01 +01006219 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006220
Bram Moolenaar923d9262016-02-25 20:56:01 +01006221 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01006222 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006223 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02006224 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006225 {
6226 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
6227 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00006228 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006229 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01006230 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006231 }
6232
6233 if (!AttachConsole(job->jv_proc_info.dwProcessId))
6234 return FAIL;
6235 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01006236 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
6237 job->jv_proc_info.dwProcessId)
6238 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006239 FreeConsole();
6240 return ret;
6241}
6242
6243/*
6244 * Clear the data related to "job".
6245 */
6246 void
6247mch_clear_job(job_T *job)
6248{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00006249 if (job->jv_status == JOB_FAILED)
6250 return;
6251
6252 if (job->jv_job_object != NULL)
6253 CloseHandle(job->jv_job_object);
6254 CloseHandle(job->jv_proc_info.hProcess);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006255}
6256#endif
6257
Bram Moolenaar071d4272004-06-13 20:20:40 +00006258
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006259#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006260
6261/*
6262 * Start termcap mode
6263 */
6264 static void
6265termcap_mode_start(void)
6266{
6267 DWORD cmodein;
6268
6269 if (g_fTermcapMode)
6270 return;
6271
6272 SaveConsoleBuffer(&g_cbNonTermcap);
6273
6274 if (g_cbTermcap.IsValid)
6275 {
6276 /*
6277 * We've been in termcap mode before. Restore certain screen
6278 * characteristics, including the buffer size and the window
6279 * size. Since we will be redrawing the screen, we don't need
6280 * to restore the actual contents of the buffer.
6281 */
6282 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006283 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006284 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
6285 Rows = g_cbTermcap.Info.dwSize.Y;
6286 Columns = g_cbTermcap.Info.dwSize.X;
6287 }
6288 else
6289 {
6290 /*
6291 * This is our first time entering termcap mode. Clear the console
6292 * screen buffer, and resize the buffer to match the current window
6293 * size. We will use this as the size of our editing environment.
6294 */
6295 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006296 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006297 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
6298 }
6299
Bram Moolenaar071d4272004-06-13 20:20:40 +00006300 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006301
6302 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006303 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006304 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006305 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006306 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
6307 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006308 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006309 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006310 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006311 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6312 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006313 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006314 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006315
6316 redraw_later_clear();
6317 g_fTermcapMode = TRUE;
6318}
6319
6320
6321/*
6322 * End termcap mode
6323 */
6324 static void
6325termcap_mode_end(void)
6326{
6327 DWORD cmodein;
6328 ConsoleBuffer *cb;
6329 COORD coord;
6330 DWORD dwDummy;
6331
6332 if (!g_fTermcapMode)
6333 return;
6334
6335 SaveConsoleBuffer(&g_cbTermcap);
6336
6337 GetConsoleMode(g_hConIn, &cmodein);
6338 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006339 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6340 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006341
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006342# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01006343 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006344# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006345 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006346# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006347 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01006348 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006349
William Breslerded59132024-10-08 21:30:48 +02006350 // Switch back to main screen buffer.
6351 if (exiting && use_alternate_screen_buffer)
6352 vtp_printf("\033[?1049l");
6353
Christopher Plewright1140b512022-11-12 18:46:05 +00006354 if (!USE_WT && (p_rs || exiting))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006355 {
6356 /*
6357 * Clear anything that happens to be on the current line.
6358 */
6359 coord.X = 0;
6360 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006361 FillConsoleOutputCharacter(g_hConOut, ' ',
6362 cb->Info.dwSize.X, coord, &dwDummy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006363 /*
6364 * The following is just for aesthetics. If we are exiting without
6365 * restoring the screen, then we want to have a prompt string
6366 * appear at the bottom line. However, the command interpreter
6367 * seems to always advance the cursor one line before displaying
6368 * the prompt string, which causes the screen to scroll. To
6369 * counter this, move the cursor up one line before exiting.
6370 */
6371 if (exiting && !p_rs)
6372 coord.Y--;
6373 /*
6374 * Position the cursor at the leftmost column of the desired row.
6375 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006376 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006377 }
Christopher Plewright1140b512022-11-12 18:46:05 +00006378 SetConsoleCursorInfo(g_hConOut, &g_cci);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006379 g_fTermcapMode = FALSE;
6380}
Christopher Plewright38804d62022-11-09 23:55:52 +00006381#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006382
6383
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006384#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006385 void
6386mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01006387 char_u *s UNUSED,
6388 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006389{
Bram Moolenaar0f873732019-12-05 20:28:46 +01006390 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00006391}
6392
6393#else
6394
6395/*
6396 * clear `n' chars, starting from `coord'
6397 */
6398 static void
6399clear_chars(
6400 COORD coord,
6401 DWORD n)
6402{
Christopher Plewright38804d62022-11-09 23:55:52 +00006403 if (!vtp_working)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006404 {
6405 DWORD dwDummy;
6406
6407 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
6408 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
6409 &dwDummy);
6410 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006411 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02006412 {
6413 set_console_color_rgb();
6414 gotoxy(coord.X + 1, coord.Y + 1);
6415 vtp_printf("\033[%dX", n);
6416 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006417}
6418
6419
6420/*
6421 * Clear the screen
6422 */
6423 static void
6424clear_screen(void)
6425{
6426 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006427
Christopher Plewright38804d62022-11-09 23:55:52 +00006428 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006429 clear_chars(g_coord, Rows * Columns);
6430 else
6431 {
6432 set_console_color_rgb();
6433 gotoxy(1, 1);
6434 vtp_printf("\033[2J");
6435 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006436}
6437
6438
6439/*
6440 * Clear to end of display
6441 */
6442 static void
6443clear_to_end_of_display(void)
6444{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006445 COORD save = g_coord;
6446
Christopher Plewright38804d62022-11-09 23:55:52 +00006447 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006448 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006449 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006450 else
6451 {
6452 set_console_color_rgb();
6453 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6454 vtp_printf("\033[0J");
6455
6456 gotoxy(save.X + 1, save.Y + 1);
6457 g_coord = save;
6458 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006459}
6460
6461
6462/*
6463 * Clear to end of line
6464 */
6465 static void
6466clear_to_end_of_line(void)
6467{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006468 COORD save = g_coord;
6469
Christopher Plewright38804d62022-11-09 23:55:52 +00006470 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006471 clear_chars(g_coord, Columns - g_coord.X);
6472 else
6473 {
6474 set_console_color_rgb();
6475 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6476 vtp_printf("\033[0K");
6477
6478 gotoxy(save.X + 1, save.Y + 1);
6479 g_coord = save;
6480 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006481}
6482
6483
6484/*
6485 * Scroll the scroll region up by `cLines' lines
6486 */
6487 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006488scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006489{
6490 COORD oldcoord = g_coord;
6491
6492 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6493 delete_lines(cLines);
6494
6495 g_coord = oldcoord;
6496}
6497
6498
6499/*
6500 * Set the scroll region
6501 */
6502 static void
6503set_scroll_region(
6504 unsigned left,
6505 unsigned top,
6506 unsigned right,
6507 unsigned bottom)
6508{
6509 if (left >= right
6510 || top >= bottom
6511 || right > (unsigned) Columns - 1
6512 || bottom > (unsigned) Rows - 1)
6513 return;
6514
6515 g_srScrollRegion.Left = left;
6516 g_srScrollRegion.Top = top;
6517 g_srScrollRegion.Right = right;
6518 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006519}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006520
Bram Moolenaar6982f422019-02-16 16:48:01 +01006521 static void
6522set_scroll_region_tb(
6523 unsigned top,
6524 unsigned bottom)
6525{
6526 if (top >= bottom || bottom > (unsigned)Rows - 1)
6527 return;
6528
6529 g_srScrollRegion.Top = top;
6530 g_srScrollRegion.Bottom = bottom;
6531}
6532
6533 static void
6534set_scroll_region_lr(
6535 unsigned left,
6536 unsigned right)
6537{
6538 if (left >= right || right > (unsigned)Columns - 1)
6539 return;
6540
6541 g_srScrollRegion.Left = left;
6542 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006543}
6544
6545
6546/*
6547 * Insert `cLines' lines at the current cursor position
6548 */
6549 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006550insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006551{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006552 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006553 COORD dest;
6554 CHAR_INFO fill;
6555
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006556 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6557
Bram Moolenaar6982f422019-02-16 16:48:01 +01006558 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006559 dest.Y = g_coord.Y + cLines;
6560
Bram Moolenaar6982f422019-02-16 16:48:01 +01006561 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006562 source.Top = g_coord.Y;
6563 source.Right = g_srScrollRegion.Right;
6564 source.Bottom = g_srScrollRegion.Bottom - cLines;
6565
Bram Moolenaar6982f422019-02-16 16:48:01 +01006566 clip.Left = g_srScrollRegion.Left;
6567 clip.Top = g_coord.Y;
6568 clip.Right = g_srScrollRegion.Right;
6569 clip.Bottom = g_srScrollRegion.Bottom;
6570
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006571 fill.Char.AsciiChar = ' ';
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006572 if (!USE_VTP)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006573 fill.Attributes = g_attrCurrent;
6574 else
6575 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006576
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006577 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006578
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006579 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6580
Bram Moolenaar6982f422019-02-16 16:48:01 +01006581 // Here we have to deal with a win32 console flake: If the scroll
6582 // region looks like abc and we scroll c to a and fill with d we get
6583 // cbd... if we scroll block c one line at a time to a, we get cdd...
6584 // vim expects cdd consistently... So we have to deal with that
6585 // here... (this also occurs scrolling the same way in the other
6586 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006587
6588 if (source.Bottom < dest.Y)
6589 {
6590 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006591 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006592
Bram Moolenaar6982f422019-02-16 16:48:01 +01006593 coord.X = source.Left;
6594 for (i = clip.Top; i < dest.Y; ++i)
6595 {
6596 coord.Y = i;
6597 clear_chars(coord, source.Right - source.Left + 1);
6598 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006599 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006600
Christopher Plewright38804d62022-11-09 23:55:52 +00006601 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006602 {
6603 COORD coord;
6604 int i;
6605
6606 coord.X = source.Left;
6607 for (i = source.Top; i < dest.Y; ++i)
6608 {
6609 coord.Y = i;
6610 clear_chars(coord, source.Right - source.Left + 1);
6611 }
6612 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006613}
6614
6615
6616/*
6617 * Delete `cLines' lines at the current cursor position
6618 */
6619 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006620delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006621{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006622 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006623 COORD dest;
6624 CHAR_INFO fill;
6625 int nb;
6626
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006627 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6628
Bram Moolenaar6982f422019-02-16 16:48:01 +01006629 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006630 dest.Y = g_coord.Y;
6631
Bram Moolenaar6982f422019-02-16 16:48:01 +01006632 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006633 source.Top = g_coord.Y + cLines;
6634 source.Right = g_srScrollRegion.Right;
6635 source.Bottom = g_srScrollRegion.Bottom;
6636
Bram Moolenaar6982f422019-02-16 16:48:01 +01006637 clip.Left = g_srScrollRegion.Left;
6638 clip.Top = g_coord.Y;
6639 clip.Right = g_srScrollRegion.Right;
6640 clip.Bottom = g_srScrollRegion.Bottom;
6641
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006642 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006643 if (!vtp_working)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006644 fill.Attributes = g_attrCurrent;
6645 else
6646 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006647
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006648 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006649
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006650 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6651
Bram Moolenaar6982f422019-02-16 16:48:01 +01006652 // Here we have to deal with a win32 console flake; See insert_lines()
6653 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006654
6655 nb = dest.Y + (source.Bottom - source.Top) + 1;
6656
6657 if (nb < source.Top)
6658 {
6659 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006660 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006661
Bram Moolenaar6982f422019-02-16 16:48:01 +01006662 coord.X = source.Left;
6663 for (i = nb; i < clip.Bottom; ++i)
6664 {
6665 coord.Y = i;
6666 clear_chars(coord, source.Right - source.Left + 1);
6667 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006668 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006669
Christopher Plewright38804d62022-11-09 23:55:52 +00006670 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006671 {
6672 COORD coord;
6673 int i;
6674
6675 coord.X = source.Left;
6676 for (i = nb; i <= source.Bottom; ++i)
6677 {
6678 coord.Y = i;
6679 clear_chars(coord, source.Right - source.Left + 1);
6680 }
6681 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006682}
6683
6684
6685/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006686 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006687 */
6688 static void
6689gotoxy(
6690 unsigned x,
6691 unsigned y)
6692{
6693 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6694 return;
6695
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006696 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006697 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006698 // There are reports of double-width characters not displayed
6699 // correctly. This workaround should fix it, similar to how it's done
6700 // for VTP.
6701 g_coord.X = 0;
6702 SetConsoleCursorPosition(g_hConOut, g_coord);
6703
Bram Moolenaar2313b612019-09-27 14:14:32 +02006704 // external cursor coords are 1-based; internal are 0-based
6705 g_coord.X = x - 1;
6706 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006707 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006708 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006709 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006710 {
6711 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006712 // destruction. Insider build bug. Always enabled because it's cheap
6713 // and avoids mistakes with recognizing the build.
6714 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006715
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006716 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006717
6718 g_coord.X = x - 1;
6719 g_coord.Y = y - 1;
6720 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006721}
6722
6723
6724/*
6725 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006726 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006727 */
6728 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006729textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006730{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006731 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006732
6733 SetConsoleTextAttribute(g_hConOut, wAttr);
6734}
6735
6736
6737 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006738textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006739{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006740 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006741
Christopher Plewright38804d62022-11-09 23:55:52 +00006742 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006743 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6744 else
6745 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006746}
6747
6748
6749 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006750textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006751{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006752 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006753
Christopher Plewright38804d62022-11-09 23:55:52 +00006754 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006755 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6756 else
6757 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006758}
6759
6760
6761/*
6762 * restore the default text attribute (whatever we started with)
6763 */
6764 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006765normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006766{
Christopher Plewright38804d62022-11-09 23:55:52 +00006767 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006768 textattr(g_attrDefault);
6769 else
6770 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006771}
6772
6773
6774static WORD g_attrPreStandout = 0;
6775
6776/*
6777 * Make the text standout, by brightening it
6778 */
6779 static void
6780standout(void)
6781{
6782 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006783
Bram Moolenaar071d4272004-06-13 20:20:40 +00006784 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6785}
6786
6787
6788/*
6789 * Turn off standout mode
6790 */
6791 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006792standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006793{
6794 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006795 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006796
6797 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006798}
6799
6800
6801/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006802 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006803 */
6804 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006805mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006806{
6807 char_u *p;
6808 int n;
6809
6810 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6811 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006812 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006813# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006814 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006815# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006816 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006817 {
6818 p = T_ME + 2;
6819 n = getdigits(&p);
6820 if (*p == 'm' && n > 0)
6821 {
6822 cterm_normal_fg_color = (n & 0xf) + 1;
6823 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6824 }
6825 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006826# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006827 cterm_normal_fg_gui_color = INVALCOLOR;
6828 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006829# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006830}
6831
6832
6833/*
6834 * visual bell: flash the screen
6835 */
6836 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006837visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006838{
6839 COORD coordOrigin = {0, 0};
6840 WORD attrFlash = ~g_attrCurrent & 0xff;
6841
6842 DWORD dwDummy;
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006843 LPWORD oldattrs = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006844
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006845# ifdef FEAT_TERMGUICOLORS
6846 if (!(p_tgc || t_colors >= 256))
6847# endif
6848 {
6849 oldattrs = ALLOC_MULT(WORD, Rows * Columns);
6850 if (oldattrs == NULL)
6851 return;
6852 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006853 coordOrigin, &dwDummy);
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006854 }
6855
Bram Moolenaar071d4272004-06-13 20:20:40 +00006856 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6857 coordOrigin, &dwDummy);
6858
Bram Moolenaar0f873732019-12-05 20:28:46 +01006859 Sleep(15); // wait for 15 msec
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006860
6861 if (oldattrs != NULL)
6862 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006863 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006864 coordOrigin, &dwDummy);
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006865 vim_free(oldattrs);
6866 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006867}
6868
6869
6870/*
6871 * Make the cursor visible or invisible
6872 */
6873 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006874cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006875{
6876 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006877
Christopher Plewright38804d62022-11-09 23:55:52 +00006878 if (vtp_working)
Bram Moolenaar2695de62020-04-17 21:13:01 +02006879 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6880
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006881# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006882 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006883# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006884}
6885
6886
6887/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006888 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006889 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006890 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006891 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006892write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006893 char_u *pchBuf,
6894 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006895{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006896 COORD coord = g_coord;
6897 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006898 DWORD n, cchwritten;
6899 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006900 static WCHAR *unicodebuf = NULL;
6901 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006902 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006903 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006904 static WCHAR *utf8spbuf = NULL;
6905 static int utf8splength;
6906 static DWORD utf8spcells;
6907 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006908
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006909 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006910 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006911 utf8usingbuf = &unicodebuf;
6912 do
6913 {
6914 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6915 unicodebuf, unibuflen);
6916 if (length && length <= unibuflen)
6917 break;
6918 vim_free(unicodebuf);
6919 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6920 unibuflen = unibuflen ? 0 : length;
Bram Moolenaarc9471b12023-05-09 15:00:00 +01006921 } while (TRUE);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006922 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006923 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006924 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6925 {
6926 if (utf8usingbuf != &utf8spbuf)
6927 {
6928 if (utf8spbuf == NULL)
6929 {
6930 cells = mb_string2cells((char_u *)" ", 1);
6931 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6932 utf8spbuf = LALLOC_MULT(WCHAR, length);
6933 if (utf8spbuf != NULL)
6934 {
6935 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6936 utf8usingbuf = &utf8spbuf;
6937 utf8splength = length;
6938 utf8spcells = cells;
6939 }
6940 }
6941 else
6942 {
6943 utf8usingbuf = &utf8spbuf;
6944 length = utf8splength;
6945 cells = utf8spcells;
6946 }
6947 }
6948 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006949
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006950 if (!USE_VTP)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006951 {
6952 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6953 coord, &written);
6954 // When writing fails or didn't write a single character, pretend one
6955 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006956 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006957 coord, &cchwritten) == 0
6958 || cchwritten == 0 || cchwritten == (DWORD)-1)
6959 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006960 }
6961 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006962 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006963 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006964 NULL) == 0 || cchwritten == 0)
6965 cchwritten = 1;
6966 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006967
K.Takata135e1522022-01-29 15:27:58 +00006968 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006969 {
6970 written = cbToWrite;
6971 g_coord.X += (SHORT)cells;
6972 }
6973 else
6974 {
6975 char_u *p = pchBuf;
6976 for (n = 0; n < cchwritten; n++)
6977 MB_CPTR_ADV(p);
6978 written = p - pchBuf;
6979 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006980 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006981
6982 while (g_coord.X > g_srScrollRegion.Right)
6983 {
6984 g_coord.X -= (SHORT) Columns;
6985 if (g_coord.Y < g_srScrollRegion.Bottom)
6986 g_coord.Y++;
6987 }
6988
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006989 // Cursor under VTP is always in the correct position, no need to reset.
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006990 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006991 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006992
6993 return written;
6994}
6995
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006996 static char_u *
6997get_seq(
6998 int *args,
6999 int *count,
7000 char_u *head)
7001{
7002 int argc;
7003 char_u *p;
7004
7005 if (head == NULL || *head != '\033')
7006 return NULL;
7007
7008 argc = 0;
7009 p = head;
7010 ++p;
7011 do
7012 {
7013 ++p;
7014 args[argc] = getdigits(&p);
7015 argc += (argc < 15) ? 1 : 0;
7016 } while (*p == ';');
7017 *count = argc;
7018
7019 return p;
7020}
7021
7022 static char_u *
7023get_sgr(
7024 int *args,
7025 int *count,
7026 char_u *head)
7027{
7028 char_u *p = get_seq(args, count, head);
7029
7030 return (p && *p == 'm') ? ++p : NULL;
7031}
7032
7033/*
7034 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
7035 */
7036 static char_u *
7037sgrn2(
7038 char_u *head,
7039 int n)
7040{
7041 int argc;
7042 int args[16];
7043 char_u *p = get_sgr(args, &argc, head);
7044
7045 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
7046}
7047
7048/*
7049 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
7050 */
7051 static char_u *
7052sgrnc(
7053 char_u *head,
7054 int n)
7055{
7056 int argc;
7057 int args[16];
7058 char_u *p = get_sgr(args, &argc, head);
7059
7060 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
7061 ? p : NULL;
7062}
7063
7064 static char_u *
7065skipblank(char_u *q)
7066{
7067 char_u *p = q;
7068
7069 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
7070 ++p;
7071 return p;
7072}
7073
7074/*
7075 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
7076 * NULL.
7077 */
7078 static char_u *
7079sgrn2c(
7080 char_u *head,
7081 int n)
7082{
7083 char_u *p = sgrn2(head, n);
7084
7085 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
7086}
7087
7088/*
7089 * If there is only a newline between the sequence immediately following it,
7090 * a pointer to the character following the newline is returned.
7091 * Otherwise NULL.
7092 */
7093 static char_u *
7094sgrn2cn(
7095 char_u *head,
7096 int n)
7097{
7098 char_u *p = sgrn2(head, n);
7099
7100 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
7101}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007102
7103/*
7104 * mch_write(): write the output buffer to the screen, translating ESC
7105 * sequences into calls to console output routines.
7106 */
7107 void
7108mch_write(
7109 char_u *s,
7110 int len)
7111{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007112 char_u *end = s + len;
7113
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007114# ifdef VIMDLL
7115 if (gui.in_use)
7116 return;
7117# endif
7118
Bram Moolenaar071d4272004-06-13 20:20:40 +00007119 if (!term_console)
7120 {
7121 write(1, s, (unsigned)len);
7122 return;
7123 }
7124
Bram Moolenaar0f873732019-12-05 20:28:46 +01007125 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00007126 while (len--)
7127 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007128 int prefix = -1;
7129 char_u ch;
7130
7131 // While processing a sequence, on rare occasions it seems that another
7132 // sequence may be inserted asynchronously.
7133 if (len < 0)
7134 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01007135 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007136 return;
7137 }
7138
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007139 while (s + ++prefix < end)
7140 {
7141 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007142 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
7143 && ch != '\a' && ch != '\033'))
7144 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007145 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007146
7147 if (p_wd)
7148 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007149 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007150 if (prefix != 0)
7151 prefix = 1;
7152 }
7153
7154 if (prefix != 0)
7155 {
7156 DWORD nWritten;
7157
7158 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007159# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007160 if (fdDump)
7161 {
7162 fputc('>', fdDump);
7163 fwrite(s, sizeof(char_u), nWritten, fdDump);
7164 fputs("<\n", fdDump);
7165 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007166# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007167 len -= (nWritten - 1);
7168 s += nWritten;
7169 }
7170 else if (s[0] == '\n')
7171 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007172 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00007173 if (g_coord.Y == g_srScrollRegion.Bottom)
7174 {
7175 scroll(1);
7176 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
7177 }
7178 else
7179 {
7180 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
7181 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007182# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007183 if (fdDump)
7184 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007185# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007186 s++;
7187 }
7188 else if (s[0] == '\r')
7189 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007190 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00007191 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007192# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007193 if (fdDump)
7194 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007195# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007196 s++;
7197 }
7198 else if (s[0] == '\b')
7199 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007200 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00007201 if (g_coord.X > g_srScrollRegion.Left)
7202 g_coord.X--;
7203 else if (g_coord.Y > g_srScrollRegion.Top)
7204 {
7205 g_coord.X = g_srScrollRegion.Right;
7206 g_coord.Y--;
7207 }
7208 gotoxy(g_coord.X + 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("\\b\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] == '\a')
7216 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007217 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00007218 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007219# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007220 if (fdDump)
7221 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007222# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007223 s++;
7224 }
7225 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
7226 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007227# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007228 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007229# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007230 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007231 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007232 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007233
7234 switch (s[2])
7235 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007236 case '0': case '1': case '2': case '3': case '4':
7237 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007238 if (*(p = get_seq(args, &argc, s)) != 'm')
7239 goto notsgr;
7240
7241 p = s;
7242
7243 // Handling frequent optional sequences. Output to the screen
7244 // takes too long, so do not output as much as possible.
7245
7246 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
7247 // resetFG,FG,BG are omitted.
7248 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007249 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007250 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
7251 len = len + 1 - (int)(p - s);
7252 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007253 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007254 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007255
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007256 // If FG,BG,BG,FG of SGR are connected, the first FG can be
7257 // omitted.
7258 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
7259 p = sp;
7260
7261 // If FG,BG,FG,BG of SGR are connected, the first FG can be
7262 // omitted.
7263 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
7264 p = sp;
7265
7266 // If BG,BG of SGR are connected, the first BG can be omitted.
7267 if (sgrn2((sp = sgrn2(p, 48)), 48))
7268 p = sp;
7269
7270 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007271 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007272 if (sgrn2((sp = sgrnc(p, 39)), 38))
7273 p = sp;
7274
7275 p = get_seq(args, &argc, p);
7276
7277notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007278 arg1 = args[0];
7279 arg2 = args[1];
7280 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007281 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007282 if (argc == 1 && args[0] == 0)
7283 normvideo();
7284 else if (argc == 1)
7285 {
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00007286 if (USE_VTP)
Christopher Plewright38804d62022-11-09 23:55:52 +00007287 textcolor((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007288 else
Christopher Plewright38804d62022-11-09 23:55:52 +00007289 textattr((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007290 }
Christopher Plewright38804d62022-11-09 23:55:52 +00007291 else if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007292 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007293 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007294 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007295 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007296 gotoxy(arg2, arg1);
7297 }
7298 else if (argc == 2 && *p == 'r')
7299 {
7300 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
7301 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01007302 else if (argc == 2 && *p == 'R')
7303 {
7304 set_scroll_region_tb(arg1, arg2);
7305 }
7306 else if (argc == 2 && *p == 'V')
7307 {
7308 set_scroll_region_lr(arg1, arg2);
7309 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007310 else if (argc == 1 && *p == 'A')
7311 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007312 gotoxy(g_coord.X + 1,
7313 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
7314 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007315 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007316 {
7317 textbackground((WORD) arg1);
7318 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007319 else if (argc == 1 && *p == 'C')
7320 {
7321 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
7322 g_coord.Y + 1);
7323 }
7324 else if (argc == 1 && *p == 'f')
7325 {
7326 textcolor((WORD) arg1);
7327 }
7328 else if (argc == 1 && *p == 'H')
7329 {
7330 gotoxy(1, arg1);
7331 }
7332 else if (argc == 1 && *p == 'L')
7333 {
7334 insert_lines(arg1);
7335 }
7336 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007337 {
7338 delete_lines(arg1);
7339 }
7340
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007341 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007342 s = p + 1;
7343 break;
7344
Bram Moolenaar071d4272004-06-13 20:20:40 +00007345 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007346 gotoxy(g_coord.X + 1,
7347 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
7348 goto got3;
7349
7350 case 'B':
7351 visual_bell();
7352 goto got3;
7353
7354 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007355 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
7356 g_coord.Y + 1);
7357 goto got3;
7358
7359 case 'E':
7360 termcap_mode_end();
7361 goto got3;
7362
7363 case 'F':
7364 standout();
7365 goto got3;
7366
7367 case 'f':
7368 standend();
7369 goto got3;
7370
7371 case 'H':
7372 gotoxy(1, 1);
7373 goto got3;
7374
7375 case 'j':
7376 clear_to_end_of_display();
7377 goto got3;
7378
7379 case 'J':
7380 clear_screen();
7381 goto got3;
7382
7383 case 'K':
7384 clear_to_end_of_line();
7385 goto got3;
7386
7387 case 'L':
7388 insert_lines(1);
7389 goto got3;
7390
7391 case 'M':
7392 delete_lines(1);
7393 goto got3;
7394
7395 case 'S':
7396 termcap_mode_start();
7397 goto got3;
7398
7399 case 'V':
7400 cursor_visible(TRUE);
7401 goto got3;
7402
7403 case 'v':
7404 cursor_visible(FALSE);
7405 goto got3;
7406
7407 got3:
7408 s += 3;
7409 len -= 2;
7410 }
7411
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007412# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007413 if (fdDump)
7414 {
7415 fputs("ESC | ", fdDump);
7416 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
7417 fputc('\n', fdDump);
7418 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007419# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007420 }
K.Takatadf5320c2022-09-01 13:20:16 +01007421 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
7422 {
7423 int l = 2;
7424
Keith Thompson184f71c2024-01-04 21:19:04 +01007425 if (SAFE_isdigit(s[l]))
K.Takatadf5320c2022-09-01 13:20:16 +01007426 l++;
7427 if (s[l] == ' ' && s[l + 1] == 'q')
7428 {
7429 // DECSCUSR (cursor style) sequences
Christopher Plewright38804d62022-11-09 23:55:52 +00007430 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01007431 vtp_printf("%.*s", l + 2, s); // Pass through
7432 s += l + 2;
7433 len -= l + 1;
7434 }
7435 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007436 else
7437 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007438 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00007439 DWORD nWritten;
7440
7441 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007442# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007443 if (fdDump)
7444 {
7445 fputc('>', fdDump);
7446 fwrite(s, sizeof(char_u), nWritten, fdDump);
7447 fputs("<\n", fdDump);
7448 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007449# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007450
7451 len -= (nWritten - 1);
7452 s += nWritten;
7453 }
7454 }
7455
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007456# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007457 if (fdDump)
7458 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007459# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007460}
7461
Bram Moolenaar0f873732019-12-05 20:28:46 +01007462#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00007463
7464
7465/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01007466 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007467 */
7468 void
7469mch_delay(
7470 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02007471 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007472{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007473#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007474 Sleep((int)msec); // never wait for input
7475#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007476# ifdef VIMDLL
7477 if (gui.in_use)
7478 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007479 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007480 return;
7481 }
7482# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02007483 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007484# ifdef FEAT_MZSCHEME
7485 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
7486 {
7487 int towait = p_mzq;
7488
Bram Moolenaar0f873732019-12-05 20:28:46 +01007489 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007490 while (msec > 0)
7491 {
7492 mzvim_check_threads();
7493 if (msec < towait)
7494 towait = msec;
7495 Sleep(towait);
7496 msec -= towait;
7497 }
7498 }
7499 else
7500# endif
7501 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007502 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007503 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007504#endif
7505}
7506
7507
7508/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01007509 * This version of remove is not scared by a readonly (backup) file.
7510 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007511 * Return 0 for success, -1 for failure.
7512 */
7513 int
7514mch_remove(char_u *name)
7515{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007516 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007517 int n;
7518
Bram Moolenaar203258c2016-01-17 22:15:16 +01007519 /*
7520 * On Windows, deleting a directory's symbolic link is done by
7521 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
7522 */
7523 if (mch_isdir(name) && mch_is_symbolic_link(name))
7524 return mch_rmdir(name);
7525
Bram Moolenaar12b559e2013-06-12 22:41:37 +02007526 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
7527
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007528 wn = enc_to_utf16(name, NULL);
7529 if (wn == NULL)
7530 return -1;
7531
7532 n = DeleteFileW(wn) ? 0 : -1;
7533 vim_free(wn);
7534 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007535}
7536
7537
7538/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007539 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007540 */
7541 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007542mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007543{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007544#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7545# ifdef VIMDLL
7546 if (!gui.in_use)
7547# endif
7548 if (g_fCtrlCPressed || g_fCBrkPressed)
7549 {
7550 ctrl_break_was_pressed = g_fCBrkPressed;
7551 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7552 got_int = TRUE;
7553 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007554#endif
7555}
7556
Bram Moolenaar0f873732019-12-05 20:28:46 +01007557// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007558#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007559
7560/*
7561 * How much main memory in KiB that can be used by VIM.
7562 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007563 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007564mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007565{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007566 MEMORYSTATUSEX ms;
7567
Bram Moolenaar0f873732019-12-05 20:28:46 +01007568 // Need to use GlobalMemoryStatusEx() when there is more memory than
7569 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007570 ms.dwLength = sizeof(MEMORYSTATUSEX);
7571 GlobalMemoryStatusEx(&ms);
7572 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007573 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007574 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007575 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007576 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007577 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007578 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007579 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007580 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007581 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007582 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007583 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007584}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007585
Bram Moolenaar071d4272004-06-13 20:20:40 +00007586/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007587 * mch_wrename() works around a bug in rename (aka MoveFile) in
Nir Lichtman563e8ec2024-09-30 19:42:28 +02007588 * Windows, the bug can be demonstrated with the following scenario:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007589 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
Nir Lichtman563e8ec2024-09-30 19:42:28 +02007590 * "abcdef~1.txt" again.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007591 *
7592 * Like rename(), returns 0 upon success, non-zero upon failure.
7593 * Should probably set errno appropriately when errors occur.
7594 */
7595 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007596mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007597{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007598 WCHAR *p;
7599 int i;
7600 WCHAR szTempFile[_MAX_PATH + 1];
7601 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007602 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007603
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007604 // No need to play tricks unless the file name contains a "~" as the
7605 // seventh character.
7606 p = wold;
7607 for (i = 0; wold[i] != NUL; ++i)
7608 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
7609 && wold[i + 1] != 0)
7610 p = wold + i + 1;
7611 if ((int)(wold + i - p) < 8 || p[6] != '~')
7612 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007613
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007614 // Get base path of new file name. Undocumented feature: If pszNewFile is
7615 // a directory, no error is returned and pszFilePart will be NULL.
7616 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007617 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007618 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007619
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007620 // Get (and create) a unique temporary file name in directory of new file
7621 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007622 return -2;
7623
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007624 // blow the temp file away
7625 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007626 return -3;
7627
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007628 // rename old file to the temp file
7629 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007630 return -4;
7631
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007632 // now create an empty file called pszOldFile; this prevents the operating
7633 // system using pszOldFile as an alias (SFN) if we're renaming within the
7634 // same directory. For example, we're editing a file called
7635 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7636 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7637 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7638 // cause all sorts of problems later in buf_write(). So, we create an
7639 // empty file called filena~1.txt and the system will have to find some
7640 // other SFN for filena~1.txt~, such as filena~2.txt
7641 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007642 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7643 return -5;
7644 if (!CloseHandle(hf))
7645 return -6;
7646
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007647 // rename the temp file to the new file
7648 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007649 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007650 // Renaming failed. Rename the file back to its old name, so that it
7651 // looks like nothing happened.
7652 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007653 return -7;
7654 }
7655
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007656 // Seems to be left around on Novell filesystems
7657 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007658
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007659 // finally, remove the empty old file
7660 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007661 return -8;
7662
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007663 return 0;
7664}
7665
7666
7667/*
7668 * Converts the filenames to UTF-16, then call mch_wrename().
7669 * Like rename(), returns 0 upon success, non-zero upon failure.
7670 */
7671 int
7672mch_rename(
7673 const char *pszOldFile,
7674 const char *pszNewFile)
7675{
7676 WCHAR *wold = NULL;
7677 WCHAR *wnew = NULL;
7678 int retval = -1;
7679
7680 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7681 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7682 if (wold != NULL && wnew != NULL)
7683 retval = mch_wrename(wold, wnew);
7684 vim_free(wold);
7685 vim_free(wnew);
7686 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007687}
7688
7689/*
7690 * Get the default shell for the current hardware platform
7691 */
7692 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007693default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007694{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007695 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007696}
7697
7698/*
7699 * mch_access() extends access() to do more detailed check on network drives.
7700 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7701 */
7702 int
7703mch_access(char *n, int p)
7704{
7705 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007706 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007707 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007708
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007709 wn = enc_to_utf16((char_u *)n, NULL);
7710 if (wn == NULL)
7711 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007712
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007713 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007714 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007715 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007716
7717 if (p & R_OK)
7718 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007719 // Read check is performed by seeing if we can do a find file on
7720 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007721 int i;
7722 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007723
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007724 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7725 TempNameW[i] = wn[i];
7726 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7727 TempNameW[i++] = '\\';
7728 TempNameW[i++] = '*';
7729 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007730
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007731 hFile = FindFirstFileW(TempNameW, &d);
7732 if (hFile == INVALID_HANDLE_VALUE)
7733 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007734 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007735 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007736 }
7737
7738 if (p & W_OK)
7739 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007740 // Trying to create a temporary file in the directory should catch
7741 // directories on read-only network shares. However, in
7742 // directories whose ACL allows writes but denies deletes will end
7743 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007744 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7745 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007746 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007747 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007748 }
7749 }
7750 else
7751 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007752 // Don't consider a file read-only if another process has opened it.
7753 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7754
Bram Moolenaar0f873732019-12-05 20:28:46 +01007755 // Trying to open the file for the required access does ACL, read-only
7756 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007757 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7758 | ((p & R_OK) ? GENERIC_READ : 0);
7759
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007760 hFile = CreateFileW(wn, access_mode, share_mode,
7761 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007762 if (hFile == INVALID_HANDLE_VALUE)
7763 goto getout;
7764 CloseHandle(hFile);
7765 }
7766
Bram Moolenaar0f873732019-12-05 20:28:46 +01007767 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007768getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007769 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007770 return retval;
7771}
7772
Bram Moolenaar071d4272004-06-13 20:20:40 +00007773/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007774 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007775 */
7776 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007777mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007778{
7779 WCHAR *wn;
7780 int f;
7781
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007782 wn = enc_to_utf16((char_u *)name, NULL);
7783 if (wn == NULL)
7784 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007785
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007786 f = _wopen(wn, flags, mode);
7787 vim_free(wn);
7788 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007789}
7790
7791/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007792 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007793 */
7794 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007795mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007796{
7797 WCHAR *wn, *wm;
7798 FILE *f = NULL;
7799
Bram Moolenaara12a1612019-01-24 16:39:02 +01007800#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007801 // Work around an annoying assertion in the Microsoft debug CRT
7802 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007803 char newMode = mode[strlen(mode) - 1];
7804 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007805
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007806 _get_fmode(&oldMode);
7807 if (newMode == 't')
7808 _set_fmode(_O_TEXT);
7809 else if (newMode == 'b')
7810 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007811#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007812 wn = enc_to_utf16((char_u *)name, NULL);
7813 wm = enc_to_utf16((char_u *)mode, NULL);
7814 if (wn != NULL && wm != NULL)
7815 f = _wfopen(wn, wm);
7816 vim_free(wn);
7817 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007818
Bram Moolenaara12a1612019-01-24 16:39:02 +01007819#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007820 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007821#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007822 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007823}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007824
Bram Moolenaar071d4272004-06-13 20:20:40 +00007825/*
7826 * SUB STREAM (aka info stream) handling:
7827 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007828 * NTFS can have sub streams for each file. The normal contents of a file is
7829 * stored in the main stream, and extra contents (author information, title and
7830 * so on) can be stored in a sub stream. After Windows 2000, the user can
7831 * access and store this information in sub streams via an explorer's property
7832 * menu item in the right click menu. This information in sub streams was lost
7833 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007834 *
7835 * Incomplete explanation:
7836 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7837 * More useful info and an example:
7838 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7839 */
7840
7841/*
7842 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7843 * and write to stream "substream" of file "to".
7844 * Errors are ignored.
7845 */
7846 static void
7847copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7848{
7849 HANDLE hTo;
7850 WCHAR *to_name;
7851
7852 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7853 wcscpy(to_name, to);
7854 wcscat(to_name, substream);
7855
7856 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7857 FILE_ATTRIBUTE_NORMAL, NULL);
7858 if (hTo != INVALID_HANDLE_VALUE)
7859 {
7860 long done;
7861 DWORD todo;
7862 DWORD readcnt, written;
7863 char buf[4096];
7864
Bram Moolenaar0f873732019-12-05 20:28:46 +01007865 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007866 for (done = 0; done < len; done += written)
7867 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007868 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007869 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7870 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007871 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7872 FALSE, FALSE, context)
7873 || readcnt != todo
7874 || !WriteFile(hTo, buf, todo, &written, NULL)
7875 || written != todo)
7876 break;
7877 }
7878 CloseHandle(hTo);
7879 }
7880
7881 free(to_name);
7882}
7883
7884/*
7885 * Copy info streams from file "from" to file "to".
7886 */
7887 static void
7888copy_infostreams(char_u *from, char_u *to)
7889{
7890 WCHAR *fromw;
7891 WCHAR *tow;
7892 HANDLE sh;
7893 WIN32_STREAM_ID sid;
7894 int headersize;
7895 WCHAR streamname[_MAX_PATH];
7896 DWORD readcount;
7897 void *context = NULL;
7898 DWORD lo, hi;
7899 int len;
7900
Bram Moolenaar0f873732019-12-05 20:28:46 +01007901 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007902 fromw = enc_to_utf16(from, NULL);
7903 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007904 if (fromw != NULL && tow != NULL)
7905 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007906 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007907 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7908 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7909 if (sh != INVALID_HANDLE_VALUE)
7910 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007911 // Use BackupRead() to find the info streams. Repeat until we
7912 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007913 for (;;)
7914 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007915 // Get the header to find the length of the stream name. If
7916 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007917 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007918 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007919 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7920 &readcount, FALSE, FALSE, &context)
7921 || readcount == 0)
7922 break;
7923
Bram Moolenaar0f873732019-12-05 20:28:46 +01007924 // We only deal with streams that have a name. The normal
7925 // file data appears to be without a name, even though docs
7926 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007927 if (sid.dwStreamNameSize > 0)
7928 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007929 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007930 if (!BackupRead(sh, (LPBYTE)streamname,
7931 sid.dwStreamNameSize,
7932 &readcount, FALSE, FALSE, &context))
7933 break;
7934
Bram Moolenaar0f873732019-12-05 20:28:46 +01007935 // Copy an info stream with a name ":anything:$DATA".
7936 // Skip "::$DATA", it has no stream name (examples suggest
7937 // it might be used for the normal file contents).
7938 // Note that BackupRead() counts bytes, but the name is in
7939 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007940 len = readcount / sizeof(WCHAR);
7941 streamname[len] = 0;
7942 if (len > 7 && wcsicmp(streamname + len - 6,
7943 L":$DATA") == 0)
7944 {
7945 streamname[len - 6] = 0;
7946 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007947 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007948 }
7949 }
7950
Bram Moolenaar0f873732019-12-05 20:28:46 +01007951 // Advance to the next stream. We might try seeking too far,
7952 // but BackupSeek() doesn't skip over stream borders, thus
7953 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007954 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007955 &lo, &hi, &context);
7956 }
7957
Bram Moolenaar0f873732019-12-05 20:28:46 +01007958 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007959 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7960
7961 CloseHandle(sh);
7962 }
7963 }
7964 vim_free(fromw);
7965 vim_free(tow);
7966}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007967
7968/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007969 * ntdll.dll definitions
7970 */
7971#define FileEaInformation 7
7972#ifndef STATUS_SUCCESS
7973# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7974#endif
7975
7976typedef struct _FILE_FULL_EA_INFORMATION_ {
7977 ULONG NextEntryOffset;
7978 UCHAR Flags;
7979 UCHAR EaNameLength;
7980 USHORT EaValueLength;
7981 CHAR EaName[1];
7982} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7983
7984typedef struct _FILE_EA_INFORMATION_ {
7985 ULONG EaSize;
7986} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7987
Paul Ollis65745772022-06-05 16:55:54 +01007988#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007989typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7990 PHANDLE FileHandle,
7991 ACCESS_MASK DesiredAccess,
7992 POBJECT_ATTRIBUTES ObjectAttributes,
7993 PIO_STATUS_BLOCK IoStatusBlock,
7994 ULONG ShareAccess,
7995 ULONG OpenOptions);
7996typedef NTSTATUS (NTAPI *PfnNtClose)(
7997 HANDLE Handle);
7998typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007999 HANDLE FileHandle,
8000 PIO_STATUS_BLOCK IoStatusBlock,
8001 PVOID Buffer,
8002 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008003typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
8004 HANDLE FileHandle,
8005 PIO_STATUS_BLOCK IoStatusBlock,
8006 PVOID Buffer,
8007 ULONG Length,
8008 BOOLEAN ReturnSingleEntry,
8009 PVOID EaList,
8010 ULONG EaListLength,
8011 PULONG EaIndex,
8012 BOOLEAN RestartScan);
8013typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01008014 HANDLE FileHandle,
8015 PIO_STATUS_BLOCK IoStatusBlock,
8016 PVOID FileInformation,
8017 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008018 FILE_INFORMATION_CLASS FileInformationClass);
8019typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
8020 PUNICODE_STRING DestinationString,
8021 PCWSTR SourceString);
8022
8023PfnNtOpenFile pNtOpenFile = NULL;
8024PfnNtClose pNtClose = NULL;
8025PfnNtSetEaFile pNtSetEaFile = NULL;
8026PfnNtQueryEaFile pNtQueryEaFile = NULL;
8027PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
8028PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01008029#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008030
8031/*
8032 * Load ntdll.dll functions.
8033 */
8034 static BOOL
8035load_ntdll(void)
8036{
8037 static int loaded = -1;
8038
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008039 if (loaded != -1)
8040 return (BOOL) loaded;
8041
8042 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
8043 if (hNtdll != NULL)
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008044 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008045 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
8046 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
8047 pNtSetEaFile = (PfnNtSetEaFile)
8048 GetProcAddress(hNtdll, "NtSetEaFile");
8049 pNtQueryEaFile = (PfnNtQueryEaFile)
8050 GetProcAddress(hNtdll, "NtQueryEaFile");
8051 pNtQueryInformationFile = (PfnNtQueryInformationFile)
8052 GetProcAddress(hNtdll, "NtQueryInformationFile");
8053 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
8054 GetProcAddress(hNtdll, "RtlInitUnicodeString");
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008055 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008056 if (pNtOpenFile == NULL
8057 || pNtClose == NULL
8058 || pNtSetEaFile == NULL
8059 || pNtQueryEaFile == NULL
8060 || pNtQueryInformationFile == NULL
8061 || pRtlInitUnicodeString == NULL)
8062 loaded = FALSE;
8063 else
8064 loaded = TRUE;
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008065 return (BOOL) loaded;
8066}
8067
8068/*
8069 * Copy extended attributes (EA) from file "from" to file "to".
8070 */
8071 static void
8072copy_extattr(char_u *from, char_u *to)
8073{
8074 char_u *fromf = NULL;
8075 char_u *tof = NULL;
8076 WCHAR *fromw = NULL;
8077 WCHAR *tow = NULL;
8078 UNICODE_STRING u;
8079 HANDLE h;
8080 OBJECT_ATTRIBUTES oa;
8081 IO_STATUS_BLOCK iosb;
8082 FILE_EA_INFORMATION_ eainfo = {0};
8083 void *ea = NULL;
8084
8085 if (!load_ntdll())
8086 return;
8087
8088 // Convert the file names to the fully qualified object names.
8089 fromf = alloc(STRLEN(from) + 5);
8090 tof = alloc(STRLEN(to) + 5);
8091 if (fromf == NULL || tof == NULL)
8092 goto theend;
8093 STRCPY(fromf, "\\??\\");
8094 STRCAT(fromf, from);
8095 STRCPY(tof, "\\??\\");
8096 STRCAT(tof, to);
8097
8098 // Convert the names to wide characters.
8099 fromw = enc_to_utf16(fromf, NULL);
8100 tow = enc_to_utf16(tof, NULL);
8101 if (fromw == NULL || tow == NULL)
8102 goto theend;
8103
8104 // Get the EA.
8105 pRtlInitUnicodeString(&u, fromw);
8106 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8107 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
8108 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8109 goto theend;
8110 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
8111 FileEaInformation);
8112 if (eainfo.EaSize != 0)
8113 {
8114 ea = alloc(eainfo.EaSize);
8115 if (ea != NULL)
8116 {
8117 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
8118 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
8119 {
Yegappan Lakshmanan960dcbd2023-03-07 17:45:11 +00008120 VIM_CLEAR(ea);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008121 }
8122 }
8123 }
8124 pNtClose(h);
8125
8126 // Set the EA.
8127 if (ea != NULL)
8128 {
8129 pRtlInitUnicodeString(&u, tow);
8130 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8131 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
8132 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8133 goto theend;
8134
8135 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
8136 pNtClose(h);
8137 }
8138
8139theend:
8140 vim_free(fromf);
8141 vim_free(tof);
8142 vim_free(fromw);
8143 vim_free(tow);
8144 vim_free(ea);
8145}
8146
8147/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008148 * Copy file attributes from file "from" to file "to".
8149 * For Windows NT and later we copy info streams.
8150 * Always returns zero, errors are ignored.
8151 */
8152 int
8153mch_copy_file_attribute(char_u *from, char_u *to)
8154{
Bram Moolenaar0f873732019-12-05 20:28:46 +01008155 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02008156 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008157 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008158 return 0;
8159}
8160
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008161
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008162/*
K.Takatadc73b4b2021-06-08 18:32:36 +02008163 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008164 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008165static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008166static LPWSTR *ArglistW = NULL;
8167static int global_argc = 0;
8168static char **global_argv;
8169
Bram Moolenaar0f873732019-12-05 20:28:46 +01008170static int used_file_argc = 0; // last argument in global_argv[] used
8171 // for the argument list.
8172static int *used_file_indexes = NULL; // indexes in global_argv[] for
8173 // command line arguments added to
8174 // the argument list
8175static int used_file_count = 0; // nr of entries in used_file_indexes
8176static int used_file_literal = FALSE; // take file names literally
8177static int used_file_full_path = FALSE; // file name was full path
8178static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008179static int used_alist_count = 0;
8180
8181
8182/*
8183 * Get the command line arguments. Unicode version.
8184 * Returns argc. Zero when something fails.
8185 */
8186 int
8187get_cmd_argsW(char ***argvp)
8188{
8189 char **argv = NULL;
8190 int argc = 0;
8191 int i;
8192
Bram Moolenaar14993322014-09-09 12:25:33 +02008193 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008194 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
8195 if (ArglistW != NULL)
8196 {
8197 argv = malloc((nArgsW + 1) * sizeof(char *));
8198 if (argv != NULL)
8199 {
8200 argc = nArgsW;
8201 argv[argc] = NULL;
8202 for (i = 0; i < argc; ++i)
8203 {
8204 int len;
8205
K.Takatadc73b4b2021-06-08 18:32:36 +02008206 // Convert each Unicode argument to UTF-8.
8207 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008208 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008209 (LPSTR *)&argv[i], &len, 0, 0);
8210 if (argv[i] == NULL)
8211 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008212 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008213 while (i > 0)
8214 free(argv[--i]);
8215 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01008216 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008217 argc = 0;
8218 }
8219 }
8220 }
8221 }
8222
8223 global_argc = argc;
8224 global_argv = argv;
8225 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02008226 {
8227 if (used_file_indexes != NULL)
8228 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008229 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02008230 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008231
8232 if (argvp != NULL)
8233 *argvp = argv;
8234 return argc;
8235}
8236
8237 void
8238free_cmd_argsW(void)
8239{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008240 if (ArglistW == NULL)
8241 return;
8242
8243 GlobalFree(ArglistW);
8244 ArglistW = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008245}
8246
8247/*
8248 * Remember "name" is an argument that was added to the argument list.
8249 * This avoids that we have to re-parse the argument list when fix_arg_enc()
8250 * is called.
8251 */
8252 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008253used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008254{
8255 int i;
8256
8257 if (used_file_indexes == NULL)
8258 return;
8259 for (i = used_file_argc + 1; i < global_argc; ++i)
8260 if (STRCMP(global_argv[i], name) == 0)
8261 {
8262 used_file_argc = i;
8263 used_file_indexes[used_file_count++] = i;
8264 break;
8265 }
8266 used_file_literal = literal;
8267 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008268 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008269}
8270
8271/*
8272 * Remember the length of the argument list as it was. If it changes then we
8273 * leave it alone when 'encoding' is set.
8274 */
8275 void
8276set_alist_count(void)
8277{
8278 used_alist_count = GARGCOUNT;
8279}
8280
8281/*
8282 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02008283 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008284 * and convert them to 'encoding'.
8285 */
8286 void
8287fix_arg_enc(void)
8288{
8289 int i;
8290 int idx;
8291 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00008292 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008293
Bram Moolenaar0f873732019-12-05 20:28:46 +01008294 // Safety checks:
8295 // - if argument count differs between the wide and non-wide argument
8296 // list, something must be wrong.
8297 // - the file name arguments must have been located.
8298 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008299 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008300 || ArglistW == NULL
8301 || used_file_indexes == NULL
8302 || used_file_count == 0
8303 || used_alist_count != GARGCOUNT)
8304 return;
8305
Bram Moolenaar0f873732019-12-05 20:28:46 +01008306 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02008307 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008308 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008309 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00008310 for (i = 0; i < GARGCOUNT; ++i)
8311 fnum_list[i] = GARGLIST[i].ae_fnum;
8312
Bram Moolenaar0f873732019-12-05 20:28:46 +01008313 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008314 alist_clear(&global_alist);
8315 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008316 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008317
8318 for (i = 0; i < used_file_count; ++i)
8319 {
8320 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008321 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008322 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00008323 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008324 int literal = used_file_literal;
8325
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008326#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01008327 // When using diff mode may need to concatenate file name to
8328 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008329 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
8330 && !mch_isdir(alist_name(&GARGLIST[0])))
8331 {
8332 char_u *r;
8333
8334 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
8335 if (r != NULL)
8336 {
8337 vim_free(str);
8338 str = r;
8339 }
8340 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008341#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01008342 // Re-use the old buffer by renaming it. When not using literal
8343 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00008344 if (used_file_literal)
8345 buf_set_name(fnum_list[i], str);
8346
Bram Moolenaar0f873732019-12-05 20:28:46 +01008347 // Check backtick literal. backtick literal is already expanded in
8348 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008349 if (literal == FALSE)
8350 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02008351 size_t len = STRLEN(str);
8352
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008353 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
8354 literal = TRUE;
8355 }
8356 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008357 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008358 }
8359
8360 if (!used_file_literal)
8361 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008362 // Now expand wildcards in the arguments.
8363 // Temporarily add '(' and ')' to 'isfname'. These are valid
8364 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00008365 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01008366 // Also, unset wildignore to not be influenced by this option.
8367 // The arguments specified in command-line should be kept even if
8368 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00008369 // Use :legacy so that it also works when in Vim9 script.
8370 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
8371 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00008372 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00008373 do_cmdline_cmd(
8374 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
8375 do_cmdline_cmd(
8376 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008377 }
8378
Bram Moolenaar0f873732019-12-05 20:28:46 +01008379 // If wildcard expansion failed, we are editing the first file of the
8380 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008381 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
8382 {
8383 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00008384 if (GARGCOUNT == 1 && used_file_full_path
8385 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
8386 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008387 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00008388
8389 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008390}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008391
8392 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02008393mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008394{
8395 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008396 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008397
Bram Moolenaar964b3742019-05-24 18:54:09 +02008398 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008399 if (envbuf == NULL)
8400 return -1;
8401
8402 sprintf((char *)envbuf, "%s=%s", var, value);
8403
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008404 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008405
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008406 vim_free(envbuf);
8407 if (p == NULL)
8408 return -1;
8409 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008410#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008411 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008412#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008413 // Unlike Un*x systems, we can free the string for _wputenv().
8414 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008415
8416 return 0;
8417}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008418
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008419/*
8420 * Support for 256 colors and 24-bit colors was added in Windows 10
8421 * version 1703 (Creators update).
8422 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008423#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
8424
8425/*
8426 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02008427 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008428 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008429#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008430
8431/*
8432 * ConPTY differences between versions, need different logic.
8433 * version 1903 (May 2019 update).
8434 */
8435#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
8436
8437/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008438 * version 1909 (November 2019 update).
8439 */
8440#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
8441
8442/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008443 * Stay ahead of the next update, and when it's done, fix this.
8444 * version ? (2020 update, temporarily use the build number of insider preview)
8445 */
8446#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
8447
8448/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02008449 * Confirm until this version. Also the logic changes.
8450 * insider preview.
8451 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02008452#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008453
8454/*
8455 * Not stable now.
8456 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008457#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Christopher Plewright1140b512022-11-12 18:46:05 +00008458// Notes:
8459// Win 10 22H2 Final is build 19045, it's conpty is widely used.
8460// Strangely, 19045 is newer but is a lower build number than the 2020 insider
8461// preview which had a build 19587. And, not sure how stable that was?
8462// Win Server 2022 (May 10, 2022) is build 20348, its conpty is widely used.
8463// Win 11 starts from build 22000, even though the major version says 10!
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008464
8465 static void
8466vtp_flag_init(void)
8467{
8468 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008469#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008470 DWORD mode;
8471 HANDLE out;
8472
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008473# ifdef VIMDLL
8474 if (!gui.in_use)
8475# endif
8476 {
8477 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008478
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008479 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
8480 GetConsoleMode(out, &mode);
8481 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
8482 if (SetConsoleMode(out, mode) == 0)
8483 vtp_working = 0;
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008484
8485 // VTP uses alternate screen buffer.
8486 // But, not if running in a nested terminal
8487 use_alternate_screen_buffer = win10_22H2_or_later && p_rs && vtp_working
8488 && !mch_getenv("VIM_TERMINAL");
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008489 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008490#endif
8491
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008492 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008493 conpty_working = 1;
8494 if (ver >= CONPTY_STABLE_BUILD)
8495 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008496
Bram Moolenaar57da6982019-09-13 22:30:11 +02008497 if (ver <= CONPTY_INSIDER_BUILD)
8498 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008499 if (ver <= CONPTY_1909_BUILD)
8500 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02008501 if (ver <= CONPTY_1903_BUILD)
8502 conpty_type = 2;
8503 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
8504 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008505
8506 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
8507 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008508}
8509
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008510#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008511
8512 static void
8513vtp_init(void)
8514{
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008515# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightd343c602023-01-22 18:58:30 +00008516 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8517 csbi.cbSize = sizeof(csbi);
8518 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8519 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
8520 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
8521 store_console_bg_rgb = save_console_bg_rgb;
8522 store_console_fg_rgb = save_console_fg_rgb;
Christopher Plewright38804d62022-11-09 23:55:52 +00008523
Christopher Plewrightd343c602023-01-22 18:58:30 +00008524 COLORREF bg;
8525 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
8526 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8527 default_console_color_bg = bg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008528
Christopher Plewrightd343c602023-01-22 18:58:30 +00008529 COLORREF fg;
8530 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
8531 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8532 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008533# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008534 set_console_color_rgb();
8535}
8536
8537 static void
8538vtp_exit(void)
8539{
Bram Moolenaardf543822020-01-30 11:53:59 +01008540 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008541}
8542
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008543 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008544vtp_printf(
8545 char *format,
8546 ...)
8547{
8548 char_u buf[100];
8549 va_list list;
8550 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008551 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008552
Nir Lichtman6cd2d1d2023-11-11 11:27:41 +01008553 if (silent_mode)
8554 return 0;
8555
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008556 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008557 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008558 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008559 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008560 return (int)result;
8561}
8562
8563 static void
8564vtp_sgr_bulk(
8565 int arg)
8566{
8567 int args[1];
8568
8569 args[0] = arg;
8570 vtp_sgr_bulks(1, args);
8571}
8572
K.Takata6e1d31e2022-02-03 13:05:32 +00008573# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008574 if ((*p-- = "0123456789"[(n = x % 10)]) \
8575 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8576 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8577
K.Takata6e1d31e2022-02-03 13:05:32 +00008578# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008579 case x: \
8580 FAST256(newargs[x - 1]);
8581
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008582 static void
8583vtp_sgr_bulks(
8584 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008585 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008586{
K.Takata6e1d31e2022-02-03 13:05:32 +00008587# define MAXSGR 16
8588# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008589 char_u buf[SGRBUFSIZE];
8590 char_u *p;
8591 int in, out;
8592 int newargs[16];
8593 static int sgrfgr = -1, sgrfgg, sgrfgb;
8594 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008595
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008596 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008597 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008598 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008599 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008600 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008601 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008602
8603 in = out = 0;
8604 while (in < argc)
8605 {
8606 int s = args[in];
8607 int copylen = 1;
8608
8609 if (s == 38)
8610 {
8611 if (argc - in >= 5 && args[in + 1] == 2)
8612 {
8613 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8614 && sgrfgb == args[in + 4])
8615 {
8616 in += 5;
8617 copylen = 0;
8618 }
8619 else
8620 {
8621 sgrfgr = args[in + 2];
8622 sgrfgg = args[in + 3];
8623 sgrfgb = args[in + 4];
8624 copylen = 5;
8625 }
8626 }
8627 else if (argc - in >= 3 && args[in + 1] == 5)
8628 {
8629 sgrfgr = -1;
8630 copylen = 3;
8631 }
8632 }
8633 else if (s == 48)
8634 {
8635 if (argc - in >= 5 && args[in + 1] == 2)
8636 {
8637 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8638 && sgrbgb == args[in + 4])
8639 {
8640 in += 5;
8641 copylen = 0;
8642 }
8643 else
8644 {
8645 sgrbgr = args[in + 2];
8646 sgrbgg = args[in + 3];
8647 sgrbgb = args[in + 4];
8648 copylen = 5;
8649 }
8650 }
8651 else if (argc - in >= 3 && args[in + 1] == 5)
8652 {
8653 sgrbgr = -1;
8654 copylen = 3;
8655 }
8656 }
8657 else if (30 <= s && s <= 39)
8658 sgrfgr = -1;
8659 else if (90 <= s && s <= 97)
8660 sgrfgr = -1;
8661 else if (40 <= s && s <= 49)
8662 sgrbgr = -1;
8663 else if (100 <= s && s <= 107)
8664 sgrbgr = -1;
8665 else if (s == 0)
8666 sgrfgr = sgrbgr = -1;
8667
8668 while (copylen--)
8669 newargs[out++] = args[in++];
8670 }
8671
8672 p = &buf[sizeof(buf) - 1];
8673 *p-- = 'm';
8674
8675 switch (out)
8676 {
8677 int n, m;
8678 DWORD r;
8679
8680 FAST256CASE(16);
8681 *p-- = ';';
8682 FAST256CASE(15);
8683 *p-- = ';';
8684 FAST256CASE(14);
8685 *p-- = ';';
8686 FAST256CASE(13);
8687 *p-- = ';';
8688 FAST256CASE(12);
8689 *p-- = ';';
8690 FAST256CASE(11);
8691 *p-- = ';';
8692 FAST256CASE(10);
8693 *p-- = ';';
8694 FAST256CASE(9);
8695 *p-- = ';';
8696 FAST256CASE(8);
8697 *p-- = ';';
8698 FAST256CASE(7);
8699 *p-- = ';';
8700 FAST256CASE(6);
8701 *p-- = ';';
8702 FAST256CASE(5);
8703 *p-- = ';';
8704 FAST256CASE(4);
8705 *p-- = ';';
8706 FAST256CASE(3);
8707 *p-- = ';';
8708 FAST256CASE(2);
8709 *p-- = ';';
8710 FAST256CASE(1);
8711 *p-- = '[';
8712 *p = '\033';
8713 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8714 default:
8715 break;
8716 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008717}
8718
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008719 static void
8720wt_init(void)
8721{
Christopher Plewright1140b512022-11-12 18:46:05 +00008722 wt_working = mch_getenv("WT_SESSION") != NULL;
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008723}
8724
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008725# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008726 static int
8727ctermtoxterm(
8728 int cterm)
8729{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008730 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008731
8732 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8733 return (((int)r << 16) | ((int)g << 8) | (int)b);
8734}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008735# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008736
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008737 static void
8738set_console_color_rgb(void)
8739{
8740# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008741 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008742 guicolor_T fg, bg;
8743 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008744
Christopher Plewright38804d62022-11-09 23:55:52 +00008745 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008746 return;
8747
Bram Moolenaara050b942019-12-02 21:35:31 +01008748 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8749
Christopher Plewright38804d62022-11-09 23:55:52 +00008750 if (p_tgc || t_colors >= 256)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008751 {
8752 term_fg_rgb_color(fg);
8753 term_bg_rgb_color(bg);
8754 return;
8755 }
8756
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008757 if (use_alternate_screen_buffer)
8758 return;
8759
Christopher Plewrightd343c602023-01-22 18:58:30 +00008760 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8761 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008762
Christopher Plewrightd343c602023-01-22 18:58:30 +00008763 csbi.cbSize = sizeof(csbi);
8764 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008765
Christopher Plewrightd343c602023-01-22 18:58:30 +00008766 csbi.cbSize = sizeof(csbi);
8767 csbi.srWindow.Right += 1;
8768 csbi.srWindow.Bottom += 1;
8769 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8770 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
8771 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8772 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
8773 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008774# endif
8775}
8776
Bram Moolenaara050b942019-12-02 21:35:31 +01008777# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8778 void
8779get_default_console_color(
8780 int *cterm_fg,
8781 int *cterm_bg,
8782 guicolor_T *gui_fg,
8783 guicolor_T *gui_bg)
8784{
8785 int id;
8786 guicolor_T guifg = INVALCOLOR;
8787 guicolor_T guibg = INVALCOLOR;
8788 int ctermfg = 0;
8789 int ctermbg = 0;
Christopher Plewright38804d62022-11-09 23:55:52 +00008790 int dummynull = 0;
Bram Moolenaara050b942019-12-02 21:35:31 +01008791
8792 id = syn_name2id((char_u *)"Normal");
8793 if (id > 0 && p_tgc)
8794 syn_id2colors(id, &guifg, &guibg);
8795 if (guifg == INVALCOLOR)
8796 {
8797 ctermfg = -1;
8798 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008799 syn_id2cterm_bg(id, &ctermfg, &dummynull);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008800 if (ctermfg != -1)
8801 guifg = ctermtoxterm(ctermfg);
Christopher Plewright38804d62022-11-09 23:55:52 +00008802 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008803 guifg = USE_WT ? INVALCOLOR : default_console_color_fg;
8804 cterm_normal_fg_gui_color = guifg;
8805 ctermfg = ctermfg < 0 ? 0 : ctermfg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008806 }
8807 if (guibg == INVALCOLOR)
8808 {
8809 ctermbg = -1;
8810 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008811 syn_id2cterm_bg(id, &dummynull, &ctermbg);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008812 if (ctermbg != -1)
8813 guibg = ctermtoxterm(ctermbg);
K.Takatae53a0d42022-09-05 21:45:11 +01008814 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008815 guibg = USE_WT ? INVALCOLOR : default_console_color_bg;
8816 cterm_normal_bg_gui_color = guibg;
8817 ctermbg = ctermbg < 0 ? 0 : ctermbg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008818 }
8819
8820 *cterm_fg = ctermfg;
8821 *cterm_bg = ctermbg;
8822 *gui_fg = guifg;
8823 *gui_bg = guibg;
8824}
8825# endif
8826
Bram Moolenaardf543822020-01-30 11:53:59 +01008827/*
8828 * Set the console colors to the original colors or the last set colors.
8829 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008830 static void
8831reset_console_color_rgb(void)
8832{
8833# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008834 if (use_alternate_screen_buffer)
8835 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008836
Christopher Plewright38804d62022-11-09 23:55:52 +00008837 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8838
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008839 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008840 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008841
8842 csbi.cbSize = sizeof(csbi);
8843 csbi.srWindow.Right += 1;
8844 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008845 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8846 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008847 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008848# endif
8849}
8850
8851/*
8852 * Set the console colors to the original colors.
8853 */
8854 static void
8855restore_console_color_rgb(void)
8856{
8857# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008858 if (use_alternate_screen_buffer)
8859 return;
Christopher Plewright38804d62022-11-09 23:55:52 +00008860
K.Takata27b53be2022-09-18 12:25:49 +01008861 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008862
8863 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008864 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008865
8866 csbi.cbSize = sizeof(csbi);
8867 csbi.srWindow.Right += 1;
8868 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008869 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8870 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008871 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008872# endif
8873}
8874
8875 void
8876control_console_color_rgb(void)
8877{
Christopher Plewright38804d62022-11-09 23:55:52 +00008878 if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008879 set_console_color_rgb();
8880 else
8881 reset_console_color_rgb();
8882}
8883
8884 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008885use_vtp(void)
8886{
8887 return USE_VTP;
8888}
8889
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008890 int
8891is_term_win32(void)
8892{
8893 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8894}
8895
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008896 int
8897has_vtp_working(void)
8898{
8899 return vtp_working;
8900}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008901
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008902#endif
8903
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008904 int
8905has_conpty_working(void)
8906{
8907 return conpty_working;
8908}
8909
8910 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008911get_conpty_type(void)
8912{
8913 return conpty_type;
8914}
8915
8916 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008917is_conpty_stable(void)
8918{
8919 return conpty_stable;
8920}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008921
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008922 int
8923get_conpty_fix_type(void)
8924{
8925 return conpty_fix_type;
8926}
8927
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008928#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008929 void
8930resize_console_buf(void)
8931{
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008932 if (use_alternate_screen_buffer)
8933 return;
8934
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008935 CONSOLE_SCREEN_BUFFER_INFO csbi;
8936 COORD coord;
8937 SMALL_RECT newsize;
8938
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008939 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8940 return;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008941
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008942 coord.X = SRWIDTH(csbi.srWindow);
8943 coord.Y = SRHEIGHT(csbi.srWindow);
8944 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008945
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008946 newsize.Left = 0;
8947 newsize.Top = 0;
8948 newsize.Right = coord.X - 1;
8949 newsize.Bottom = coord.Y - 1;
8950 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8951
8952 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008953}
8954#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008955
8956 char *
8957GetWin32Error(void)
8958{
K.Takatad68b2fc2022-02-12 11:18:37 +00008959 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008960 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008961
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008962 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8963 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008964 if (oldmsg != NULL)
8965 LocalFree(oldmsg);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008966 if (msg == NULL)
8967 return NULL;
8968
8969 // remove trailing \r\n
8970 char *pcrlf = strstr(msg, "\r\n");
8971 if (pcrlf != NULL)
8972 *pcrlf = '\0';
8973 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008974 return msg;
8975}
Paul Ollis65745772022-06-05 16:55:54 +01008976
8977#if defined(FEAT_RELTIME) || defined(PROTO)
8978static HANDLE timer_handle;
8979static int timer_active = FALSE;
8980
8981/*
8982 * Calls to start_timeout alternate the return value pointer between the two
8983 * entries in timeout_flags. If the previously active timeout is very close to
8984 * expiring when start_timeout() is called then a race condition means that the
8985 * set_flag() function may still be invoked after the previous timer is
8986 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8987 * timeouts.
8988 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008989static sig_atomic_t timeout_flags[2];
8990static int timeout_flag_idx = 0;
8991static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01008992
8993
8994 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01008995set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01008996{
8997 int *timeout_flag = (int *)param;
8998
8999 *timeout_flag = TRUE;
9000}
9001
9002/*
9003 * Stop any active timeout.
9004 */
9005 void
9006stop_timeout(void)
9007{
9008 if (timer_active)
9009 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01009010 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01009011 timer_active = FALSE;
9012 if (!ret && GetLastError() != ERROR_IO_PENDING)
9013 {
9014 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
9015 }
9016 }
9017 *timeout_flag = FALSE;
9018}
9019
9020/*
9021 * Start the timeout timer.
9022 *
9023 * The period is defined in milliseconds.
9024 *
9025 * The return value is a pointer to a flag that is initialised to 0. If the
9026 * timeout expires, the flag is set to 1. This will only return pointers to
9027 * static memory; i.e. any pointer returned by this function may always be
9028 * safely dereferenced.
9029 *
9030 * This function is not expected to fail, but if it does it still returns a
9031 * valid flag pointer; the flag will remain stuck at zero.
9032 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01009033 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01009034start_timeout(long msec)
9035{
Paul Ollis65745772022-06-05 16:55:54 +01009036 BOOL ret;
9037
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01009038 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01009039
9040 stop_timeout();
9041 ret = CreateTimerQueueTimer(
9042 &timer_handle, NULL, set_flag, timeout_flag,
9043 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
9044 if (!ret)
9045 {
9046 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
9047 }
9048 else
9049 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01009050 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01009051 timer_active = TRUE;
9052 *timeout_flag = FALSE;
9053 }
9054 return timeout_flag;
9055}
9056#endif