blob: 92bc8c157f7e676fae575ee0b771e7d5374f4e20 [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 *
15 * Win32 (Windows NT and Windows 95) system-dependent routines.
16 * 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 Moolenaar82881492012-11-20 16:53:39 +010037#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000038
39#undef chdir
40#ifdef __GNUC__
41# ifndef __MINGW32__
42# include <dirent.h>
43# endif
44#else
45# include <direct.h>
46#endif
47
Bram Moolenaar82881492012-11-20 16:53:39 +010048#ifndef PROTO
Bram Moolenaar651fca82021-11-29 20:39:38 +000049# if !defined(FEAT_GUI_MSWIN)
Bram Moolenaar82881492012-11-20 16:53:39 +010050# include <shellapi.h>
51# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000052#endif
53
Bram Moolenaarfb630902016-10-29 14:55:00 +020054#ifdef FEAT_JOB_CHANNEL
55# include <tlhelp32.h>
56#endif
57
Bram Moolenaar071d4272004-06-13 20:20:40 +000058#ifdef __MINGW32__
59# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
60# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
61# endif
62# ifndef RIGHTMOST_BUTTON_PRESSED
63# define RIGHTMOST_BUTTON_PRESSED 0x0002
64# endif
65# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
66# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
67# endif
68# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
69# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
70# endif
71# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
72# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
73# endif
74
75/*
76 * EventFlags
77 */
78# ifndef MOUSE_MOVED
79# define MOUSE_MOVED 0x0001
80# endif
81# ifndef DOUBLE_CLICK
82# define DOUBLE_CLICK 0x0002
83# endif
84#endif
85
Bram Moolenaar0f873732019-12-05 20:28:46 +010086// Record all output and all keyboard & mouse input
87// #define MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +000088
89#ifdef MCH_WRITE_DUMP
90FILE* fdDump = NULL;
91#endif
92
93/*
94 * When generating prototypes for Win32 on Unix, these lines make the syntax
95 * errors disappear. They do not need to be correct.
96 */
97#ifdef PROTO
Bram Moolenaar912bc4a2019-12-01 18:58:11 +010098# define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000099typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000100typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000101typedef int ACCESS_MASK;
102typedef int BOOL;
Paul Ollis65745772022-06-05 16:55:54 +0100103typedef int BOOLEAN;
104typedef int CALLBACK;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000105typedef int COLORREF;
106typedef int CONSOLE_CURSOR_INFO;
107typedef int COORD;
108typedef int DWORD;
109typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100110typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000111typedef int HDC;
112typedef int HFONT;
113typedef int HICON;
114typedef int HINSTANCE;
115typedef int HWND;
116typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200117typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000118typedef int KEY_EVENT_RECORD;
119typedef int LOGFONT;
120typedef int LPBOOL;
121typedef int LPCTSTR;
122typedef int LPDWORD;
123typedef int LPSTR;
124typedef int LPTSTR;
125typedef int LPVOID;
126typedef int MOUSE_EVENT_RECORD;
127typedef int PACL;
128typedef int PDWORD;
129typedef int PHANDLE;
130typedef int PRINTDLG;
131typedef int PSECURITY_DESCRIPTOR;
132typedef int PSID;
133typedef int SECURITY_INFORMATION;
134typedef int SHORT;
135typedef int SMALL_RECT;
136typedef int TEXTMETRIC;
137typedef int TOKEN_INFORMATION_CLASS;
138typedef int TRUSTEE;
139typedef int WORD;
140typedef int WCHAR;
141typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100142typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200143typedef int SE_OBJECT_TYPE;
144typedef int PSNSECINFO;
145typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100146typedef int STARTUPINFO;
147typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200148typedef int LPSECURITY_ATTRIBUTES;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100149# define __stdcall // empty
Bram Moolenaar071d4272004-06-13 20:20:40 +0000150#endif
151
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200152#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100153// Win32 Console handles for input and output
Bram Moolenaar071d4272004-06-13 20:20:40 +0000154static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
155static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
156
Bram Moolenaar0f873732019-12-05 20:28:46 +0100157// Win32 Screen buffer,coordinate,console I/O information
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158static SMALL_RECT g_srScrollRegion;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100159static COORD g_coord; // 0-based, but external coords are 1-based
Bram Moolenaar071d4272004-06-13 20:20:40 +0000160
Bram Moolenaar0f873732019-12-05 20:28:46 +0100161// The attribute of the screen when the editor was started
162static WORD g_attrDefault = 7; // lightgray text on black background
Bram Moolenaar071d4272004-06-13 20:20:40 +0000163static WORD g_attrCurrent;
164
Bram Moolenaar0f873732019-12-05 20:28:46 +0100165static int g_fCBrkPressed = FALSE; // set by ctrl-break interrupt
166static int g_fCtrlCPressed = FALSE; // set when ctrl-C or ctrl-break detected
167static int g_fForceExit = FALSE; // set when forcefully exiting
Bram Moolenaar071d4272004-06-13 20:20:40 +0000168
Bram Moolenaar071d4272004-06-13 20:20:40 +0000169static void scroll(unsigned cLines);
170static void set_scroll_region(unsigned left, unsigned top,
171 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100172static void set_scroll_region_tb(unsigned top, unsigned bottom);
173static void set_scroll_region_lr(unsigned left, unsigned right);
174static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000175static void delete_lines(unsigned cLines);
176static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000177static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000178static int s_cursor_visible = TRUE;
179static int did_create_conin = FALSE;
Christopher Plewright20b795e2022-12-20 20:01:58 +0000180// The 'input_record_buffer' is an internal dynamic fifo queue of MS-Windows
181// console INPUT_RECORD events that are normally read from the console input
182// buffer. This provides an injection point for testing the low-level handling
183// of INPUT_RECORDs.
184typedef struct input_record_buffer_node_S
185{
186 INPUT_RECORD ir;
187 struct input_record_buffer_node_S *next;
188} input_record_buffer_node_T;
189typedef struct input_record_buffer_S
190{
191 input_record_buffer_node_T *head;
192 input_record_buffer_node_T *tail;
193 int length;
194} input_record_buffer_T;
195static input_record_buffer_T input_record_buffer;
Christopher Plewright20b795e2022-12-20 20:01:58 +0000196static int read_input_record_buffer(INPUT_RECORD* irEvents, int nMaxLength);
197static int write_input_record_buffer(INPUT_RECORD* irEvents, int nLength);
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200198#endif
199#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000200static int s_dont_use_vimrun = TRUE;
201static int need_vimrun_warning = FALSE;
202static char *vimrun_path = "vimrun ";
203#endif
204
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200205static int win32_getattrs(char_u *name);
206static int win32_setattrs(char_u *name, int attrs);
207static int win32_set_archive(char_u *name);
208
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100209static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200210static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100211static int conpty_stable = 0;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +0200212static int conpty_fix_type = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100213static void vtp_flag_init();
214
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200215#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100216static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100217static void vtp_init();
218static void vtp_exit();
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100219static void vtp_sgr_bulk(int arg);
220static void vtp_sgr_bulks(int argc, int *argv);
221
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200222static int wt_working = 0;
Christopher Plewright1140b512022-11-12 18:46:05 +0000223static void wt_init(void);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200224
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200225static int g_color_index_bg = 0;
226static int g_color_index_fg = 7;
227
228# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +0000229static guicolor_T save_console_bg_rgb;
230static guicolor_T save_console_fg_rgb;
231static guicolor_T store_console_bg_rgb;
232static guicolor_T store_console_fg_rgb;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +0100233static int default_console_color_bg = 0x000000; // black
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200234static int default_console_color_fg = 0xc0c0c0; // white
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +0000235# define USE_VTP (vtp_working && is_term_win32() \
236 && (p_tgc || t_colors >= 256))
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200237# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100238# else
239# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200240# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100241# endif
242
243static void set_console_color_rgb(void);
244static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100245static void restore_console_color_rgb(void);
Christopher Plewright20b795e2022-12-20 20:01:58 +0000246#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100247
Bram Moolenaar0f873732019-12-05 20:28:46 +0100248// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100249#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
250# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
251#endif
252
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200253#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100254static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000255#endif
256
K.Takatace3189d2023-02-15 19:13:43 +0000257static WCHAR *exe_pathw = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200258
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100259static BOOL win8_or_later = FALSE;
Christopher Plewrightc8b126d2022-12-22 13:45:23 +0000260static BOOL win10_22H2_or_later = FALSE;
Bram Moolenaar9fca1332022-12-22 21:06:41 +0000261#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Christopher Plewrightc8b126d2022-12-22 13:45:23 +0000262static BOOL use_alternate_screen_buffer = FALSE;
Bram Moolenaar9fca1332022-12-22 21:06:41 +0000263#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100264
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100265/*
266 * Get version number including build number
267 */
268typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100269#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100270 (((major) << 24) | ((minor) << 16) | (build))
271
272 static DWORD
273get_build_number(void)
274{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100275 OSVERSIONINFOW osver;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100276 HMODULE hNtdll;
277 PfnRtlGetVersion pRtlGetVersion;
278 DWORD ver = MAKE_VER(0, 0, 0);
279
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100280 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100281 hNtdll = GetModuleHandle("ntdll.dll");
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000282 if (hNtdll == NULL)
283 return ver;
284
285 pRtlGetVersion =
286 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
287 pRtlGetVersion(&osver);
288 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
289 min(osver.dwMinorVersion, 255),
290 min(osver.dwBuildNumber, 32767));
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100291 return ver;
292}
293
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200294#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200295 static BOOL
296is_ambiwidth_event(
297 INPUT_RECORD *ir)
298{
299 return ir->EventType == KEY_EVENT
300 && ir->Event.KeyEvent.bKeyDown
301 && ir->Event.KeyEvent.wRepeatCount == 1
302 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
303 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000304 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200305 && ir->Event.KeyEvent.dwControlKeyState == 2;
306}
307
308 static void
309make_ambiwidth_event(
310 INPUT_RECORD *down,
311 INPUT_RECORD *up)
312{
313 down->Event.KeyEvent.wVirtualKeyCode = 0;
314 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000315 down->Event.KeyEvent.uChar.UnicodeChar
316 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200317 down->Event.KeyEvent.dwControlKeyState = 0;
318}
319
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100320/*
321 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100322 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100323 */
324 static BOOL
325read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100326 HANDLE hInput,
327 INPUT_RECORD *lpBuffer,
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100328 int nLength,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100329 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100330{
331 enum
332 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100333 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100334 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100335 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100336 static DWORD s_dwIndex = 0;
337 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100338 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100339 int head;
340 int tail;
341 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200342 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100343
Christopher Plewright20b795e2022-12-20 20:01:58 +0000344 if (s_dwMax == 0 && input_record_buffer.length > 0)
345 {
346 dwEvents = read_input_record_buffer(s_irCache, IRSIZE);
347 s_dwIndex = 0;
348 s_dwMax = dwEvents;
349 }
350
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200351 if (nLength == -2)
352 return (s_dwMax > 0) ? TRUE : FALSE;
353
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100354 if (!win8_or_later)
355 {
356 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200357 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
358 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100359 }
360
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100361 if (s_dwMax == 0)
362 {
Christopher Plewright38804d62022-11-09 23:55:52 +0000363 if (!vtp_working && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200364 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200365 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
366 if (dwEvents == 0 && nLength == -1)
367 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
368 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100369 s_dwIndex = 0;
370 s_dwMax = dwEvents;
371 if (dwEvents == 0)
372 {
373 *lpEvents = 0;
374 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100375 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100376
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200377 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
378 if (is_ambiwidth_event(&s_irCache[i]))
379 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
380
Bram Moolenaardd415a62014-02-05 14:02:27 +0100381 if (s_dwMax > 1)
382 {
383 head = 0;
384 tail = s_dwMax - 1;
385 while (head != tail)
386 {
387 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
388 && s_irCache[head + 1].EventType
389 == WINDOW_BUFFER_SIZE_EVENT)
390 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100391 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100392 for (i = head; i < tail; ++i)
393 s_irCache[i] = s_irCache[i + 1];
394 --tail;
395 continue;
396 }
397 head++;
398 }
399 s_dwMax = tail + 1;
400 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100401 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100402
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200403 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
404 {
405 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
406 {
407 s_irPseudo = s_irCache[s_dwIndex];
408 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
409 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
410 *lpBuffer = s_irPseudo;
411 *lpEvents = 1;
412 return TRUE;
413 }
414 }
415
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100416 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200417 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100418 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100419 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100420 return TRUE;
421}
422
423/*
424 * Version of PeekConsoleInput() that works with IME.
425 */
426 static BOOL
427peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100428 HANDLE hInput,
429 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200430 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100431 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100432{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100433 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100434}
435
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100436# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200437 static DWORD
438msg_wait_for_multiple_objects(
439 DWORD nCount,
440 LPHANDLE pHandles,
441 BOOL fWaitAll,
442 DWORD dwMilliseconds,
443 DWORD dwWakeMask)
444{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100445 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200446 return WAIT_OBJECT_0;
447 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
448 dwMilliseconds, dwWakeMask);
449}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100450# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200451
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100452# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200453 static DWORD
454wait_for_single_object(
455 HANDLE hHandle,
456 DWORD dwMilliseconds)
457{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100458 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200459 return WAIT_OBJECT_0;
460 return WaitForSingleObject(hHandle, dwMilliseconds);
461}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100462# endif
Christopher Plewright20b795e2022-12-20 20:01:58 +0000463#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200464
K.Takatace3189d2023-02-15 19:13:43 +0000465 void
466mch_get_exe_name(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000467{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100468 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
K.Takataf741e3e2023-05-15 16:41:40 +0100469 // as the maximum length that works. Add 1 for a NUL byte and 5 for
470 // "PATH=".
471#define MAX_ENV_PATH_LEN (8191 + 1 + 5)
472 WCHAR temp[MAX_ENV_PATH_LEN];
K.Takatace3189d2023-02-15 19:13:43 +0000473 WCHAR buf[MAX_PATH];
474 int updated = FALSE;
475 static int enc_prev = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000476
K.Takatace3189d2023-02-15 19:13:43 +0000477 if (exe_name == NULL || exe_pathw == NULL || enc_prev != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000478 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100479 // store the name of the executable, may be used for $VIM
K.Takatace3189d2023-02-15 19:13:43 +0000480 GetModuleFileNameW(NULL, buf, MAX_PATH);
481 if (*buf != NUL)
482 {
483 if (enc_codepage == -1)
484 enc_codepage = GetACP();
K.Takataf741e3e2023-05-15 16:41:40 +0100485 vim_free(exe_name);
K.Takatace3189d2023-02-15 19:13:43 +0000486 exe_name = utf16_to_enc(buf, NULL);
487 enc_prev = enc_codepage;
488
489 WCHAR *wp = wcsrchr(buf, '\\');
490 if (wp != NULL)
491 *wp = NUL;
K.Takataf741e3e2023-05-15 16:41:40 +0100492 vim_free(exe_pathw);
K.Takatace3189d2023-02-15 19:13:43 +0000493 exe_pathw = _wcsdup(buf);
494 updated = TRUE;
495 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000496 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000497
K.Takatace3189d2023-02-15 19:13:43 +0000498 if (exe_pathw == NULL || !updated)
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000499 return;
500
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000501 // Append our starting directory to $PATH, so that when doing
502 // "!xxd" it's found in our starting directory. Needed because
503 // SearchPath() also looks there.
K.Takataf741e3e2023-05-15 16:41:40 +0100504 WCHAR *p = _wgetenv(L"PATH");
505 if (p == NULL || wcslen(p) + wcslen(exe_pathw) + 2 + 5 < MAX_ENV_PATH_LEN)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000506 {
K.Takataf741e3e2023-05-15 16:41:40 +0100507 wcscpy(temp, L"PATH=");
508
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000509 if (p == NULL || *p == NUL)
K.Takataf741e3e2023-05-15 16:41:40 +0100510 wcscat(temp, exe_pathw);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000511 else
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000512 {
K.Takataf741e3e2023-05-15 16:41:40 +0100513 wcscat(temp, p);
514
515 // Check if exe_path is already included in $PATH.
516 if (wcsstr(temp, exe_pathw) == NULL)
517 {
518 // Append ';' if $PATH doesn't end with it.
519 size_t len = wcslen(temp);
520 if (temp[len - 1] != L';')
521 wcscat(temp, L";");
522
523 wcscat(temp, exe_pathw);
524 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000525 }
K.Takataf741e3e2023-05-15 16:41:40 +0100526 _wputenv(temp);
527#ifdef libintl_wputenv
528 libintl_wputenv(temp);
529#endif
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000530 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000531}
532
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200533/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100534 * Unescape characters in "p" that appear in "escaped".
535 */
536 static void
537unescape_shellxquote(char_u *p, char_u *escaped)
538{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100539 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100540 int n;
541
542 while (*p != NUL)
543 {
544 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
545 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100546 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100547 p += n;
548 l -= n;
549 }
550}
551
552/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200553 * Load library "name".
554 */
555 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000556vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200557{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200558 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200559
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200560 // No need to load any library when registering OLE.
561 if (found_register_arg)
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000562 return NULL;
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200563
Bram Moolenaar0f873732019-12-05 20:28:46 +0100564 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
565 // vimLoadLib() recursively, which causes a stack overflow.
K.Takatace3189d2023-02-15 19:13:43 +0000566 if (exe_pathw == NULL)
K.Takataf741e3e2023-05-15 16:41:40 +0100567 {
K.Takatace3189d2023-02-15 19:13:43 +0000568 mch_get_exe_name();
K.Takataf741e3e2023-05-15 16:41:40 +0100569 if (exe_pathw == NULL)
570 return NULL;
571 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000572
573 WCHAR old_dirw[MAXPATHL];
574
575 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) == 0)
576 return NULL;
577
578 // Change directory to where the executable is, both to make
579 // sure we find a .dll there and to avoid looking for a .dll
580 // in the current directory.
K.Takatace3189d2023-02-15 19:13:43 +0000581 SetCurrentDirectoryW(exe_pathw);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000582 dll = LoadLibrary(name);
583 SetCurrentDirectoryW(old_dirw);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200584 return dll;
585}
586
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200587#if defined(VIMDLL) || defined(PROTO)
588/*
589 * Check if the current executable file is for the GUI subsystem.
590 */
591 int
592mch_is_gui_executable(void)
593{
594 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
595 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
596 PIMAGE_NT_HEADERS pPE;
597
598 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
599 return FALSE;
600 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
601 if (pPE->Signature != IMAGE_NT_SIGNATURE)
602 return FALSE;
603 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
604 return TRUE;
605 return FALSE;
606}
607#endif
608
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000609#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
610 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100611/*
612 * Get related information about 'funcname' which is imported by 'hInst'.
613 * If 'info' is 0, return the function address.
614 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000615 * If 'info' is 2, hook the function with 'ptr', and return the original
616 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100617 */
618 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000619get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
620 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100621{
622 PBYTE pImage = (PBYTE)hInst;
623 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
624 PIMAGE_NT_HEADERS pPE;
625 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100626 PIMAGE_THUNK_DATA pIAT; // Import Address Table
627 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100628 PIMAGE_IMPORT_BY_NAME pImpName;
Ken Takata119fdd92023-10-04 20:05:05 +0200629 DWORD ImpVA;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100630
631 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
632 return NULL;
633 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
634 if (pPE->Signature != IMAGE_NT_SIGNATURE)
635 return NULL;
Ken Takata119fdd92023-10-04 20:05:05 +0200636
637 ImpVA = pPE->OptionalHeader
638 .DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
639 if (ImpVA == 0)
640 return NULL; // No Import Table
641 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage + ImpVA);
642
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100643 for (; pImpDesc->FirstThunk; ++pImpDesc)
644 {
645 if (!pImpDesc->OriginalFirstThunk)
646 continue;
647 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
648 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
649 for (; pIAT->u1.Function; ++pIAT, ++pINT)
650 {
651 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
652 continue;
653 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
654 + (UINT_PTR)(pINT->u1.AddressOfData));
655 if (strcmp((char *)pImpName->Name, funcname) == 0)
656 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000657 void *original;
658 DWORD old, new = PAGE_READWRITE;
659
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100660 switch (info)
661 {
662 case 0:
663 return (void *)pIAT->u1.Function;
664 case 1:
665 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000666 case 2:
667 original = (void *)pIAT->u1.Function;
668 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
669 new, &old);
670 pIAT->u1.Function = (UINT_PTR)ptr;
671 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
672 old, &new);
673 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100674 default:
675 return NULL;
676 }
677 }
678 }
679 }
680 return NULL;
681}
682
683/*
684 * Get the module handle which 'funcname' in 'hInst' is imported from.
685 */
686 HINSTANCE
687find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
688{
689 char *modulename;
690
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000691 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100692 if (modulename != NULL)
693 return GetModuleHandleA(modulename);
694 return NULL;
695}
696
697/*
698 * Get the address of 'funcname' which is imported by 'hInst' DLL.
699 */
700 void *
701get_dll_import_func(HINSTANCE hInst, const char *funcname)
702{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000703 return get_imported_func_info(hInst, funcname, 0, NULL);
704}
705
706/*
707 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
708 * and return the original function address.
709 */
710 void *
711hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
712{
713 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100714}
715#endif
716
Ken Takata119fdd92023-10-04 20:05:05 +0200717#if defined(FEAT_PYTHON3) || defined(PROTO)
718/*
719 * Check if the specified DLL is a function forwarder.
720 * If yes, return the instance of the forwarded DLL.
721 * If no, return the specified DLL.
722 * If error, return NULL.
723 * This assumes that the DLL forwards all the function to a single DLL.
724 */
725 HINSTANCE
726get_forwarded_dll(HINSTANCE hInst)
727{
728 PBYTE pImage = (PBYTE)hInst;
729 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
730 PIMAGE_NT_HEADERS pPE;
731 PIMAGE_EXPORT_DIRECTORY pExpDir;
732 DWORD ExpVA;
733 DWORD ExpSize;
734 LPDWORD pFunctionTable;
735
736 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
737 return NULL;
738 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
739 if (pPE->Signature != IMAGE_NT_SIGNATURE)
740 return NULL;
741
742 ExpVA = pPE->OptionalHeader
743 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
744 ExpSize = pPE->OptionalHeader
745 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
746 if (ExpVA == 0)
747 return hInst; // No Export Directory
748 pExpDir = (PIMAGE_EXPORT_DIRECTORY)(pImage + ExpVA);
749 pFunctionTable = (LPDWORD)(pImage + pExpDir->AddressOfFunctions);
750
751 if (pExpDir->NumberOfNames == 0)
752 return hInst; // No export names.
753
754 // Check only the first entry.
755 if ((pFunctionTable[0] < ExpVA) || (pFunctionTable[0] >= ExpVA + ExpSize))
756 // The first entry is not a function forwarder.
757 return hInst;
758
759 // The first entry is a function forwarder.
760 // The name is represented as "DllName.FunctionName".
761 const char *name = (const char *)(pImage + pFunctionTable[0]);
762 const char *p = strchr(name, '.');
763 if (p == NULL)
764 return hInst;
765
766 // Extract DllName.
767 char buf[MAX_PATH];
768 if (p - name + 1 > sizeof(buf))
769 return NULL;
770 strncpy(buf, name, p - name);
771 buf[p - name] = '\0';
772 return GetModuleHandleA(buf);
773}
774#endif
775
Bram Moolenaar071d4272004-06-13 20:20:40 +0000776#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
777# ifndef GETTEXT_DLL
778# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200779# define GETTEXT_DLL_ALT1 "libintl-8.dll"
780# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000781# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100782// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000783static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200784static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000785static char *null_libintl_textdomain(const char *);
786static char *null_libintl_bindtextdomain(const char *, const char *);
787static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100788static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000789
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200790static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000791char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200792char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
793 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000794char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
795char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000796 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000797char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
798 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100799int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000800
801 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100802dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000803{
804 int i;
805 static struct
806 {
807 char *name;
808 FARPROC *ptr;
809 } libintl_entry[] =
810 {
811 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200812 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000813 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
814 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
815 {NULL, NULL}
816 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100817 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000818
Bram Moolenaar7554c542018-10-06 15:03:15 +0200819 // No need to initialize twice.
820 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000821 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200822 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100823 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100824# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100825 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200826 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100827# endif
828# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200829 if (!hLibintlDLL)
830 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100831# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100832 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000833 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200834 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000835 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200836 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000837 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200838 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000839 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200840 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000841 }
842 for (i = 0; libintl_entry[i].name != NULL
843 && libintl_entry[i].ptr != NULL; ++i)
844 {
K.Takata54119102022-02-03 13:33:03 +0000845 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000846 libintl_entry[i].name)) == NULL)
847 {
848 dyn_libintl_end();
849 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000850 {
851 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000852 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000853 verbose_leave();
854 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000855 return 0;
856 }
857 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000858
Bram Moolenaar0f873732019-12-05 20:28:46 +0100859 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100860 dyn_libintl_bind_textdomain_codeset = (char *(*)(const char *, const char *))
861 GetProcAddress(hLibintlDLL, "bind_textdomain_codeset");
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000862 if (dyn_libintl_bind_textdomain_codeset == NULL)
863 dyn_libintl_bind_textdomain_codeset =
864 null_libintl_bind_textdomain_codeset;
865
Bram Moolenaar0f873732019-12-05 20:28:46 +0100866 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100867 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
868 if (hmsvcrt != NULL)
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100869 dyn_libintl_wputenv = (int (*)(const wchar_t *))
870 GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100871 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
872 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100873
Bram Moolenaar071d4272004-06-13 20:20:40 +0000874 return 1;
875}
876
877 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100878dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000879{
880 if (hLibintlDLL)
881 FreeLibrary(hLibintlDLL);
882 hLibintlDLL = NULL;
883 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200884 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000885 dyn_libintl_textdomain = null_libintl_textdomain;
886 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000887 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100888 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000889}
890
891 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000892null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000893{
894 return (char*)msgid;
895}
896
897 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200898null_libintl_ngettext(
899 const char *msgid,
900 const char *msgid_plural,
901 unsigned long n)
902{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200903 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200904}
905
Bram Moolenaaree695f72016-08-03 22:08:45 +0200906 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100907null_libintl_bindtextdomain(
908 const char *domainname UNUSED,
909 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000910{
911 return NULL;
912}
913
914 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100915null_libintl_bind_textdomain_codeset(
916 const char *domainname UNUSED,
917 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000918{
919 return NULL;
920}
921
922 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100923null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000924{
925 return NULL;
926}
927
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200928 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100929null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100930{
931 return 0;
932}
933
Bram Moolenaar0f873732019-12-05 20:28:46 +0100934#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000935
Bram Moolenaar0f873732019-12-05 20:28:46 +0100936// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000937
938#ifndef VER_PLATFORM_WIN32_WINDOWS
939# define VER_PLATFORM_WIN32_WINDOWS 1
940#endif
941
Bram Moolenaar071d4272004-06-13 20:20:40 +0000942#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100943# ifndef PROTO
944# include <aclapi.h>
945# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200946# ifndef PROTECTED_DACL_SECURITY_INFORMATION
947# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
948# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000949#endif
950
Bram Moolenaar27515922013-06-29 15:36:26 +0200951#ifdef HAVE_ACL
952/*
953 * Enables or disables the specified privilege.
954 */
955 static BOOL
956win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
957{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100958 BOOL bResult;
959 LUID luid;
960 HANDLE hToken;
961 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200962
963 if (!OpenProcessToken(GetCurrentProcess(),
964 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
965 return FALSE;
966
967 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
968 {
969 CloseHandle(hToken);
970 return FALSE;
971 }
972
Bram Moolenaar45500912014-07-09 20:51:07 +0200973 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200974 tokenPrivileges.Privileges[0].Luid = luid;
975 tokenPrivileges.Privileges[0].Attributes = bEnable ?
976 SE_PRIVILEGE_ENABLED : 0;
977
978 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
979 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
980
981 CloseHandle(hToken);
982
983 return bResult && GetLastError() == ERROR_SUCCESS;
984}
985#endif
986
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100987#ifdef _MSC_VER
988// Suppress the deprecation warning for using GetVersionEx().
989// It is needed for implementing "windowsversion()".
990# pragma warning(push)
991# pragma warning(disable: 4996)
992#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000993/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200994 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000995 */
996 void
997PlatformId(void)
998{
999 static int done = FALSE;
1000
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00001001 if (done)
1002 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001003
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00001004 OSVERSIONINFO ovi;
1005
1006 ovi.dwOSVersionInfoSize = sizeof(ovi);
1007 GetVersionEx(&ovi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001008
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +02001009#ifdef FEAT_EVAL
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00001010 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
1011 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +02001012#endif
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00001013 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
1014 || ovi.dwMajorVersion > 6)
1015 win8_or_later = TRUE;
Bram Moolenaarf50eb782014-02-05 13:36:54 +01001016
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00001017 if ((ovi.dwMajorVersion == 10 && ovi.dwBuildNumber >= 19045)
1018 || ovi.dwMajorVersion > 10)
1019 win10_22H2_or_later = TRUE;
Christopher Plewright1140b512022-11-12 18:46:05 +00001020
Bram Moolenaar071d4272004-06-13 20:20:40 +00001021#ifdef HAVE_ACL
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00001022 // Enable privilege for getting or setting SACLs.
1023 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001024#endif
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00001025 done = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001026}
Bram Moolenaar29d2f452020-12-04 19:42:52 +01001027#ifdef _MSC_VER
1028# pragma warning(pop)
1029#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001030
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001031#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001032
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001033# define SHIFT (SHIFT_PRESSED)
1034# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
1035# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
1036# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001037
1038
Bram Moolenaar0f873732019-12-05 20:28:46 +01001039// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
1040// We map function keys to their ANSI terminal equivalents, as produced
1041// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
1042// ANSI key with a value >= '\300' is nonstandard, but provided anyway
1043// so that the user can have access to all SHIFT-, CTRL-, and ALT-
1044// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001045
Bram Moolenaard6f676d2005-06-01 21:51:55 +00001046static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +00001047{
1048 WORD wVirtKey;
1049 BOOL fAnsiKey;
1050 int chAlone;
1051 int chShift;
1052 int chCtrl;
1053 int chAlt;
1054} VirtKeyMap[] =
1055{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001056// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +00001057 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
1058
1059 { VK_F1, TRUE, ';', 'T', '^', 'h', },
1060 { VK_F2, TRUE, '<', 'U', '_', 'i', },
1061 { VK_F3, TRUE, '=', 'V', '`', 'j', },
1062 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
1063 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
1064 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
1065 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
1066 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
1067 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
1068 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001069 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
1070 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001071
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001072 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
1073 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
1074 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
1075 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
1076 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
1077 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
1078 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
1079 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
1080 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
1081 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001082 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +00001083
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001084 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +00001085
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001086# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001087 // Most people don't have F13-F20, but what the hell...
1088 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
1089 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
1090 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
1091 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
1092 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
1093 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
1094 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
1095 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001096# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001097 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
1098 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
1099 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
1100 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001101
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001102 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
1103 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
1104 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
1105 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
1106 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
1107 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
1108 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
1109 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
1110 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
1111 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001112 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001113};
1114
1115
Bram Moolenaar0f873732019-12-05 20:28:46 +01001116/*
1117 * The return code indicates key code size.
1118 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001119 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001120win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001121 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001122{
1123 UINT uMods = pker->dwControlKeyState;
1124 static int s_iIsDead = 0;
1125 static WORD awAnsiCode[2];
1126 static BYTE abKeystate[256];
1127
1128
1129 if (s_iIsDead == 2)
1130 {
K.Takata972db232022-02-04 10:45:38 +00001131 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001132 s_iIsDead = 0;
1133 return 1;
1134 }
1135
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001136 // check if it already has a valid unicode character.
Christopher Plewright566f76e2023-01-10 13:43:04 +00001137 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001138 return 1;
1139
Bram Moolenaara80faa82020-04-12 19:37:17 +02001140 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001141
Bram Moolenaar0f873732019-12-05 20:28:46 +01001142 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001143 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001144
1145 if (uMods & SHIFT_PRESSED)
1146 abKeystate[VK_SHIFT] = 0x80;
1147 if (uMods & CAPSLOCK_ON)
1148 abKeystate[VK_CAPITAL] = 1;
1149
1150 if ((uMods & ALT_GR) == ALT_GR)
1151 {
1152 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1153 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1154 }
1155
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001156 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1157 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001158
1159 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001160 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001161
1162 return s_iIsDead;
1163}
1164
Bram Moolenaar071d4272004-06-13 20:20:40 +00001165static BOOL g_fJustGotFocus = FALSE;
1166
1167/*
1168 * Decode a KEY_EVENT into one or two keystrokes
1169 */
1170 static BOOL
1171decode_key_event(
1172 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001173 WCHAR *pch,
1174 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001175 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001176 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001177{
1178 int i;
1179 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1180
1181 *pch = *pch2 = NUL;
1182 g_fJustGotFocus = FALSE;
1183
Bram Moolenaar0f873732019-12-05 20:28:46 +01001184 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001185 if (!pker->bKeyDown)
1186 return FALSE;
1187
Bram Moolenaar0f873732019-12-05 20:28:46 +01001188 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001189 switch (pker->wVirtualKeyCode)
1190 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001191 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001192 case VK_SHIFT:
1193 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001194 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001195 return FALSE;
1196
1197 default:
1198 break;
1199 }
1200
Bram Moolenaar0f873732019-12-05 20:28:46 +01001201 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001202 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1203 {
1204 *pch = K_NUL;
1205 *pch2 = '\017';
1206 return TRUE;
1207 }
1208
K.Takataeeec2542021-06-02 13:28:16 +02001209 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001210 {
1211 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1212 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001213 *pch = VirtKeyMap[i].chAlone;
1214 if ((nModifs & SHIFT) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001215 *pch = VirtKeyMap[i].chShift;
1216 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1217 *pch = VirtKeyMap[i].chCtrl;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001218 else if ((nModifs & ALT) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001219 *pch = VirtKeyMap[i].chAlt;
1220
1221 if (*pch != 0)
1222 {
1223 if (VirtKeyMap[i].fAnsiKey)
1224 {
1225 *pch2 = *pch;
1226 *pch = K_NUL;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001227 if (pmodifiers)
1228 {
1229 if (pker->wVirtualKeyCode >= VK_F1
1230 && pker->wVirtualKeyCode <= VK_F12)
1231 {
1232 if ((nModifs & ALT) != 0)
1233 {
1234 *pmodifiers |= MOD_MASK_ALT;
1235 if ((nModifs & SHIFT) == 0)
1236 *pch2 = VirtKeyMap[i].chAlone;
1237 }
1238 if ((nModifs & CTRL) != 0)
1239 {
1240 *pmodifiers |= MOD_MASK_CTRL;
1241 if ((nModifs & SHIFT) == 0)
1242 *pch2 = VirtKeyMap[i].chAlone;
1243 }
1244 }
1245 else if (pker->wVirtualKeyCode >= VK_END
1246 && pker->wVirtualKeyCode <= VK_DOWN)
1247 {
Christopher Plewright566f76e2023-01-10 13:43:04 +00001248 // (0x23 - 0x28): VK_END, VK_HOME,
1249 // VK_LEFT, VK_UP, VK_RIGHT, VK_DOWN
1250
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001251 *pmodifiers = 0;
1252 *pch2 = VirtKeyMap[i].chAlone;
1253 if ((nModifs & SHIFT) != 0
1254 && (nModifs & ~SHIFT) == 0)
1255 {
1256 *pch2 = VirtKeyMap[i].chShift;
1257 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001258 if ((nModifs & CTRL) != 0
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001259 && (nModifs & ~CTRL) == 0)
1260 {
1261 *pch2 = VirtKeyMap[i].chCtrl;
1262 if (pker->wVirtualKeyCode == VK_UP
1263 || pker->wVirtualKeyCode == VK_DOWN)
1264 {
1265 *pmodifiers |= MOD_MASK_CTRL;
1266 *pch2 = VirtKeyMap[i].chAlone;
1267 }
1268 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001269 if ((nModifs & SHIFT) != 0
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001270 && (nModifs & CTRL) != 0)
1271 {
1272 *pmodifiers |= MOD_MASK_CTRL;
1273 *pch2 = VirtKeyMap[i].chShift;
1274 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001275 if ((nModifs & ALT) != 0)
1276 {
1277 *pch2 = VirtKeyMap[i].chAlt;
1278 *pmodifiers |= MOD_MASK_ALT;
1279 if ((nModifs & ~ALT) == 0)
1280 {
1281 *pch2 = VirtKeyMap[i].chAlone;
1282 }
1283 else if ((nModifs & SHIFT) != 0)
1284 {
1285 *pch2 = VirtKeyMap[i].chShift;
1286 }
1287 else if ((nModifs & CTRL) != 0)
1288 {
1289 if (pker->wVirtualKeyCode == VK_UP
1290 || pker->wVirtualKeyCode == VK_DOWN)
1291 {
1292 *pmodifiers |= MOD_MASK_CTRL;
1293 *pch2 = VirtKeyMap[i].chAlone;
1294 }
1295 else
1296 {
1297 *pch2 = VirtKeyMap[i].chCtrl;
1298 }
1299 }
1300 }
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001301 }
1302 else
1303 {
1304 *pch2 = VirtKeyMap[i].chAlone;
1305 if ((nModifs & SHIFT) != 0)
1306 *pmodifiers |= MOD_MASK_SHIFT;
1307 if ((nModifs & CTRL) != 0)
1308 *pmodifiers |= MOD_MASK_CTRL;
1309 if ((nModifs & ALT) != 0)
1310 *pmodifiers |= MOD_MASK_ALT;
1311 }
1312 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001313 }
1314
1315 return TRUE;
1316 }
1317 }
1318 }
1319
1320 i = win32_kbd_patch_key(pker);
1321
1322 if (i < 0)
1323 *pch = NUL;
1324 else
1325 {
K.Takata972db232022-02-04 10:45:38 +00001326 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001327
1328 if (pmodifiers != NULL)
1329 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001330 // Pass on the ALT key as a modifier, but only when not combined
1331 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001332 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1333 *pmodifiers |= MOD_MASK_ALT;
1334
Bram Moolenaar0f873732019-12-05 20:28:46 +01001335 // Pass on SHIFT only for special keys, because we don't know when
1336 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001337 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1338 *pmodifiers |= MOD_MASK_SHIFT;
1339
Bram Moolenaar0f873732019-12-05 20:28:46 +01001340 // Pass on CTRL only for non-special keys, because we don't know
1341 // when it's already included with the character. And not when
1342 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001343 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1344 && *pch >= 0x20 && *pch < 0x80)
1345 *pmodifiers |= MOD_MASK_CTRL;
1346 }
1347 }
1348
1349 return (*pch != NUL);
1350}
1351
Christopher Plewright20b795e2022-12-20 20:01:58 +00001352# if defined(FEAT_EVAL)
1353 static int
1354encode_key_event(dict_T *args, INPUT_RECORD *ir)
1355{
1356 static int s_dwMods = 0;
1357
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001358 char_u *action = dict_get_string(args, "event", TRUE);
1359 if (action && (STRICMP(action, "keydown") == 0
1360 || STRICMP(action, "keyup") == 0))
Christopher Plewright20b795e2022-12-20 20:01:58 +00001361 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001362 BOOL isKeyDown = STRICMP(action, "keydown") == 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001363 WORD vkCode = dict_get_number_def(args, "keycode", 0);
1364 if (vkCode <= 0 || vkCode >= 0xFF)
1365 {
1366 semsg(_(e_invalid_argument_nr), (long)vkCode);
1367 return FALSE;
1368 }
1369
1370 ir->EventType = KEY_EVENT;
1371 KEY_EVENT_RECORD ker;
1372 ZeroMemory(&ker, sizeof(ker));
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001373 ker.bKeyDown = isKeyDown;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001374 ker.wRepeatCount = 1;
1375 ker.wVirtualScanCode = 0;
1376 ker.dwControlKeyState = 0;
1377 int mods = (int)dict_get_number(args, "modifiers");
1378 // Encode the win32 console key modifiers from Vim keyboard modifiers.
1379 if (mods)
1380 {
1381 // If "modifiers" is explicitly set in the args, then we reset any
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00001382 // remembered modifier key state that may have been set from
1383 // earlier mod-key-down events, even if they are not yet unset by
1384 // earlier mod-key-up events.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001385 s_dwMods = 0;
1386 if (mods & MOD_MASK_SHIFT)
1387 ker.dwControlKeyState |= SHIFT_PRESSED;
1388 if (mods & MOD_MASK_CTRL)
1389 ker.dwControlKeyState |= LEFT_CTRL_PRESSED;
1390 if (mods & MOD_MASK_ALT)
1391 ker.dwControlKeyState |= LEFT_ALT_PRESSED;
1392 }
1393
1394 if (vkCode == VK_LSHIFT || vkCode == VK_RSHIFT || vkCode == VK_SHIFT)
1395 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001396 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001397 s_dwMods |= SHIFT_PRESSED;
1398 else
1399 s_dwMods &= ~SHIFT_PRESSED;
1400 }
1401 else if (vkCode == VK_LCONTROL || vkCode == VK_CONTROL)
1402 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001403 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001404 s_dwMods |= LEFT_CTRL_PRESSED;
1405 else
1406 s_dwMods &= ~LEFT_CTRL_PRESSED;
1407 }
1408 else if (vkCode == VK_RCONTROL)
1409 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001410 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001411 s_dwMods |= RIGHT_CTRL_PRESSED;
1412 else
1413 s_dwMods &= ~RIGHT_CTRL_PRESSED;
1414 }
1415 else if (vkCode == VK_LMENU || vkCode == VK_MENU)
1416 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001417 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001418 s_dwMods |= LEFT_ALT_PRESSED;
1419 else
1420 s_dwMods &= ~LEFT_ALT_PRESSED;
1421 }
1422 else if (vkCode == VK_RMENU)
1423 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001424 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001425 s_dwMods |= RIGHT_ALT_PRESSED;
1426 else
1427 s_dwMods &= ~RIGHT_ALT_PRESSED;
1428 }
1429 ker.dwControlKeyState |= s_dwMods;
1430 ker.wVirtualKeyCode = vkCode;
Christopher Plewright566f76e2023-01-10 13:43:04 +00001431 ker.uChar.UnicodeChar = 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001432 ir->Event.KeyEvent = ker;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001433 vim_free(action);
Christopher Plewright20b795e2022-12-20 20:01:58 +00001434 }
1435 else
1436 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001437 if (action == NULL)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001438 {
1439 semsg(_(e_missing_argument_str), "event");
1440 }
1441 else
1442 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001443 semsg(_(e_invalid_value_for_argument_str_str), "event", action);
1444 vim_free(action);
Christopher Plewright20b795e2022-12-20 20:01:58 +00001445 }
1446 return FALSE;
1447 }
1448 return TRUE;
1449}
1450# endif // FEAT_EVAL
1451#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00001452
1453
Bram Moolenaar071d4272004-06-13 20:20:40 +00001454/*
1455 * For the GUI the mouse handling is in gui_w32.c.
1456 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001457#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001458 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001459mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001460{
1461}
Christopher Plewright20b795e2022-12-20 20:01:58 +00001462#else // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar0f873732019-12-05 20:28:46 +01001463static int g_fMouseAvail = FALSE; // mouse present
1464static int g_fMouseActive = FALSE; // mouse enabled
1465static int g_nMouseClick = -1; // mouse status
1466static int g_xMouse; // mouse x coordinate
1467static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001468static DWORD g_cmodein = 0; // Original console input mode
1469static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001470
1471/*
1472 * Enable or disable mouse input
1473 */
1474 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001475mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001476{
1477 DWORD cmodein;
1478
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001479# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001480 if (gui.in_use)
1481 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001482# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001483 if (!g_fMouseAvail)
1484 return;
1485
1486 g_fMouseActive = on;
1487 GetConsoleMode(g_hConIn, &cmodein);
1488
1489 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001490 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001491 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001492 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1493 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001494 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001495 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001496 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001497 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1498 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001499
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001500 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001501}
1502
Bram Moolenaar157d8132018-03-06 17:09:20 +01001503
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001504# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001505/*
1506 * Called when 'balloonevalterm' changed.
1507 */
1508 void
1509mch_bevalterm_changed(void)
1510{
1511 mch_setmouse(g_fMouseActive);
1512}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001513# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001514
Christopher Plewright2a46f812022-10-16 19:47:45 +01001515/*
1516 * Win32 console mouse scroll event handler.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001517 * Console version of the _OnMouseWheel() function in gui_w32.c
Christopher Plewright2a46f812022-10-16 19:47:45 +01001518 *
1519 * This encodes the mouse scroll direction and keyboard modifiers into
1520 * g_nMouseClick, and the mouse position into g_xMouse and g_yMouse
1521 *
1522 * The direction of the scroll is decoded from two fields of the win32 console
1523 * mouse event record;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001524 * 1. The orientation - vertical or horizontal flag - from dwEventFlags
Christopher Plewright2a46f812022-10-16 19:47:45 +01001525 * 2. The sign - positive or negative (aka delta flag) - from dwButtonState
1526 *
Christopher Plewright20b795e2022-12-20 20:01:58 +00001527 * When scroll orientation is HORIZONTAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001528 * - If the high word of the dwButtonState member contains a positive
1529 * value, the wheel was rotated to the right.
1530 * - Otherwise, the wheel was rotated to the left.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001531 * When scroll orientation is VERTICAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001532 * - If the high word of the dwButtonState member contains a positive value,
1533 * the wheel was rotated forward, away from the user.
1534 * - Otherwise, the wheel was rotated backward, toward the user.
1535 */
1536 static void
1537decode_mouse_wheel(MOUSE_EVENT_RECORD *pmer)
1538{
Christopher Plewright2a46f812022-10-16 19:47:45 +01001539 int horizontal = (pmer->dwEventFlags == MOUSE_HWHEELED);
1540 int zDelta = pmer->dwButtonState;
1541
1542 g_xMouse = pmer->dwMousePosition.X;
1543 g_yMouse = pmer->dwMousePosition.Y;
1544
K.Takata161b6ac2022-11-14 15:31:07 +00001545# ifdef FEAT_PROP_POPUP
Christopher Plewright605d02a2022-10-19 11:54:46 +01001546 int lcol = g_xMouse;
1547 int lrow = g_yMouse;
Christopher Plewright38804d62022-11-09 23:55:52 +00001548 win_T *wp = mouse_find_win(&lrow, &lcol, FIND_POPUP);
Christopher Plewright2a46f812022-10-16 19:47:45 +01001549 if (wp != NULL && popup_is_popup(wp))
1550 {
1551 g_nMouseClick = -1;
1552 cmdarg_T cap;
1553 oparg_T oa;
1554 CLEAR_FIELD(cap);
1555 clear_oparg(&oa);
1556 cap.oap = &oa;
1557 if (horizontal)
1558 {
1559 cap.arg = zDelta < 0 ? MSCR_LEFT : MSCR_RIGHT;
1560 cap.cmdchar = zDelta < 0 ? K_MOUSELEFT : K_MOUSERIGHT;
1561 }
1562 else
1563 {
1564 cap.cmdchar = zDelta < 0 ? K_MOUSEUP : K_MOUSEDOWN;
1565 cap.arg = zDelta < 0 ? MSCR_UP : MSCR_DOWN;
1566 }
1567
1568 // Mouse hovers over popup window, scroll it if possible.
1569 mouse_row = wp->w_winrow;
1570 mouse_col = wp->w_wincol;
1571 nv_mousescroll(&cap);
1572 update_screen(0);
1573 setcursor();
1574 out_flush();
1575 return;
1576 }
K.Takata161b6ac2022-11-14 15:31:07 +00001577# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01001578 mouse_col = g_xMouse;
1579 mouse_row = g_yMouse;
1580
1581 char_u modifiers = 0;
1582 char_u direction = 0;
1583
1584 // Decode the direction into an event that Vim can process
1585 if (horizontal)
1586 direction = zDelta >= 0 ? KE_MOUSELEFT : KE_MOUSERIGHT;
1587 else
1588 direction = zDelta >= 0 ? KE_MOUSEDOWN : KE_MOUSEUP;
1589
dundargocc57b5bc2022-11-02 13:30:51 +00001590 // Decode the win32 console key modifiers into Vim mouse modifiers.
Christopher Plewright2a46f812022-10-16 19:47:45 +01001591 if (pmer->dwControlKeyState & SHIFT_PRESSED)
Christopher Plewright605d02a2022-10-19 11:54:46 +01001592 modifiers |= MOD_MASK_SHIFT; // MOUSE_SHIFT;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001593 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
Christopher Plewright605d02a2022-10-19 11:54:46 +01001594 modifiers |= MOD_MASK_CTRL; // MOUSE_CTRL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001595 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1596 modifiers |= MOD_MASK_ALT; // MOUSE_ALT;
1597
1598 // add (bitwise or) the scroll direction and the key modifier chars
1599 // together.
1600 g_nMouseClick = ((direction << 8) | modifiers);
1601
1602 return;
1603}
1604
Bram Moolenaar071d4272004-06-13 20:20:40 +00001605/*
1606 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1607 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1608 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1609 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1610 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1611 * and we return the mouse position in g_xMouse and g_yMouse.
1612 *
1613 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1614 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1615 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1616 *
1617 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1618 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1619 *
1620 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1621 * moves, even if it stays within the same character cell. We ignore
1622 * all MOUSE_MOVED messages if the position hasn't really changed, and
1623 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1624 * we're only interested in MOUSE_DRAG).
1625 *
1626 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1627 * 2-button mouses by pressing the left & right buttons simultaneously.
1628 * In practice, it's almost impossible to click both at the same time,
1629 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1630 * in such cases, if the user is clicking quickly.
1631 */
1632 static BOOL
1633decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001634 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001635{
1636 static int s_nOldButton = -1;
1637 static int s_nOldMouseClick = -1;
1638 static int s_xOldMouse = -1;
1639 static int s_yOldMouse = -1;
1640 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001641# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001642 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001643# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001644 static int s_cClicks = 1;
1645 static BOOL s_fReleased = TRUE;
1646 static DWORD s_dwLastClickTime = 0;
1647 static BOOL s_fNextIsMiddle = FALSE;
1648
Bram Moolenaar0f873732019-12-05 20:28:46 +01001649 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001650
1651 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1652 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1653 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1654 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1655
1656 int nButton;
1657
1658 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1659 cButtons = 2;
1660
1661 if (!g_fMouseAvail || !g_fMouseActive)
1662 {
1663 g_nMouseClick = -1;
1664 return FALSE;
1665 }
1666
Bram Moolenaar0f873732019-12-05 20:28:46 +01001667 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001668 if (g_fJustGotFocus)
1669 {
1670 g_fJustGotFocus = FALSE;
1671 return FALSE;
1672 }
1673
Christopher Plewright605d02a2022-10-19 11:54:46 +01001674 // If there is an unprocessed mouse click drop this one.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001675 if (g_nMouseClick != -1)
1676 return TRUE;
Christopher Plewright605d02a2022-10-19 11:54:46 +01001677
Christopher Plewright2a46f812022-10-16 19:47:45 +01001678 if (pmer->dwEventFlags == MOUSE_WHEELED
1679 || pmer->dwEventFlags == MOUSE_HWHEELED)
1680 {
1681 decode_mouse_wheel(pmer);
1682 return TRUE; // we now should have a mouse scroll in g_nMouseClick
1683 }
Christopher Plewright605d02a2022-10-19 11:54:46 +01001684
Bram Moolenaar071d4272004-06-13 20:20:40 +00001685 nButton = -1;
1686 g_xMouse = pmer->dwMousePosition.X;
1687 g_yMouse = pmer->dwMousePosition.Y;
1688
1689 if (pmer->dwEventFlags == MOUSE_MOVED)
1690 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001691 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1692 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001693 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1694 return FALSE;
1695 }
1696
Bram Moolenaar0f873732019-12-05 20:28:46 +01001697 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001698 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1699 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001700 nButton = MOUSE_RELEASE;
1701
Bram Moolenaar0f873732019-12-05 20:28:46 +01001702 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001703 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001704 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001705# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001706 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001707 if (p_bevalterm)
1708 nButton = MOUSE_DRAG;
1709 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001710# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001711 return FALSE;
1712 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001713
Bram Moolenaar071d4272004-06-13 20:20:40 +00001714 s_fReleased = TRUE;
1715 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001716 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001718 // on a 2-button mouse, hold down left and right buttons
1719 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001720
1721 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1722 {
1723 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1724
Bram Moolenaar0f873732019-12-05 20:28:46 +01001725 // if either left or right button only is pressed, see if the
1726 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001727 if (dwLR == LEFT || dwLR == RIGHT)
1728 {
1729 for (;;)
1730 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001731 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001732 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1733 != WAIT_OBJECT_0)
1734 break;
1735 else
1736 {
1737 DWORD cRecords = 0;
1738 INPUT_RECORD ir;
1739 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1740
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001741 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001742
1743 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1744 || !(pmer2->dwButtonState & LEFT_RIGHT))
1745 break;
1746 else
1747 {
1748 if (pmer2->dwEventFlags != MOUSE_MOVED)
1749 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001750 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001751
1752 return decode_mouse_event(pmer2);
1753 }
1754 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1755 s_yOldMouse == pmer2->dwMousePosition.Y)
1756 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001757 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001758 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001759
Bram Moolenaar0f873732019-12-05 20:28:46 +01001760 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001761 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001762
1763 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1764 break;
1765 }
1766 else
1767 break;
1768 }
1769 }
1770 }
1771 }
1772 }
1773
1774 if (s_fNextIsMiddle)
1775 {
1776 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1777 ? MOUSE_DRAG : MOUSE_MIDDLE;
1778 s_fNextIsMiddle = FALSE;
1779 }
1780 else if (cButtons == 2 &&
1781 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1782 {
1783 nButton = MOUSE_MIDDLE;
1784
1785 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1786 {
1787 s_fNextIsMiddle = TRUE;
1788 nButton = MOUSE_RELEASE;
1789 }
1790 }
1791 else if ((pmer->dwButtonState & LEFT) == LEFT)
1792 nButton = MOUSE_LEFT;
1793 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1794 nButton = MOUSE_MIDDLE;
1795 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1796 nButton = MOUSE_RIGHT;
1797
1798 if (! s_fReleased && ! s_fNextIsMiddle
1799 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1800 return FALSE;
1801
1802 s_fReleased = s_fNextIsMiddle;
1803 }
1804
1805 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1806 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001807 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001808 if (nButton != -1 && nButton != MOUSE_RELEASE)
1809 {
1810 DWORD dwCurrentTime = GetTickCount();
1811
1812 if (s_xOldMouse != g_xMouse
1813 || s_yOldMouse != g_yMouse
1814 || s_nOldButton != nButton
1815 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001816# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001817 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001818# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001819 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1820 {
1821 s_cClicks = 1;
1822 }
1823 else if (++s_cClicks > 4)
1824 {
1825 s_cClicks = 1;
1826 }
1827
1828 s_dwLastClickTime = dwCurrentTime;
1829 }
1830 }
1831 else if (pmer->dwEventFlags == MOUSE_MOVED)
1832 {
1833 if (nButton != -1 && nButton != MOUSE_RELEASE)
1834 nButton = MOUSE_DRAG;
1835
1836 s_cClicks = 1;
1837 }
1838
1839 if (nButton == -1)
1840 return FALSE;
1841
1842 if (nButton != MOUSE_RELEASE)
1843 s_nOldButton = nButton;
1844
1845 g_nMouseClick = nButton;
1846
1847 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1848 g_nMouseClick |= MOUSE_SHIFT;
1849 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1850 g_nMouseClick |= MOUSE_CTRL;
1851 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1852 g_nMouseClick |= MOUSE_ALT;
1853
1854 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1855 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1856
Bram Moolenaar0f873732019-12-05 20:28:46 +01001857 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001858 if (s_xOldMouse == g_xMouse
1859 && s_yOldMouse == g_yMouse
1860 && s_nOldMouseClick == g_nMouseClick)
1861 {
1862 g_nMouseClick = -1;
1863 return FALSE;
1864 }
1865
1866 s_xOldMouse = g_xMouse;
1867 s_yOldMouse = g_yMouse;
1868 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001869# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001870 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001871# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001872 s_nOldMouseClick = g_nMouseClick;
1873
1874 return TRUE;
1875}
1876
Christopher Plewright20b795e2022-12-20 20:01:58 +00001877# ifdef FEAT_EVAL
1878 static int
1879encode_mouse_event(dict_T *args, INPUT_RECORD *ir)
1880{
1881 int button;
1882 int row;
1883 int col;
1884 int repeated_click;
Bram Moolenaar9b8a3652022-12-20 20:47:28 +00001885 int_u mods = 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001886 int move;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001887
Christopher Plewright20b795e2022-12-20 20:01:58 +00001888 if (!dict_has_key(args, "row") || !dict_has_key(args, "col"))
1889 return FALSE;
1890
1891 // Note: "move" is optional, requires fewer arguments
1892 move = (int)dict_get_bool(args, "move", FALSE);
1893 if (!move && (!dict_has_key(args, "button")
1894 || !dict_has_key(args, "multiclick")
1895 || !dict_has_key(args, "modifiers")))
1896 return FALSE;
1897
1898 row = (int)dict_get_number(args, "row") - 1;
1899 col = (int)dict_get_number(args, "col") - 1;
1900
1901 ir->EventType = MOUSE_EVENT;
1902 MOUSE_EVENT_RECORD mer;
1903 ZeroMemory(&mer, sizeof(mer));
1904 mer.dwMousePosition.X = col;
1905 mer.dwMousePosition.Y = row;
1906
1907 if (move)
1908 {
1909 mer.dwButtonState = 0;
1910 mer.dwEventFlags = MOUSE_MOVED;
1911 }
1912 else
1913 {
1914 button = (int)dict_get_number(args, "button");
1915 repeated_click = (int)dict_get_number(args, "multiclick");
1916 mods = (int)dict_get_number(args, "modifiers");
1917 // Reset the scroll values to known values.
1918 // XXX: Remove this when/if the scroll step is made configurable.
1919 mouse_set_hor_scroll_step(6);
1920 mouse_set_vert_scroll_step(3);
1921
1922 switch (button)
1923 {
1924 case MOUSE_LEFT:
1925 mer.dwButtonState = FROM_LEFT_1ST_BUTTON_PRESSED;
1926 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1927 break;
1928 case MOUSE_MIDDLE:
1929 mer.dwButtonState = FROM_LEFT_2ND_BUTTON_PRESSED;
1930 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1931 break;
1932 case MOUSE_RIGHT:
1933 mer.dwButtonState = RIGHTMOST_BUTTON_PRESSED;
1934 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1935 break;
1936 case MOUSE_RELEASE:
1937 // umm? Assume Left Release?
1938 mer.dwEventFlags = 0;
1939
1940 case MOUSE_MOVE:
1941 mer.dwButtonState = 0;
1942 mer.dwEventFlags = MOUSE_MOVED;
1943 break;
1944 case MOUSE_X1:
1945 mer.dwButtonState = FROM_LEFT_3RD_BUTTON_PRESSED;
1946 break;
1947 case MOUSE_X2:
1948 mer.dwButtonState = FROM_LEFT_4TH_BUTTON_PRESSED;
1949 break;
1950 case MOUSE_4: // KE_MOUSEDOWN;
1951 mer.dwButtonState = -1;
1952 mer.dwEventFlags = MOUSE_WHEELED;
1953 break;
1954 case MOUSE_5: // KE_MOUSEUP;
1955 mer.dwButtonState = +1;
1956 mer.dwEventFlags = MOUSE_WHEELED;
1957 break;
1958 case MOUSE_6: // KE_MOUSELEFT;
1959 mer.dwButtonState = -1;
1960 mer.dwEventFlags = MOUSE_HWHEELED;
1961 break;
1962 case MOUSE_7: // KE_MOUSERIGHT;
1963 mer.dwButtonState = +1;
1964 mer.dwEventFlags = MOUSE_HWHEELED;
1965 break;
1966 default:
1967 semsg(_(e_invalid_argument_str), "button");
1968 return FALSE;
1969 }
1970 }
1971
1972 mer.dwControlKeyState = 0;
1973 if (mods != 0)
1974 {
1975 // Encode the win32 console key modifiers from Vim MOUSE modifiers.
1976 if (mods & MOUSE_SHIFT)
1977 mer.dwControlKeyState |= SHIFT_PRESSED;
1978 if (mods & MOUSE_CTRL)
1979 mer.dwControlKeyState |= LEFT_CTRL_PRESSED;
1980 if (mods & MOUSE_ALT)
1981 mer.dwControlKeyState |= LEFT_ALT_PRESSED;
1982 }
1983 ir->Event.MouseEvent = mer;
1984 return TRUE;
1985}
1986# endif // FEAT_EVAL
1987
1988 static int
1989write_input_record_buffer(INPUT_RECORD* irEvents, int nLength)
1990{
1991 int nCount = 0;
1992 while (nCount < nLength)
1993 {
1994 input_record_buffer.length++;
1995 input_record_buffer_node_T *event_node =
1996 malloc(sizeof(input_record_buffer_node_T));
1997 event_node->ir = irEvents[nCount++];
1998 event_node->next = NULL;
1999 if (input_record_buffer.tail == NULL)
2000 {
2001 input_record_buffer.head = event_node;
2002 input_record_buffer.tail = event_node;
2003 }
2004 else
2005 {
2006 input_record_buffer.tail->next = event_node;
2007 input_record_buffer.tail = input_record_buffer.tail->next;
2008 }
2009 }
2010 return nCount;
2011}
2012
2013 static int
2014read_input_record_buffer(INPUT_RECORD* irEvents, int nMaxLength)
2015{
2016 int nCount = 0;
2017 while (nCount < nMaxLength && input_record_buffer.head != NULL)
2018 {
2019 input_record_buffer.length--;
2020 input_record_buffer_node_T *pop_head = input_record_buffer.head;
2021 irEvents[nCount++] = pop_head->ir;
2022 input_record_buffer.head = pop_head->next;
2023 vim_free(pop_head);
2024 if (input_record_buffer.length == 0)
2025 input_record_buffer.tail = NULL;
2026 }
2027 return nCount;
2028}
Christopher Plewright20b795e2022-12-20 20:01:58 +00002029#endif // !FEAT_GUI_MSWIN || VIMDLL
2030
2031#ifdef FEAT_EVAL
2032/*
2033 * The 'test_mswin_event' function is for testing Vim's low-level handling of
2034 * user input events. ie, this manages the encoding of INPUT_RECORD events
2035 * so that we have a way to test how Vim decodes INPUT_RECORD events in Windows
2036 * consoles.
2037 *
2038 * The 'test_mswin_event' function is based on 'test_gui_event'. In fact, when
2039 * the Windows GUI is running, the arguments; 'event' and 'args', are the same.
2040 * So, it acts as an alias for 'test_gui_event' for the Windows GUI.
2041 *
2042 * When the Windows console is running, the arguments; 'event' and 'args', are
2043 * a subset of what 'test_gui_event' handles, ie, only "key" and "mouse"
2044 * events are encoded as INPUT_RECORD events.
2045 *
2046 * Note: INPUT_RECORDs are only used by the Windows console, not the GUI. The
2047 * GUI sends MSG structs instead.
2048 */
2049 int
2050test_mswin_event(char_u *event, dict_T *args)
2051{
2052 int lpEventsWritten = 0;
2053
2054# if defined(VIMDLL) || defined(FEAT_GUI_MSWIN)
2055 if (gui.in_use)
2056 return test_gui_w32_sendevent(event, args);
2057# endif
2058
2059# if defined(VIMDLL) || !defined(FEAT_GUI_MSWIN)
2060
2061// Currently implemented event record types are; KEY_EVENT and MOUSE_EVENT
2062// Potentially could also implement: FOCUS_EVENT and WINDOW_BUFFER_SIZE_EVENT
2063// Maybe also: MENU_EVENT
2064
2065 INPUT_RECORD ir;
2066 BOOL input_encoded = FALSE;
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002067 BOOL execute = FALSE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00002068 if (STRCMP(event, "key") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002069 {
2070 execute = dict_get_bool(args, "execute", FALSE);
2071 if (dict_has_key(args, "event"))
2072 input_encoded = encode_key_event(args, &ir);
2073 else if (!execute)
2074 {
2075 semsg(_(e_missing_argument_str), "event");
2076 return FALSE;
2077 }
2078 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002079 else if (STRCMP(event, "mouse") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002080 {
2081 execute = TRUE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00002082 input_encoded = encode_mouse_event(args, &ir);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002083 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002084 else
2085 {
2086 semsg(_(e_invalid_value_for_argument_str_str), "event", event);
2087 return FALSE;
2088 }
2089
2090 // Ideally, WriteConsoleInput would be used to inject these low-level
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00002091 // events. But, this doesn't work well in the CI test environment. So
Christopher Plewright20b795e2022-12-20 20:01:58 +00002092 // implementing an input_record_buffer instead.
2093 if (input_encoded)
2094 lpEventsWritten = write_input_record_buffer(&ir, 1);
2095
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002096 // Set flags to execute the event, ie. like feedkeys mode X.
2097 if (execute)
2098 {
2099 int save_msg_scroll = msg_scroll;
2100 // Avoid a 1 second delay when the keys start Insert mode.
2101 msg_scroll = FALSE;
2102 ch_log(NULL, "test_mswin_event() executing");
Christopher Plewright20b795e2022-12-20 20:01:58 +00002103 exec_normal(TRUE, TRUE, TRUE);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002104 msg_scroll |= save_msg_scroll;
2105 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002106
2107# endif
2108 return lpEventsWritten;
2109}
2110#endif // FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002111
2112#ifdef MCH_CURSOR_SHAPE
2113/*
2114 * Set the shape of the cursor.
2115 * 'thickness' can be from 1 (thin) to 99 (block)
2116 */
2117 static void
2118mch_set_cursor_shape(int thickness)
2119{
Christopher Plewright38804d62022-11-09 23:55:52 +00002120 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01002121 {
2122 if (*T_CSI == NUL)
2123 {
2124 // If 't_SI' is not set, use the default cursor styles.
2125 if (thickness < 50)
2126 vtp_printf("\033[3 q"); // underline
2127 else
2128 vtp_printf("\033[0 q"); // default
2129 }
2130 }
2131 else
2132 {
2133 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
2134 ConsoleCursorInfo.dwSize = thickness;
2135 ConsoleCursorInfo.bVisible = s_cursor_visible;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002136
K.Takatadf5320c2022-09-01 13:20:16 +01002137 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
2138 if (s_cursor_visible)
2139 SetConsoleCursorPosition(g_hConOut, g_coord);
2140 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002141}
2142
2143 void
2144mch_update_cursor(void)
2145{
2146 int idx;
2147 int thickness;
2148
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002149# ifdef VIMDLL
2150 if (gui.in_use)
2151 return;
2152# endif
2153
Bram Moolenaar071d4272004-06-13 20:20:40 +00002154 /*
2155 * How the cursor is drawn depends on the current mode.
2156 */
2157 idx = get_shape_idx(FALSE);
2158
2159 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002160 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00002161 else
2162 thickness = shape_table[idx].percentage;
2163 mch_set_cursor_shape(thickness);
2164}
2165#endif
2166
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002167#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002168/*
2169 * Handle FOCUS_EVENT.
2170 */
2171 static void
2172handle_focus_event(INPUT_RECORD ir)
2173{
2174 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
2175 ui_focus_change((int)g_fJustGotFocus);
2176}
2177
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002178static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
2179
Bram Moolenaar071d4272004-06-13 20:20:40 +00002180/*
2181 * Wait until console input from keyboard or mouse is available,
2182 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002183 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002184 * Return TRUE if something is available FALSE if not.
2185 */
2186 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002187WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002188{
2189 DWORD dwNow = 0, dwEndTime = 0;
2190 INPUT_RECORD ir;
2191 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002192 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002193# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02002194 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002195# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002196
2197 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002198 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002199 dwEndTime = GetTickCount() + msec;
2200 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002201 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002202 dwEndTime = INFINITE;
2203
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002204 // We need to loop until the end of the time period, because
2205 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002206 for (;;)
2207 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002208 // Only process messages when waiting.
2209 if (msec != 0)
2210 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002211# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002212 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002213# endif
2214# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002215 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002216# endif
2217# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002218 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002219# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002220 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002221
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02002222 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002223# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002224 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002225# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002226 )
2227 return TRUE;
2228
2229 if (msec > 0)
2230 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002231 // If the specified wait time has passed, return. Beware that
2232 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002233 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02002234 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002235 break;
2236 }
2237 if (msec != 0)
2238 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00002239 DWORD dwWaitTime = dwEndTime - dwNow;
2240
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002241 // Don't wait for more than 11 msec to avoid dropping characters,
2242 // check channel while waiting for input and handle a callback from
2243 // 'balloonexpr'.
2244 if (dwWaitTime > 11)
2245 dwWaitTime = 11;
2246
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002247# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002248 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002249 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002250# endif
2251# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002252 // When waiting very briefly don't trigger timers.
2253 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002254 {
2255 long due_time;
2256
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002257 // Trigger timers and then get the time in msec until the next
2258 // one is due. Wait up to that time.
2259 due_time = check_due_timer();
2260 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002261 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002262 // timer may have used feedkeys().
2263 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002264 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002265 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
2266 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002267 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002268# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002269 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002270# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002271 // Wait for either an event on the console input or a
2272 // message in the client-server window.
2273 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
2274 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002275# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002276 wait_for_single_object(g_hConIn, dwWaitTime)
2277 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002278# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002279 )
2280 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002281 }
2282
2283 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002284 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002285
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002286# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02002287 // May have to redraw if the cursor ends up in the wrong place.
2288 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01002289 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002290 {
2291 CONSOLE_SCREEN_BUFFER_INFO csbi;
2292
2293 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2294 {
2295 if (csbi.dwCursorPosition.Y != msg_row)
2296 {
matveyte08795e2021-05-07 15:00:17 +02002297 // The screen is now messed up, must redraw the command
2298 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002299 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02002300 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002301 redrawcmd();
2302 }
2303 }
2304 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002305# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002306
2307 if (cRecords > 0)
2308 {
2309 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
2310 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002311# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01002312 // Windows IME sends two '\n's with only one 'ENTER'. First:
2313 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00002314 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002315 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
2316 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002317 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002318 continue;
2319 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002320# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002321 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
2322 NULL, FALSE))
2323 return TRUE;
2324 }
2325
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002326 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002327
2328 if (ir.EventType == FOCUS_EVENT)
2329 handle_focus_event(ir);
2330 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002331 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002332 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
2333
Bram Moolenaar36698e32019-12-11 22:57:40 +01002334 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002335 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002336 if (dwSize.X != Columns || dwSize.Y != Rows)
2337 {
2338 CONSOLE_SCREEN_BUFFER_INFO csbi;
2339 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01002340 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002341 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01002342 if (dwSize.X != Columns || dwSize.Y != Rows)
2343 {
2344 ResizeConBuf(g_hConOut, dwSize);
2345 shell_resized();
2346 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002347 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002348 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002349 else if (ir.EventType == MOUSE_EVENT
2350 && decode_mouse_event(&ir.Event.MouseEvent))
2351 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002352 }
2353 else if (msec == 0)
2354 break;
2355 }
2356
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002357# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01002358 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002359 if (input_available())
2360 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002361# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002362
Bram Moolenaar071d4272004-06-13 20:20:40 +00002363 return FALSE;
2364}
2365
Bram Moolenaar071d4272004-06-13 20:20:40 +00002366/*
2367 * return non-zero if a character is available
2368 */
2369 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002370mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002371{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002372# ifdef VIMDLL
2373 if (gui.in_use)
2374 return TRUE;
2375# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002376 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002377}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002378
2379# if defined(FEAT_TERMINAL) || defined(PROTO)
2380/*
2381 * Check for any pending input or messages.
2382 */
2383 int
2384mch_check_messages(void)
2385{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002386# ifdef VIMDLL
2387 if (gui.in_use)
2388 return TRUE;
2389# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002390 return WaitForChar(0L, TRUE);
2391}
2392# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002393
2394/*
2395 * Create the console input. Used when reading stdin doesn't work.
2396 */
2397 static void
2398create_conin(void)
2399{
2400 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
2401 FILE_SHARE_READ|FILE_SHARE_WRITE,
2402 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002403 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002404 did_create_conin = TRUE;
2405}
2406
2407/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002408 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002409 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002410 static WCHAR
2411tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002412{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002413 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002414
2415 for (;;)
2416 {
2417 INPUT_RECORD ir;
2418 DWORD cRecords = 0;
2419
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002420# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002421 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002422 if (input_available())
2423 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002424 if (g_nMouseClick != -1)
2425 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002426# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002427 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002428 {
2429 if (did_create_conin)
2430 read_error_exit();
2431 create_conin();
2432 continue;
2433 }
2434
2435 if (ir.EventType == KEY_EVENT)
2436 {
2437 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
2438 pmodifiers, TRUE))
2439 return ch;
2440 }
2441 else if (ir.EventType == FOCUS_EVENT)
2442 handle_focus_event(ir);
2443 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
2444 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002445 else if (ir.EventType == MOUSE_EVENT)
2446 {
2447 if (decode_mouse_event(&ir.Event.MouseEvent))
2448 return 0;
2449 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002450 }
2451}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002452#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002453
2454
2455/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02002456 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002457 * Get one or more characters from the keyboard or the mouse.
2458 * If time == 0, do not wait for characters.
2459 * If time == n, wait a short time for characters.
2460 * If time == -1, wait forever for characters.
2461 * Returns the number of characters read into buf.
2462 */
2463 int
2464mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002465 char_u *buf UNUSED,
2466 int maxlen UNUSED,
2467 long time UNUSED,
2468 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002469{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002470#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002471
2472 int len;
2473 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002474# ifdef VIMDLL
2475// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
2476# define TYPEAHEADSPACE 6
2477# else
2478# define TYPEAHEADSPACE 0
2479# endif
2480# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002481 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002482 static int typeaheadlen = 0;
2483
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002484# ifdef VIMDLL
2485 if (gui.in_use)
2486 return 0;
2487# endif
2488
Bram Moolenaar0f873732019-12-05 20:28:46 +01002489 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002490 if (typeaheadlen > 0)
2491 goto theend;
2492
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493 if (time >= 0)
2494 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002495 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00002496 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002497 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01002498 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00002499 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002500 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00002501
Bram Moolenaar3918c952005-03-15 22:34:55 +00002502 /*
2503 * If there is no character available within 2 seconds (default)
2504 * write the autoscript file to disk. Or cause the CursorHold event
2505 * to be triggered.
2506 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002507 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002508 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00002509 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002510 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00002511 buf[0] = K_SPECIAL;
2512 buf[1] = KS_EXTRA;
2513 buf[2] = (int)KE_CURSORHOLD;
2514 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002515 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00002516 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002517 }
2518 }
2519
2520 /*
2521 * Try to read as many characters as there are, until the buffer is full.
2522 */
2523
Bram Moolenaar0f873732019-12-05 20:28:46 +01002524 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002525 g_fCBrkPressed = FALSE;
2526
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002527# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002528 if (fdDump)
2529 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002530# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002531
Bram Moolenaar0f873732019-12-05 20:28:46 +01002532 // Keep looping until there is something in the typeahead buffer and more
2533 // to get and still room in the buffer (up to two bytes for a char and
2534 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002535 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01002536 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002537 {
2538 if (typebuf_changed(tb_change_cnt))
2539 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002540 // "buf" may be invalid now if a client put something in the
2541 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002542 typeaheadlen = 0;
2543 break;
2544 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002545 if (g_nMouseClick != -1)
2546 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002547# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002548 if (fdDump)
2549 fprintf(fdDump, "{%02x @ %d, %d}",
2550 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002551# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01002552 char_u modifiers = ((char_u *)(&g_nMouseClick))[0];
2553 char_u scroll_dir = ((char_u *)(&g_nMouseClick))[1];
2554
2555 if (scroll_dir == KE_MOUSEDOWN
2556 || scroll_dir == KE_MOUSEUP
2557 || scroll_dir == KE_MOUSELEFT
2558 || scroll_dir == KE_MOUSERIGHT)
2559 {
2560 if (modifiers > 0)
2561 {
Christopher Plewright03193062022-11-22 12:58:27 +00002562 // use K_SPECIAL instead of CSI to make mappings work
2563 typeahead[typeaheadlen++] = K_SPECIAL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002564 typeahead[typeaheadlen++] = KS_MODIFIER;
2565 typeahead[typeaheadlen++] = modifiers;
2566 }
2567 typeahead[typeaheadlen++] = CSI;
2568 typeahead[typeaheadlen++] = KS_EXTRA;
2569 typeahead[typeaheadlen++] = scroll_dir;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002570 }
2571 else
2572 {
2573 typeahead[typeaheadlen++] = ESC + 128;
2574 typeahead[typeaheadlen++] = 'M';
2575 typeahead[typeaheadlen++] = g_nMouseClick;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002576 }
Christopher Plewright36446bb2022-11-23 22:28:08 +00002577
2578 // Pass the pointer coordinates of the mouse event in 2 bytes,
2579 // allowing for > 223 columns. Both for click and scroll events.
2580 // This is the same as what is used for the GUI.
2581 typeahead[typeaheadlen++] = (char_u)(g_xMouse / 128 + ' ' + 1);
2582 typeahead[typeaheadlen++] = (char_u)(g_xMouse % 128 + ' ' + 1);
2583 typeahead[typeaheadlen++] = (char_u)(g_yMouse / 128 + ' ' + 1);
2584 typeahead[typeaheadlen++] = (char_u)(g_yMouse % 128 + ' ' + 1);
2585
2586 g_nMouseClick = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002587 }
2588 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002589 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002590 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002591 int modifiers = 0;
2592
2593 c = tgetch(&modifiers, &ch2);
2594
Christopher Plewrightc8b20492023-01-04 18:06:00 +00002595 c = simplify_key(c, &modifiers);
2596
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002597 // Some chars need adjustment when the Ctrl modifier is used.
2598 ++no_reduce_keys;
2599 c = may_adjust_key_for_ctrl(modifiers, c);
2600 --no_reduce_keys;
2601
2602 // remove the SHIFT modifier for keys where it's already included,
2603 // e.g., '(' and '*'
2604 modifiers = may_remove_shift_modifier(modifiers, c);
2605
Bram Moolenaar071d4272004-06-13 20:20:40 +00002606 if (typebuf_changed(tb_change_cnt))
2607 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002608 // "buf" may be invalid now if a client put something in the
2609 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002610 typeaheadlen = 0;
2611 break;
2612 }
2613
2614 if (c == Ctrl_C && ctrl_c_interrupts)
2615 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002616# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002617 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002618# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002619 got_int = TRUE;
2620 }
2621
Bram Moolenaar071d4272004-06-13 20:20:40 +00002622 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002623 {
2624 int n = 1;
2625
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002626 if (ch2 == NUL)
2627 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002628 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002629 char_u *p;
2630 WCHAR ch[2];
2631
2632 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002633 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002634 {
2635 ch[1] = tgetch(&modifiers, &ch2);
2636 n++;
2637 }
2638 p = utf16_to_enc(ch, &n);
2639 if (p != NULL)
2640 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002641 for (i = 0, j = 0; i < n; i++)
2642 {
2643 typeahead[typeaheadlen + j++] = p[i];
2644# ifdef VIMDLL
2645 if (p[i] == CSI)
2646 {
2647 typeahead[typeaheadlen + j++] = KS_EXTRA;
2648 typeahead[typeaheadlen + j++] = KE_CSI;
2649 }
2650# endif
2651 }
2652 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002653 vim_free(p);
2654 }
2655 }
2656 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002657 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002658 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002659# ifdef VIMDLL
2660 if (c == CSI)
2661 {
2662 typeahead[typeaheadlen + 1] = KS_EXTRA;
2663 typeahead[typeaheadlen + 2] = KE_CSI;
2664 n = 3;
2665 }
2666# endif
2667 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002668 if (ch2 != NUL)
2669 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002670 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002671 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002672 switch (ch2)
2673 {
2674 case (WCHAR)'\324': // SHIFT+Insert
2675 case (WCHAR)'\325': // CTRL+Insert
2676 case (WCHAR)'\327': // SHIFT+Delete
2677 case (WCHAR)'\330': // CTRL+Delete
2678 typeahead[typeaheadlen + n] = (char_u)ch2;
2679 n++;
2680 break;
2681
2682 default:
2683 typeahead[typeaheadlen + n] = 3;
2684 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2685 n += 2;
2686 break;
2687 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002688 }
2689 else
2690 {
2691 typeahead[typeaheadlen + n] = 3;
2692 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2693 n += 2;
2694 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002695 }
2696
Bram Moolenaar0f873732019-12-05 20:28:46 +01002697 // Use the ALT key to set the 8th bit of the character
2698 // when it's one byte, the 8th bit isn't set yet and not
2699 // using a double-byte encoding (would become a lead
2700 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002701 if ((modifiers & MOD_MASK_ALT)
2702 && n == 1
2703 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002704 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002705 )
2706 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002707 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2708 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002709 modifiers &= ~MOD_MASK_ALT;
2710 }
2711
2712 if (modifiers != 0)
2713 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002714 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002715 mch_memmove(typeahead + typeaheadlen + 3,
2716 typeahead + typeaheadlen, n);
2717 typeahead[typeaheadlen++] = K_SPECIAL;
2718 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2719 typeahead[typeaheadlen++] = modifiers;
2720 }
2721
2722 typeaheadlen += n;
2723
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002724# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002725 if (fdDump)
2726 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002727# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002728 }
2729 }
2730 }
2731
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002732# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002733 if (fdDump)
2734 {
2735 fputs("]\n", fdDump);
2736 fflush(fdDump);
2737 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002738# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002739
Bram Moolenaar071d4272004-06-13 20:20:40 +00002740theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002741 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002742 len = 0;
2743 while (len < maxlen && typeaheadlen > 0)
2744 {
2745 buf[len++] = typeahead[0];
2746 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2747 }
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00002748# ifdef FEAT_EVAL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002749 if (len > 0)
2750 {
2751 buf[len] = NUL;
2752 ch_log(NULL, "raw key input: \"%s\"", buf);
2753 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002754# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002755 return len;
2756
Bram Moolenaar0f873732019-12-05 20:28:46 +01002757#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002758 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002759#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002760}
2761
Bram Moolenaar82881492012-11-20 16:53:39 +01002762#ifndef PROTO
2763# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002764# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002765# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002766#endif
2767
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002768/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002769 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002770 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2771 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002772 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002773 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002774 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002775executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002776{
LemonBoy40fd7e62022-05-05 20:18:16 +01002777 int attrs = win32_getattrs((char_u *)name);
2778
2779 // The file doesn't exist or is a folder.
2780 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2781 return FALSE;
2782 // Check if the file is an AppExecLink, a special alias used by Windows
2783 // Store for its apps.
2784 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002785 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002786 char_u *res = resolve_appexeclink((char_u *)name);
2787 if (res == NULL)
AmberArrf5d0f542023-08-20 20:03:45 +02002788 res = resolve_reparse_point((char_u *)name);
2789 if (res == NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002790 return FALSE;
2791 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002792 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002793 *path = res;
2794 else
2795 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002796 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002797 else if (path != NULL)
2798 *path = FullName_save((char_u *)name, FALSE);
2799 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002800}
2801
2802/*
2803 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2804 * If "use_path" is FALSE: Return TRUE if "name" exists.
2805 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2806 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2807 * the allocated memory.
2808 */
2809 static int
2810executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2811{
2812 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2813 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2814 // UTF-8.
2815 char_u buf[_MAX_PATH * 3];
2816 size_t len = STRLEN(name);
2817 size_t tmplen;
2818 char_u *p, *e, *e2;
2819 char_u *pathbuf = NULL;
2820 char_u *pathext = NULL;
2821 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002822 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002823 int noext = FALSE;
2824 int retval = FALSE;
2825
2826 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002827 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002828
2829 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002830 shname = gettail(p_sh);
2831 if (strstr((char *)shname, "sh") != NULL &&
2832 !(strstr((char *)shname, "powershell") != NULL
2833 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002834 noext = TRUE;
2835
2836 if (use_pathext)
2837 {
2838 pathext = mch_getenv("PATHEXT");
2839 if (pathext == NULL)
2840 pathext = (char_u *)".com;.exe;.bat;.cmd";
2841
2842 if (noext == FALSE)
2843 {
2844 /*
2845 * Loop over all extensions in $PATHEXT.
2846 * Check "name" ends with extension.
2847 */
2848 p = pathext;
2849 while (*p)
2850 {
2851 if (p[0] == ';'
2852 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2853 {
2854 // Skip empty or single ".".
2855 ++p;
2856 continue;
2857 }
2858 e = vim_strchr(p, ';');
2859 if (e == NULL)
2860 e = p + STRLEN(p);
2861 tmplen = e - p;
2862
2863 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2864 {
2865 noext = TRUE;
2866 break;
2867 }
2868
2869 p = e;
2870 }
2871 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002872 }
2873
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002874 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002875 if (pathext == NULL)
2876 pathext = (char_u *)".";
2877 else if (noext == TRUE)
2878 {
2879 if (pathextbuf == NULL)
2880 pathextbuf = alloc(STRLEN(pathext) + 3);
2881 if (pathextbuf == NULL)
2882 {
2883 retval = FALSE;
2884 goto theend;
2885 }
2886 STRCPY(pathextbuf, ".;");
2887 STRCAT(pathextbuf, pathext);
2888 pathext = pathextbuf;
2889 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002890
Bram Moolenaar95da1362020-05-30 18:37:55 +02002891 // Use $PATH when "use_path" is TRUE and "name" is basename.
2892 if (use_path && gettail((char_u *)name) == (char_u *)name)
2893 {
2894 p = mch_getenv("PATH");
2895 if (p != NULL)
2896 {
2897 pathbuf = alloc(STRLEN(p) + 3);
2898 if (pathbuf == NULL)
2899 {
2900 retval = FALSE;
2901 goto theend;
2902 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002903
2904 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2905 STRCPY(pathbuf, ".;");
2906 else
2907 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002908 STRCAT(pathbuf, p);
2909 }
2910 }
2911
2912 /*
2913 * Walk through all entries in $PATH to check if "name" exists there and
2914 * is an executable file.
2915 */
2916 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2917 while (*p)
2918 {
2919 if (*p == ';') // Skip empty entry
2920 {
2921 ++p;
2922 continue;
2923 }
2924 e = vim_strchr(p, ';');
2925 if (e == NULL)
2926 e = p + STRLEN(p);
2927
2928 if (e - p + len + 2 > sizeof(buf))
2929 {
2930 retval = FALSE;
2931 goto theend;
2932 }
2933 // A single "." that means current dir.
2934 if (e - p == 1 && *p == '.')
2935 STRCPY(buf, name);
2936 else
2937 {
2938 vim_strncpy(buf, p, e - p);
2939 add_pathsep(buf);
2940 STRCAT(buf, name);
2941 }
2942 tmplen = STRLEN(buf);
2943
2944 /*
2945 * Loop over all extensions in $PATHEXT.
2946 * Check "name" with extension added.
2947 */
2948 p = pathext;
2949 while (*p)
2950 {
2951 if (*p == ';')
2952 {
2953 // Skip empty entry
2954 ++p;
2955 continue;
2956 }
2957 e2 = vim_strchr(p, (int)';');
2958 if (e2 == NULL)
2959 e2 = p + STRLEN(p);
2960
2961 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2962 {
2963 // Not a single "." that means no extension is added.
2964 if (e2 - p + tmplen + 1 > sizeof(buf))
2965 {
2966 retval = FALSE;
2967 goto theend;
2968 }
2969 vim_strncpy(buf + tmplen, p, e2 - p);
2970 }
2971 if (executable_file((char *)buf, path))
2972 {
2973 retval = TRUE;
2974 goto theend;
2975 }
2976
2977 p = e2;
2978 }
2979
2980 p = e;
2981 }
2982
2983theend:
2984 free(pathextbuf);
2985 free(pathbuf);
2986 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002987}
2988
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002989#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2990 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002991/*
2992 * Bad parameter handler.
2993 *
2994 * Certain MS CRT functions will intentionally crash when passed invalid
2995 * parameters to highlight possible security holes. Setting this function as
2996 * the bad parameter handler will prevent the crash.
2997 *
2998 * In debug builds the parameters contain CRT information that might help track
2999 * down the source of a problem, but in non-debug builds the arguments are all
3000 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
3001 * worth allowing these to make debugging of issues easier.
3002 */
3003 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01003004bad_param_handler(const wchar_t *expression UNUSED,
3005 const wchar_t *function UNUSED,
3006 const wchar_t *file UNUSED,
3007 unsigned int line UNUSED,
3008 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02003009{
3010}
3011
3012# define SET_INVALID_PARAM_HANDLER \
3013 ((void)_set_invalid_parameter_handler(bad_param_handler))
3014#else
3015# define SET_INVALID_PARAM_HANDLER
3016#endif
3017
Bram Moolenaar4f974752019-02-17 17:44:42 +01003018#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003019
3020/*
3021 * GUI version of mch_init().
3022 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003023 static void
3024mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003026# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00003027 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003028# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003029
Bram Moolenaar0f873732019-12-05 20:28:46 +01003030 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02003031 SET_INVALID_PARAM_HANDLER;
3032
Bram Moolenaar0f873732019-12-05 20:28:46 +01003033 // Let critical errors result in a failure, not in a dialog box. Required
3034 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003035 SetErrorMode(SEM_FAILCRITICALERRORS);
3036
Bram Moolenaar0f873732019-12-05 20:28:46 +01003037 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00003038
Bram Moolenaar0f873732019-12-05 20:28:46 +01003039 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00003040 Rows = 25;
3041 Columns = 80;
3042
Bram Moolenaar0f873732019-12-05 20:28:46 +01003043 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00003044 {
3045 char_u vimrun_location[_MAX_PATH + 4];
3046
Bram Moolenaar0f873732019-12-05 20:28:46 +01003047 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048 STRCPY(vimrun_location, exe_name);
3049 STRCPY(gettail(vimrun_location), "vimrun.exe");
3050 if (mch_getperm(vimrun_location) >= 0)
3051 {
3052 if (*skiptowhite(vimrun_location) != NUL)
3053 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01003054 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003055 mch_memmove(vimrun_location + 1, vimrun_location,
3056 STRLEN(vimrun_location) + 1);
3057 *vimrun_location = '"';
3058 STRCPY(gettail(vimrun_location), "vimrun\" ");
3059 }
3060 else
3061 STRCPY(gettail(vimrun_location), "vimrun ");
3062
3063 vimrun_path = (char *)vim_strsave(vimrun_location);
3064 s_dont_use_vimrun = FALSE;
3065 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02003066 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003067 s_dont_use_vimrun = FALSE;
3068
Bram Moolenaar0f873732019-12-05 20:28:46 +01003069 // Don't give the warning for a missing vimrun.exe right now, but only
3070 // when vimrun was supposed to be used. Don't bother people that do
3071 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003072 if (s_dont_use_vimrun)
3073 need_vimrun_warning = TRUE;
3074 }
3075
3076 /*
3077 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
3078 * Otherwise the default "findstr /n" is used.
3079 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02003080 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01003081 set_option_value_give_err((char_u *)"grepprg",
3082 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003083
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003084# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003085 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003086# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003087
3088 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003089}
3090
3091
Bram Moolenaar0f873732019-12-05 20:28:46 +01003092#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003093
3094#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003095
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003096# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
3097# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003098
3099/*
3100 * ClearConsoleBuffer()
3101 * Description:
3102 * Clears the entire contents of the console screen buffer, using the
3103 * specified attribute.
3104 * Returns:
3105 * TRUE on success
3106 */
3107 static BOOL
3108ClearConsoleBuffer(WORD wAttribute)
3109{
3110 CONSOLE_SCREEN_BUFFER_INFO csbi;
3111 COORD coord;
3112 DWORD NumCells, dummy;
3113
3114 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3115 return FALSE;
3116
3117 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
3118 coord.X = 0;
3119 coord.Y = 0;
3120 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
3121 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003122 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003123 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
3124 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003125 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003126
3127 return TRUE;
3128}
3129
3130/*
3131 * FitConsoleWindow()
3132 * Description:
3133 * Checks if the console window will fit within given buffer dimensions.
3134 * Also, if requested, will shrink the window to fit.
3135 * Returns:
3136 * TRUE on success
3137 */
3138 static BOOL
3139FitConsoleWindow(
3140 COORD dwBufferSize,
3141 BOOL WantAdjust)
3142{
3143 CONSOLE_SCREEN_BUFFER_INFO csbi;
3144 COORD dwWindowSize;
3145 BOOL NeedAdjust = FALSE;
3146
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003147 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3148 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003149
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003150 /*
3151 * A buffer resize will fail if the current console window does
3152 * not lie completely within that buffer. To avoid this, we might
3153 * have to move and possibly shrink the window.
3154 */
3155 if (csbi.srWindow.Right >= dwBufferSize.X)
3156 {
3157 dwWindowSize.X = SRWIDTH(csbi.srWindow);
3158 if (dwWindowSize.X > dwBufferSize.X)
3159 dwWindowSize.X = dwBufferSize.X;
3160 csbi.srWindow.Right = dwBufferSize.X - 1;
3161 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
3162 NeedAdjust = TRUE;
3163 }
3164 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
3165 {
3166 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
3167 if (dwWindowSize.Y > dwBufferSize.Y)
3168 dwWindowSize.Y = dwBufferSize.Y;
3169 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
3170 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
3171 NeedAdjust = TRUE;
3172 }
3173 if (NeedAdjust && WantAdjust)
3174 {
3175 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
3176 return FALSE;
3177 }
3178 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003179}
3180
3181typedef struct ConsoleBufferStruct
3182{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003183 BOOL IsValid;
3184 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003185 PCHAR_INFO Buffer;
3186 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003187 PSMALL_RECT Regions;
3188 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003189} ConsoleBuffer;
3190
3191/*
3192 * SaveConsoleBuffer()
3193 * Description:
3194 * Saves important information about the console buffer, including the
3195 * actual buffer contents. The saved information is suitable for later
3196 * restoration by RestoreConsoleBuffer().
3197 * Returns:
3198 * TRUE if all information was saved; FALSE otherwise
3199 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
3200 */
3201 static BOOL
3202SaveConsoleBuffer(
3203 ConsoleBuffer *cb)
3204{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003205 DWORD NumCells;
3206 COORD BufferCoord;
3207 SMALL_RECT ReadRegion;
3208 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003209 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003210
Bram Moolenaar071d4272004-06-13 20:20:40 +00003211 if (cb == NULL)
3212 return FALSE;
3213
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003214 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003215 {
3216 cb->IsValid = FALSE;
3217 return FALSE;
3218 }
3219 cb->IsValid = TRUE;
3220
Christopher Plewright1140b512022-11-12 18:46:05 +00003221 // VTP uses alternate screen buffer.
3222 // No need to save buffer contents for restoration.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003223 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003224 return TRUE;
3225
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003226 /*
3227 * Allocate a buffer large enough to hold the entire console screen
3228 * buffer. If this ConsoleBuffer structure has already been initialized
3229 * with a buffer of the correct size, then just use that one.
3230 */
3231 if (!cb->IsValid || cb->Buffer == NULL ||
3232 cb->BufferSize.X != cb->Info.dwSize.X ||
3233 cb->BufferSize.Y != cb->Info.dwSize.Y)
3234 {
3235 cb->BufferSize.X = cb->Info.dwSize.X;
3236 cb->BufferSize.Y = cb->Info.dwSize.Y;
3237 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
3238 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003239 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003240 if (cb->Buffer == NULL)
3241 return FALSE;
3242 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003243
3244 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003245 * We will now copy the console screen buffer into our buffer.
3246 * ReadConsoleOutput() seems to be limited as far as how much you
3247 * can read at a time. Empirically, this number seems to be about
3248 * 12000 cells (rows * columns). Start at position (0, 0) and copy
3249 * in chunks until it is all copied. The chunks will all have the
3250 * same horizontal characteristics, so initialize them now. The
3251 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003252 */
Bram Moolenaar61594242015-09-01 20:23:37 +02003253 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003254 ReadRegion.Left = 0;
3255 ReadRegion.Right = cb->Info.dwSize.X - 1;
3256 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003257
3258 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
3259 if (cb->Regions == NULL || numregions != cb->NumRegions)
3260 {
3261 cb->NumRegions = numregions;
3262 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003263 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003264 if (cb->Regions == NULL)
3265 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003266 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003267 return FALSE;
3268 }
3269 }
3270
3271 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003272 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003273 /*
3274 * Read into position (0, Y) in our buffer.
3275 */
3276 BufferCoord.Y = Y;
3277 /*
3278 * Read the region whose top left corner is (0, Y) and whose bottom
3279 * right corner is (width - 1, Y + Y_incr - 1). This should define
3280 * a region of size width by Y_incr. Don't worry if this region is
3281 * too large for the remaining buffer; it will be cropped.
3282 */
3283 ReadRegion.Top = Y;
3284 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003285 if (!ReadConsoleOutputW(g_hConOut, // output handle
3286 cb->Buffer, // our buffer
3287 cb->BufferSize, // dimensions of our buffer
3288 BufferCoord, // offset in our buffer
3289 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003290 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003291 VIM_CLEAR(cb->Buffer);
3292 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003293 return FALSE;
3294 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02003295 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003296 }
3297
3298 return TRUE;
3299}
3300
3301/*
3302 * RestoreConsoleBuffer()
3303 * Description:
3304 * Restores important information about the console buffer, including the
3305 * actual buffer contents, if desired. The information to restore is in
3306 * the same format used by SaveConsoleBuffer().
3307 * Returns:
3308 * TRUE on success
3309 */
3310 static BOOL
3311RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003312 ConsoleBuffer *cb,
3313 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003314{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003315 COORD BufferCoord;
3316 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003317 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003318
Christopher Plewright1140b512022-11-12 18:46:05 +00003319 // VTP uses alternate screen buffer.
3320 // No need to restore buffer contents.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003321 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003322 return TRUE;
3323
Bram Moolenaar071d4272004-06-13 20:20:40 +00003324 if (cb == NULL || !cb->IsValid)
3325 return FALSE;
3326
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003327 /*
3328 * Before restoring the buffer contents, clear the current buffer, and
3329 * restore the cursor position and window information. Doing this now
3330 * prevents old buffer contents from "flashing" onto the screen.
3331 */
3332 if (RestoreScreen)
3333 ClearConsoleBuffer(cb->Info.wAttributes);
3334
3335 FitConsoleWindow(cb->Info.dwSize, TRUE);
3336 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
3337 return FALSE;
3338 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
3339 return FALSE;
3340
3341 if (!RestoreScreen)
3342 {
3343 /*
3344 * No need to restore the screen buffer contents, so we're done.
3345 */
3346 return TRUE;
3347 }
3348
3349 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
3350 return FALSE;
3351 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
3352 return FALSE;
3353
3354 /*
3355 * Restore the screen buffer contents.
3356 */
3357 if (cb->Buffer != NULL)
3358 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003359 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003360 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003361 BufferCoord.X = cb->Regions[i].Left;
3362 BufferCoord.Y = cb->Regions[i].Top;
3363 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01003364 if (!WriteConsoleOutputW(g_hConOut, // output handle
3365 cb->Buffer, // our buffer
3366 cb->BufferSize, // dimensions of our buffer
3367 BufferCoord, // offset in our buffer
3368 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02003369 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003370 }
3371 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003372
3373 return TRUE;
3374}
3375
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003376# define FEAT_RESTORE_ORIG_SCREEN
3377# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003378static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003379# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003380static ConsoleBuffer g_cbNonTermcap = { 0 };
3381static ConsoleBuffer g_cbTermcap = { 0 };
3382
Bram Moolenaar071d4272004-06-13 20:20:40 +00003383char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01003384HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00003385static HICON g_hOrigIconSmall = NULL;
3386static HICON g_hOrigIcon = NULL;
3387static HICON g_hVimIcon = NULL;
3388static BOOL g_fCanChangeIcon = FALSE;
3389
Bram Moolenaar071d4272004-06-13 20:20:40 +00003390/*
3391 * GetConsoleIcon()
3392 * Description:
3393 * Attempts to retrieve the small icon and/or the big icon currently in
3394 * use by a given window.
3395 * Returns:
3396 * TRUE on success
3397 */
3398 static BOOL
3399GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003400 HWND hWnd,
3401 HICON *phIconSmall,
3402 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003403{
3404 if (hWnd == NULL)
3405 return FALSE;
3406
3407 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003408 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
3409 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003410 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003411 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
3412 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003413 return TRUE;
3414}
3415
3416/*
3417 * SetConsoleIcon()
3418 * Description:
3419 * Attempts to change the small icon and/or the big icon currently in
3420 * use by a given window.
3421 * Returns:
3422 * TRUE on success
3423 */
3424 static BOOL
3425SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003426 HWND hWnd,
3427 HICON hIconSmall,
3428 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003429{
Bram Moolenaar071d4272004-06-13 20:20:40 +00003430 if (hWnd == NULL)
3431 return FALSE;
3432
3433 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003434 SendMessage(hWnd, WM_SETICON,
3435 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003436 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003437 SendMessage(hWnd, WM_SETICON,
3438 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003439 return TRUE;
3440}
3441
3442/*
3443 * SaveConsoleTitleAndIcon()
3444 * Description:
3445 * Saves the current console window title in g_szOrigTitle, for later
3446 * restoration. Also, attempts to obtain a handle to the console window,
3447 * and use it to save the small and big icons currently in use by the
3448 * console window. This is not always possible on some versions of Windows;
3449 * nor is it possible when running Vim remotely using Telnet (since the
3450 * console window the user sees is owned by a remote process).
3451 */
3452 static void
3453SaveConsoleTitleAndIcon(void)
3454{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003455 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003456 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
3457 return;
3458
3459 /*
3460 * Obtain a handle to the console window using GetConsoleWindow() from
3461 * KERNEL32.DLL; we need to handle in order to change the window icon.
3462 * This function only exists on NT-based Windows, starting with Windows
3463 * 2000. On older operating systems, we can't change the window icon
3464 * anyway.
3465 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003466 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003467 if (g_hWnd == NULL)
3468 return;
3469
Bram Moolenaar0f873732019-12-05 20:28:46 +01003470 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003471 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
3472 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
3473 return;
3474
Bram Moolenaar0f873732019-12-05 20:28:46 +01003475 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01003476 if (
3477# ifdef FEAT_LIBCALL
3478 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
3479# endif
3480 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003481 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003482 if (g_hVimIcon != NULL)
3483 g_fCanChangeIcon = TRUE;
3484}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003485
3486static int g_fWindInitCalled = FALSE;
3487static int g_fTermcapMode = FALSE;
3488static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003489
3490/*
3491 * non-GUI version of mch_init().
3492 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003493 static void
3494mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003495{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003496# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003497 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003498# endif
3499# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00003500 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003501# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003502
Bram Moolenaar0f873732019-12-05 20:28:46 +01003503 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02003504 SET_INVALID_PARAM_HANDLER;
3505
Bram Moolenaar0f873732019-12-05 20:28:46 +01003506 // Let critical errors result in a failure, not in a dialog box. Required
3507 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003508 SetErrorMode(SEM_FAILCRITICALERRORS);
3509
Bram Moolenaar0f873732019-12-05 20:28:46 +01003510 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00003511 out_flush();
3512
Bram Moolenaar0f873732019-12-05 20:28:46 +01003513 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00003514 if (read_cmd_fd == 0)
3515 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
3516 else
3517 create_conin();
3518 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
3519
Christopher Plewright38804d62022-11-09 23:55:52 +00003520 wt_init();
3521 vtp_flag_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003522# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01003523 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003524 SaveConsoleBuffer(&g_cbOrig);
3525 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003526# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01003527 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003528 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
3529 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003530# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003531 if (cterm_normal_fg_color == 0)
3532 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
3533 if (cterm_normal_bg_color == 0)
3534 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
3535
Bram Moolenaarbdace832019-03-02 10:13:42 +01003536 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02003537 g_color_index_fg = g_attrDefault & 0xf;
3538 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
3539
Bram Moolenaar0f873732019-12-05 20:28:46 +01003540 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00003541 update_tcap(g_attrCurrent);
3542
3543 GetConsoleCursorInfo(g_hConOut, &g_cci);
3544 GetConsoleMode(g_hConIn, &g_cmodein);
3545 GetConsoleMode(g_hConOut, &g_cmodeout);
3546
Bram Moolenaar071d4272004-06-13 20:20:40 +00003547 SaveConsoleTitleAndIcon();
3548 /*
3549 * Set both the small and big icons of the console window to Vim's icon.
3550 * Note that Vim presently only has one size of icon (32x32), but it
3551 * automatically gets scaled down to 16x16 when setting the small icon.
3552 */
3553 if (g_fCanChangeIcon)
3554 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003555
3556 ui_get_shellsize();
3557
Christopher Plewrightd343c602023-01-22 18:58:30 +00003558 vtp_init();
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00003559 // Switch to a new alternate screen buffer.
3560 if (use_alternate_screen_buffer)
3561 vtp_printf("\033[?1049h");
Christopher Plewrightd343c602023-01-22 18:58:30 +00003562
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003563# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003564 fdDump = fopen("dump", "wt");
3565
3566 if (fdDump)
3567 {
3568 time_t t;
3569
3570 time(&t);
3571 fputs(ctime(&t), fdDump);
3572 fflush(fdDump);
3573 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003574# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003575
3576 g_fWindInitCalled = TRUE;
3577
Bram Moolenaar071d4272004-06-13 20:20:40 +00003578 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003579
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003580# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003581 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003582# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003583}
3584
3585/*
3586 * non-GUI version of mch_exit().
3587 * Shut down and exit with status `r'
3588 * Careful: mch_exit() may be called before mch_init()!
3589 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003590 static void
3591mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003592{
Bram Moolenaar955f1982017-02-05 15:10:51 +01003593 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003594
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003595 vtp_exit();
3596
Bram Moolenaar955f1982017-02-05 15:10:51 +01003597 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003598 if (g_fWindInitCalled)
3599 settmode(TMODE_COOK);
3600
Bram Moolenaar0f873732019-12-05 20:28:46 +01003601 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00003602
3603 if (g_fWindInitCalled)
3604 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02003605 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003606 /*
3607 * Restore both the small and big icons of the console window to
3608 * what they were at startup. Don't do this when the window is
3609 * closed, Vim would hang here.
3610 */
3611 if (g_fCanChangeIcon && !g_fForceExit)
3612 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003613
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003614# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003615 if (fdDump)
3616 {
3617 time_t t;
3618
3619 time(&t);
3620 fputs(ctime(&t), fdDump);
3621 fclose(fdDump);
3622 }
3623 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003624# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003625 }
3626
3627 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003628 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003629 SetConsoleMode(g_hConOut, g_cmodeout);
3630
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003631# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003632 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003633# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003634
3635 exit(r);
3636}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003637#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003638
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003639 void
3640mch_init(void)
3641{
3642#ifdef VIMDLL
3643 if (gui.starting)
3644 mch_init_g();
3645 else
3646 mch_init_c();
3647#elif defined(FEAT_GUI_MSWIN)
3648 mch_init_g();
3649#else
3650 mch_init_c();
3651#endif
3652}
3653
3654 void
3655mch_exit(int r)
3656{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003657#ifdef FEAT_NETBEANS_INTG
3658 netbeans_send_disconnect();
3659#endif
3660
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003661#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003662 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003663 mch_exit_g(r);
3664 else
3665 mch_exit_c(r);
3666#elif defined(FEAT_GUI_MSWIN)
3667 mch_exit_g(r);
3668#else
3669 mch_exit_c(r);
3670#endif
3671}
3672
Bram Moolenaar071d4272004-06-13 20:20:40 +00003673/*
3674 * Do we have an interactive window?
3675 */
3676 int
3677mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003678 int argc UNUSED,
3679 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003680{
K.Takatace3189d2023-02-15 19:13:43 +00003681 mch_get_exe_name();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003682
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003683#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003684 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003685#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003686# ifdef VIMDLL
3687 if (gui.in_use)
3688 return OK;
3689# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003690 if (isatty(1))
3691 return OK;
3692 return FAIL;
3693#endif
3694}
3695
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003696/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003697 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003698 * When "len" is > 0, also expand short to long filenames.
3699 */
3700 void
3701fname_case(
3702 char_u *name,
3703 int len)
3704{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003705 int flen;
3706 WCHAR *p;
3707 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003708
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003709 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003710 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003711 return;
3712
3713 slash_adjust(name);
3714
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003715 p = enc_to_utf16(name, NULL);
3716 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003717 return;
3718
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003719 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003720 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003721 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003722
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003723 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003724 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003725 if (len > 0 || flen >= (int)STRLEN(q))
3726 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3727 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003728 }
3729 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003730 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003731}
3732
3733
3734/*
3735 * Insert user name in s[len].
3736 */
3737 int
3738mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003739 char_u *s,
3740 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003741{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003742 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003743 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003744
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003745 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003746 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003747 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003748
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003749 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003750 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003751 vim_strncpy(s, p, len - 1);
3752 vim_free(p);
3753 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003754 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003755 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003756 s[0] = NUL;
3757 return FAIL;
3758}
3759
3760
3761/*
3762 * Insert host name in s[len].
3763 */
3764 void
3765mch_get_host_name(
3766 char_u *s,
3767 int len)
3768{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003769 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003770 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003771
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003772 if (!GetComputerNameW(wszHostName, &wcch))
3773 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003774
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003775 char_u *p = utf16_to_enc(wszHostName, NULL);
3776 if (p == NULL)
3777 return;
3778
3779 vim_strncpy(s, p, len - 1);
3780 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003781}
3782
3783
3784/*
3785 * return process ID
3786 */
3787 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003788mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003789{
3790 return (long)GetCurrentProcessId();
3791}
3792
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003793/*
3794 * return TRUE if process "pid" is still running
3795 */
3796 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003797mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003798{
3799 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3800 DWORD status = 0;
3801 int ret = FALSE;
3802
3803 if (hProcess == NULL)
3804 return FALSE; // might not have access
3805 if (GetExitCodeProcess(hProcess, &status) )
3806 ret = status == STILL_ACTIVE;
3807 CloseHandle(hProcess);
3808 return ret;
3809}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003810
3811/*
3812 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3813 * Return OK for success, FAIL for failure.
3814 */
3815 int
3816mch_dirname(
3817 char_u *buf,
3818 int len)
3819{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003820 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003821
Bram Moolenaar071d4272004-06-13 20:20:40 +00003822 /*
3823 * Originally this was:
3824 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3825 * But the Win32s known bug list says that getcwd() doesn't work
3826 * so use the Win32 system call instead. <Negri>
3827 */
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003828 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) == 0)
3829 return FAIL;
3830
3831 WCHAR wcbuf[_MAX_PATH + 1];
3832 char_u *p = NULL;
3833
3834 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003835 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003836 p = utf16_to_enc(wcbuf, NULL);
3837 if (STRLEN(p) >= (size_t)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003838 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003839 // long path name is too long, fall back to short one
Yegappan Lakshmanan960dcbd2023-03-07 17:45:11 +00003840 VIM_CLEAR(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003841 }
3842 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003843 if (p == NULL)
3844 p = utf16_to_enc(wbuf, NULL);
3845
3846 if (p == NULL)
3847 return FAIL;
3848
3849 vim_strncpy(buf, p, len - 1);
3850 vim_free(p);
3851 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003852}
3853
3854/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003855 * Get file permissions for "name".
3856 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003857 */
3858 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003859mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003860{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003861 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003862 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003863
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003864 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003865 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003866}
3867
3868
3869/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003870 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003871 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003872 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003873 */
3874 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003875mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003876{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003877 long n;
3878 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003879
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003880 p = enc_to_utf16(name, NULL);
3881 if (p == NULL)
3882 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003883
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003884 n = _wchmod(p, perm);
3885 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003886 if (n == -1)
3887 return FAIL;
3888
3889 win32_set_archive(name);
3890
3891 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003892}
3893
3894/*
3895 * Set hidden flag for "name".
3896 */
3897 void
3898mch_hide(char_u *name)
3899{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003900 int attrs = win32_getattrs(name);
3901 if (attrs == -1)
3902 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003903
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003904 attrs |= FILE_ATTRIBUTE_HIDDEN;
3905 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003906}
3907
3908/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003909 * Return TRUE if file "name" exists and is hidden.
3910 */
3911 int
3912mch_ishidden(char_u *name)
3913{
3914 int f = win32_getattrs(name);
3915
3916 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003917 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003918
3919 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3920}
3921
3922/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003923 * return TRUE if "name" is a directory
3924 * return FALSE if "name" is not a directory or upon error
3925 */
3926 int
3927mch_isdir(char_u *name)
3928{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003929 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003930
3931 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003932 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003933
3934 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3935}
3936
3937/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003938 * return TRUE if "name" is a directory, NOT a symlink to a directory
3939 * return FALSE if "name" is not a directory
3940 * return FALSE for error
3941 */
3942 int
3943mch_isrealdir(char_u *name)
3944{
3945 return mch_isdir(name) && !mch_is_symbolic_link(name);
3946}
3947
3948/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003949 * Create directory "name".
3950 * Return 0 on success, -1 on error.
3951 */
3952 int
3953mch_mkdir(char_u *name)
3954{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003955 WCHAR *p;
3956 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003957
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003958 p = enc_to_utf16(name, NULL);
3959 if (p == NULL)
3960 return -1;
3961 retval = _wmkdir(p);
3962 vim_free(p);
3963 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003964}
3965
3966/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003967 * Delete directory "name".
3968 * Return 0 on success, -1 on error.
3969 */
3970 int
3971mch_rmdir(char_u *name)
3972{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003973 WCHAR *p;
3974 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003975
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003976 p = enc_to_utf16(name, NULL);
3977 if (p == NULL)
3978 return -1;
3979 retval = _wrmdir(p);
3980 vim_free(p);
3981 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003982}
3983
3984/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003985 * Return TRUE if file "fname" has more than one link.
3986 */
3987 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003988mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003989{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003990 BY_HANDLE_FILE_INFORMATION info;
3991
3992 return win32_fileinfo(fname, &info) == FILEINFO_OK
3993 && info.nNumberOfLinks > 1;
3994}
3995
3996/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003997 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003998 */
3999 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01004000mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004001{
4002 HANDLE hFind;
4003 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004004 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004005 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004006 WIN32_FIND_DATAW findDataW;
4007
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004008 wn = enc_to_utf16(name, NULL);
4009 if (wn == NULL)
4010 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004011
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004012 hFind = FindFirstFileW(wn, &findDataW);
4013 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004014 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004015 {
4016 fileFlags = findDataW.dwFileAttributes;
4017 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004018 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004019 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004020
4021 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01004022 && (reparseTag == IO_REPARSE_TAG_SYMLINK
4023 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004024 res = TRUE;
4025
4026 return res;
4027}
4028
4029/*
4030 * Return TRUE if file "fname" has more than one link or if it is a symbolic
4031 * link.
4032 */
4033 int
4034mch_is_linked(char_u *fname)
4035{
4036 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
4037 return TRUE;
4038 return FALSE;
4039}
4040
4041/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02004042 * Get the by-handle-file-information for "fname".
4043 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004044 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02004045 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
4046 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
4047 */
4048 int
4049win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
4050{
Bram Moolenaar03f48552006-02-28 23:52:23 +00004051 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02004052 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004053 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00004054
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004055 wn = enc_to_utf16(fname, NULL);
4056 if (wn == NULL)
4057 return FILEINFO_ENC_FAIL;
4058
4059 hFile = CreateFileW(wn, // file name
4060 GENERIC_READ, // access mode
4061 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
4062 NULL, // security descriptor
4063 OPEN_EXISTING, // creation disposition
4064 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
4065 NULL); // handle to template file
4066 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00004067
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00004068 if (hFile == INVALID_HANDLE_VALUE)
4069 return FILEINFO_READ_FAIL;
4070
4071 if (GetFileInformationByHandle(hFile, info) != 0)
4072 res = FILEINFO_OK;
4073 else
4074 res = FILEINFO_INFO_FAIL;
4075 CloseHandle(hFile);
Bram Moolenaar03f48552006-02-28 23:52:23 +00004076
Bram Moolenaar03f48552006-02-28 23:52:23 +00004077 return res;
4078}
4079
4080/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004081 * get file attributes for `name'
4082 * -1 : error
4083 * else FILE_ATTRIBUTE_* defined in winnt.h
4084 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01004085 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004086win32_getattrs(char_u *name)
4087{
4088 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004089 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 INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004094
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004095 attr = GetFileAttributesW(p);
4096 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004097
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004098 return attr;
4099}
4100
4101/*
4102 * set file attributes for `name' to `attrs'
4103 *
4104 * return -1 for failure, 0 otherwise
4105 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004106 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004107win32_setattrs(char_u *name, int attrs)
4108{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004109 int res;
4110 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004111
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004112 p = enc_to_utf16(name, NULL);
4113 if (p == NULL)
4114 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004115
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004116 res = SetFileAttributesW(p, attrs);
4117 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004118
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004119 return res ? 0 : -1;
4120}
4121
4122/*
4123 * Set archive flag for "name".
4124 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004125 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004126win32_set_archive(char_u *name)
4127{
4128 int attrs = win32_getattrs(name);
4129 if (attrs == -1)
4130 return -1;
4131
4132 attrs |= FILE_ATTRIBUTE_ARCHIVE;
4133 return win32_setattrs(name, attrs);
4134}
4135
4136/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004137 * Return TRUE if file or directory "name" is writable (not readonly).
4138 * Strange semantics of Win32: a readonly directory is writable, but you can't
4139 * delete a file. Let's say this means it is writable.
4140 */
4141 int
4142mch_writable(char_u *name)
4143{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004144 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004145
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004146 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
4147 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004148}
4149
Bram Moolenaar071d4272004-06-13 20:20:40 +00004150/*
Bram Moolenaar43663192017-03-05 14:29:12 +01004151 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01004152 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01004153 * When returning TRUE and "path" is not NULL save the path and set "*path" to
4154 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004155 */
4156 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01004157mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004158{
Bram Moolenaar95da1362020-05-30 18:37:55 +02004159 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004160}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004161
4162/*
4163 * Check what "name" is:
4164 * NODE_NORMAL: file or directory (or doesn't exist)
4165 * NODE_WRITABLE: writable device, socket, fifo, etc.
4166 * NODE_OTHER: non-writable things
4167 */
4168 int
4169mch_nodetype(char_u *name)
4170{
4171 HANDLE hFile;
4172 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004173 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004174
Bram Moolenaar0f873732019-12-05 20:28:46 +01004175 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
4176 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
4177 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00004178 if (STRNCMP(name, "\\\\.\\", 4) == 0)
4179 return NODE_WRITABLE;
4180
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004181 wn = enc_to_utf16(name, NULL);
4182 if (wn == NULL)
4183 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004184
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004185 hFile = CreateFileW(wn, // file name
4186 GENERIC_WRITE, // access mode
4187 0, // share mode
4188 NULL, // security descriptor
4189 OPEN_EXISTING, // creation disposition
4190 0, // file attributes
4191 NULL); // handle to template file
4192 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004193 if (hFile == INVALID_HANDLE_VALUE)
4194 return NODE_NORMAL;
4195
4196 type = GetFileType(hFile);
4197 CloseHandle(hFile);
4198 if (type == FILE_TYPE_CHAR)
4199 return NODE_WRITABLE;
4200 if (type == FILE_TYPE_DISK)
4201 return NODE_NORMAL;
4202 return NODE_OTHER;
4203}
4204
4205#ifdef HAVE_ACL
4206struct my_acl
4207{
4208 PSECURITY_DESCRIPTOR pSecurityDescriptor;
4209 PSID pSidOwner;
4210 PSID pSidGroup;
4211 PACL pDacl;
4212 PACL pSacl;
4213};
4214#endif
4215
4216/*
4217 * Return a pointer to the ACL of file "fname" in allocated memory.
4218 * Return NULL if the ACL is not available for whatever reason.
4219 */
4220 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004221mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004222{
4223#ifndef HAVE_ACL
4224 return (vim_acl_T)NULL;
4225#else
4226 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02004227 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004228
Bram Moolenaarc799fe22019-05-28 23:08:19 +02004229 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004230 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004231 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004232 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02004233
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004234 wn = enc_to_utf16(fname, NULL);
4235 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004236 {
4237 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004238 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004239 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004240
4241 // Try to retrieve the entire security descriptor.
4242 err = GetNamedSecurityInfoW(
4243 wn, // Abstract filename
4244 SE_FILE_OBJECT, // File Object
4245 OWNER_SECURITY_INFORMATION |
4246 GROUP_SECURITY_INFORMATION |
4247 DACL_SECURITY_INFORMATION |
4248 SACL_SECURITY_INFORMATION,
4249 &p->pSidOwner, // Ownership information.
4250 &p->pSidGroup, // Group membership.
4251 &p->pDacl, // Discretionary information.
4252 &p->pSacl, // For auditing purposes.
4253 &p->pSecurityDescriptor);
4254 if (err == ERROR_ACCESS_DENIED ||
4255 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004256 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004257 // Retrieve only DACL.
4258 (void)GetNamedSecurityInfoW(
4259 wn,
4260 SE_FILE_OBJECT,
4261 DACL_SECURITY_INFORMATION,
4262 NULL,
4263 NULL,
4264 &p->pDacl,
4265 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004266 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004267 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004268 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004269 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004270 mch_free_acl((vim_acl_T)p);
4271 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004272 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004273 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004274 }
4275
4276 return (vim_acl_T)p;
4277#endif
4278}
4279
Bram Moolenaar27515922013-06-29 15:36:26 +02004280#ifdef HAVE_ACL
4281/*
4282 * Check if "acl" contains inherited ACE.
4283 */
4284 static BOOL
4285is_acl_inherited(PACL acl)
4286{
4287 DWORD i;
4288 ACL_SIZE_INFORMATION acl_info;
4289 PACCESS_ALLOWED_ACE ace;
4290
4291 acl_info.AceCount = 0;
4292 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
4293 for (i = 0; i < acl_info.AceCount; i++)
4294 {
4295 GetAce(acl, i, (LPVOID *)&ace);
4296 if (ace->Header.AceFlags & INHERITED_ACE)
4297 return TRUE;
4298 }
4299 return FALSE;
4300}
4301#endif
4302
Bram Moolenaar071d4272004-06-13 20:20:40 +00004303/*
4304 * Set the ACL of file "fname" to "acl" (unless it's NULL).
4305 * Errors are ignored.
4306 * This must only be called with "acl" equal to what mch_get_acl() returned.
4307 */
4308 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004309mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004310{
4311#ifdef HAVE_ACL
4312 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02004313 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004314 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004315
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004316 if (p == NULL)
4317 return;
4318
4319 wn = enc_to_utf16(fname, NULL);
4320 if (wn == NULL)
4321 return;
4322
4323 // Set security flags
4324 if (p->pSidOwner)
4325 sec_info |= OWNER_SECURITY_INFORMATION;
4326 if (p->pSidGroup)
4327 sec_info |= GROUP_SECURITY_INFORMATION;
4328 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02004329 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004330 sec_info |= DACL_SECURITY_INFORMATION;
4331 // Do not inherit its parent's DACL.
4332 // If the DACL is inherited, Cygwin permissions would be changed.
4333 if (!is_acl_inherited(p->pDacl))
4334 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02004335 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004336 if (p->pSacl)
4337 sec_info |= SACL_SECURITY_INFORMATION;
4338
4339 (void)SetNamedSecurityInfoW(
4340 wn, // Abstract filename
4341 SE_FILE_OBJECT, // File Object
4342 sec_info,
4343 p->pSidOwner, // Ownership information.
4344 p->pSidGroup, // Group membership.
4345 p->pDacl, // Discretionary information.
4346 p->pSacl // For auditing purposes.
4347 );
4348 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004349#endif
4350}
4351
4352 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004353mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004354{
4355#ifdef HAVE_ACL
4356 struct my_acl *p = (struct my_acl *)acl;
4357
4358 if (p != NULL)
4359 {
4360 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
4361 vim_free(p);
4362 }
4363#endif
4364}
4365
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004366#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004367
4368/*
4369 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
4370 */
4371 static BOOL WINAPI
4372handler_routine(
4373 DWORD dwCtrlType)
4374{
Bram Moolenaar589b1102017-08-12 16:39:05 +02004375 INPUT_RECORD ir;
4376 DWORD out;
4377
Bram Moolenaar071d4272004-06-13 20:20:40 +00004378 switch (dwCtrlType)
4379 {
4380 case CTRL_C_EVENT:
4381 if (ctrl_c_interrupts)
4382 g_fCtrlCPressed = TRUE;
4383 return TRUE;
4384
4385 case CTRL_BREAK_EVENT:
4386 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02004387 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004388 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02004389 ir.EventType = KEY_EVENT;
4390 ir.Event.KeyEvent.bKeyDown = TRUE;
4391 ir.Event.KeyEvent.wRepeatCount = 1;
4392 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
4393 ir.Event.KeyEvent.wVirtualScanCode = 0;
4394 ir.Event.KeyEvent.dwControlKeyState = 0;
4395 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
4396 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004397 return TRUE;
4398
Bram Moolenaar0f873732019-12-05 20:28:46 +01004399 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00004400 case CTRL_CLOSE_EVENT:
4401 case CTRL_LOGOFF_EVENT:
4402 case CTRL_SHUTDOWN_EVENT:
4403 windgoto((int)Rows - 1, 0);
4404 g_fForceExit = TRUE;
4405
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004406 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004407 (dwCtrlType == CTRL_CLOSE_EVENT
4408 ? _("close")
4409 : dwCtrlType == CTRL_LOGOFF_EVENT
4410 ? _("logoff")
4411 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004412# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00004413 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004414# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004415
Bram Moolenaar0f873732019-12-05 20:28:46 +01004416 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00004417
Bram Moolenaar0f873732019-12-05 20:28:46 +01004418 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00004419
4420 default:
4421 return FALSE;
4422 }
4423}
4424
4425
4426/*
4427 * set the tty in (raw) ? "raw" : "cooked" mode
4428 */
4429 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02004430mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004431{
4432 DWORD cmodein;
4433 DWORD cmodeout;
4434 BOOL bEnableHandler;
4435
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004436# ifdef VIMDLL
4437 if (gui.in_use)
4438 return;
4439# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004440 GetConsoleMode(g_hConIn, &cmodein);
4441 GetConsoleMode(g_hConOut, &cmodeout);
4442 if (tmode == TMODE_RAW)
4443 {
4444 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4445 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004446 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004447 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004448 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004449 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
4450 }
4451 else
4452 {
4453 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
4454 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004455 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004456# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01004457 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
4458 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004459 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004460# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004461 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004462# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004463 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004464 bEnableHandler = TRUE;
4465 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004466 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00004467 {
4468 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4469 ENABLE_ECHO_INPUT);
4470 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
4471 bEnableHandler = FALSE;
4472 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004473 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004474 SetConsoleMode(g_hConOut, cmodeout);
4475 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
4476
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004477# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004478 if (fdDump)
4479 {
4480 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
4481 tmode == TMODE_RAW ? "raw" :
4482 tmode == TMODE_COOK ? "cooked" : "normal",
4483 cmodein, cmodeout);
4484 fflush(fdDump);
4485 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004486# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004487}
4488
4489
4490/*
4491 * Get the size of the current window in `Rows' and `Columns'
4492 * Return OK when size could be determined, FAIL otherwise.
4493 */
4494 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004495mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004496{
4497 CONSOLE_SCREEN_BUFFER_INFO csbi;
4498
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004499# ifdef VIMDLL
4500 if (gui.in_use)
4501 return OK;
4502# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004503 if (!g_fTermcapMode && g_cbTermcap.IsValid)
4504 {
4505 /*
4506 * For some reason, we are trying to get the screen dimensions
4507 * even though we are not in termcap mode. The 'Rows' and 'Columns'
4508 * variables are really intended to mean the size of Vim screen
4509 * while in termcap mode.
4510 */
4511 Rows = g_cbTermcap.Info.dwSize.Y;
4512 Columns = g_cbTermcap.Info.dwSize.X;
4513 }
4514 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4515 {
4516 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4517 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4518 }
4519 else
4520 {
4521 Rows = 25;
4522 Columns = 80;
4523 }
4524 return OK;
4525}
4526
4527/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004528 * Resize console buffer to 'COORD'
4529 */
4530 static void
4531ResizeConBuf(
4532 HANDLE hConsole,
4533 COORD coordScreen)
4534{
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00004535 if (use_alternate_screen_buffer)
4536 return;
4537
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004538 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
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, "SetConsoleScreenBufferSize 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/*
4552 * Resize console window size to 'srWindowRect'
4553 */
4554 static void
4555ResizeWindow(
4556 HANDLE hConsole,
4557 SMALL_RECT srWindowRect)
4558{
4559 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4560 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004561# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004562 if (fdDump)
4563 {
4564 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4565 GetLastError());
4566 fflush(fdDump);
4567 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004568# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004569 }
4570}
4571
4572/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004573 * Set a console window to `xSize' * `ySize'
4574 */
4575 static void
4576ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004577 HANDLE hConsole,
4578 int xSize,
4579 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004580{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004581 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
4582 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004583 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004584 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004585 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004586
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004587# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004588 if (fdDump)
4589 {
4590 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4591 fflush(fdDump);
4592 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004593# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004594
Bram Moolenaar0f873732019-12-05 20:28:46 +01004595 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00004596 coordScreen = GetLargestConsoleWindowSize(hConsole);
4597
Bram Moolenaar0f873732019-12-05 20:28:46 +01004598 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00004599 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4600 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4601 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4602
4603 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4604 {
4605 int sx, sy;
4606
4607 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4608 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4609 if (sy < ySize || sx < xSize)
4610 {
4611 /*
4612 * Increasing number of lines/columns, do buffer first.
4613 * Use the maximal size in x and y direction.
4614 */
4615 if (sy < ySize)
4616 coordScreen.Y = ySize;
4617 else
4618 coordScreen.Y = sy;
4619 if (sx < xSize)
4620 coordScreen.X = xSize;
4621 else
4622 coordScreen.X = sx;
4623 SetConsoleScreenBufferSize(hConsole, coordScreen);
4624 }
4625 }
4626
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004627 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004628 coordScreen.X = xSize;
4629 coordScreen.Y = ySize;
4630
Bram Moolenaar2551c032018-08-23 22:38:31 +02004631 // In the new console call API, only the first time in reverse order
4632 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004633 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004634 ResizeWindow(hConsole, srWindowRect);
4635 ResizeConBuf(hConsole, coordScreen);
4636 }
4637 else
4638 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004639 // Workaround for a Windows 10 bug
4640 cursor.X = srWindowRect.Left;
4641 cursor.Y = srWindowRect.Top;
4642 SetConsoleCursorPosition(hConsole, cursor);
4643
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004644 ResizeConBuf(hConsole, coordScreen);
4645 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004646 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004647 }
4648}
4649
4650
4651/*
4652 * Set the console window to `Rows' * `Columns'
4653 */
4654 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004655mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004656{
4657 COORD coordScreen;
4658
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004659# ifdef VIMDLL
4660 if (gui.in_use)
4661 return;
4662# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004663 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004664 if (suppress_winsize != 0)
4665 {
4666 suppress_winsize = 2;
4667 return;
4668 }
4669
4670 if (term_console)
4671 {
4672 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4673
Bram Moolenaar0f873732019-12-05 20:28:46 +01004674 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004675 if (Rows > coordScreen.Y)
4676 Rows = coordScreen.Y;
4677 if (Columns > coordScreen.X)
4678 Columns = coordScreen.X;
4679
4680 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4681 }
4682}
4683
4684/*
4685 * Rows and/or Columns has changed.
4686 */
4687 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004688mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004689{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004690# ifdef VIMDLL
4691 if (gui.in_use)
4692 return;
4693# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004694 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4695}
4696
4697
4698/*
4699 * Called when started up, to set the winsize that was delayed.
4700 */
4701 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004702mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004703{
4704 if (suppress_winsize == 2)
4705 {
4706 suppress_winsize = 0;
4707 mch_set_shellsize();
4708 shell_resized();
4709 }
4710 suppress_winsize = 0;
4711}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004712#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004713
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004714 static BOOL
4715vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004716 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004717 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004718 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004719 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004720 PROCESS_INFORMATION *pi,
4721 LPVOID *env,
4722 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004723{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004724 BOOL ret = FALSE;
4725 WCHAR *wcmd, *wcwd = NULL;
4726
4727 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4728 if (wcmd == NULL)
4729 return FALSE;
4730 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004731 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004732 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4733 if (wcwd == NULL)
4734 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004735 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004736
4737 ret = CreateProcessW(
4738 NULL, // Executable name
4739 wcmd, // Command to execute
4740 NULL, // Process security attributes
4741 NULL, // Thread security attributes
4742 inherit_handles, // Inherit handles
4743 flags, // Creation flags
4744 env, // Environment
4745 wcwd, // Current directory
4746 (LPSTARTUPINFOW)si, // Startup information
4747 pi); // Process information
4748theend:
4749 vim_free(wcmd);
4750 vim_free(wcwd);
4751 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004752}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004753
4754
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004755 static HINSTANCE
4756vim_shell_execute(
4757 char *cmd,
4758 INT n_show_cmd)
4759{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004760 HINSTANCE ret;
4761 WCHAR *wcmd;
4762
4763 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4764 if (wcmd == NULL)
4765 return (HINSTANCE) 0;
4766
4767 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4768 vim_free(wcmd);
4769 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004770}
4771
4772
Bram Moolenaar4f974752019-02-17 17:44:42 +01004773#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004774
4775/*
4776 * Specialised version of system() for Win32 GUI mode.
4777 * This version proceeds as follows:
4778 * 1. Create a console window for use by the subprocess
4779 * 2. Run the subprocess (it gets the allocated console by default)
4780 * 3. Wait for the subprocess to terminate and get its exit code
4781 * 4. Prompt the user to press a key to close the console window
4782 */
4783 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004784mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004785{
4786 STARTUPINFO si;
4787 PROCESS_INFORMATION pi;
4788 DWORD ret = 0;
4789 HWND hwnd = GetFocus();
4790
4791 si.cb = sizeof(si);
4792 si.lpReserved = NULL;
4793 si.lpDesktop = NULL;
4794 si.lpTitle = NULL;
4795 si.dwFlags = STARTF_USESHOWWINDOW;
4796 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004797 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004798 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004799 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004800 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004801 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004802 else
4803 si.wShowWindow = SW_SHOWNORMAL;
4804 si.cbReserved2 = 0;
4805 si.lpReserved2 = NULL;
4806
Bram Moolenaar0f873732019-12-05 20:28:46 +01004807 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004808 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004809 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4810 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004811
Bram Moolenaar0f873732019-12-05 20:28:46 +01004812 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004813 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004814# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004815 int delay = 1;
4816
Bram Moolenaar0f873732019-12-05 20:28:46 +01004817 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004818 for (;;)
4819 {
4820 MSG msg;
4821
K.Takatab7057bd2022-01-21 11:37:07 +00004822 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004823 {
4824 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004825 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004826 delay = 1;
4827 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004828 }
4829 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4830 break;
4831
Bram Moolenaar0f873732019-12-05 20:28:46 +01004832 // We start waiting for a very short time and then increase it, so
4833 // that we respond quickly when the process is quick, and don't
4834 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004835 if (delay < 50)
4836 delay += 10;
4837 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004838# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004839 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004840# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004841
Bram Moolenaar0f873732019-12-05 20:28:46 +01004842 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004843 GetExitCodeProcess(pi.hProcess, &ret);
4844 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004845
Bram Moolenaar0f873732019-12-05 20:28:46 +01004846 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004847 CloseHandle(pi.hThread);
4848 CloseHandle(pi.hProcess);
4849
Bram Moolenaar0f873732019-12-05 20:28:46 +01004850 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004851 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4852
4853 return ret;
4854}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004855
4856/*
4857 * Thread launched by the gui to send the current buffer data to the
4858 * process. This way avoid to hang up vim totally if the children
4859 * process take a long time to process the lines.
4860 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004861 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004862sub_process_writer(LPVOID param)
4863{
4864 HANDLE g_hChildStd_IN_Wr = param;
4865 linenr_T lnum = curbuf->b_op_start.lnum;
4866 DWORD len = 0;
4867 DWORD l;
4868 char_u *lp = ml_get(lnum);
4869 char_u *s;
4870 int written = 0;
4871
4872 for (;;)
4873 {
4874 l = (DWORD)STRLEN(lp + written);
4875 if (l == 0)
4876 len = 0;
4877 else if (lp[written] == NL)
4878 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004879 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004880 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4881 }
4882 else
4883 {
4884 s = vim_strchr(lp + written, NL);
4885 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4886 s == NULL ? l : (DWORD)(s - (lp + written)),
4887 &len, NULL);
4888 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004889 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004890 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004891 // Finished a line, add a NL, unless this line should not have
4892 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004893 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004894 || (!curbuf->b_p_bin
4895 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004896 || (lnum != curbuf->b_no_eol_lnum
4897 && (lnum != curbuf->b_ml.ml_line_count
4898 || curbuf->b_p_eol)))
4899 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004900 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4901 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004902 }
4903
4904 ++lnum;
4905 if (lnum > curbuf->b_op_end.lnum)
4906 break;
4907
4908 lp = ml_get(lnum);
4909 written = 0;
4910 }
4911 else if (len > 0)
4912 written += len;
4913 }
4914
Bram Moolenaar0f873732019-12-05 20:28:46 +01004915 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004916 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004917 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004918}
4919
4920
Bram Moolenaar0f873732019-12-05 20:28:46 +01004921# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004922
4923/*
4924 * This function read from the children's stdout and write the
4925 * data on screen or in the buffer accordingly.
4926 */
4927 static void
4928dump_pipe(int options,
4929 HANDLE g_hChildStd_OUT_Rd,
4930 garray_T *ga,
4931 char_u buffer[],
4932 DWORD *buffer_off)
4933{
4934 DWORD availableBytes = 0;
4935 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004936 int ret;
4937 DWORD len;
4938 DWORD toRead;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004939
Bram Moolenaar0f873732019-12-05 20:28:46 +01004940 // we query the pipe to see if there is any data to read
4941 // to avoid to perform a blocking read
4942 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4943 NULL, // optional buffer
4944 0, // buffer size
4945 NULL, // number of read bytes
4946 &availableBytes, // available bytes total
4947 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004948
Bram Moolenaar0f873732019-12-05 20:28:46 +01004949 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004950 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004951 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01004952 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004953 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004954 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004955
Bram Moolenaar0f873732019-12-05 20:28:46 +01004956 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004957 if (len == 0)
4958 break;
4959
4960 availableBytes -= len;
4961
4962 if (options & SHELL_READ)
4963 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004964 // Do NUL -> NL translation, append NL separated
4965 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004966 for (i = 0; i < len; ++i)
4967 {
4968 if (buffer[i] == NL)
4969 append_ga_line(ga);
4970 else if (buffer[i] == NUL)
4971 ga_append(ga, NL);
4972 else
4973 ga_append(ga, buffer[i]);
4974 }
4975 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004976 else if (has_mbyte)
4977 {
4978 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004979 int c;
4980 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004981
4982 len += *buffer_off;
4983 buffer[len] = NUL;
4984
Bram Moolenaar0f873732019-12-05 20:28:46 +01004985 // Check if the last character in buffer[] is
4986 // incomplete, keep these bytes for the next
4987 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004988 for (p = buffer; p < buffer + len; p += l)
4989 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004990 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004991 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004992 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004993 else if (MB_BYTE2LEN(*p) != l)
4994 break;
4995 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004996 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004997 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004998 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004999 if (len >= 12)
5000 ++p;
5001 else
5002 {
5003 *buffer_off = len;
5004 return;
5005 }
5006 }
5007 c = *p;
5008 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01005009 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005010 if (p < buffer + len)
5011 {
5012 *p = c;
5013 *buffer_off = (DWORD)((buffer + len) - p);
5014 mch_memmove(buffer, p, *buffer_off);
5015 return;
5016 }
5017 *buffer_off = 0;
5018 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005019 else
5020 {
5021 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01005022 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005023 }
5024
5025 windgoto(msg_row, msg_col);
5026 cursor_on();
5027 out_flush();
5028 }
5029}
5030
5031/*
5032 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
5033 * for communication and doesn't open any new window.
5034 */
5035 static int
5036mch_system_piped(char *cmd, int options)
5037{
5038 STARTUPINFO si;
5039 PROCESS_INFORMATION pi;
5040 DWORD ret = 0;
5041
5042 HANDLE g_hChildStd_IN_Rd = NULL;
5043 HANDLE g_hChildStd_IN_Wr = NULL;
5044 HANDLE g_hChildStd_OUT_Rd = NULL;
5045 HANDLE g_hChildStd_OUT_Wr = NULL;
5046
Bram Moolenaar0f873732019-12-05 20:28:46 +01005047 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005048 DWORD len;
5049
Bram Moolenaar0f873732019-12-05 20:28:46 +01005050 // buffer used to receive keys
5051 char_u ta_buf[BUFLEN + 1]; // TypeAHead
5052 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005053
5054 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005055 int noread_cnt = 0;
5056 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005057 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005058 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005059 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005060
5061 SECURITY_ATTRIBUTES saAttr;
5062
Bram Moolenaar0f873732019-12-05 20:28:46 +01005063 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005064 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5065 saAttr.bInheritHandle = TRUE;
5066 saAttr.lpSecurityDescriptor = NULL;
5067
5068 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005069 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005070 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005071 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005072 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005073 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005074 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005075 {
5076 CloseHandle(g_hChildStd_IN_Rd);
5077 CloseHandle(g_hChildStd_IN_Wr);
5078 CloseHandle(g_hChildStd_OUT_Rd);
5079 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01005080 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005081 }
5082
5083 si.cb = sizeof(si);
5084 si.lpReserved = NULL;
5085 si.lpDesktop = NULL;
5086 si.lpTitle = NULL;
5087 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
5088
Bram Moolenaar0f873732019-12-05 20:28:46 +01005089 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005090 si.hStdError = g_hChildStd_OUT_Wr;
5091 si.hStdOutput = g_hChildStd_OUT_Wr;
5092 si.hStdInput = g_hChildStd_IN_Rd;
5093 si.wShowWindow = SW_HIDE;
5094 si.cbReserved2 = 0;
5095 si.lpReserved2 = NULL;
5096
5097 if (options & SHELL_READ)
5098 ga_init2(&ga, 1, BUFLEN);
5099
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005100 if (cmd != NULL)
5101 {
5102 p = (char *)vim_strsave((char_u *)cmd);
5103 if (p != NULL)
5104 unescape_shellxquote((char_u *)p, p_sxe);
5105 else
5106 p = cmd;
5107 }
5108
Bram Moolenaar0f873732019-12-05 20:28:46 +01005109 // Now, run the command.
5110 // About "Inherit handles" being TRUE: this command can be litigious,
5111 // handle inheritance was deactivated for pending temp file, but, if we
5112 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005113 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
5114 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005115
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005116 if (p != cmd)
5117 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005118
Bram Moolenaar0f873732019-12-05 20:28:46 +01005119 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005120 CloseHandle(g_hChildStd_IN_Rd);
5121 CloseHandle(g_hChildStd_OUT_Wr);
5122
5123 if (options & SHELL_WRITE)
5124 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02005125 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005126 _beginthreadex(NULL, // security attributes
5127 0, // default stack size
5128 sub_process_writer, // function to be executed
5129 g_hChildStd_IN_Wr, // parameter
5130 0, // creation flag, start immediately
5131 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005132 CloseHandle(thread);
5133 g_hChildStd_IN_Wr = NULL;
5134 }
5135
Bram Moolenaar0f873732019-12-05 20:28:46 +01005136 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005137 for (;;)
5138 {
5139 MSG msg;
5140
K.Takatab7057bd2022-01-21 11:37:07 +00005141 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005142 {
5143 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00005144 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005145 }
5146
Bram Moolenaar0f873732019-12-05 20:28:46 +01005147 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005148 if ((options & (SHELL_READ|SHELL_WRITE))
5149# ifdef FEAT_GUI
5150 || gui.in_use
5151# endif
5152 )
5153 {
5154 len = 0;
5155 if (!(options & SHELL_EXPAND)
5156 && ((options &
5157 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
5158 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
5159# ifdef FEAT_GUI
5160 || gui.in_use
5161# endif
5162 )
5163 && (ta_len > 0 || noread_cnt > 4))
5164 {
5165 if (ta_len == 0)
5166 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005167 // Get extra characters when we don't have any. Reset the
5168 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005169 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005170 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
5171 }
5172 if (ta_len > 0 || len > 0)
5173 {
5174 /*
5175 * For pipes: Check for CTRL-C: send interrupt signal to
5176 * child. Check for CTRL-D: EOF, close pipe to child.
5177 */
5178 if (len == 1 && cmd != NULL)
5179 {
5180 if (ta_buf[ta_len] == Ctrl_C)
5181 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005182 // Learn what exit code is expected, for
5183 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005184 TerminateProcess(pi.hProcess, 9);
5185 }
5186 if (ta_buf[ta_len] == Ctrl_D)
5187 {
5188 CloseHandle(g_hChildStd_IN_Wr);
5189 g_hChildStd_IN_Wr = NULL;
5190 }
5191 }
5192
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01005193 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005194
5195 /*
5196 * For pipes: echo the typed characters. For a pty this
5197 * does not seem to work.
5198 */
5199 for (i = ta_len; i < ta_len + len; ++i)
5200 {
5201 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
5202 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005203 else if (has_mbyte)
5204 {
5205 int l = (*mb_ptr2len)(ta_buf + i);
5206
5207 msg_outtrans_len(ta_buf + i, l);
5208 i += l - 1;
5209 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005210 else
5211 msg_outtrans_len(ta_buf + i, 1);
5212 }
5213 windgoto(msg_row, msg_col);
5214 out_flush();
5215
5216 ta_len += len;
5217
5218 /*
5219 * Write the characters to the child, unless EOF has been
5220 * typed for pipes. Write one character at a time, to
5221 * avoid losing too much typeahead. When writing buffer
5222 * lines, drop the typed characters (only check for
5223 * CTRL-C).
5224 */
5225 if (options & SHELL_WRITE)
5226 ta_len = 0;
5227 else if (g_hChildStd_IN_Wr != NULL)
5228 {
5229 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
5230 1, &len, NULL);
5231 // if we are typing in, we want to keep things reactive
5232 delay = 1;
5233 if (len > 0)
5234 {
5235 ta_len -= len;
5236 mch_memmove(ta_buf, ta_buf + len, ta_len);
5237 }
5238 }
5239 }
5240 }
5241 }
5242
5243 if (ta_len)
5244 ui_inchar_undo(ta_buf, ta_len);
5245
5246 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
5247 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005248 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005249 break;
5250 }
5251
5252 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005253 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005254
Bram Moolenaar0f873732019-12-05 20:28:46 +01005255 // We start waiting for a very short time and then increase it, so
5256 // that we respond quickly when the process is quick, and don't
5257 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005258 if (delay < 50)
5259 delay += 10;
5260 }
5261
Bram Moolenaar0f873732019-12-05 20:28:46 +01005262 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005263 CloseHandle(g_hChildStd_OUT_Rd);
5264 if (g_hChildStd_IN_Wr != NULL)
5265 CloseHandle(g_hChildStd_IN_Wr);
5266
5267 WaitForSingleObject(pi.hProcess, INFINITE);
5268
Bram Moolenaar0f873732019-12-05 20:28:46 +01005269 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005270 GetExitCodeProcess(pi.hProcess, &ret);
5271
5272 if (options & SHELL_READ)
5273 {
5274 if (ga.ga_len > 0)
5275 {
5276 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01005277 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005278 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
5279 }
5280 else
5281 curbuf->b_no_eol_lnum = 0;
5282 ga_clear(&ga);
5283 }
5284
Bram Moolenaar0f873732019-12-05 20:28:46 +01005285 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005286 CloseHandle(pi.hThread);
5287 CloseHandle(pi.hProcess);
5288
5289 return ret;
5290}
5291
5292 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005293mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005294{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005295 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005296 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005297 return mch_system_piped(cmd, options);
5298 else
5299 return mch_system_classic(cmd, options);
5300}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005301#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005302
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005303#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005304 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02005305mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005306{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005307 int ret;
5308 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005309 char_u *buf;
5310 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005311
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005312 // If the command starts and ends with double quotes, enclose the command
5313 // in parentheses.
5314 len = STRLEN(cmd);
5315 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
5316 {
5317 len += 3;
5318 buf = alloc(len);
5319 if (buf == NULL)
5320 return -1;
5321 vim_snprintf((char *)buf, len, "(%s)", cmd);
5322 wcmd = enc_to_utf16(buf, NULL);
5323 free(buf);
5324 }
5325 else
5326 wcmd = enc_to_utf16((char_u *)cmd, NULL);
5327
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005328 if (wcmd == NULL)
5329 return -1;
5330
5331 ret = _wsystem(wcmd);
5332 vim_free(wcmd);
5333 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005334}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005335
5336#endif
5337
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005338 static int
5339mch_system(char *cmd, int options)
5340{
5341#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005342 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005343 return mch_system_g(cmd, options);
5344 else
5345 return mch_system_c(cmd, options);
5346#elif defined(FEAT_GUI_MSWIN)
5347 return mch_system_g(cmd, options);
5348#else
5349 return mch_system_c(cmd, options);
5350#endif
5351}
5352
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005353#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
5354/*
5355 * Use a terminal window to run a shell command in.
5356 */
5357 static int
5358mch_call_shell_terminal(
5359 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005360 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005361{
5362 jobopt_T opt;
5363 char_u *newcmd = NULL;
5364 typval_T argvar[2];
5365 long_u cmdlen;
5366 int retval = -1;
5367 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005368 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005369 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005370 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005371
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005372 if (cmd == NULL)
5373 cmdlen = STRLEN(p_sh) + 1;
5374 else
5375 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005376 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005377 if (newcmd == NULL)
5378 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005379 if (cmd == NULL)
5380 {
5381 STRCPY(newcmd, p_sh);
5382 ch_log(NULL, "starting terminal to run a shell");
5383 }
5384 else
5385 {
5386 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
5387 ch_log(NULL, "starting terminal for system command '%s'", cmd);
5388 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005389
5390 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005391
5392 argvar[0].v_type = VAR_STRING;
5393 argvar[0].vval.v_string = newcmd;
5394 argvar[1].v_type = VAR_UNKNOWN;
5395 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005396 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01005397 {
5398 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005399 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01005400 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005401
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005402 job = term_getjob(buf->b_term);
5403 ++job->jv_refcount;
5404
Bram Moolenaar0f873732019-12-05 20:28:46 +01005405 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005406 aucmd_prepbuf(&aco, buf);
Bram Moolenaare76062c2022-11-28 18:51:43 +00005407 if (curbuf == buf)
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005408 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005409 // Only do this when a window was found for "buf".
5410 clear_oparg(&oa);
5411 while (term_use_loop())
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005412 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005413 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
5414 {
5415 // If terminal_loop() returns OK we got a key that is handled
5416 // in Normal model. We don't do redrawing anyway.
5417 if (terminal_loop(TRUE) == OK)
5418 normal_cmd(&oa, TRUE);
5419 }
5420 else
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005421 normal_cmd(&oa, TRUE);
5422 }
Bram Moolenaare76062c2022-11-28 18:51:43 +00005423 retval = job->jv_exitval;
5424 ch_log(NULL, "system command finished");
5425
5426 job_unref(job);
5427
5428 // restore curwin/curbuf and a few other things
5429 aucmd_restbuf(&aco);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005430 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005431
5432 wait_return(TRUE);
5433 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
5434
5435 vim_free(newcmd);
5436 return retval;
5437}
5438#endif
5439
Bram Moolenaar071d4272004-06-13 20:20:40 +00005440/*
5441 * Either execute a command by calling the shell or start a new shell
5442 */
5443 int
5444mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005445 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005446 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00005447{
5448 int x = 0;
5449 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005450 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02005451
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00005452#ifdef FEAT_EVAL
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01005453 ch_log(NULL, "executing shell command: %s", cmd);
5454#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01005455 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02005456 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005457 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005458 if (cmd == NULL)
5459 wcscat(szShellTitle, L" :sh");
5460 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005461 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005462 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005463
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005464 if (wn != NULL)
5465 {
5466 wcscat(szShellTitle, L" - !");
5467 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02005468 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005469 wcscat(szShellTitle, wn);
5470 SetConsoleTitleW(szShellTitle);
5471 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005472 }
5473 }
5474 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005475
5476 out_flush();
5477
5478#ifdef MCH_WRITE_DUMP
5479 if (fdDump)
5480 {
5481 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
5482 fflush(fdDump);
5483 }
5484#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005485#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005486 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005487 if (
5488# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005489 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005490# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005491 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005492 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
5493 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005494 char_u *cmdbase = cmd;
5495
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02005496 if (cmdbase != NULL)
5497 // Skip a leading quote and (.
5498 while (*cmdbase == '"' || *cmdbase == '(')
5499 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005500
5501 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01005502 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
5503 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005504 {
5505 // Use a terminal window to run the command in.
5506 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005507 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005508 return x;
5509 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005510 }
5511#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005512
5513 /*
5514 * Catch all deadly signals while running the external command, because a
5515 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5516 */
ichizok378447f2023-05-11 22:25:42 +01005517 mch_signal(SIGINT, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005518#if defined(__GNUC__) && !defined(__MINGW32__)
ichizok378447f2023-05-11 22:25:42 +01005519 mch_signal(SIGKILL, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005520#else
ichizok378447f2023-05-11 22:25:42 +01005521 mch_signal(SIGBREAK, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005522#endif
ichizok378447f2023-05-11 22:25:42 +01005523 mch_signal(SIGILL, SIG_IGN);
5524 mch_signal(SIGFPE, SIG_IGN);
5525 mch_signal(SIGSEGV, SIG_IGN);
5526 mch_signal(SIGTERM, SIG_IGN);
5527 mch_signal(SIGABRT, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005528
5529 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005530 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00005531
5532 if (cmd == NULL)
5533 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005534 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005535 }
5536 else
5537 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005538 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005539 char_u *newcmd = NULL;
5540 char_u *cmdbase = cmd;
5541 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005542
Bram Moolenaar0f873732019-12-05 20:28:46 +01005543 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005544 if (*cmdbase == '"' )
5545 ++cmdbase;
5546 if (*cmdbase == '(')
5547 ++cmdbase;
5548
Bram Moolenaar1c465442017-03-12 20:10:05 +01005549 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005550 {
5551 STARTUPINFO si;
5552 PROCESS_INFORMATION pi;
5553 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005554 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005555 char_u *p;
5556
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005557 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005558 si.cb = sizeof(si);
5559 si.lpReserved = NULL;
5560 si.lpDesktop = NULL;
5561 si.lpTitle = NULL;
5562 si.dwFlags = 0;
5563 si.cbReserved2 = 0;
5564 si.lpReserved2 = NULL;
5565
5566 cmdbase = skipwhite(cmdbase + 5);
5567 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005568 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005569 {
5570 cmdbase = skipwhite(cmdbase + 4);
5571 si.dwFlags = STARTF_USESHOWWINDOW;
5572 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005573 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005574 }
5575 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005576 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005577 {
5578 cmdbase = skipwhite(cmdbase + 2);
5579 flags = CREATE_NO_WINDOW;
5580 si.dwFlags = STARTF_USESTDHANDLES;
5581 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005582 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005583 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005584 NULL, // Security att.
5585 OPEN_EXISTING, // Open flags
5586 FILE_ATTRIBUTE_NORMAL, // File att.
5587 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005588 si.hStdOutput = si.hStdInput;
5589 si.hStdError = si.hStdInput;
5590 }
5591
Bram Moolenaar0f873732019-12-05 20:28:46 +01005592 // Remove a trailing ", ) and )" if they have a match
5593 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005594 if (cmdbase > cmd)
5595 {
5596 p = cmdbase + STRLEN(cmdbase);
5597 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5598 *--p = NUL;
5599 if (p > cmdbase && p[-1] == ')'
5600 && (*cmd =='(' || cmd[1] == '('))
5601 *--p = NUL;
5602 }
5603
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005604 newcmd = cmdbase;
5605 unescape_shellxquote(cmdbase, p_sxe);
5606
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005607 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005608 * If creating new console, arguments are passed to the
5609 * 'cmd.exe' as-is. If it's not, arguments are not treated
5610 * correctly for current 'cmd.exe'. So unescape characters in
5611 * shellxescape except '|' for avoiding to be treated as
5612 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005613 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005614 if (flags != CREATE_NEW_CONSOLE)
5615 {
5616 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005617 char_u *cmd_shell = mch_getenv("COMSPEC");
5618
5619 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005620 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005621
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005622 subcmd = vim_strsave_escaped_ext(cmdbase,
5623 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005624 if (subcmd != NULL)
5625 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005626 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005627 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005628 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005629 if (newcmd != NULL)
5630 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005631 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005632 else
5633 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005634 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005635 }
5636 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005637
5638 /*
5639 * Now, start the command as a process, so that it doesn't
5640 * inherit our handles which causes unpleasant dangling swap
5641 * files if we exit before the spawned process
5642 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005643 if (vim_create_process((char *)newcmd, FALSE, flags,
5644 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005645 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005646 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5647 > (HINSTANCE)32)
5648 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005649 else
5650 {
5651 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005652#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005653# ifdef VIMDLL
5654 if (gui.in_use)
5655# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005656 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005657#endif
5658 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005659
5660 if (newcmd != cmdbase)
5661 vim_free(newcmd);
5662
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005663 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005664 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005665 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005666 CloseHandle(si.hStdInput);
5667 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005668 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005669 CloseHandle(pi.hThread);
5670 CloseHandle(pi.hProcess);
5671 }
5672 else
5673 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005674 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005675#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005676 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005677 (!s_dont_use_vimrun && p_stmp ?
5678 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5679 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005680#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005681 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005682
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005683 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005684 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005685 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005686#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005687 if (
5688# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005689 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005690# endif
5691 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005692 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005693 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5694 "External commands will not pause after completion.\n"
5695 "See :help win32-vimrun for more information.");
5696 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005697 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5698 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005699
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005700 if (wmsg != NULL && wtitle != NULL)
5701 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5702 vim_free(wmsg);
5703 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005704 need_vimrun_warning = FALSE;
5705 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005706 if (
5707# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005708 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005709# endif
5710 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005711 // Use vimrun to execute the command. It opens a console
5712 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005713 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005714 vimrun_path,
5715 (msg_silent != 0 || (options & SHELL_DOOUT))
5716 ? "-s " : "",
5717 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005718 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005719# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005720 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005721# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005722 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005723 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005724 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5725 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005726 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005727#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005728 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005729 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005730 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005731 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005732 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005733 }
5734 }
5735
5736 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005737 {
5738 // The shell may have messed with the mode, always set it.
5739 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005740 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005741 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005742
Bram Moolenaar0f873732019-12-05 20:28:46 +01005743 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005744 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005745#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005746 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005747 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005748#endif
5749 )
5750 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005751 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005752 msg_putchar('\n');
5753 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005754 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005755
ichizok378447f2023-05-11 22:25:42 +01005756 mch_signal(SIGINT, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005757#if defined(__GNUC__) && !defined(__MINGW32__)
ichizok378447f2023-05-11 22:25:42 +01005758 mch_signal(SIGKILL, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005759#else
ichizok378447f2023-05-11 22:25:42 +01005760 mch_signal(SIGBREAK, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005761#endif
ichizok378447f2023-05-11 22:25:42 +01005762 mch_signal(SIGILL, SIG_DFL);
5763 mch_signal(SIGFPE, SIG_DFL);
5764 mch_signal(SIGSEGV, SIG_DFL);
5765 mch_signal(SIGTERM, SIG_DFL);
5766 mch_signal(SIGABRT, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005767
5768 return x;
5769}
5770
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005771#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005772 static HANDLE
5773job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005774 char_u *fname,
5775 DWORD dwDesiredAccess,
5776 DWORD dwShareMode,
5777 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5778 DWORD dwCreationDisposition,
5779 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005780{
5781 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005782 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005783
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005784 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005785 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005786 return INVALID_HANDLE_VALUE;
5787
5788 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5789 lpSecurityAttributes, dwCreationDisposition,
5790 dwFlagsAndAttributes, NULL);
5791 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005792 return h;
5793}
5794
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005795/*
5796 * Turn the dictionary "env" into a NUL separated list that can be used as the
5797 * environment argument of vim_create_process().
5798 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005799 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005800win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005801{
5802 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005803 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005804 LPVOID base = GetEnvironmentStringsW();
5805
Bram Moolenaar0f873732019-12-05 20:28:46 +01005806 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005807 if (ga_grow(gap, 1) == FAIL)
5808 return;
5809
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005810 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005811 {
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00005812 FOR_ALL_HASHTAB_ITEMS(&env->dv_hashtab, hi, todo)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005813 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005814 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005815 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005816 typval_T *item = &dict_lookup(hi)->di_tv;
5817 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005818 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005819 --todo;
5820 if (wkey != NULL && wval != NULL)
5821 {
5822 size_t n;
5823 size_t lkey = wcslen(wkey);
5824 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005825
Yegappan Lakshmananfadc02a2023-01-27 21:03:12 +00005826 if (ga_grow(gap, (int)(lkey + lval + 2)) == FAIL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005827 continue;
5828 for (n = 0; n < lkey; n++)
5829 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5830 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5831 for (n = 0; n < lval; n++)
5832 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5833 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5834 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005835 vim_free(wkey);
5836 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005837 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005838 }
5839 }
5840
Bram Moolenaar355757a2020-02-10 22:06:32 +01005841 if (base)
5842 {
5843 WCHAR *p = (WCHAR*) base;
5844
5845 // for last \0
5846 if (ga_grow(gap, 1) == FAIL)
5847 return;
5848
5849 while (*p != 0 || *(p + 1) != 0)
5850 {
5851 if (ga_grow(gap, 1) == OK)
5852 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5853 p++;
5854 }
Ken Takataad29f6a2023-09-16 13:56:02 +02005855 FreeEnvironmentStringsW(base);
Bram Moolenaar355757a2020-02-10 22:06:32 +01005856 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5857 }
5858
Bram Moolenaar493359e2018-06-12 20:25:52 +02005859# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005860 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005861# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005862 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005863 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005864# endif
5865# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005866 char_u *version = get_vim_var_str(VV_VERSION);
5867 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005868# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005869 // size of "VIM_SERVERNAME=" and value,
5870 // plus "VIM_TERMINAL=" and value,
5871 // plus two terminating NULs
5872 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005873# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005874 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005875# endif
5876# ifdef FEAT_TERMINAL
5877 + 13 + version_len + 2
5878# endif
5879 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005880
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005881 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005882 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005883# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005884 for (n = 0; n < 15; n++)
5885 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5886 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005887 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005888 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5889 (WCHAR)servername[n];
5890 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005891# endif
5892# ifdef FEAT_TERMINAL
5893 if (is_terminal)
5894 {
5895 for (n = 0; n < 13; n++)
5896 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5897 (WCHAR)"VIM_TERMINAL="[n];
5898 for (n = 0; n < version_len; n++)
5899 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5900 (WCHAR)version[n];
5901 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5902 }
5903# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005904 }
5905 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005906# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005907}
5908
Bram Moolenaarb091f302019-01-19 14:37:00 +01005909/*
5910 * Create a pair of pipes.
5911 * Return TRUE for success, FALSE for failure.
5912 */
5913 static BOOL
5914create_pipe_pair(HANDLE handles[2])
5915{
5916 static LONG s;
5917 char name[64];
5918 SECURITY_ATTRIBUTES sa;
5919
5920 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5921 GetCurrentProcessId(),
5922 InterlockedIncrement(&s));
5923
5924 // Create named pipe. Max size of named pipe is 65535.
5925 handles[1] = CreateNamedPipe(
5926 name,
5927 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5928 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005929 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005930
5931 if (handles[1] == INVALID_HANDLE_VALUE)
5932 return FALSE;
5933
5934 sa.nLength = sizeof(sa);
5935 sa.bInheritHandle = TRUE;
5936 sa.lpSecurityDescriptor = NULL;
5937
5938 handles[0] = CreateFile(name,
5939 FILE_GENERIC_READ,
5940 FILE_SHARE_READ, &sa,
5941 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5942
5943 if (handles[0] == INVALID_HANDLE_VALUE)
5944 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005945 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005946 return FALSE;
5947 }
5948
5949 return TRUE;
5950}
5951
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005952 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005953mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005954{
5955 STARTUPINFO si;
5956 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005957 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005958 SECURITY_ATTRIBUTES saAttr;
5959 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005960 HANDLE ifd[2];
5961 HANDLE ofd[2];
5962 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005963 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005964
5965 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5966 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5967 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5968 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5969 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5970 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5971 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5972
5973 if (use_out_for_err && use_null_for_out)
5974 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005975
5976 ifd[0] = INVALID_HANDLE_VALUE;
5977 ifd[1] = INVALID_HANDLE_VALUE;
5978 ofd[0] = INVALID_HANDLE_VALUE;
5979 ofd[1] = INVALID_HANDLE_VALUE;
5980 efd[0] = INVALID_HANDLE_VALUE;
5981 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005982 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005983
Bram Moolenaar14207f42016-10-27 21:13:10 +02005984 jo = CreateJobObject(NULL, NULL);
5985 if (jo == NULL)
5986 {
5987 job->jv_status = JOB_FAILED;
5988 goto failed;
5989 }
5990
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005991 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005992 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005993
Bram Moolenaar76467df2016-02-12 19:30:26 +01005994 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005995 ZeroMemory(&si, sizeof(si));
5996 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005997 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005998 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005999
Bram Moolenaard8070362016-02-15 21:56:54 +01006000 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
6001 saAttr.bInheritHandle = TRUE;
6002 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006003
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006004 if (use_file_for_in)
6005 {
6006 char_u *fname = options->jo_io_name[PART_IN];
6007
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01006008 ifd[0] = job_io_file_open(fname, GENERIC_READ,
6009 FILE_SHARE_READ | FILE_SHARE_WRITE,
6010 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
6011 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01006012 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006013 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01006014 goto failed;
6015 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006016 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01006017 else if (!use_null_for_in
6018 && (!create_pipe_pair(ifd)
6019 || !SetHandleInformation(ifd[1], 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_out)
6023 {
6024 char_u *fname = options->jo_io_name[PART_OUT];
6025
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01006026 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
6027 FILE_SHARE_READ | FILE_SHARE_WRITE,
6028 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
6029 if (ofd[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_null_for_out &&
6036 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006037 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006038 goto failed;
6039
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006040 if (use_file_for_err)
6041 {
6042 char_u *fname = options->jo_io_name[PART_ERR];
6043
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01006044 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
6045 FILE_SHARE_READ | FILE_SHARE_WRITE,
6046 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
6047 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006048 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006049 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006050 goto failed;
6051 }
6052 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006053 else if (!use_out_for_err && !use_null_for_err &&
6054 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006055 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01006056 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006057
Bram Moolenaard8070362016-02-15 21:56:54 +01006058 si.dwFlags |= STARTF_USESTDHANDLES;
6059 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006060 si.hStdOutput = ofd[1];
6061 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
6062
6063 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
6064 {
Bram Moolenaarde279892016-03-11 22:19:44 +01006065 if (options->jo_set & JO_CHANNEL)
6066 {
6067 channel = options->jo_channel;
6068 if (channel != NULL)
6069 ++channel->ch_refcount;
6070 }
6071 else
6072 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006073 if (channel == NULL)
6074 goto failed;
6075 }
Bram Moolenaard8070362016-02-15 21:56:54 +01006076
6077 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02006078 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006079 CREATE_DEFAULT_ERROR_MODE |
6080 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006081 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01006082 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006083 &si, &pi,
6084 ga.ga_data,
6085 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01006086 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02006087 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006088 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006089 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006090 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006091
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006092 ga_clear(&ga);
6093
Bram Moolenaar14207f42016-10-27 21:13:10 +02006094 if (!AssignProcessToJobObject(jo, pi.hProcess))
6095 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006096 // if failing, switch the way to terminate
6097 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02006098 CloseHandle(jo);
6099 jo = NULL;
6100 }
6101 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01006102 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006103 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02006104 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006105 job->jv_status = JOB_STARTED;
6106
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02006107 CloseHandle(ifd[0]);
6108 CloseHandle(ofd[1]);
6109 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01006110 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01006111
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006112 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006113 if (channel != NULL)
6114 {
6115 channel_set_pipes(channel,
6116 use_file_for_in || use_null_for_in
6117 ? INVALID_FD : (sock_T)ifd[1],
6118 use_file_for_out || use_null_for_out
6119 ? INVALID_FD : (sock_T)ofd[0],
6120 use_out_for_err || use_file_for_err || use_null_for_err
6121 ? INVALID_FD : (sock_T)efd[0]);
6122 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006123 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006124 return;
6125
6126failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01006127 CloseHandle(ifd[0]);
6128 CloseHandle(ofd[0]);
6129 CloseHandle(efd[0]);
6130 CloseHandle(ifd[1]);
6131 CloseHandle(ofd[1]);
6132 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01006133 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006134 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006135}
6136
6137 char *
6138mch_job_status(job_T *job)
6139{
6140 DWORD dwExitCode = 0;
6141
Bram Moolenaar76467df2016-02-12 19:30:26 +01006142 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
6143 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006144 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01006145 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01006146 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02006147 {
6148 ch_log(job->jv_channel, "Job ended");
6149 job->jv_status = JOB_ENDED;
6150 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006151 return "dead";
6152 }
6153 return "run";
6154}
6155
Bram Moolenaar97792de2016-10-15 18:36:49 +02006156 job_T *
6157mch_detect_ended_job(job_T *job_list)
6158{
6159 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
6160 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
6161 job_T *job = job_list;
6162
6163 while (job != NULL)
6164 {
6165 DWORD n;
6166 DWORD result;
6167
6168 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
6169 && job != NULL; job = job->jv_next)
6170 {
6171 if (job->jv_status == JOB_STARTED)
6172 {
6173 jobHandles[n] = job->jv_proc_info.hProcess;
6174 jobArray[n] = job;
6175 ++n;
6176 }
6177 }
6178 if (n == 0)
6179 continue;
6180 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
6181 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
6182 {
6183 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
6184
6185 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
6186 return wait_job;
6187 }
6188 }
6189 return NULL;
6190}
6191
Bram Moolenaarfb630902016-10-29 14:55:00 +02006192 static BOOL
6193terminate_all(HANDLE process, int code)
6194{
6195 PROCESSENTRY32 pe;
6196 HANDLE h = INVALID_HANDLE_VALUE;
6197 DWORD pid = GetProcessId(process);
6198
6199 if (pid != 0)
6200 {
6201 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
6202 if (h != INVALID_HANDLE_VALUE)
6203 {
6204 pe.dwSize = sizeof(PROCESSENTRY32);
6205 if (!Process32First(h, &pe))
6206 goto theend;
6207
6208 do
6209 {
6210 if (pe.th32ParentProcessID == pid)
6211 {
6212 HANDLE ph = OpenProcess(
6213 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
6214 if (ph != NULL)
6215 {
6216 terminate_all(ph, code);
6217 CloseHandle(ph);
6218 }
6219 }
6220 } while (Process32Next(h, &pe));
6221
6222 CloseHandle(h);
6223 }
6224 }
6225
6226theend:
6227 return TerminateProcess(process, code);
6228}
6229
6230/*
6231 * Send a (deadly) signal to "job".
6232 * Return FAIL if it didn't work.
6233 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006234 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02006235mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006236{
Bram Moolenaar923d9262016-02-25 20:56:01 +01006237 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006238
Bram Moolenaar923d9262016-02-25 20:56:01 +01006239 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01006240 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006241 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02006242 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006243 {
6244 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
6245 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00006246 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006247 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01006248 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006249 }
6250
6251 if (!AttachConsole(job->jv_proc_info.dwProcessId))
6252 return FAIL;
6253 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01006254 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
6255 job->jv_proc_info.dwProcessId)
6256 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006257 FreeConsole();
6258 return ret;
6259}
6260
6261/*
6262 * Clear the data related to "job".
6263 */
6264 void
6265mch_clear_job(job_T *job)
6266{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00006267 if (job->jv_status == JOB_FAILED)
6268 return;
6269
6270 if (job->jv_job_object != NULL)
6271 CloseHandle(job->jv_job_object);
6272 CloseHandle(job->jv_proc_info.hProcess);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006273}
6274#endif
6275
Bram Moolenaar071d4272004-06-13 20:20:40 +00006276
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006277#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006278
6279/*
6280 * Start termcap mode
6281 */
6282 static void
6283termcap_mode_start(void)
6284{
6285 DWORD cmodein;
6286
6287 if (g_fTermcapMode)
6288 return;
6289
6290 SaveConsoleBuffer(&g_cbNonTermcap);
6291
6292 if (g_cbTermcap.IsValid)
6293 {
6294 /*
6295 * We've been in termcap mode before. Restore certain screen
6296 * characteristics, including the buffer size and the window
6297 * size. Since we will be redrawing the screen, we don't need
6298 * to restore the actual contents of the buffer.
6299 */
6300 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006301 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006302 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
6303 Rows = g_cbTermcap.Info.dwSize.Y;
6304 Columns = g_cbTermcap.Info.dwSize.X;
6305 }
6306 else
6307 {
6308 /*
6309 * This is our first time entering termcap mode. Clear the console
6310 * screen buffer, and resize the buffer to match the current window
6311 * size. We will use this as the size of our editing environment.
6312 */
6313 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006314 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006315 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
6316 }
6317
Bram Moolenaar071d4272004-06-13 20:20:40 +00006318 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006319
6320 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006321 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006322 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006323 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006324 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
6325 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006326 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006327 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006328 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006329 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6330 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006331 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006332 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006333
6334 redraw_later_clear();
6335 g_fTermcapMode = TRUE;
6336}
6337
6338
6339/*
6340 * End termcap mode
6341 */
6342 static void
6343termcap_mode_end(void)
6344{
6345 DWORD cmodein;
6346 ConsoleBuffer *cb;
6347 COORD coord;
6348 DWORD dwDummy;
6349
6350 if (!g_fTermcapMode)
6351 return;
6352
6353 SaveConsoleBuffer(&g_cbTermcap);
6354
6355 GetConsoleMode(g_hConIn, &cmodein);
6356 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006357 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6358 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006359
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006360# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01006361 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006362# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006363 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006364# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006365 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01006366 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006367
Christopher Plewright1140b512022-11-12 18:46:05 +00006368 // Switch back to main screen buffer.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00006369 if (exiting && use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00006370 vtp_printf("\033[?1049l");
6371
6372 if (!USE_WT && (p_rs || exiting))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006373 {
6374 /*
6375 * Clear anything that happens to be on the current line.
6376 */
6377 coord.X = 0;
6378 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006379 FillConsoleOutputCharacter(g_hConOut, ' ',
6380 cb->Info.dwSize.X, coord, &dwDummy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006381 /*
6382 * The following is just for aesthetics. If we are exiting without
6383 * restoring the screen, then we want to have a prompt string
6384 * appear at the bottom line. However, the command interpreter
6385 * seems to always advance the cursor one line before displaying
6386 * the prompt string, which causes the screen to scroll. To
6387 * counter this, move the cursor up one line before exiting.
6388 */
6389 if (exiting && !p_rs)
6390 coord.Y--;
6391 /*
6392 * Position the cursor at the leftmost column of the desired row.
6393 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006394 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006395 }
Christopher Plewright1140b512022-11-12 18:46:05 +00006396 SetConsoleCursorInfo(g_hConOut, &g_cci);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006397 g_fTermcapMode = FALSE;
6398}
Christopher Plewright38804d62022-11-09 23:55:52 +00006399#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006400
6401
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006402#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006403 void
6404mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01006405 char_u *s UNUSED,
6406 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006407{
Bram Moolenaar0f873732019-12-05 20:28:46 +01006408 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00006409}
6410
6411#else
6412
6413/*
6414 * clear `n' chars, starting from `coord'
6415 */
6416 static void
6417clear_chars(
6418 COORD coord,
6419 DWORD n)
6420{
Christopher Plewright38804d62022-11-09 23:55:52 +00006421 if (!vtp_working)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006422 {
6423 DWORD dwDummy;
6424
6425 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
6426 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
6427 &dwDummy);
6428 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006429 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02006430 {
6431 set_console_color_rgb();
6432 gotoxy(coord.X + 1, coord.Y + 1);
6433 vtp_printf("\033[%dX", n);
6434 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006435}
6436
6437
6438/*
6439 * Clear the screen
6440 */
6441 static void
6442clear_screen(void)
6443{
6444 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006445
Christopher Plewright38804d62022-11-09 23:55:52 +00006446 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006447 clear_chars(g_coord, Rows * Columns);
6448 else
6449 {
6450 set_console_color_rgb();
6451 gotoxy(1, 1);
6452 vtp_printf("\033[2J");
6453 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006454}
6455
6456
6457/*
6458 * Clear to end of display
6459 */
6460 static void
6461clear_to_end_of_display(void)
6462{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006463 COORD save = g_coord;
6464
Christopher Plewright38804d62022-11-09 23:55:52 +00006465 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006466 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006467 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006468 else
6469 {
6470 set_console_color_rgb();
6471 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6472 vtp_printf("\033[0J");
6473
6474 gotoxy(save.X + 1, save.Y + 1);
6475 g_coord = save;
6476 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006477}
6478
6479
6480/*
6481 * Clear to end of line
6482 */
6483 static void
6484clear_to_end_of_line(void)
6485{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006486 COORD save = g_coord;
6487
Christopher Plewright38804d62022-11-09 23:55:52 +00006488 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006489 clear_chars(g_coord, Columns - g_coord.X);
6490 else
6491 {
6492 set_console_color_rgb();
6493 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6494 vtp_printf("\033[0K");
6495
6496 gotoxy(save.X + 1, save.Y + 1);
6497 g_coord = save;
6498 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006499}
6500
6501
6502/*
6503 * Scroll the scroll region up by `cLines' lines
6504 */
6505 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006506scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006507{
6508 COORD oldcoord = g_coord;
6509
6510 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6511 delete_lines(cLines);
6512
6513 g_coord = oldcoord;
6514}
6515
6516
6517/*
6518 * Set the scroll region
6519 */
6520 static void
6521set_scroll_region(
6522 unsigned left,
6523 unsigned top,
6524 unsigned right,
6525 unsigned bottom)
6526{
6527 if (left >= right
6528 || top >= bottom
6529 || right > (unsigned) Columns - 1
6530 || bottom > (unsigned) Rows - 1)
6531 return;
6532
6533 g_srScrollRegion.Left = left;
6534 g_srScrollRegion.Top = top;
6535 g_srScrollRegion.Right = right;
6536 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006537}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006538
Bram Moolenaar6982f422019-02-16 16:48:01 +01006539 static void
6540set_scroll_region_tb(
6541 unsigned top,
6542 unsigned bottom)
6543{
6544 if (top >= bottom || bottom > (unsigned)Rows - 1)
6545 return;
6546
6547 g_srScrollRegion.Top = top;
6548 g_srScrollRegion.Bottom = bottom;
6549}
6550
6551 static void
6552set_scroll_region_lr(
6553 unsigned left,
6554 unsigned right)
6555{
6556 if (left >= right || right > (unsigned)Columns - 1)
6557 return;
6558
6559 g_srScrollRegion.Left = left;
6560 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006561}
6562
6563
6564/*
6565 * Insert `cLines' lines at the current cursor position
6566 */
6567 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006568insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006569{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006570 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006571 COORD dest;
6572 CHAR_INFO fill;
6573
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006574 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6575
Bram Moolenaar6982f422019-02-16 16:48:01 +01006576 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006577 dest.Y = g_coord.Y + cLines;
6578
Bram Moolenaar6982f422019-02-16 16:48:01 +01006579 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006580 source.Top = g_coord.Y;
6581 source.Right = g_srScrollRegion.Right;
6582 source.Bottom = g_srScrollRegion.Bottom - cLines;
6583
Bram Moolenaar6982f422019-02-16 16:48:01 +01006584 clip.Left = g_srScrollRegion.Left;
6585 clip.Top = g_coord.Y;
6586 clip.Right = g_srScrollRegion.Right;
6587 clip.Bottom = g_srScrollRegion.Bottom;
6588
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006589 fill.Char.AsciiChar = ' ';
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006590 if (!USE_VTP)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006591 fill.Attributes = g_attrCurrent;
6592 else
6593 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006594
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006595 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006596
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006597 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6598
Bram Moolenaar6982f422019-02-16 16:48:01 +01006599 // Here we have to deal with a win32 console flake: If the scroll
6600 // region looks like abc and we scroll c to a and fill with d we get
6601 // cbd... if we scroll block c one line at a time to a, we get cdd...
6602 // vim expects cdd consistently... So we have to deal with that
6603 // here... (this also occurs scrolling the same way in the other
6604 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006605
6606 if (source.Bottom < dest.Y)
6607 {
6608 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006609 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006610
Bram Moolenaar6982f422019-02-16 16:48:01 +01006611 coord.X = source.Left;
6612 for (i = clip.Top; i < dest.Y; ++i)
6613 {
6614 coord.Y = i;
6615 clear_chars(coord, source.Right - source.Left + 1);
6616 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006617 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006618
Christopher Plewright38804d62022-11-09 23:55:52 +00006619 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006620 {
6621 COORD coord;
6622 int i;
6623
6624 coord.X = source.Left;
6625 for (i = source.Top; i < dest.Y; ++i)
6626 {
6627 coord.Y = i;
6628 clear_chars(coord, source.Right - source.Left + 1);
6629 }
6630 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006631}
6632
6633
6634/*
6635 * Delete `cLines' lines at the current cursor position
6636 */
6637 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006638delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006639{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006640 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006641 COORD dest;
6642 CHAR_INFO fill;
6643 int nb;
6644
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006645 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6646
Bram Moolenaar6982f422019-02-16 16:48:01 +01006647 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006648 dest.Y = g_coord.Y;
6649
Bram Moolenaar6982f422019-02-16 16:48:01 +01006650 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006651 source.Top = g_coord.Y + cLines;
6652 source.Right = g_srScrollRegion.Right;
6653 source.Bottom = g_srScrollRegion.Bottom;
6654
Bram Moolenaar6982f422019-02-16 16:48:01 +01006655 clip.Left = g_srScrollRegion.Left;
6656 clip.Top = g_coord.Y;
6657 clip.Right = g_srScrollRegion.Right;
6658 clip.Bottom = g_srScrollRegion.Bottom;
6659
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006660 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006661 if (!vtp_working)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006662 fill.Attributes = g_attrCurrent;
6663 else
6664 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006665
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006666 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006667
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006668 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6669
Bram Moolenaar6982f422019-02-16 16:48:01 +01006670 // Here we have to deal with a win32 console flake; See insert_lines()
6671 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006672
6673 nb = dest.Y + (source.Bottom - source.Top) + 1;
6674
6675 if (nb < source.Top)
6676 {
6677 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006678 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006679
Bram Moolenaar6982f422019-02-16 16:48:01 +01006680 coord.X = source.Left;
6681 for (i = nb; i < clip.Bottom; ++i)
6682 {
6683 coord.Y = i;
6684 clear_chars(coord, source.Right - source.Left + 1);
6685 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006686 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006687
Christopher Plewright38804d62022-11-09 23:55:52 +00006688 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006689 {
6690 COORD coord;
6691 int i;
6692
6693 coord.X = source.Left;
6694 for (i = nb; i <= source.Bottom; ++i)
6695 {
6696 coord.Y = i;
6697 clear_chars(coord, source.Right - source.Left + 1);
6698 }
6699 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006700}
6701
6702
6703/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006704 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006705 */
6706 static void
6707gotoxy(
6708 unsigned x,
6709 unsigned y)
6710{
6711 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6712 return;
6713
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006714 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006715 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006716 // There are reports of double-width characters not displayed
6717 // correctly. This workaround should fix it, similar to how it's done
6718 // for VTP.
6719 g_coord.X = 0;
6720 SetConsoleCursorPosition(g_hConOut, g_coord);
6721
Bram Moolenaar2313b612019-09-27 14:14:32 +02006722 // external cursor coords are 1-based; internal are 0-based
6723 g_coord.X = x - 1;
6724 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006725 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006726 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006727 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006728 {
6729 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006730 // destruction. Insider build bug. Always enabled because it's cheap
6731 // and avoids mistakes with recognizing the build.
6732 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006733
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006734 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006735
6736 g_coord.X = x - 1;
6737 g_coord.Y = y - 1;
6738 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006739}
6740
6741
6742/*
6743 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006744 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006745 */
6746 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006747textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006748{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006749 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006750
6751 SetConsoleTextAttribute(g_hConOut, wAttr);
6752}
6753
6754
6755 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006756textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006757{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006758 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006759
Christopher Plewright38804d62022-11-09 23:55:52 +00006760 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006761 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6762 else
6763 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006764}
6765
6766
6767 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006768textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006769{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006770 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006771
Christopher Plewright38804d62022-11-09 23:55:52 +00006772 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006773 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6774 else
6775 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006776}
6777
6778
6779/*
6780 * restore the default text attribute (whatever we started with)
6781 */
6782 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006783normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006784{
Christopher Plewright38804d62022-11-09 23:55:52 +00006785 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006786 textattr(g_attrDefault);
6787 else
6788 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006789}
6790
6791
6792static WORD g_attrPreStandout = 0;
6793
6794/*
6795 * Make the text standout, by brightening it
6796 */
6797 static void
6798standout(void)
6799{
6800 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006801
Bram Moolenaar071d4272004-06-13 20:20:40 +00006802 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6803}
6804
6805
6806/*
6807 * Turn off standout mode
6808 */
6809 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006810standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006811{
6812 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006813 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006814
6815 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006816}
6817
6818
6819/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006820 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006821 */
6822 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006823mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006824{
6825 char_u *p;
6826 int n;
6827
6828 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6829 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006830 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006831# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006832 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006833# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006834 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006835 {
6836 p = T_ME + 2;
6837 n = getdigits(&p);
6838 if (*p == 'm' && n > 0)
6839 {
6840 cterm_normal_fg_color = (n & 0xf) + 1;
6841 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6842 }
6843 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006844# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006845 cterm_normal_fg_gui_color = INVALCOLOR;
6846 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006847# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006848}
6849
6850
6851/*
6852 * visual bell: flash the screen
6853 */
6854 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006855visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006856{
6857 COORD coordOrigin = {0, 0};
6858 WORD attrFlash = ~g_attrCurrent & 0xff;
6859
6860 DWORD dwDummy;
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006861 LPWORD oldattrs = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006862
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006863# ifdef FEAT_TERMGUICOLORS
6864 if (!(p_tgc || t_colors >= 256))
6865# endif
6866 {
6867 oldattrs = ALLOC_MULT(WORD, Rows * Columns);
6868 if (oldattrs == NULL)
6869 return;
6870 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006871 coordOrigin, &dwDummy);
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006872 }
6873
Bram Moolenaar071d4272004-06-13 20:20:40 +00006874 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6875 coordOrigin, &dwDummy);
6876
Bram Moolenaar0f873732019-12-05 20:28:46 +01006877 Sleep(15); // wait for 15 msec
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006878
6879 if (oldattrs != NULL)
6880 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006881 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006882 coordOrigin, &dwDummy);
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006883 vim_free(oldattrs);
6884 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006885}
6886
6887
6888/*
6889 * Make the cursor visible or invisible
6890 */
6891 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006892cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006893{
6894 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006895
Christopher Plewright38804d62022-11-09 23:55:52 +00006896 if (vtp_working)
Bram Moolenaar2695de62020-04-17 21:13:01 +02006897 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6898
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006899# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006900 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006901# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006902}
6903
6904
6905/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006906 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006907 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006908 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006909 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006910write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006911 char_u *pchBuf,
6912 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006913{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006914 COORD coord = g_coord;
6915 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006916 DWORD n, cchwritten;
6917 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006918 static WCHAR *unicodebuf = NULL;
6919 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006920 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006921 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006922 static WCHAR *utf8spbuf = NULL;
6923 static int utf8splength;
6924 static DWORD utf8spcells;
6925 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006926
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006927 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006928 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006929 utf8usingbuf = &unicodebuf;
6930 do
6931 {
6932 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6933 unicodebuf, unibuflen);
6934 if (length && length <= unibuflen)
6935 break;
6936 vim_free(unicodebuf);
6937 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6938 unibuflen = unibuflen ? 0 : length;
Bram Moolenaarc9471b12023-05-09 15:00:00 +01006939 } while (TRUE);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006940 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006941 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006942 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6943 {
6944 if (utf8usingbuf != &utf8spbuf)
6945 {
6946 if (utf8spbuf == NULL)
6947 {
6948 cells = mb_string2cells((char_u *)" ", 1);
6949 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6950 utf8spbuf = LALLOC_MULT(WCHAR, length);
6951 if (utf8spbuf != NULL)
6952 {
6953 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6954 utf8usingbuf = &utf8spbuf;
6955 utf8splength = length;
6956 utf8spcells = cells;
6957 }
6958 }
6959 else
6960 {
6961 utf8usingbuf = &utf8spbuf;
6962 length = utf8splength;
6963 cells = utf8spcells;
6964 }
6965 }
6966 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006967
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006968 if (!USE_VTP)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006969 {
6970 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6971 coord, &written);
6972 // When writing fails or didn't write a single character, pretend one
6973 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006974 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006975 coord, &cchwritten) == 0
6976 || cchwritten == 0 || cchwritten == (DWORD)-1)
6977 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006978 }
6979 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006980 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006981 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006982 NULL) == 0 || cchwritten == 0)
6983 cchwritten = 1;
6984 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006985
K.Takata135e1522022-01-29 15:27:58 +00006986 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006987 {
6988 written = cbToWrite;
6989 g_coord.X += (SHORT)cells;
6990 }
6991 else
6992 {
6993 char_u *p = pchBuf;
6994 for (n = 0; n < cchwritten; n++)
6995 MB_CPTR_ADV(p);
6996 written = p - pchBuf;
6997 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006998 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006999
7000 while (g_coord.X > g_srScrollRegion.Right)
7001 {
7002 g_coord.X -= (SHORT) Columns;
7003 if (g_coord.Y < g_srScrollRegion.Bottom)
7004 g_coord.Y++;
7005 }
7006
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007007 // Cursor under VTP is always in the correct position, no need to reset.
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00007008 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007009 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007010
7011 return written;
7012}
7013
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007014 static char_u *
7015get_seq(
7016 int *args,
7017 int *count,
7018 char_u *head)
7019{
7020 int argc;
7021 char_u *p;
7022
7023 if (head == NULL || *head != '\033')
7024 return NULL;
7025
7026 argc = 0;
7027 p = head;
7028 ++p;
7029 do
7030 {
7031 ++p;
7032 args[argc] = getdigits(&p);
7033 argc += (argc < 15) ? 1 : 0;
7034 } while (*p == ';');
7035 *count = argc;
7036
7037 return p;
7038}
7039
7040 static char_u *
7041get_sgr(
7042 int *args,
7043 int *count,
7044 char_u *head)
7045{
7046 char_u *p = get_seq(args, count, head);
7047
7048 return (p && *p == 'm') ? ++p : NULL;
7049}
7050
7051/*
7052 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
7053 */
7054 static char_u *
7055sgrn2(
7056 char_u *head,
7057 int n)
7058{
7059 int argc;
7060 int args[16];
7061 char_u *p = get_sgr(args, &argc, head);
7062
7063 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
7064}
7065
7066/*
7067 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
7068 */
7069 static char_u *
7070sgrnc(
7071 char_u *head,
7072 int n)
7073{
7074 int argc;
7075 int args[16];
7076 char_u *p = get_sgr(args, &argc, head);
7077
7078 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
7079 ? p : NULL;
7080}
7081
7082 static char_u *
7083skipblank(char_u *q)
7084{
7085 char_u *p = q;
7086
7087 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
7088 ++p;
7089 return p;
7090}
7091
7092/*
7093 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
7094 * NULL.
7095 */
7096 static char_u *
7097sgrn2c(
7098 char_u *head,
7099 int n)
7100{
7101 char_u *p = sgrn2(head, n);
7102
7103 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
7104}
7105
7106/*
7107 * If there is only a newline between the sequence immediately following it,
7108 * a pointer to the character following the newline is returned.
7109 * Otherwise NULL.
7110 */
7111 static char_u *
7112sgrn2cn(
7113 char_u *head,
7114 int n)
7115{
7116 char_u *p = sgrn2(head, n);
7117
7118 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
7119}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007120
7121/*
7122 * mch_write(): write the output buffer to the screen, translating ESC
7123 * sequences into calls to console output routines.
7124 */
7125 void
7126mch_write(
7127 char_u *s,
7128 int len)
7129{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007130 char_u *end = s + len;
7131
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007132# ifdef VIMDLL
7133 if (gui.in_use)
7134 return;
7135# endif
7136
Bram Moolenaar071d4272004-06-13 20:20:40 +00007137 if (!term_console)
7138 {
7139 write(1, s, (unsigned)len);
7140 return;
7141 }
7142
Bram Moolenaar0f873732019-12-05 20:28:46 +01007143 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00007144 while (len--)
7145 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007146 int prefix = -1;
7147 char_u ch;
7148
7149 // While processing a sequence, on rare occasions it seems that another
7150 // sequence may be inserted asynchronously.
7151 if (len < 0)
7152 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01007153 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007154 return;
7155 }
7156
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007157 while (s + ++prefix < end)
7158 {
7159 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007160 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
7161 && ch != '\a' && ch != '\033'))
7162 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007163 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007164
7165 if (p_wd)
7166 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007167 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007168 if (prefix != 0)
7169 prefix = 1;
7170 }
7171
7172 if (prefix != 0)
7173 {
7174 DWORD nWritten;
7175
7176 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007177# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007178 if (fdDump)
7179 {
7180 fputc('>', fdDump);
7181 fwrite(s, sizeof(char_u), nWritten, fdDump);
7182 fputs("<\n", fdDump);
7183 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007184# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007185 len -= (nWritten - 1);
7186 s += nWritten;
7187 }
7188 else if (s[0] == '\n')
7189 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007190 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00007191 if (g_coord.Y == g_srScrollRegion.Bottom)
7192 {
7193 scroll(1);
7194 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
7195 }
7196 else
7197 {
7198 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
7199 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007200# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007201 if (fdDump)
7202 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007203# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007204 s++;
7205 }
7206 else if (s[0] == '\r')
7207 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007208 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00007209 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007210# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007211 if (fdDump)
7212 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007213# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007214 s++;
7215 }
7216 else if (s[0] == '\b')
7217 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007218 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00007219 if (g_coord.X > g_srScrollRegion.Left)
7220 g_coord.X--;
7221 else if (g_coord.Y > g_srScrollRegion.Top)
7222 {
7223 g_coord.X = g_srScrollRegion.Right;
7224 g_coord.Y--;
7225 }
7226 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007227# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007228 if (fdDump)
7229 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007230# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007231 s++;
7232 }
7233 else if (s[0] == '\a')
7234 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007235 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00007236 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007237# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007238 if (fdDump)
7239 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007240# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007241 s++;
7242 }
7243 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
7244 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007245# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007246 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007247# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007248 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007249 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007250 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007251
7252 switch (s[2])
7253 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007254 case '0': case '1': case '2': case '3': case '4':
7255 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007256 if (*(p = get_seq(args, &argc, s)) != 'm')
7257 goto notsgr;
7258
7259 p = s;
7260
7261 // Handling frequent optional sequences. Output to the screen
7262 // takes too long, so do not output as much as possible.
7263
7264 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
7265 // resetFG,FG,BG are omitted.
7266 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007267 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007268 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
7269 len = len + 1 - (int)(p - s);
7270 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007271 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007272 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007273
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007274 // If FG,BG,BG,FG of SGR are connected, the first FG can be
7275 // omitted.
7276 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
7277 p = sp;
7278
7279 // If FG,BG,FG,BG of SGR are connected, the first FG can be
7280 // omitted.
7281 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
7282 p = sp;
7283
7284 // If BG,BG of SGR are connected, the first BG can be omitted.
7285 if (sgrn2((sp = sgrn2(p, 48)), 48))
7286 p = sp;
7287
7288 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007289 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007290 if (sgrn2((sp = sgrnc(p, 39)), 38))
7291 p = sp;
7292
7293 p = get_seq(args, &argc, p);
7294
7295notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007296 arg1 = args[0];
7297 arg2 = args[1];
7298 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007299 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007300 if (argc == 1 && args[0] == 0)
7301 normvideo();
7302 else if (argc == 1)
7303 {
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00007304 if (USE_VTP)
Christopher Plewright38804d62022-11-09 23:55:52 +00007305 textcolor((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007306 else
Christopher Plewright38804d62022-11-09 23:55:52 +00007307 textattr((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007308 }
Christopher Plewright38804d62022-11-09 23:55:52 +00007309 else if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007310 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007311 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007312 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007313 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007314 gotoxy(arg2, arg1);
7315 }
7316 else if (argc == 2 && *p == 'r')
7317 {
7318 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
7319 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01007320 else if (argc == 2 && *p == 'R')
7321 {
7322 set_scroll_region_tb(arg1, arg2);
7323 }
7324 else if (argc == 2 && *p == 'V')
7325 {
7326 set_scroll_region_lr(arg1, arg2);
7327 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007328 else if (argc == 1 && *p == 'A')
7329 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007330 gotoxy(g_coord.X + 1,
7331 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
7332 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007333 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007334 {
7335 textbackground((WORD) arg1);
7336 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007337 else if (argc == 1 && *p == 'C')
7338 {
7339 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
7340 g_coord.Y + 1);
7341 }
7342 else if (argc == 1 && *p == 'f')
7343 {
7344 textcolor((WORD) arg1);
7345 }
7346 else if (argc == 1 && *p == 'H')
7347 {
7348 gotoxy(1, arg1);
7349 }
7350 else if (argc == 1 && *p == 'L')
7351 {
7352 insert_lines(arg1);
7353 }
7354 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007355 {
7356 delete_lines(arg1);
7357 }
7358
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007359 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007360 s = p + 1;
7361 break;
7362
Bram Moolenaar071d4272004-06-13 20:20:40 +00007363 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007364 gotoxy(g_coord.X + 1,
7365 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
7366 goto got3;
7367
7368 case 'B':
7369 visual_bell();
7370 goto got3;
7371
7372 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007373 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
7374 g_coord.Y + 1);
7375 goto got3;
7376
7377 case 'E':
7378 termcap_mode_end();
7379 goto got3;
7380
7381 case 'F':
7382 standout();
7383 goto got3;
7384
7385 case 'f':
7386 standend();
7387 goto got3;
7388
7389 case 'H':
7390 gotoxy(1, 1);
7391 goto got3;
7392
7393 case 'j':
7394 clear_to_end_of_display();
7395 goto got3;
7396
7397 case 'J':
7398 clear_screen();
7399 goto got3;
7400
7401 case 'K':
7402 clear_to_end_of_line();
7403 goto got3;
7404
7405 case 'L':
7406 insert_lines(1);
7407 goto got3;
7408
7409 case 'M':
7410 delete_lines(1);
7411 goto got3;
7412
7413 case 'S':
7414 termcap_mode_start();
7415 goto got3;
7416
7417 case 'V':
7418 cursor_visible(TRUE);
7419 goto got3;
7420
7421 case 'v':
7422 cursor_visible(FALSE);
7423 goto got3;
7424
7425 got3:
7426 s += 3;
7427 len -= 2;
7428 }
7429
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007430# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007431 if (fdDump)
7432 {
7433 fputs("ESC | ", fdDump);
7434 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
7435 fputc('\n', fdDump);
7436 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007437# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007438 }
K.Takatadf5320c2022-09-01 13:20:16 +01007439 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
7440 {
7441 int l = 2;
7442
7443 if (isdigit(s[l]))
7444 l++;
7445 if (s[l] == ' ' && s[l + 1] == 'q')
7446 {
7447 // DECSCUSR (cursor style) sequences
Christopher Plewright38804d62022-11-09 23:55:52 +00007448 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01007449 vtp_printf("%.*s", l + 2, s); // Pass through
7450 s += l + 2;
7451 len -= l + 1;
7452 }
7453 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007454 else
7455 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007456 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00007457 DWORD nWritten;
7458
7459 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007460# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007461 if (fdDump)
7462 {
7463 fputc('>', fdDump);
7464 fwrite(s, sizeof(char_u), nWritten, fdDump);
7465 fputs("<\n", fdDump);
7466 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007467# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007468
7469 len -= (nWritten - 1);
7470 s += nWritten;
7471 }
7472 }
7473
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007474# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007475 if (fdDump)
7476 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007477# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007478}
7479
Bram Moolenaar0f873732019-12-05 20:28:46 +01007480#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00007481
7482
7483/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01007484 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007485 */
7486 void
7487mch_delay(
7488 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02007489 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007490{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007491#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007492 Sleep((int)msec); // never wait for input
7493#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007494# ifdef VIMDLL
7495 if (gui.in_use)
7496 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007497 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007498 return;
7499 }
7500# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02007501 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007502# ifdef FEAT_MZSCHEME
7503 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
7504 {
7505 int towait = p_mzq;
7506
Bram Moolenaar0f873732019-12-05 20:28:46 +01007507 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007508 while (msec > 0)
7509 {
7510 mzvim_check_threads();
7511 if (msec < towait)
7512 towait = msec;
7513 Sleep(towait);
7514 msec -= towait;
7515 }
7516 }
7517 else
7518# endif
7519 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007520 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007521 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007522#endif
7523}
7524
7525
7526/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01007527 * This version of remove is not scared by a readonly (backup) file.
7528 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007529 * Return 0 for success, -1 for failure.
7530 */
7531 int
7532mch_remove(char_u *name)
7533{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007534 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007535 int n;
7536
Bram Moolenaar203258c2016-01-17 22:15:16 +01007537 /*
7538 * On Windows, deleting a directory's symbolic link is done by
7539 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
7540 */
7541 if (mch_isdir(name) && mch_is_symbolic_link(name))
7542 return mch_rmdir(name);
7543
Bram Moolenaar12b559e2013-06-12 22:41:37 +02007544 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
7545
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007546 wn = enc_to_utf16(name, NULL);
7547 if (wn == NULL)
7548 return -1;
7549
7550 n = DeleteFileW(wn) ? 0 : -1;
7551 vim_free(wn);
7552 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007553}
7554
7555
7556/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007557 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007558 */
7559 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007560mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007561{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007562#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7563# ifdef VIMDLL
7564 if (!gui.in_use)
7565# endif
7566 if (g_fCtrlCPressed || g_fCBrkPressed)
7567 {
7568 ctrl_break_was_pressed = g_fCBrkPressed;
7569 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7570 got_int = TRUE;
7571 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007572#endif
7573}
7574
Bram Moolenaar0f873732019-12-05 20:28:46 +01007575// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007576#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007577
7578/*
7579 * How much main memory in KiB that can be used by VIM.
7580 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007581 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007582mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007583{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007584 MEMORYSTATUSEX ms;
7585
Bram Moolenaar0f873732019-12-05 20:28:46 +01007586 // Need to use GlobalMemoryStatusEx() when there is more memory than
7587 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007588 ms.dwLength = sizeof(MEMORYSTATUSEX);
7589 GlobalMemoryStatusEx(&ms);
7590 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007591 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007592 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007593 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007594 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007595 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007596 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007597 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007598 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007599 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007600 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007601 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007602}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007603
Bram Moolenaar071d4272004-06-13 20:20:40 +00007604/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007605 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00007606 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
7607 * file whose short file name is "FOO.BAR" (its long file name will
7608 * be correct: "foo.bar~"). Because a file can be accessed by
7609 * either its SFN or its LFN, "foo.bar" has effectively been
7610 * renamed to "foo.bar", which is not at all what was wanted. This
7611 * seems to happen only when renaming files with three-character
7612 * extensions by appending a suffix that does not include ".".
7613 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
7614 *
7615 * There is another problem, which isn't really a bug but isn't right either:
7616 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
7617 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
7618 * service pack 6. Doesn't seem to happen on Windows 98.
7619 *
7620 * Like rename(), returns 0 upon success, non-zero upon failure.
7621 * Should probably set errno appropriately when errors occur.
7622 */
7623 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007624mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007625{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007626 WCHAR *p;
7627 int i;
7628 WCHAR szTempFile[_MAX_PATH + 1];
7629 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007630 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007631
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007632 // No need to play tricks unless the file name contains a "~" as the
7633 // seventh character.
7634 p = wold;
7635 for (i = 0; wold[i] != NUL; ++i)
7636 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
7637 && wold[i + 1] != 0)
7638 p = wold + i + 1;
7639 if ((int)(wold + i - p) < 8 || p[6] != '~')
7640 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007641
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007642 // Get base path of new file name. Undocumented feature: If pszNewFile is
7643 // a directory, no error is returned and pszFilePart will be NULL.
7644 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007645 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007646 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007647
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007648 // Get (and create) a unique temporary file name in directory of new file
7649 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007650 return -2;
7651
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007652 // blow the temp file away
7653 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007654 return -3;
7655
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007656 // rename old file to the temp file
7657 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007658 return -4;
7659
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007660 // now create an empty file called pszOldFile; this prevents the operating
7661 // system using pszOldFile as an alias (SFN) if we're renaming within the
7662 // same directory. For example, we're editing a file called
7663 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7664 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7665 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7666 // cause all sorts of problems later in buf_write(). So, we create an
7667 // empty file called filena~1.txt and the system will have to find some
7668 // other SFN for filena~1.txt~, such as filena~2.txt
7669 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007670 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7671 return -5;
7672 if (!CloseHandle(hf))
7673 return -6;
7674
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007675 // rename the temp file to the new file
7676 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007677 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007678 // Renaming failed. Rename the file back to its old name, so that it
7679 // looks like nothing happened.
7680 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007681 return -7;
7682 }
7683
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007684 // Seems to be left around on Novell filesystems
7685 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007686
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007687 // finally, remove the empty old file
7688 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007689 return -8;
7690
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007691 return 0;
7692}
7693
7694
7695/*
7696 * Converts the filenames to UTF-16, then call mch_wrename().
7697 * Like rename(), returns 0 upon success, non-zero upon failure.
7698 */
7699 int
7700mch_rename(
7701 const char *pszOldFile,
7702 const char *pszNewFile)
7703{
7704 WCHAR *wold = NULL;
7705 WCHAR *wnew = NULL;
7706 int retval = -1;
7707
7708 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7709 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7710 if (wold != NULL && wnew != NULL)
7711 retval = mch_wrename(wold, wnew);
7712 vim_free(wold);
7713 vim_free(wnew);
7714 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007715}
7716
7717/*
7718 * Get the default shell for the current hardware platform
7719 */
7720 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007721default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007722{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007723 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007724}
7725
7726/*
7727 * mch_access() extends access() to do more detailed check on network drives.
7728 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7729 */
7730 int
7731mch_access(char *n, int p)
7732{
7733 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007734 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007735 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007736
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007737 wn = enc_to_utf16((char_u *)n, NULL);
7738 if (wn == NULL)
7739 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007740
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007741 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007742 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007743 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007744
7745 if (p & R_OK)
7746 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007747 // Read check is performed by seeing if we can do a find file on
7748 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007749 int i;
7750 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007751
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007752 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7753 TempNameW[i] = wn[i];
7754 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7755 TempNameW[i++] = '\\';
7756 TempNameW[i++] = '*';
7757 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007758
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007759 hFile = FindFirstFileW(TempNameW, &d);
7760 if (hFile == INVALID_HANDLE_VALUE)
7761 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007762 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007763 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007764 }
7765
7766 if (p & W_OK)
7767 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007768 // Trying to create a temporary file in the directory should catch
7769 // directories on read-only network shares. However, in
7770 // directories whose ACL allows writes but denies deletes will end
7771 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007772 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7773 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007774 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007775 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007776 }
7777 }
7778 else
7779 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007780 // Don't consider a file read-only if another process has opened it.
7781 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7782
Bram Moolenaar0f873732019-12-05 20:28:46 +01007783 // Trying to open the file for the required access does ACL, read-only
7784 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007785 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7786 | ((p & R_OK) ? GENERIC_READ : 0);
7787
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007788 hFile = CreateFileW(wn, access_mode, share_mode,
7789 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007790 if (hFile == INVALID_HANDLE_VALUE)
7791 goto getout;
7792 CloseHandle(hFile);
7793 }
7794
Bram Moolenaar0f873732019-12-05 20:28:46 +01007795 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007796getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007797 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007798 return retval;
7799}
7800
Bram Moolenaar071d4272004-06-13 20:20:40 +00007801/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007802 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007803 */
7804 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007805mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007806{
7807 WCHAR *wn;
7808 int f;
7809
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007810 wn = enc_to_utf16((char_u *)name, NULL);
7811 if (wn == NULL)
7812 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007813
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007814 f = _wopen(wn, flags, mode);
7815 vim_free(wn);
7816 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007817}
7818
7819/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007820 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007821 */
7822 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007823mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007824{
7825 WCHAR *wn, *wm;
7826 FILE *f = NULL;
7827
Bram Moolenaara12a1612019-01-24 16:39:02 +01007828#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007829 // Work around an annoying assertion in the Microsoft debug CRT
7830 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007831 char newMode = mode[strlen(mode) - 1];
7832 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007833
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007834 _get_fmode(&oldMode);
7835 if (newMode == 't')
7836 _set_fmode(_O_TEXT);
7837 else if (newMode == 'b')
7838 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007839#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007840 wn = enc_to_utf16((char_u *)name, NULL);
7841 wm = enc_to_utf16((char_u *)mode, NULL);
7842 if (wn != NULL && wm != NULL)
7843 f = _wfopen(wn, wm);
7844 vim_free(wn);
7845 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007846
Bram Moolenaara12a1612019-01-24 16:39:02 +01007847#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007848 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007849#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007850 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007851}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007852
Bram Moolenaar071d4272004-06-13 20:20:40 +00007853/*
7854 * SUB STREAM (aka info stream) handling:
7855 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007856 * NTFS can have sub streams for each file. The normal contents of a file is
7857 * stored in the main stream, and extra contents (author information, title and
7858 * so on) can be stored in a sub stream. After Windows 2000, the user can
7859 * access and store this information in sub streams via an explorer's property
7860 * menu item in the right click menu. This information in sub streams was lost
7861 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007862 *
7863 * Incomplete explanation:
7864 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7865 * More useful info and an example:
7866 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7867 */
7868
7869/*
7870 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7871 * and write to stream "substream" of file "to".
7872 * Errors are ignored.
7873 */
7874 static void
7875copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7876{
7877 HANDLE hTo;
7878 WCHAR *to_name;
7879
7880 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7881 wcscpy(to_name, to);
7882 wcscat(to_name, substream);
7883
7884 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7885 FILE_ATTRIBUTE_NORMAL, NULL);
7886 if (hTo != INVALID_HANDLE_VALUE)
7887 {
7888 long done;
7889 DWORD todo;
7890 DWORD readcnt, written;
7891 char buf[4096];
7892
Bram Moolenaar0f873732019-12-05 20:28:46 +01007893 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007894 for (done = 0; done < len; done += written)
7895 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007896 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007897 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7898 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007899 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7900 FALSE, FALSE, context)
7901 || readcnt != todo
7902 || !WriteFile(hTo, buf, todo, &written, NULL)
7903 || written != todo)
7904 break;
7905 }
7906 CloseHandle(hTo);
7907 }
7908
7909 free(to_name);
7910}
7911
7912/*
7913 * Copy info streams from file "from" to file "to".
7914 */
7915 static void
7916copy_infostreams(char_u *from, char_u *to)
7917{
7918 WCHAR *fromw;
7919 WCHAR *tow;
7920 HANDLE sh;
7921 WIN32_STREAM_ID sid;
7922 int headersize;
7923 WCHAR streamname[_MAX_PATH];
7924 DWORD readcount;
7925 void *context = NULL;
7926 DWORD lo, hi;
7927 int len;
7928
Bram Moolenaar0f873732019-12-05 20:28:46 +01007929 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007930 fromw = enc_to_utf16(from, NULL);
7931 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007932 if (fromw != NULL && tow != NULL)
7933 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007934 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007935 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7936 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7937 if (sh != INVALID_HANDLE_VALUE)
7938 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007939 // Use BackupRead() to find the info streams. Repeat until we
7940 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007941 for (;;)
7942 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007943 // Get the header to find the length of the stream name. If
7944 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007945 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007946 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007947 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7948 &readcount, FALSE, FALSE, &context)
7949 || readcount == 0)
7950 break;
7951
Bram Moolenaar0f873732019-12-05 20:28:46 +01007952 // We only deal with streams that have a name. The normal
7953 // file data appears to be without a name, even though docs
7954 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007955 if (sid.dwStreamNameSize > 0)
7956 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007957 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007958 if (!BackupRead(sh, (LPBYTE)streamname,
7959 sid.dwStreamNameSize,
7960 &readcount, FALSE, FALSE, &context))
7961 break;
7962
Bram Moolenaar0f873732019-12-05 20:28:46 +01007963 // Copy an info stream with a name ":anything:$DATA".
7964 // Skip "::$DATA", it has no stream name (examples suggest
7965 // it might be used for the normal file contents).
7966 // Note that BackupRead() counts bytes, but the name is in
7967 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007968 len = readcount / sizeof(WCHAR);
7969 streamname[len] = 0;
7970 if (len > 7 && wcsicmp(streamname + len - 6,
7971 L":$DATA") == 0)
7972 {
7973 streamname[len - 6] = 0;
7974 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007975 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007976 }
7977 }
7978
Bram Moolenaar0f873732019-12-05 20:28:46 +01007979 // Advance to the next stream. We might try seeking too far,
7980 // but BackupSeek() doesn't skip over stream borders, thus
7981 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007982 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007983 &lo, &hi, &context);
7984 }
7985
Bram Moolenaar0f873732019-12-05 20:28:46 +01007986 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007987 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7988
7989 CloseHandle(sh);
7990 }
7991 }
7992 vim_free(fromw);
7993 vim_free(tow);
7994}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007995
7996/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007997 * ntdll.dll definitions
7998 */
7999#define FileEaInformation 7
8000#ifndef STATUS_SUCCESS
8001# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
8002#endif
8003
8004typedef struct _FILE_FULL_EA_INFORMATION_ {
8005 ULONG NextEntryOffset;
8006 UCHAR Flags;
8007 UCHAR EaNameLength;
8008 USHORT EaValueLength;
8009 CHAR EaName[1];
8010} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
8011
8012typedef struct _FILE_EA_INFORMATION_ {
8013 ULONG EaSize;
8014} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
8015
Paul Ollis65745772022-06-05 16:55:54 +01008016#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008017typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
8018 PHANDLE FileHandle,
8019 ACCESS_MASK DesiredAccess,
8020 POBJECT_ATTRIBUTES ObjectAttributes,
8021 PIO_STATUS_BLOCK IoStatusBlock,
8022 ULONG ShareAccess,
8023 ULONG OpenOptions);
8024typedef NTSTATUS (NTAPI *PfnNtClose)(
8025 HANDLE Handle);
8026typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01008027 HANDLE FileHandle,
8028 PIO_STATUS_BLOCK IoStatusBlock,
8029 PVOID Buffer,
8030 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008031typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
8032 HANDLE FileHandle,
8033 PIO_STATUS_BLOCK IoStatusBlock,
8034 PVOID Buffer,
8035 ULONG Length,
8036 BOOLEAN ReturnSingleEntry,
8037 PVOID EaList,
8038 ULONG EaListLength,
8039 PULONG EaIndex,
8040 BOOLEAN RestartScan);
8041typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01008042 HANDLE FileHandle,
8043 PIO_STATUS_BLOCK IoStatusBlock,
8044 PVOID FileInformation,
8045 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008046 FILE_INFORMATION_CLASS FileInformationClass);
8047typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
8048 PUNICODE_STRING DestinationString,
8049 PCWSTR SourceString);
8050
8051PfnNtOpenFile pNtOpenFile = NULL;
8052PfnNtClose pNtClose = NULL;
8053PfnNtSetEaFile pNtSetEaFile = NULL;
8054PfnNtQueryEaFile pNtQueryEaFile = NULL;
8055PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
8056PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01008057#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008058
8059/*
8060 * Load ntdll.dll functions.
8061 */
8062 static BOOL
8063load_ntdll(void)
8064{
8065 static int loaded = -1;
8066
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008067 if (loaded != -1)
8068 return (BOOL) loaded;
8069
8070 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
8071 if (hNtdll != NULL)
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008072 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008073 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
8074 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
8075 pNtSetEaFile = (PfnNtSetEaFile)
8076 GetProcAddress(hNtdll, "NtSetEaFile");
8077 pNtQueryEaFile = (PfnNtQueryEaFile)
8078 GetProcAddress(hNtdll, "NtQueryEaFile");
8079 pNtQueryInformationFile = (PfnNtQueryInformationFile)
8080 GetProcAddress(hNtdll, "NtQueryInformationFile");
8081 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
8082 GetProcAddress(hNtdll, "RtlInitUnicodeString");
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008083 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008084 if (pNtOpenFile == NULL
8085 || pNtClose == NULL
8086 || pNtSetEaFile == NULL
8087 || pNtQueryEaFile == NULL
8088 || pNtQueryInformationFile == NULL
8089 || pRtlInitUnicodeString == NULL)
8090 loaded = FALSE;
8091 else
8092 loaded = TRUE;
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008093 return (BOOL) loaded;
8094}
8095
8096/*
8097 * Copy extended attributes (EA) from file "from" to file "to".
8098 */
8099 static void
8100copy_extattr(char_u *from, char_u *to)
8101{
8102 char_u *fromf = NULL;
8103 char_u *tof = NULL;
8104 WCHAR *fromw = NULL;
8105 WCHAR *tow = NULL;
8106 UNICODE_STRING u;
8107 HANDLE h;
8108 OBJECT_ATTRIBUTES oa;
8109 IO_STATUS_BLOCK iosb;
8110 FILE_EA_INFORMATION_ eainfo = {0};
8111 void *ea = NULL;
8112
8113 if (!load_ntdll())
8114 return;
8115
8116 // Convert the file names to the fully qualified object names.
8117 fromf = alloc(STRLEN(from) + 5);
8118 tof = alloc(STRLEN(to) + 5);
8119 if (fromf == NULL || tof == NULL)
8120 goto theend;
8121 STRCPY(fromf, "\\??\\");
8122 STRCAT(fromf, from);
8123 STRCPY(tof, "\\??\\");
8124 STRCAT(tof, to);
8125
8126 // Convert the names to wide characters.
8127 fromw = enc_to_utf16(fromf, NULL);
8128 tow = enc_to_utf16(tof, NULL);
8129 if (fromw == NULL || tow == NULL)
8130 goto theend;
8131
8132 // Get the EA.
8133 pRtlInitUnicodeString(&u, fromw);
8134 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8135 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
8136 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8137 goto theend;
8138 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
8139 FileEaInformation);
8140 if (eainfo.EaSize != 0)
8141 {
8142 ea = alloc(eainfo.EaSize);
8143 if (ea != NULL)
8144 {
8145 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
8146 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
8147 {
Yegappan Lakshmanan960dcbd2023-03-07 17:45:11 +00008148 VIM_CLEAR(ea);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008149 }
8150 }
8151 }
8152 pNtClose(h);
8153
8154 // Set the EA.
8155 if (ea != NULL)
8156 {
8157 pRtlInitUnicodeString(&u, tow);
8158 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8159 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
8160 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8161 goto theend;
8162
8163 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
8164 pNtClose(h);
8165 }
8166
8167theend:
8168 vim_free(fromf);
8169 vim_free(tof);
8170 vim_free(fromw);
8171 vim_free(tow);
8172 vim_free(ea);
8173}
8174
8175/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008176 * Copy file attributes from file "from" to file "to".
8177 * For Windows NT and later we copy info streams.
8178 * Always returns zero, errors are ignored.
8179 */
8180 int
8181mch_copy_file_attribute(char_u *from, char_u *to)
8182{
Bram Moolenaar0f873732019-12-05 20:28:46 +01008183 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02008184 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008185 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008186 return 0;
8187}
8188
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008189
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008190/*
K.Takatadc73b4b2021-06-08 18:32:36 +02008191 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008192 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008193static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008194static LPWSTR *ArglistW = NULL;
8195static int global_argc = 0;
8196static char **global_argv;
8197
Bram Moolenaar0f873732019-12-05 20:28:46 +01008198static int used_file_argc = 0; // last argument in global_argv[] used
8199 // for the argument list.
8200static int *used_file_indexes = NULL; // indexes in global_argv[] for
8201 // command line arguments added to
8202 // the argument list
8203static int used_file_count = 0; // nr of entries in used_file_indexes
8204static int used_file_literal = FALSE; // take file names literally
8205static int used_file_full_path = FALSE; // file name was full path
8206static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008207static int used_alist_count = 0;
8208
8209
8210/*
8211 * Get the command line arguments. Unicode version.
8212 * Returns argc. Zero when something fails.
8213 */
8214 int
8215get_cmd_argsW(char ***argvp)
8216{
8217 char **argv = NULL;
8218 int argc = 0;
8219 int i;
8220
Bram Moolenaar14993322014-09-09 12:25:33 +02008221 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008222 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
8223 if (ArglistW != NULL)
8224 {
8225 argv = malloc((nArgsW + 1) * sizeof(char *));
8226 if (argv != NULL)
8227 {
8228 argc = nArgsW;
8229 argv[argc] = NULL;
8230 for (i = 0; i < argc; ++i)
8231 {
8232 int len;
8233
K.Takatadc73b4b2021-06-08 18:32:36 +02008234 // Convert each Unicode argument to UTF-8.
8235 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008236 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008237 (LPSTR *)&argv[i], &len, 0, 0);
8238 if (argv[i] == NULL)
8239 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008240 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008241 while (i > 0)
8242 free(argv[--i]);
8243 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01008244 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008245 argc = 0;
8246 }
8247 }
8248 }
8249 }
8250
8251 global_argc = argc;
8252 global_argv = argv;
8253 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02008254 {
8255 if (used_file_indexes != NULL)
8256 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008257 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02008258 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008259
8260 if (argvp != NULL)
8261 *argvp = argv;
8262 return argc;
8263}
8264
8265 void
8266free_cmd_argsW(void)
8267{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008268 if (ArglistW == NULL)
8269 return;
8270
8271 GlobalFree(ArglistW);
8272 ArglistW = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008273}
8274
8275/*
8276 * Remember "name" is an argument that was added to the argument list.
8277 * This avoids that we have to re-parse the argument list when fix_arg_enc()
8278 * is called.
8279 */
8280 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008281used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008282{
8283 int i;
8284
8285 if (used_file_indexes == NULL)
8286 return;
8287 for (i = used_file_argc + 1; i < global_argc; ++i)
8288 if (STRCMP(global_argv[i], name) == 0)
8289 {
8290 used_file_argc = i;
8291 used_file_indexes[used_file_count++] = i;
8292 break;
8293 }
8294 used_file_literal = literal;
8295 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008296 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008297}
8298
8299/*
8300 * Remember the length of the argument list as it was. If it changes then we
8301 * leave it alone when 'encoding' is set.
8302 */
8303 void
8304set_alist_count(void)
8305{
8306 used_alist_count = GARGCOUNT;
8307}
8308
8309/*
8310 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02008311 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008312 * and convert them to 'encoding'.
8313 */
8314 void
8315fix_arg_enc(void)
8316{
8317 int i;
8318 int idx;
8319 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00008320 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008321
Bram Moolenaar0f873732019-12-05 20:28:46 +01008322 // Safety checks:
8323 // - if argument count differs between the wide and non-wide argument
8324 // list, something must be wrong.
8325 // - the file name arguments must have been located.
8326 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008327 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008328 || ArglistW == NULL
8329 || used_file_indexes == NULL
8330 || used_file_count == 0
8331 || used_alist_count != GARGCOUNT)
8332 return;
8333
Bram Moolenaar0f873732019-12-05 20:28:46 +01008334 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02008335 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008336 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008337 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00008338 for (i = 0; i < GARGCOUNT; ++i)
8339 fnum_list[i] = GARGLIST[i].ae_fnum;
8340
Bram Moolenaar0f873732019-12-05 20:28:46 +01008341 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008342 alist_clear(&global_alist);
8343 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008344 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008345
8346 for (i = 0; i < used_file_count; ++i)
8347 {
8348 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008349 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008350 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00008351 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008352 int literal = used_file_literal;
8353
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008354#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01008355 // When using diff mode may need to concatenate file name to
8356 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008357 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
8358 && !mch_isdir(alist_name(&GARGLIST[0])))
8359 {
8360 char_u *r;
8361
8362 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
8363 if (r != NULL)
8364 {
8365 vim_free(str);
8366 str = r;
8367 }
8368 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008369#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01008370 // Re-use the old buffer by renaming it. When not using literal
8371 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00008372 if (used_file_literal)
8373 buf_set_name(fnum_list[i], str);
8374
Bram Moolenaar0f873732019-12-05 20:28:46 +01008375 // Check backtick literal. backtick literal is already expanded in
8376 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008377 if (literal == FALSE)
8378 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02008379 size_t len = STRLEN(str);
8380
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008381 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
8382 literal = TRUE;
8383 }
8384 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008385 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008386 }
8387
8388 if (!used_file_literal)
8389 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008390 // Now expand wildcards in the arguments.
8391 // Temporarily add '(' and ')' to 'isfname'. These are valid
8392 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00008393 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01008394 // Also, unset wildignore to not be influenced by this option.
8395 // The arguments specified in command-line should be kept even if
8396 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00008397 // Use :legacy so that it also works when in Vim9 script.
8398 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
8399 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00008400 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00008401 do_cmdline_cmd(
8402 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
8403 do_cmdline_cmd(
8404 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008405 }
8406
Bram Moolenaar0f873732019-12-05 20:28:46 +01008407 // If wildcard expansion failed, we are editing the first file of the
8408 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008409 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
8410 {
8411 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00008412 if (GARGCOUNT == 1 && used_file_full_path
8413 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
8414 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008415 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00008416
8417 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008418}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008419
8420 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02008421mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008422{
8423 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008424 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008425
Bram Moolenaar964b3742019-05-24 18:54:09 +02008426 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008427 if (envbuf == NULL)
8428 return -1;
8429
8430 sprintf((char *)envbuf, "%s=%s", var, value);
8431
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008432 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008433
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008434 vim_free(envbuf);
8435 if (p == NULL)
8436 return -1;
8437 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008438#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008439 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008440#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008441 // Unlike Un*x systems, we can free the string for _wputenv().
8442 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008443
8444 return 0;
8445}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008446
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008447/*
8448 * Support for 256 colors and 24-bit colors was added in Windows 10
8449 * version 1703 (Creators update).
8450 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008451#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
8452
8453/*
8454 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02008455 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008456 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008457#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008458
8459/*
8460 * ConPTY differences between versions, need different logic.
8461 * version 1903 (May 2019 update).
8462 */
8463#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
8464
8465/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008466 * version 1909 (November 2019 update).
8467 */
8468#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
8469
8470/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008471 * Stay ahead of the next update, and when it's done, fix this.
8472 * version ? (2020 update, temporarily use the build number of insider preview)
8473 */
8474#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
8475
8476/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02008477 * Confirm until this version. Also the logic changes.
8478 * insider preview.
8479 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02008480#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008481
8482/*
8483 * Not stable now.
8484 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008485#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Christopher Plewright1140b512022-11-12 18:46:05 +00008486// Notes:
8487// Win 10 22H2 Final is build 19045, it's conpty is widely used.
8488// Strangely, 19045 is newer but is a lower build number than the 2020 insider
8489// preview which had a build 19587. And, not sure how stable that was?
8490// Win Server 2022 (May 10, 2022) is build 20348, its conpty is widely used.
8491// Win 11 starts from build 22000, even though the major version says 10!
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008492
8493 static void
8494vtp_flag_init(void)
8495{
8496 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008497#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008498 DWORD mode;
8499 HANDLE out;
8500
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008501# ifdef VIMDLL
8502 if (!gui.in_use)
8503# endif
8504 {
8505 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008506
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008507 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
8508 GetConsoleMode(out, &mode);
8509 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
8510 if (SetConsoleMode(out, mode) == 0)
8511 vtp_working = 0;
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008512
8513 // VTP uses alternate screen buffer.
8514 // But, not if running in a nested terminal
8515 use_alternate_screen_buffer = win10_22H2_or_later && p_rs && vtp_working
8516 && !mch_getenv("VIM_TERMINAL");
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008517 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008518#endif
8519
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008520 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008521 conpty_working = 1;
8522 if (ver >= CONPTY_STABLE_BUILD)
8523 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008524
Bram Moolenaar57da6982019-09-13 22:30:11 +02008525 if (ver <= CONPTY_INSIDER_BUILD)
8526 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008527 if (ver <= CONPTY_1909_BUILD)
8528 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02008529 if (ver <= CONPTY_1903_BUILD)
8530 conpty_type = 2;
8531 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
8532 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008533
8534 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
8535 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008536}
8537
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008538#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008539
8540 static void
8541vtp_init(void)
8542{
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008543# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightd343c602023-01-22 18:58:30 +00008544 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8545 csbi.cbSize = sizeof(csbi);
8546 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8547 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
8548 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
8549 store_console_bg_rgb = save_console_bg_rgb;
8550 store_console_fg_rgb = save_console_fg_rgb;
Christopher Plewright38804d62022-11-09 23:55:52 +00008551
Christopher Plewrightd343c602023-01-22 18:58:30 +00008552 COLORREF bg;
8553 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
8554 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8555 default_console_color_bg = bg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008556
Christopher Plewrightd343c602023-01-22 18:58:30 +00008557 COLORREF fg;
8558 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
8559 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8560 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008561# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008562 set_console_color_rgb();
8563}
8564
8565 static void
8566vtp_exit(void)
8567{
Bram Moolenaardf543822020-01-30 11:53:59 +01008568 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008569}
8570
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008571 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008572vtp_printf(
8573 char *format,
8574 ...)
8575{
8576 char_u buf[100];
8577 va_list list;
8578 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008579 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008580
8581 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008582 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008583 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008584 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008585 return (int)result;
8586}
8587
8588 static void
8589vtp_sgr_bulk(
8590 int arg)
8591{
8592 int args[1];
8593
8594 args[0] = arg;
8595 vtp_sgr_bulks(1, args);
8596}
8597
K.Takata6e1d31e2022-02-03 13:05:32 +00008598# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008599 if ((*p-- = "0123456789"[(n = x % 10)]) \
8600 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8601 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8602
K.Takata6e1d31e2022-02-03 13:05:32 +00008603# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008604 case x: \
8605 FAST256(newargs[x - 1]);
8606
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008607 static void
8608vtp_sgr_bulks(
8609 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008610 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008611{
K.Takata6e1d31e2022-02-03 13:05:32 +00008612# define MAXSGR 16
8613# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008614 char_u buf[SGRBUFSIZE];
8615 char_u *p;
8616 int in, out;
8617 int newargs[16];
8618 static int sgrfgr = -1, sgrfgg, sgrfgb;
8619 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008620
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008621 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008622 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008623 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008624 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008625 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008626 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008627
8628 in = out = 0;
8629 while (in < argc)
8630 {
8631 int s = args[in];
8632 int copylen = 1;
8633
8634 if (s == 38)
8635 {
8636 if (argc - in >= 5 && args[in + 1] == 2)
8637 {
8638 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8639 && sgrfgb == args[in + 4])
8640 {
8641 in += 5;
8642 copylen = 0;
8643 }
8644 else
8645 {
8646 sgrfgr = args[in + 2];
8647 sgrfgg = args[in + 3];
8648 sgrfgb = args[in + 4];
8649 copylen = 5;
8650 }
8651 }
8652 else if (argc - in >= 3 && args[in + 1] == 5)
8653 {
8654 sgrfgr = -1;
8655 copylen = 3;
8656 }
8657 }
8658 else if (s == 48)
8659 {
8660 if (argc - in >= 5 && args[in + 1] == 2)
8661 {
8662 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8663 && sgrbgb == args[in + 4])
8664 {
8665 in += 5;
8666 copylen = 0;
8667 }
8668 else
8669 {
8670 sgrbgr = args[in + 2];
8671 sgrbgg = args[in + 3];
8672 sgrbgb = args[in + 4];
8673 copylen = 5;
8674 }
8675 }
8676 else if (argc - in >= 3 && args[in + 1] == 5)
8677 {
8678 sgrbgr = -1;
8679 copylen = 3;
8680 }
8681 }
8682 else if (30 <= s && s <= 39)
8683 sgrfgr = -1;
8684 else if (90 <= s && s <= 97)
8685 sgrfgr = -1;
8686 else if (40 <= s && s <= 49)
8687 sgrbgr = -1;
8688 else if (100 <= s && s <= 107)
8689 sgrbgr = -1;
8690 else if (s == 0)
8691 sgrfgr = sgrbgr = -1;
8692
8693 while (copylen--)
8694 newargs[out++] = args[in++];
8695 }
8696
8697 p = &buf[sizeof(buf) - 1];
8698 *p-- = 'm';
8699
8700 switch (out)
8701 {
8702 int n, m;
8703 DWORD r;
8704
8705 FAST256CASE(16);
8706 *p-- = ';';
8707 FAST256CASE(15);
8708 *p-- = ';';
8709 FAST256CASE(14);
8710 *p-- = ';';
8711 FAST256CASE(13);
8712 *p-- = ';';
8713 FAST256CASE(12);
8714 *p-- = ';';
8715 FAST256CASE(11);
8716 *p-- = ';';
8717 FAST256CASE(10);
8718 *p-- = ';';
8719 FAST256CASE(9);
8720 *p-- = ';';
8721 FAST256CASE(8);
8722 *p-- = ';';
8723 FAST256CASE(7);
8724 *p-- = ';';
8725 FAST256CASE(6);
8726 *p-- = ';';
8727 FAST256CASE(5);
8728 *p-- = ';';
8729 FAST256CASE(4);
8730 *p-- = ';';
8731 FAST256CASE(3);
8732 *p-- = ';';
8733 FAST256CASE(2);
8734 *p-- = ';';
8735 FAST256CASE(1);
8736 *p-- = '[';
8737 *p = '\033';
8738 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8739 default:
8740 break;
8741 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008742}
8743
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008744 static void
8745wt_init(void)
8746{
Christopher Plewright1140b512022-11-12 18:46:05 +00008747 wt_working = mch_getenv("WT_SESSION") != NULL;
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008748}
8749
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008750# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008751 static int
8752ctermtoxterm(
8753 int cterm)
8754{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008755 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008756
8757 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8758 return (((int)r << 16) | ((int)g << 8) | (int)b);
8759}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008760# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008761
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008762 static void
8763set_console_color_rgb(void)
8764{
8765# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008766 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008767 guicolor_T fg, bg;
8768 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008769
Christopher Plewright38804d62022-11-09 23:55:52 +00008770 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008771 return;
8772
Bram Moolenaara050b942019-12-02 21:35:31 +01008773 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8774
Christopher Plewright38804d62022-11-09 23:55:52 +00008775 if (p_tgc || t_colors >= 256)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008776 {
8777 term_fg_rgb_color(fg);
8778 term_bg_rgb_color(bg);
8779 return;
8780 }
8781
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008782 if (use_alternate_screen_buffer)
8783 return;
8784
Christopher Plewrightd343c602023-01-22 18:58:30 +00008785 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8786 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008787
Christopher Plewrightd343c602023-01-22 18:58:30 +00008788 csbi.cbSize = sizeof(csbi);
8789 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008790
Christopher Plewrightd343c602023-01-22 18:58:30 +00008791 csbi.cbSize = sizeof(csbi);
8792 csbi.srWindow.Right += 1;
8793 csbi.srWindow.Bottom += 1;
8794 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8795 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
8796 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8797 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
8798 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008799# endif
8800}
8801
Bram Moolenaara050b942019-12-02 21:35:31 +01008802# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8803 void
8804get_default_console_color(
8805 int *cterm_fg,
8806 int *cterm_bg,
8807 guicolor_T *gui_fg,
8808 guicolor_T *gui_bg)
8809{
8810 int id;
8811 guicolor_T guifg = INVALCOLOR;
8812 guicolor_T guibg = INVALCOLOR;
8813 int ctermfg = 0;
8814 int ctermbg = 0;
Christopher Plewright38804d62022-11-09 23:55:52 +00008815 int dummynull = 0;
Bram Moolenaara050b942019-12-02 21:35:31 +01008816
8817 id = syn_name2id((char_u *)"Normal");
8818 if (id > 0 && p_tgc)
8819 syn_id2colors(id, &guifg, &guibg);
8820 if (guifg == INVALCOLOR)
8821 {
8822 ctermfg = -1;
8823 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008824 syn_id2cterm_bg(id, &ctermfg, &dummynull);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008825 if (ctermfg != -1)
8826 guifg = ctermtoxterm(ctermfg);
Christopher Plewright38804d62022-11-09 23:55:52 +00008827 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008828 guifg = USE_WT ? INVALCOLOR : default_console_color_fg;
8829 cterm_normal_fg_gui_color = guifg;
8830 ctermfg = ctermfg < 0 ? 0 : ctermfg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008831 }
8832 if (guibg == INVALCOLOR)
8833 {
8834 ctermbg = -1;
8835 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008836 syn_id2cterm_bg(id, &dummynull, &ctermbg);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008837 if (ctermbg != -1)
8838 guibg = ctermtoxterm(ctermbg);
K.Takatae53a0d42022-09-05 21:45:11 +01008839 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008840 guibg = USE_WT ? INVALCOLOR : default_console_color_bg;
8841 cterm_normal_bg_gui_color = guibg;
8842 ctermbg = ctermbg < 0 ? 0 : ctermbg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008843 }
8844
8845 *cterm_fg = ctermfg;
8846 *cterm_bg = ctermbg;
8847 *gui_fg = guifg;
8848 *gui_bg = guibg;
8849}
8850# endif
8851
Bram Moolenaardf543822020-01-30 11:53:59 +01008852/*
8853 * Set the console colors to the original colors or the last set colors.
8854 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008855 static void
8856reset_console_color_rgb(void)
8857{
8858# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008859 if (use_alternate_screen_buffer)
8860 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008861
Christopher Plewright38804d62022-11-09 23:55:52 +00008862 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8863
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008864 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008865 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008866
8867 csbi.cbSize = sizeof(csbi);
8868 csbi.srWindow.Right += 1;
8869 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008870 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8871 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008872 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008873# endif
8874}
8875
8876/*
8877 * Set the console colors to the original colors.
8878 */
8879 static void
8880restore_console_color_rgb(void)
8881{
8882# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008883 if (use_alternate_screen_buffer)
8884 return;
Christopher Plewright38804d62022-11-09 23:55:52 +00008885
K.Takata27b53be2022-09-18 12:25:49 +01008886 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008887
8888 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008889 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008890
8891 csbi.cbSize = sizeof(csbi);
8892 csbi.srWindow.Right += 1;
8893 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008894 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8895 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008896 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008897# endif
8898}
8899
8900 void
8901control_console_color_rgb(void)
8902{
Christopher Plewright38804d62022-11-09 23:55:52 +00008903 if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008904 set_console_color_rgb();
8905 else
8906 reset_console_color_rgb();
8907}
8908
8909 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008910use_vtp(void)
8911{
8912 return USE_VTP;
8913}
8914
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008915 int
8916is_term_win32(void)
8917{
8918 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8919}
8920
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008921 int
8922has_vtp_working(void)
8923{
8924 return vtp_working;
8925}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008926
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008927#endif
8928
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008929 int
8930has_conpty_working(void)
8931{
8932 return conpty_working;
8933}
8934
8935 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008936get_conpty_type(void)
8937{
8938 return conpty_type;
8939}
8940
8941 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008942is_conpty_stable(void)
8943{
8944 return conpty_stable;
8945}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008946
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008947 int
8948get_conpty_fix_type(void)
8949{
8950 return conpty_fix_type;
8951}
8952
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008953#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008954 void
8955resize_console_buf(void)
8956{
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008957 if (use_alternate_screen_buffer)
8958 return;
8959
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008960 CONSOLE_SCREEN_BUFFER_INFO csbi;
8961 COORD coord;
8962 SMALL_RECT newsize;
8963
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008964 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8965 return;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008966
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008967 coord.X = SRWIDTH(csbi.srWindow);
8968 coord.Y = SRHEIGHT(csbi.srWindow);
8969 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008970
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008971 newsize.Left = 0;
8972 newsize.Top = 0;
8973 newsize.Right = coord.X - 1;
8974 newsize.Bottom = coord.Y - 1;
8975 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8976
8977 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008978}
8979#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008980
8981 char *
8982GetWin32Error(void)
8983{
K.Takatad68b2fc2022-02-12 11:18:37 +00008984 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008985 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008986
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008987 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8988 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008989 if (oldmsg != NULL)
8990 LocalFree(oldmsg);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008991 if (msg == NULL)
8992 return NULL;
8993
8994 // remove trailing \r\n
8995 char *pcrlf = strstr(msg, "\r\n");
8996 if (pcrlf != NULL)
8997 *pcrlf = '\0';
8998 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008999 return msg;
9000}
Paul Ollis65745772022-06-05 16:55:54 +01009001
9002#if defined(FEAT_RELTIME) || defined(PROTO)
9003static HANDLE timer_handle;
9004static int timer_active = FALSE;
9005
9006/*
9007 * Calls to start_timeout alternate the return value pointer between the two
9008 * entries in timeout_flags. If the previously active timeout is very close to
9009 * expiring when start_timeout() is called then a race condition means that the
9010 * set_flag() function may still be invoked after the previous timer is
9011 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
9012 * timeouts.
9013 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01009014static sig_atomic_t timeout_flags[2];
9015static int timeout_flag_idx = 0;
9016static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01009017
9018
9019 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01009020set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01009021{
9022 int *timeout_flag = (int *)param;
9023
9024 *timeout_flag = TRUE;
9025}
9026
9027/*
9028 * Stop any active timeout.
9029 */
9030 void
9031stop_timeout(void)
9032{
9033 if (timer_active)
9034 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01009035 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01009036 timer_active = FALSE;
9037 if (!ret && GetLastError() != ERROR_IO_PENDING)
9038 {
9039 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
9040 }
9041 }
9042 *timeout_flag = FALSE;
9043}
9044
9045/*
9046 * Start the timeout timer.
9047 *
9048 * The period is defined in milliseconds.
9049 *
9050 * The return value is a pointer to a flag that is initialised to 0. If the
9051 * timeout expires, the flag is set to 1. This will only return pointers to
9052 * static memory; i.e. any pointer returned by this function may always be
9053 * safely dereferenced.
9054 *
9055 * This function is not expected to fail, but if it does it still returns a
9056 * valid flag pointer; the flag will remain stuck at zero.
9057 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01009058 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01009059start_timeout(long msec)
9060{
Paul Ollis65745772022-06-05 16:55:54 +01009061 BOOL ret;
9062
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01009063 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01009064
9065 stop_timeout();
9066 ret = CreateTimerQueueTimer(
9067 &timer_handle, NULL, set_flag, timeout_flag,
9068 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
9069 if (!ret)
9070 {
9071 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
9072 }
9073 else
9074 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01009075 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01009076 timer_active = TRUE;
9077 *timeout_flag = FALSE;
9078 }
9079 return timeout_flag;
9080}
9081#endif