blob: 0785e95453766dc87bff480a41cc687f4b404d42 [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
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200257static char_u *exe_path = NULL;
258
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
Bram Moolenaar071d4272004-06-13 20:20:40 +0000465 static void
466get_exe_name(void)
467{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100468 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
469 // as the maximum length that works (plus a NUL byte).
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100470#define MAX_ENV_PATH_LEN 8192
471 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200472 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000473
474 if (exe_name == NULL)
475 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100476 // store the name of the executable, may be used for $VIM
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100477 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000478 if (*temp != NUL)
479 exe_name = FullName_save((char_u *)temp, FALSE);
480 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000481
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000482 if (exe_path != NULL || exe_name == NULL)
483 return;
484
485 exe_path = vim_strnsave(exe_name, gettail_sep(exe_name) - exe_name);
486 if (exe_path == NULL)
487 return;
488
489 // Append our starting directory to $PATH, so that when doing
490 // "!xxd" it's found in our starting directory. Needed because
491 // SearchPath() also looks there.
492 p = mch_getenv("PATH");
493 if (p == NULL
494 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000495 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000496 if (p == NULL || *p == NUL)
497 temp[0] = NUL;
498 else
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000499 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000500 STRCPY(temp, p);
501 STRCAT(temp, ";");
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000502 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000503 STRCAT(temp, exe_path);
504 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000505 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000506}
507
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200508/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100509 * Unescape characters in "p" that appear in "escaped".
510 */
511 static void
512unescape_shellxquote(char_u *p, char_u *escaped)
513{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100514 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100515 int n;
516
517 while (*p != NUL)
518 {
519 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
520 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100521 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100522 p += n;
523 l -= n;
524 }
525}
526
527/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200528 * Load library "name".
529 */
530 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000531vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200532{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200533 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200534
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200535 // No need to load any library when registering OLE.
536 if (found_register_arg)
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000537 return NULL;
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200538
Bram Moolenaar0f873732019-12-05 20:28:46 +0100539 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
540 // vimLoadLib() recursively, which causes a stack overflow.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200541 if (exe_path == NULL)
542 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200543
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000544 if (exe_path == NULL)
545 return NULL;
546
547 WCHAR old_dirw[MAXPATHL];
548
549 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) == 0)
550 return NULL;
551
552 // Change directory to where the executable is, both to make
553 // sure we find a .dll there and to avoid looking for a .dll
554 // in the current directory.
555 SetCurrentDirectory((LPCSTR)exe_path);
556 dll = LoadLibrary(name);
557 SetCurrentDirectoryW(old_dirw);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200558 return dll;
559}
560
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200561#if defined(VIMDLL) || defined(PROTO)
562/*
563 * Check if the current executable file is for the GUI subsystem.
564 */
565 int
566mch_is_gui_executable(void)
567{
568 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
569 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
570 PIMAGE_NT_HEADERS pPE;
571
572 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
573 return FALSE;
574 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
575 if (pPE->Signature != IMAGE_NT_SIGNATURE)
576 return FALSE;
577 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
578 return TRUE;
579 return FALSE;
580}
581#endif
582
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000583#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
584 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100585/*
586 * Get related information about 'funcname' which is imported by 'hInst'.
587 * If 'info' is 0, return the function address.
588 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000589 * If 'info' is 2, hook the function with 'ptr', and return the original
590 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100591 */
592 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000593get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
594 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100595{
596 PBYTE pImage = (PBYTE)hInst;
597 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
598 PIMAGE_NT_HEADERS pPE;
599 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100600 PIMAGE_THUNK_DATA pIAT; // Import Address Table
601 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100602 PIMAGE_IMPORT_BY_NAME pImpName;
603
604 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
605 return NULL;
606 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
607 if (pPE->Signature != IMAGE_NT_SIGNATURE)
608 return NULL;
609 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
610 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
611 .VirtualAddress);
612 for (; pImpDesc->FirstThunk; ++pImpDesc)
613 {
614 if (!pImpDesc->OriginalFirstThunk)
615 continue;
616 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
617 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
618 for (; pIAT->u1.Function; ++pIAT, ++pINT)
619 {
620 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
621 continue;
622 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
623 + (UINT_PTR)(pINT->u1.AddressOfData));
624 if (strcmp((char *)pImpName->Name, funcname) == 0)
625 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000626 void *original;
627 DWORD old, new = PAGE_READWRITE;
628
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100629 switch (info)
630 {
631 case 0:
632 return (void *)pIAT->u1.Function;
633 case 1:
634 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000635 case 2:
636 original = (void *)pIAT->u1.Function;
637 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
638 new, &old);
639 pIAT->u1.Function = (UINT_PTR)ptr;
640 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
641 old, &new);
642 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100643 default:
644 return NULL;
645 }
646 }
647 }
648 }
649 return NULL;
650}
651
652/*
653 * Get the module handle which 'funcname' in 'hInst' is imported from.
654 */
655 HINSTANCE
656find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
657{
658 char *modulename;
659
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000660 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100661 if (modulename != NULL)
662 return GetModuleHandleA(modulename);
663 return NULL;
664}
665
666/*
667 * Get the address of 'funcname' which is imported by 'hInst' DLL.
668 */
669 void *
670get_dll_import_func(HINSTANCE hInst, const char *funcname)
671{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000672 return get_imported_func_info(hInst, funcname, 0, NULL);
673}
674
675/*
676 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
677 * and return the original function address.
678 */
679 void *
680hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
681{
682 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100683}
684#endif
685
Bram Moolenaar071d4272004-06-13 20:20:40 +0000686#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
687# ifndef GETTEXT_DLL
688# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200689# define GETTEXT_DLL_ALT1 "libintl-8.dll"
690# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000691# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100692// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000693static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200694static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000695static char *null_libintl_textdomain(const char *);
696static char *null_libintl_bindtextdomain(const char *, const char *);
697static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100698static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000699
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200700static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000701char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200702char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
703 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000704char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
705char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000706 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000707char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
708 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100709int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000710
711 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100712dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000713{
714 int i;
715 static struct
716 {
717 char *name;
718 FARPROC *ptr;
719 } libintl_entry[] =
720 {
721 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200722 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000723 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
724 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
725 {NULL, NULL}
726 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100727 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000728
Bram Moolenaar7554c542018-10-06 15:03:15 +0200729 // No need to initialize twice.
730 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000731 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200732 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100733 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100734# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100735 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200736 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100737# endif
738# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200739 if (!hLibintlDLL)
740 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100741# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100742 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000743 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200744 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000745 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200746 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000747 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200748 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000749 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200750 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000751 }
752 for (i = 0; libintl_entry[i].name != NULL
753 && libintl_entry[i].ptr != NULL; ++i)
754 {
K.Takata54119102022-02-03 13:33:03 +0000755 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000756 libintl_entry[i].name)) == NULL)
757 {
758 dyn_libintl_end();
759 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000760 {
761 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000762 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000763 verbose_leave();
764 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000765 return 0;
766 }
767 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000768
Bram Moolenaar0f873732019-12-05 20:28:46 +0100769 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100770 dyn_libintl_bind_textdomain_codeset = (char *(*)(const char *, const char *))
771 GetProcAddress(hLibintlDLL, "bind_textdomain_codeset");
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000772 if (dyn_libintl_bind_textdomain_codeset == NULL)
773 dyn_libintl_bind_textdomain_codeset =
774 null_libintl_bind_textdomain_codeset;
775
Bram Moolenaar0f873732019-12-05 20:28:46 +0100776 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100777 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
778 if (hmsvcrt != NULL)
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100779 dyn_libintl_wputenv = (int (*)(const wchar_t *))
780 GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100781 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
782 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100783
Bram Moolenaar071d4272004-06-13 20:20:40 +0000784 return 1;
785}
786
787 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100788dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000789{
790 if (hLibintlDLL)
791 FreeLibrary(hLibintlDLL);
792 hLibintlDLL = NULL;
793 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200794 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000795 dyn_libintl_textdomain = null_libintl_textdomain;
796 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000797 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100798 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000799}
800
801 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000802null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000803{
804 return (char*)msgid;
805}
806
807 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200808null_libintl_ngettext(
809 const char *msgid,
810 const char *msgid_plural,
811 unsigned long n)
812{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200813 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200814}
815
Bram Moolenaaree695f72016-08-03 22:08:45 +0200816 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100817null_libintl_bindtextdomain(
818 const char *domainname UNUSED,
819 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000820{
821 return NULL;
822}
823
824 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100825null_libintl_bind_textdomain_codeset(
826 const char *domainname UNUSED,
827 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000828{
829 return NULL;
830}
831
832 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100833null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000834{
835 return NULL;
836}
837
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200838 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100839null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100840{
841 return 0;
842}
843
Bram Moolenaar0f873732019-12-05 20:28:46 +0100844#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000845
Bram Moolenaar0f873732019-12-05 20:28:46 +0100846// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000847
848#ifndef VER_PLATFORM_WIN32_WINDOWS
849# define VER_PLATFORM_WIN32_WINDOWS 1
850#endif
851
Bram Moolenaar071d4272004-06-13 20:20:40 +0000852#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100853# ifndef PROTO
854# include <aclapi.h>
855# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200856# ifndef PROTECTED_DACL_SECURITY_INFORMATION
857# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
858# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000859#endif
860
Bram Moolenaar27515922013-06-29 15:36:26 +0200861#ifdef HAVE_ACL
862/*
863 * Enables or disables the specified privilege.
864 */
865 static BOOL
866win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
867{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100868 BOOL bResult;
869 LUID luid;
870 HANDLE hToken;
871 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200872
873 if (!OpenProcessToken(GetCurrentProcess(),
874 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
875 return FALSE;
876
877 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
878 {
879 CloseHandle(hToken);
880 return FALSE;
881 }
882
Bram Moolenaar45500912014-07-09 20:51:07 +0200883 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200884 tokenPrivileges.Privileges[0].Luid = luid;
885 tokenPrivileges.Privileges[0].Attributes = bEnable ?
886 SE_PRIVILEGE_ENABLED : 0;
887
888 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
889 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
890
891 CloseHandle(hToken);
892
893 return bResult && GetLastError() == ERROR_SUCCESS;
894}
895#endif
896
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100897#ifdef _MSC_VER
898// Suppress the deprecation warning for using GetVersionEx().
899// It is needed for implementing "windowsversion()".
900# pragma warning(push)
901# pragma warning(disable: 4996)
902#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000903/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200904 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000905 */
906 void
907PlatformId(void)
908{
909 static int done = FALSE;
910
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000911 if (done)
912 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000913
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000914 OSVERSIONINFO ovi;
915
916 ovi.dwOSVersionInfoSize = sizeof(ovi);
917 GetVersionEx(&ovi);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000918
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200919#ifdef FEAT_EVAL
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000920 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
921 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200922#endif
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000923 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
924 || ovi.dwMajorVersion > 6)
925 win8_or_later = TRUE;
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100926
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000927 if ((ovi.dwMajorVersion == 10 && ovi.dwBuildNumber >= 19045)
928 || ovi.dwMajorVersion > 10)
929 win10_22H2_or_later = TRUE;
Christopher Plewright1140b512022-11-12 18:46:05 +0000930
Bram Moolenaar071d4272004-06-13 20:20:40 +0000931#ifdef HAVE_ACL
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000932 // Enable privilege for getting or setting SACLs.
933 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000934#endif
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000935 done = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000936}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100937#ifdef _MSC_VER
938# pragma warning(pop)
939#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000940
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200941#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000942
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100943# define SHIFT (SHIFT_PRESSED)
944# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
945# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
946# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000947
948
Bram Moolenaar0f873732019-12-05 20:28:46 +0100949// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
950// We map function keys to their ANSI terminal equivalents, as produced
951// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
952// ANSI key with a value >= '\300' is nonstandard, but provided anyway
953// so that the user can have access to all SHIFT-, CTRL-, and ALT-
954// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000955
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000956static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000957{
958 WORD wVirtKey;
959 BOOL fAnsiKey;
960 int chAlone;
961 int chShift;
962 int chCtrl;
963 int chAlt;
964} VirtKeyMap[] =
965{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200966// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000967 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
968
969 { VK_F1, TRUE, ';', 'T', '^', 'h', },
970 { VK_F2, TRUE, '<', 'U', '_', 'i', },
971 { VK_F3, TRUE, '=', 'V', '`', 'j', },
972 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
973 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
974 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
975 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
976 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
977 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
978 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200979 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
980 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000981
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200982 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
983 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
984 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
985 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
986 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
987 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
988 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
989 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
990 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
991 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100992 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000993
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200994 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000995
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100996# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200997 // Most people don't have F13-F20, but what the hell...
998 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
999 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
1000 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
1001 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
1002 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
1003 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
1004 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
1005 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001006# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001007 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
1008 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
1009 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
1010 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001011
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001012 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
1013 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
1014 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
1015 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
1016 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
1017 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
1018 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
1019 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
1020 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
1021 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001022 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001023};
1024
1025
Bram Moolenaar0f873732019-12-05 20:28:46 +01001026/*
1027 * The return code indicates key code size.
1028 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001029 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001030win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001031 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001032{
1033 UINT uMods = pker->dwControlKeyState;
1034 static int s_iIsDead = 0;
1035 static WORD awAnsiCode[2];
1036 static BYTE abKeystate[256];
1037
1038
1039 if (s_iIsDead == 2)
1040 {
K.Takata972db232022-02-04 10:45:38 +00001041 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001042 s_iIsDead = 0;
1043 return 1;
1044 }
1045
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001046 // check if it already has a valid unicode character.
Christopher Plewright566f76e2023-01-10 13:43:04 +00001047 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001048 return 1;
1049
Bram Moolenaara80faa82020-04-12 19:37:17 +02001050 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001051
Bram Moolenaar0f873732019-12-05 20:28:46 +01001052 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001053 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001054
1055 if (uMods & SHIFT_PRESSED)
1056 abKeystate[VK_SHIFT] = 0x80;
1057 if (uMods & CAPSLOCK_ON)
1058 abKeystate[VK_CAPITAL] = 1;
1059
1060 if ((uMods & ALT_GR) == ALT_GR)
1061 {
1062 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1063 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1064 }
1065
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001066 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1067 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001068
1069 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001070 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001071
1072 return s_iIsDead;
1073}
1074
Bram Moolenaar071d4272004-06-13 20:20:40 +00001075static BOOL g_fJustGotFocus = FALSE;
1076
1077/*
1078 * Decode a KEY_EVENT into one or two keystrokes
1079 */
1080 static BOOL
1081decode_key_event(
1082 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001083 WCHAR *pch,
1084 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001085 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001086 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001087{
1088 int i;
1089 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1090
1091 *pch = *pch2 = NUL;
1092 g_fJustGotFocus = FALSE;
1093
Bram Moolenaar0f873732019-12-05 20:28:46 +01001094 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001095 if (!pker->bKeyDown)
1096 return FALSE;
1097
Bram Moolenaar0f873732019-12-05 20:28:46 +01001098 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001099 switch (pker->wVirtualKeyCode)
1100 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001101 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001102 case VK_SHIFT:
1103 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001104 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001105 return FALSE;
1106
1107 default:
1108 break;
1109 }
1110
Bram Moolenaar0f873732019-12-05 20:28:46 +01001111 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001112 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1113 {
1114 *pch = K_NUL;
1115 *pch2 = '\017';
1116 return TRUE;
1117 }
1118
K.Takataeeec2542021-06-02 13:28:16 +02001119 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001120 {
1121 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1122 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001123 *pch = VirtKeyMap[i].chAlone;
1124 if ((nModifs & SHIFT) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001125 *pch = VirtKeyMap[i].chShift;
1126 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1127 *pch = VirtKeyMap[i].chCtrl;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001128 else if ((nModifs & ALT) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001129 *pch = VirtKeyMap[i].chAlt;
1130
1131 if (*pch != 0)
1132 {
1133 if (VirtKeyMap[i].fAnsiKey)
1134 {
1135 *pch2 = *pch;
1136 *pch = K_NUL;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001137 if (pmodifiers)
1138 {
1139 if (pker->wVirtualKeyCode >= VK_F1
1140 && pker->wVirtualKeyCode <= VK_F12)
1141 {
1142 if ((nModifs & ALT) != 0)
1143 {
1144 *pmodifiers |= MOD_MASK_ALT;
1145 if ((nModifs & SHIFT) == 0)
1146 *pch2 = VirtKeyMap[i].chAlone;
1147 }
1148 if ((nModifs & CTRL) != 0)
1149 {
1150 *pmodifiers |= MOD_MASK_CTRL;
1151 if ((nModifs & SHIFT) == 0)
1152 *pch2 = VirtKeyMap[i].chAlone;
1153 }
1154 }
1155 else if (pker->wVirtualKeyCode >= VK_END
1156 && pker->wVirtualKeyCode <= VK_DOWN)
1157 {
Christopher Plewright566f76e2023-01-10 13:43:04 +00001158 // (0x23 - 0x28): VK_END, VK_HOME,
1159 // VK_LEFT, VK_UP, VK_RIGHT, VK_DOWN
1160
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001161 *pmodifiers = 0;
1162 *pch2 = VirtKeyMap[i].chAlone;
1163 if ((nModifs & SHIFT) != 0
1164 && (nModifs & ~SHIFT) == 0)
1165 {
1166 *pch2 = VirtKeyMap[i].chShift;
1167 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001168 if ((nModifs & CTRL) != 0
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001169 && (nModifs & ~CTRL) == 0)
1170 {
1171 *pch2 = VirtKeyMap[i].chCtrl;
1172 if (pker->wVirtualKeyCode == VK_UP
1173 || pker->wVirtualKeyCode == VK_DOWN)
1174 {
1175 *pmodifiers |= MOD_MASK_CTRL;
1176 *pch2 = VirtKeyMap[i].chAlone;
1177 }
1178 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001179 if ((nModifs & SHIFT) != 0
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001180 && (nModifs & CTRL) != 0)
1181 {
1182 *pmodifiers |= MOD_MASK_CTRL;
1183 *pch2 = VirtKeyMap[i].chShift;
1184 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001185 if ((nModifs & ALT) != 0)
1186 {
1187 *pch2 = VirtKeyMap[i].chAlt;
1188 *pmodifiers |= MOD_MASK_ALT;
1189 if ((nModifs & ~ALT) == 0)
1190 {
1191 *pch2 = VirtKeyMap[i].chAlone;
1192 }
1193 else if ((nModifs & SHIFT) != 0)
1194 {
1195 *pch2 = VirtKeyMap[i].chShift;
1196 }
1197 else if ((nModifs & CTRL) != 0)
1198 {
1199 if (pker->wVirtualKeyCode == VK_UP
1200 || pker->wVirtualKeyCode == VK_DOWN)
1201 {
1202 *pmodifiers |= MOD_MASK_CTRL;
1203 *pch2 = VirtKeyMap[i].chAlone;
1204 }
1205 else
1206 {
1207 *pch2 = VirtKeyMap[i].chCtrl;
1208 }
1209 }
1210 }
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001211 }
1212 else
1213 {
1214 *pch2 = VirtKeyMap[i].chAlone;
1215 if ((nModifs & SHIFT) != 0)
1216 *pmodifiers |= MOD_MASK_SHIFT;
1217 if ((nModifs & CTRL) != 0)
1218 *pmodifiers |= MOD_MASK_CTRL;
1219 if ((nModifs & ALT) != 0)
1220 *pmodifiers |= MOD_MASK_ALT;
1221 }
1222 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001223 }
1224
1225 return TRUE;
1226 }
1227 }
1228 }
1229
1230 i = win32_kbd_patch_key(pker);
1231
1232 if (i < 0)
1233 *pch = NUL;
1234 else
1235 {
K.Takata972db232022-02-04 10:45:38 +00001236 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001237
1238 if (pmodifiers != NULL)
1239 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001240 // Pass on the ALT key as a modifier, but only when not combined
1241 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001242 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1243 *pmodifiers |= MOD_MASK_ALT;
1244
Bram Moolenaar0f873732019-12-05 20:28:46 +01001245 // Pass on SHIFT only for special keys, because we don't know when
1246 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001247 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1248 *pmodifiers |= MOD_MASK_SHIFT;
1249
Bram Moolenaar0f873732019-12-05 20:28:46 +01001250 // Pass on CTRL only for non-special keys, because we don't know
1251 // when it's already included with the character. And not when
1252 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001253 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1254 && *pch >= 0x20 && *pch < 0x80)
1255 *pmodifiers |= MOD_MASK_CTRL;
1256 }
1257 }
1258
1259 return (*pch != NUL);
1260}
1261
Christopher Plewright20b795e2022-12-20 20:01:58 +00001262# if defined(FEAT_EVAL)
1263 static int
1264encode_key_event(dict_T *args, INPUT_RECORD *ir)
1265{
1266 static int s_dwMods = 0;
1267
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001268 char_u *action = dict_get_string(args, "event", TRUE);
1269 if (action && (STRICMP(action, "keydown") == 0
1270 || STRICMP(action, "keyup") == 0))
Christopher Plewright20b795e2022-12-20 20:01:58 +00001271 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001272 BOOL isKeyDown = STRICMP(action, "keydown") == 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001273 WORD vkCode = dict_get_number_def(args, "keycode", 0);
1274 if (vkCode <= 0 || vkCode >= 0xFF)
1275 {
1276 semsg(_(e_invalid_argument_nr), (long)vkCode);
1277 return FALSE;
1278 }
1279
1280 ir->EventType = KEY_EVENT;
1281 KEY_EVENT_RECORD ker;
1282 ZeroMemory(&ker, sizeof(ker));
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001283 ker.bKeyDown = isKeyDown;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001284 ker.wRepeatCount = 1;
1285 ker.wVirtualScanCode = 0;
1286 ker.dwControlKeyState = 0;
1287 int mods = (int)dict_get_number(args, "modifiers");
1288 // Encode the win32 console key modifiers from Vim keyboard modifiers.
1289 if (mods)
1290 {
1291 // If "modifiers" is explicitly set in the args, then we reset any
1292 // remembered modifer key state that may have been set from earlier
1293 // mod-key-down events, even if they are not yet unset by earlier
1294 // mod-key-up events.
1295 s_dwMods = 0;
1296 if (mods & MOD_MASK_SHIFT)
1297 ker.dwControlKeyState |= SHIFT_PRESSED;
1298 if (mods & MOD_MASK_CTRL)
1299 ker.dwControlKeyState |= LEFT_CTRL_PRESSED;
1300 if (mods & MOD_MASK_ALT)
1301 ker.dwControlKeyState |= LEFT_ALT_PRESSED;
1302 }
1303
1304 if (vkCode == VK_LSHIFT || vkCode == VK_RSHIFT || vkCode == VK_SHIFT)
1305 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001306 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001307 s_dwMods |= SHIFT_PRESSED;
1308 else
1309 s_dwMods &= ~SHIFT_PRESSED;
1310 }
1311 else if (vkCode == VK_LCONTROL || vkCode == VK_CONTROL)
1312 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001313 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001314 s_dwMods |= LEFT_CTRL_PRESSED;
1315 else
1316 s_dwMods &= ~LEFT_CTRL_PRESSED;
1317 }
1318 else if (vkCode == VK_RCONTROL)
1319 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001320 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001321 s_dwMods |= RIGHT_CTRL_PRESSED;
1322 else
1323 s_dwMods &= ~RIGHT_CTRL_PRESSED;
1324 }
1325 else if (vkCode == VK_LMENU || vkCode == VK_MENU)
1326 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001327 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001328 s_dwMods |= LEFT_ALT_PRESSED;
1329 else
1330 s_dwMods &= ~LEFT_ALT_PRESSED;
1331 }
1332 else if (vkCode == VK_RMENU)
1333 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001334 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001335 s_dwMods |= RIGHT_ALT_PRESSED;
1336 else
1337 s_dwMods &= ~RIGHT_ALT_PRESSED;
1338 }
1339 ker.dwControlKeyState |= s_dwMods;
1340 ker.wVirtualKeyCode = vkCode;
Christopher Plewright566f76e2023-01-10 13:43:04 +00001341 ker.uChar.UnicodeChar = 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001342 ir->Event.KeyEvent = ker;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001343 vim_free(action);
Christopher Plewright20b795e2022-12-20 20:01:58 +00001344 }
1345 else
1346 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001347 if (action == NULL)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001348 {
1349 semsg(_(e_missing_argument_str), "event");
1350 }
1351 else
1352 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001353 semsg(_(e_invalid_value_for_argument_str_str), "event", action);
1354 vim_free(action);
Christopher Plewright20b795e2022-12-20 20:01:58 +00001355 }
1356 return FALSE;
1357 }
1358 return TRUE;
1359}
1360# endif // FEAT_EVAL
1361#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00001362
1363
Bram Moolenaar071d4272004-06-13 20:20:40 +00001364/*
1365 * For the GUI the mouse handling is in gui_w32.c.
1366 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001367#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001368 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001369mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001370{
1371}
Christopher Plewright20b795e2022-12-20 20:01:58 +00001372#else // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar0f873732019-12-05 20:28:46 +01001373static int g_fMouseAvail = FALSE; // mouse present
1374static int g_fMouseActive = FALSE; // mouse enabled
1375static int g_nMouseClick = -1; // mouse status
1376static int g_xMouse; // mouse x coordinate
1377static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001378static DWORD g_cmodein = 0; // Original console input mode
1379static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001380
1381/*
1382 * Enable or disable mouse input
1383 */
1384 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001385mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001386{
1387 DWORD cmodein;
1388
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001389# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001390 if (gui.in_use)
1391 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001392# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001393 if (!g_fMouseAvail)
1394 return;
1395
1396 g_fMouseActive = on;
1397 GetConsoleMode(g_hConIn, &cmodein);
1398
1399 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001400 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001401 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001402 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1403 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001404 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001405 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001406 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001407 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1408 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001409
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001410 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001411}
1412
Bram Moolenaar157d8132018-03-06 17:09:20 +01001413
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001414# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001415/*
1416 * Called when 'balloonevalterm' changed.
1417 */
1418 void
1419mch_bevalterm_changed(void)
1420{
1421 mch_setmouse(g_fMouseActive);
1422}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001423# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001424
Christopher Plewright2a46f812022-10-16 19:47:45 +01001425/*
1426 * Win32 console mouse scroll event handler.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001427 * Console version of the _OnMouseWheel() function in gui_w32.c
Christopher Plewright2a46f812022-10-16 19:47:45 +01001428 *
1429 * This encodes the mouse scroll direction and keyboard modifiers into
1430 * g_nMouseClick, and the mouse position into g_xMouse and g_yMouse
1431 *
1432 * The direction of the scroll is decoded from two fields of the win32 console
1433 * mouse event record;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001434 * 1. The orientation - vertical or horizontal flag - from dwEventFlags
Christopher Plewright2a46f812022-10-16 19:47:45 +01001435 * 2. The sign - positive or negative (aka delta flag) - from dwButtonState
1436 *
Christopher Plewright20b795e2022-12-20 20:01:58 +00001437 * When scroll orientation is HORIZONTAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001438 * - If the high word of the dwButtonState member contains a positive
1439 * value, the wheel was rotated to the right.
1440 * - Otherwise, the wheel was rotated to the left.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001441 * When scroll orientation is VERTICAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001442 * - If the high word of the dwButtonState member contains a positive value,
1443 * the wheel was rotated forward, away from the user.
1444 * - Otherwise, the wheel was rotated backward, toward the user.
1445 */
1446 static void
1447decode_mouse_wheel(MOUSE_EVENT_RECORD *pmer)
1448{
Christopher Plewright2a46f812022-10-16 19:47:45 +01001449 int horizontal = (pmer->dwEventFlags == MOUSE_HWHEELED);
1450 int zDelta = pmer->dwButtonState;
1451
1452 g_xMouse = pmer->dwMousePosition.X;
1453 g_yMouse = pmer->dwMousePosition.Y;
1454
K.Takata161b6ac2022-11-14 15:31:07 +00001455# ifdef FEAT_PROP_POPUP
Christopher Plewright605d02a2022-10-19 11:54:46 +01001456 int lcol = g_xMouse;
1457 int lrow = g_yMouse;
Christopher Plewright38804d62022-11-09 23:55:52 +00001458 win_T *wp = mouse_find_win(&lrow, &lcol, FIND_POPUP);
Christopher Plewright2a46f812022-10-16 19:47:45 +01001459 if (wp != NULL && popup_is_popup(wp))
1460 {
1461 g_nMouseClick = -1;
1462 cmdarg_T cap;
1463 oparg_T oa;
1464 CLEAR_FIELD(cap);
1465 clear_oparg(&oa);
1466 cap.oap = &oa;
1467 if (horizontal)
1468 {
1469 cap.arg = zDelta < 0 ? MSCR_LEFT : MSCR_RIGHT;
1470 cap.cmdchar = zDelta < 0 ? K_MOUSELEFT : K_MOUSERIGHT;
1471 }
1472 else
1473 {
1474 cap.cmdchar = zDelta < 0 ? K_MOUSEUP : K_MOUSEDOWN;
1475 cap.arg = zDelta < 0 ? MSCR_UP : MSCR_DOWN;
1476 }
1477
1478 // Mouse hovers over popup window, scroll it if possible.
1479 mouse_row = wp->w_winrow;
1480 mouse_col = wp->w_wincol;
1481 nv_mousescroll(&cap);
1482 update_screen(0);
1483 setcursor();
1484 out_flush();
1485 return;
1486 }
K.Takata161b6ac2022-11-14 15:31:07 +00001487# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01001488 mouse_col = g_xMouse;
1489 mouse_row = g_yMouse;
1490
1491 char_u modifiers = 0;
1492 char_u direction = 0;
1493
1494 // Decode the direction into an event that Vim can process
1495 if (horizontal)
1496 direction = zDelta >= 0 ? KE_MOUSELEFT : KE_MOUSERIGHT;
1497 else
1498 direction = zDelta >= 0 ? KE_MOUSEDOWN : KE_MOUSEUP;
1499
dundargocc57b5bc2022-11-02 13:30:51 +00001500 // Decode the win32 console key modifiers into Vim mouse modifiers.
Christopher Plewright2a46f812022-10-16 19:47:45 +01001501 if (pmer->dwControlKeyState & SHIFT_PRESSED)
Christopher Plewright605d02a2022-10-19 11:54:46 +01001502 modifiers |= MOD_MASK_SHIFT; // MOUSE_SHIFT;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001503 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
Christopher Plewright605d02a2022-10-19 11:54:46 +01001504 modifiers |= MOD_MASK_CTRL; // MOUSE_CTRL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001505 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1506 modifiers |= MOD_MASK_ALT; // MOUSE_ALT;
1507
1508 // add (bitwise or) the scroll direction and the key modifier chars
1509 // together.
1510 g_nMouseClick = ((direction << 8) | modifiers);
1511
1512 return;
1513}
1514
Bram Moolenaar071d4272004-06-13 20:20:40 +00001515/*
1516 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1517 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1518 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1519 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1520 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1521 * and we return the mouse position in g_xMouse and g_yMouse.
1522 *
1523 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1524 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1525 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1526 *
1527 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1528 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1529 *
1530 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1531 * moves, even if it stays within the same character cell. We ignore
1532 * all MOUSE_MOVED messages if the position hasn't really changed, and
1533 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1534 * we're only interested in MOUSE_DRAG).
1535 *
1536 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1537 * 2-button mouses by pressing the left & right buttons simultaneously.
1538 * In practice, it's almost impossible to click both at the same time,
1539 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1540 * in such cases, if the user is clicking quickly.
1541 */
1542 static BOOL
1543decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001544 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001545{
1546 static int s_nOldButton = -1;
1547 static int s_nOldMouseClick = -1;
1548 static int s_xOldMouse = -1;
1549 static int s_yOldMouse = -1;
1550 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001551# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001552 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001553# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001554 static int s_cClicks = 1;
1555 static BOOL s_fReleased = TRUE;
1556 static DWORD s_dwLastClickTime = 0;
1557 static BOOL s_fNextIsMiddle = FALSE;
1558
Bram Moolenaar0f873732019-12-05 20:28:46 +01001559 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001560
1561 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1562 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1563 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1564 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1565
1566 int nButton;
1567
1568 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1569 cButtons = 2;
1570
1571 if (!g_fMouseAvail || !g_fMouseActive)
1572 {
1573 g_nMouseClick = -1;
1574 return FALSE;
1575 }
1576
Bram Moolenaar0f873732019-12-05 20:28:46 +01001577 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001578 if (g_fJustGotFocus)
1579 {
1580 g_fJustGotFocus = FALSE;
1581 return FALSE;
1582 }
1583
Christopher Plewright605d02a2022-10-19 11:54:46 +01001584 // If there is an unprocessed mouse click drop this one.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001585 if (g_nMouseClick != -1)
1586 return TRUE;
Christopher Plewright605d02a2022-10-19 11:54:46 +01001587
Christopher Plewright2a46f812022-10-16 19:47:45 +01001588 if (pmer->dwEventFlags == MOUSE_WHEELED
1589 || pmer->dwEventFlags == MOUSE_HWHEELED)
1590 {
1591 decode_mouse_wheel(pmer);
1592 return TRUE; // we now should have a mouse scroll in g_nMouseClick
1593 }
Christopher Plewright605d02a2022-10-19 11:54:46 +01001594
Bram Moolenaar071d4272004-06-13 20:20:40 +00001595 nButton = -1;
1596 g_xMouse = pmer->dwMousePosition.X;
1597 g_yMouse = pmer->dwMousePosition.Y;
1598
1599 if (pmer->dwEventFlags == MOUSE_MOVED)
1600 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001601 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1602 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001603 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1604 return FALSE;
1605 }
1606
Bram Moolenaar0f873732019-12-05 20:28:46 +01001607 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001608 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1609 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001610 nButton = MOUSE_RELEASE;
1611
Bram Moolenaar0f873732019-12-05 20:28:46 +01001612 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001613 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001614 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001615# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001616 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001617 if (p_bevalterm)
1618 nButton = MOUSE_DRAG;
1619 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001620# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001621 return FALSE;
1622 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001623
Bram Moolenaar071d4272004-06-13 20:20:40 +00001624 s_fReleased = TRUE;
1625 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001626 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001627 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001628 // on a 2-button mouse, hold down left and right buttons
1629 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001630
1631 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1632 {
1633 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1634
Bram Moolenaar0f873732019-12-05 20:28:46 +01001635 // if either left or right button only is pressed, see if the
1636 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001637 if (dwLR == LEFT || dwLR == RIGHT)
1638 {
1639 for (;;)
1640 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001641 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001642 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1643 != WAIT_OBJECT_0)
1644 break;
1645 else
1646 {
1647 DWORD cRecords = 0;
1648 INPUT_RECORD ir;
1649 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1650
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001651 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001652
1653 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1654 || !(pmer2->dwButtonState & LEFT_RIGHT))
1655 break;
1656 else
1657 {
1658 if (pmer2->dwEventFlags != MOUSE_MOVED)
1659 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001660 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001661
1662 return decode_mouse_event(pmer2);
1663 }
1664 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1665 s_yOldMouse == pmer2->dwMousePosition.Y)
1666 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001667 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001668 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001669
Bram Moolenaar0f873732019-12-05 20:28:46 +01001670 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001671 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001672
1673 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1674 break;
1675 }
1676 else
1677 break;
1678 }
1679 }
1680 }
1681 }
1682 }
1683
1684 if (s_fNextIsMiddle)
1685 {
1686 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1687 ? MOUSE_DRAG : MOUSE_MIDDLE;
1688 s_fNextIsMiddle = FALSE;
1689 }
1690 else if (cButtons == 2 &&
1691 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1692 {
1693 nButton = MOUSE_MIDDLE;
1694
1695 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1696 {
1697 s_fNextIsMiddle = TRUE;
1698 nButton = MOUSE_RELEASE;
1699 }
1700 }
1701 else if ((pmer->dwButtonState & LEFT) == LEFT)
1702 nButton = MOUSE_LEFT;
1703 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1704 nButton = MOUSE_MIDDLE;
1705 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1706 nButton = MOUSE_RIGHT;
1707
1708 if (! s_fReleased && ! s_fNextIsMiddle
1709 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1710 return FALSE;
1711
1712 s_fReleased = s_fNextIsMiddle;
1713 }
1714
1715 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1716 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001717 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001718 if (nButton != -1 && nButton != MOUSE_RELEASE)
1719 {
1720 DWORD dwCurrentTime = GetTickCount();
1721
1722 if (s_xOldMouse != g_xMouse
1723 || s_yOldMouse != g_yMouse
1724 || s_nOldButton != nButton
1725 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001726# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001727 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001728# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001729 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1730 {
1731 s_cClicks = 1;
1732 }
1733 else if (++s_cClicks > 4)
1734 {
1735 s_cClicks = 1;
1736 }
1737
1738 s_dwLastClickTime = dwCurrentTime;
1739 }
1740 }
1741 else if (pmer->dwEventFlags == MOUSE_MOVED)
1742 {
1743 if (nButton != -1 && nButton != MOUSE_RELEASE)
1744 nButton = MOUSE_DRAG;
1745
1746 s_cClicks = 1;
1747 }
1748
1749 if (nButton == -1)
1750 return FALSE;
1751
1752 if (nButton != MOUSE_RELEASE)
1753 s_nOldButton = nButton;
1754
1755 g_nMouseClick = nButton;
1756
1757 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1758 g_nMouseClick |= MOUSE_SHIFT;
1759 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1760 g_nMouseClick |= MOUSE_CTRL;
1761 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1762 g_nMouseClick |= MOUSE_ALT;
1763
1764 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1765 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1766
Bram Moolenaar0f873732019-12-05 20:28:46 +01001767 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001768 if (s_xOldMouse == g_xMouse
1769 && s_yOldMouse == g_yMouse
1770 && s_nOldMouseClick == g_nMouseClick)
1771 {
1772 g_nMouseClick = -1;
1773 return FALSE;
1774 }
1775
1776 s_xOldMouse = g_xMouse;
1777 s_yOldMouse = g_yMouse;
1778 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001779# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001780 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001781# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001782 s_nOldMouseClick = g_nMouseClick;
1783
1784 return TRUE;
1785}
1786
Christopher Plewright20b795e2022-12-20 20:01:58 +00001787# ifdef FEAT_EVAL
1788 static int
1789encode_mouse_event(dict_T *args, INPUT_RECORD *ir)
1790{
1791 int button;
1792 int row;
1793 int col;
1794 int repeated_click;
Bram Moolenaar9b8a3652022-12-20 20:47:28 +00001795 int_u mods = 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001796 int move;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001797
Christopher Plewright20b795e2022-12-20 20:01:58 +00001798 if (!dict_has_key(args, "row") || !dict_has_key(args, "col"))
1799 return FALSE;
1800
1801 // Note: "move" is optional, requires fewer arguments
1802 move = (int)dict_get_bool(args, "move", FALSE);
1803 if (!move && (!dict_has_key(args, "button")
1804 || !dict_has_key(args, "multiclick")
1805 || !dict_has_key(args, "modifiers")))
1806 return FALSE;
1807
1808 row = (int)dict_get_number(args, "row") - 1;
1809 col = (int)dict_get_number(args, "col") - 1;
1810
1811 ir->EventType = MOUSE_EVENT;
1812 MOUSE_EVENT_RECORD mer;
1813 ZeroMemory(&mer, sizeof(mer));
1814 mer.dwMousePosition.X = col;
1815 mer.dwMousePosition.Y = row;
1816
1817 if (move)
1818 {
1819 mer.dwButtonState = 0;
1820 mer.dwEventFlags = MOUSE_MOVED;
1821 }
1822 else
1823 {
1824 button = (int)dict_get_number(args, "button");
1825 repeated_click = (int)dict_get_number(args, "multiclick");
1826 mods = (int)dict_get_number(args, "modifiers");
1827 // Reset the scroll values to known values.
1828 // XXX: Remove this when/if the scroll step is made configurable.
1829 mouse_set_hor_scroll_step(6);
1830 mouse_set_vert_scroll_step(3);
1831
1832 switch (button)
1833 {
1834 case MOUSE_LEFT:
1835 mer.dwButtonState = FROM_LEFT_1ST_BUTTON_PRESSED;
1836 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1837 break;
1838 case MOUSE_MIDDLE:
1839 mer.dwButtonState = FROM_LEFT_2ND_BUTTON_PRESSED;
1840 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1841 break;
1842 case MOUSE_RIGHT:
1843 mer.dwButtonState = RIGHTMOST_BUTTON_PRESSED;
1844 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1845 break;
1846 case MOUSE_RELEASE:
1847 // umm? Assume Left Release?
1848 mer.dwEventFlags = 0;
1849
1850 case MOUSE_MOVE:
1851 mer.dwButtonState = 0;
1852 mer.dwEventFlags = MOUSE_MOVED;
1853 break;
1854 case MOUSE_X1:
1855 mer.dwButtonState = FROM_LEFT_3RD_BUTTON_PRESSED;
1856 break;
1857 case MOUSE_X2:
1858 mer.dwButtonState = FROM_LEFT_4TH_BUTTON_PRESSED;
1859 break;
1860 case MOUSE_4: // KE_MOUSEDOWN;
1861 mer.dwButtonState = -1;
1862 mer.dwEventFlags = MOUSE_WHEELED;
1863 break;
1864 case MOUSE_5: // KE_MOUSEUP;
1865 mer.dwButtonState = +1;
1866 mer.dwEventFlags = MOUSE_WHEELED;
1867 break;
1868 case MOUSE_6: // KE_MOUSELEFT;
1869 mer.dwButtonState = -1;
1870 mer.dwEventFlags = MOUSE_HWHEELED;
1871 break;
1872 case MOUSE_7: // KE_MOUSERIGHT;
1873 mer.dwButtonState = +1;
1874 mer.dwEventFlags = MOUSE_HWHEELED;
1875 break;
1876 default:
1877 semsg(_(e_invalid_argument_str), "button");
1878 return FALSE;
1879 }
1880 }
1881
1882 mer.dwControlKeyState = 0;
1883 if (mods != 0)
1884 {
1885 // Encode the win32 console key modifiers from Vim MOUSE modifiers.
1886 if (mods & MOUSE_SHIFT)
1887 mer.dwControlKeyState |= SHIFT_PRESSED;
1888 if (mods & MOUSE_CTRL)
1889 mer.dwControlKeyState |= LEFT_CTRL_PRESSED;
1890 if (mods & MOUSE_ALT)
1891 mer.dwControlKeyState |= LEFT_ALT_PRESSED;
1892 }
1893 ir->Event.MouseEvent = mer;
1894 return TRUE;
1895}
1896# endif // FEAT_EVAL
1897
1898 static int
1899write_input_record_buffer(INPUT_RECORD* irEvents, int nLength)
1900{
1901 int nCount = 0;
1902 while (nCount < nLength)
1903 {
1904 input_record_buffer.length++;
1905 input_record_buffer_node_T *event_node =
1906 malloc(sizeof(input_record_buffer_node_T));
1907 event_node->ir = irEvents[nCount++];
1908 event_node->next = NULL;
1909 if (input_record_buffer.tail == NULL)
1910 {
1911 input_record_buffer.head = event_node;
1912 input_record_buffer.tail = event_node;
1913 }
1914 else
1915 {
1916 input_record_buffer.tail->next = event_node;
1917 input_record_buffer.tail = input_record_buffer.tail->next;
1918 }
1919 }
1920 return nCount;
1921}
1922
1923 static int
1924read_input_record_buffer(INPUT_RECORD* irEvents, int nMaxLength)
1925{
1926 int nCount = 0;
1927 while (nCount < nMaxLength && input_record_buffer.head != NULL)
1928 {
1929 input_record_buffer.length--;
1930 input_record_buffer_node_T *pop_head = input_record_buffer.head;
1931 irEvents[nCount++] = pop_head->ir;
1932 input_record_buffer.head = pop_head->next;
1933 vim_free(pop_head);
1934 if (input_record_buffer.length == 0)
1935 input_record_buffer.tail = NULL;
1936 }
1937 return nCount;
1938}
Christopher Plewright20b795e2022-12-20 20:01:58 +00001939#endif // !FEAT_GUI_MSWIN || VIMDLL
1940
1941#ifdef FEAT_EVAL
1942/*
1943 * The 'test_mswin_event' function is for testing Vim's low-level handling of
1944 * user input events. ie, this manages the encoding of INPUT_RECORD events
1945 * so that we have a way to test how Vim decodes INPUT_RECORD events in Windows
1946 * consoles.
1947 *
1948 * The 'test_mswin_event' function is based on 'test_gui_event'. In fact, when
1949 * the Windows GUI is running, the arguments; 'event' and 'args', are the same.
1950 * So, it acts as an alias for 'test_gui_event' for the Windows GUI.
1951 *
1952 * When the Windows console is running, the arguments; 'event' and 'args', are
1953 * a subset of what 'test_gui_event' handles, ie, only "key" and "mouse"
1954 * events are encoded as INPUT_RECORD events.
1955 *
1956 * Note: INPUT_RECORDs are only used by the Windows console, not the GUI. The
1957 * GUI sends MSG structs instead.
1958 */
1959 int
1960test_mswin_event(char_u *event, dict_T *args)
1961{
1962 int lpEventsWritten = 0;
1963
1964# if defined(VIMDLL) || defined(FEAT_GUI_MSWIN)
1965 if (gui.in_use)
1966 return test_gui_w32_sendevent(event, args);
1967# endif
1968
1969# if defined(VIMDLL) || !defined(FEAT_GUI_MSWIN)
1970
1971// Currently implemented event record types are; KEY_EVENT and MOUSE_EVENT
1972// Potentially could also implement: FOCUS_EVENT and WINDOW_BUFFER_SIZE_EVENT
1973// Maybe also: MENU_EVENT
1974
1975 INPUT_RECORD ir;
1976 BOOL input_encoded = FALSE;
Christopher Plewright7b0afc12022-12-30 16:54:58 +00001977 BOOL execute = FALSE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001978 if (STRCMP(event, "key") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00001979 {
1980 execute = dict_get_bool(args, "execute", FALSE);
1981 if (dict_has_key(args, "event"))
1982 input_encoded = encode_key_event(args, &ir);
1983 else if (!execute)
1984 {
1985 semsg(_(e_missing_argument_str), "event");
1986 return FALSE;
1987 }
1988 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00001989 else if (STRCMP(event, "mouse") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00001990 {
1991 execute = TRUE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001992 input_encoded = encode_mouse_event(args, &ir);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00001993 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00001994 else
1995 {
1996 semsg(_(e_invalid_value_for_argument_str_str), "event", event);
1997 return FALSE;
1998 }
1999
2000 // Ideally, WriteConsoleInput would be used to inject these low-level
2001 // events. But, this doesnt work well in the CI test environment. So
2002 // implementing an input_record_buffer instead.
2003 if (input_encoded)
2004 lpEventsWritten = write_input_record_buffer(&ir, 1);
2005
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002006 // Set flags to execute the event, ie. like feedkeys mode X.
2007 if (execute)
2008 {
2009 int save_msg_scroll = msg_scroll;
2010 // Avoid a 1 second delay when the keys start Insert mode.
2011 msg_scroll = FALSE;
2012 ch_log(NULL, "test_mswin_event() executing");
Christopher Plewright20b795e2022-12-20 20:01:58 +00002013 exec_normal(TRUE, TRUE, TRUE);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002014 msg_scroll |= save_msg_scroll;
2015 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002016
2017# endif
2018 return lpEventsWritten;
2019}
2020#endif // FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002021
2022#ifdef MCH_CURSOR_SHAPE
2023/*
2024 * Set the shape of the cursor.
2025 * 'thickness' can be from 1 (thin) to 99 (block)
2026 */
2027 static void
2028mch_set_cursor_shape(int thickness)
2029{
Christopher Plewright38804d62022-11-09 23:55:52 +00002030 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01002031 {
2032 if (*T_CSI == NUL)
2033 {
2034 // If 't_SI' is not set, use the default cursor styles.
2035 if (thickness < 50)
2036 vtp_printf("\033[3 q"); // underline
2037 else
2038 vtp_printf("\033[0 q"); // default
2039 }
2040 }
2041 else
2042 {
2043 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
2044 ConsoleCursorInfo.dwSize = thickness;
2045 ConsoleCursorInfo.bVisible = s_cursor_visible;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002046
K.Takatadf5320c2022-09-01 13:20:16 +01002047 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
2048 if (s_cursor_visible)
2049 SetConsoleCursorPosition(g_hConOut, g_coord);
2050 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002051}
2052
2053 void
2054mch_update_cursor(void)
2055{
2056 int idx;
2057 int thickness;
2058
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002059# ifdef VIMDLL
2060 if (gui.in_use)
2061 return;
2062# endif
2063
Bram Moolenaar071d4272004-06-13 20:20:40 +00002064 /*
2065 * How the cursor is drawn depends on the current mode.
2066 */
2067 idx = get_shape_idx(FALSE);
2068
2069 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002070 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00002071 else
2072 thickness = shape_table[idx].percentage;
2073 mch_set_cursor_shape(thickness);
2074}
2075#endif
2076
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002077#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002078/*
2079 * Handle FOCUS_EVENT.
2080 */
2081 static void
2082handle_focus_event(INPUT_RECORD ir)
2083{
2084 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
2085 ui_focus_change((int)g_fJustGotFocus);
2086}
2087
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002088static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
2089
Bram Moolenaar071d4272004-06-13 20:20:40 +00002090/*
2091 * Wait until console input from keyboard or mouse is available,
2092 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002093 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002094 * Return TRUE if something is available FALSE if not.
2095 */
2096 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002097WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002098{
2099 DWORD dwNow = 0, dwEndTime = 0;
2100 INPUT_RECORD ir;
2101 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002102 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002103# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02002104 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002105# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002106
2107 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002108 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002109 dwEndTime = GetTickCount() + msec;
2110 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002111 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002112 dwEndTime = INFINITE;
2113
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002114 // We need to loop until the end of the time period, because
2115 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002116 for (;;)
2117 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002118 // Only process messages when waiting.
2119 if (msec != 0)
2120 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002121# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002122 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002123# endif
2124# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002125 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002126# endif
2127# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002128 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002129# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002130 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002131
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02002132 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002133# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002134 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002135# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002136 )
2137 return TRUE;
2138
2139 if (msec > 0)
2140 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002141 // If the specified wait time has passed, return. Beware that
2142 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002143 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02002144 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002145 break;
2146 }
2147 if (msec != 0)
2148 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00002149 DWORD dwWaitTime = dwEndTime - dwNow;
2150
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002151 // Don't wait for more than 11 msec to avoid dropping characters,
2152 // check channel while waiting for input and handle a callback from
2153 // 'balloonexpr'.
2154 if (dwWaitTime > 11)
2155 dwWaitTime = 11;
2156
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002157# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002158 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002159 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002160# endif
2161# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002162 // When waiting very briefly don't trigger timers.
2163 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002164 {
2165 long due_time;
2166
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002167 // Trigger timers and then get the time in msec until the next
2168 // one is due. Wait up to that time.
2169 due_time = check_due_timer();
2170 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002171 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002172 // timer may have used feedkeys().
2173 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002174 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002175 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
2176 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002177 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002178# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002179 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002180# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002181 // Wait for either an event on the console input or a
2182 // message in the client-server window.
2183 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
2184 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002185# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002186 wait_for_single_object(g_hConIn, dwWaitTime)
2187 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002188# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002189 )
2190 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002191 }
2192
2193 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002194 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002195
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002196# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02002197 // May have to redraw if the cursor ends up in the wrong place.
2198 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01002199 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002200 {
2201 CONSOLE_SCREEN_BUFFER_INFO csbi;
2202
2203 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2204 {
2205 if (csbi.dwCursorPosition.Y != msg_row)
2206 {
matveyte08795e2021-05-07 15:00:17 +02002207 // The screen is now messed up, must redraw the command
2208 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002209 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02002210 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002211 redrawcmd();
2212 }
2213 }
2214 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002215# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002216
2217 if (cRecords > 0)
2218 {
2219 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
2220 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002221# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01002222 // Windows IME sends two '\n's with only one 'ENTER'. First:
2223 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00002224 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002225 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
2226 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002227 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002228 continue;
2229 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002230# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002231 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
2232 NULL, FALSE))
2233 return TRUE;
2234 }
2235
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002236 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002237
2238 if (ir.EventType == FOCUS_EVENT)
2239 handle_focus_event(ir);
2240 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002241 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002242 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
2243
Bram Moolenaar36698e32019-12-11 22:57:40 +01002244 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002245 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002246 if (dwSize.X != Columns || dwSize.Y != Rows)
2247 {
2248 CONSOLE_SCREEN_BUFFER_INFO csbi;
2249 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01002250 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002251 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01002252 if (dwSize.X != Columns || dwSize.Y != Rows)
2253 {
2254 ResizeConBuf(g_hConOut, dwSize);
2255 shell_resized();
2256 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002257 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002258 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002259 else if (ir.EventType == MOUSE_EVENT
2260 && decode_mouse_event(&ir.Event.MouseEvent))
2261 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002262 }
2263 else if (msec == 0)
2264 break;
2265 }
2266
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002267# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01002268 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002269 if (input_available())
2270 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002271# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002272
Bram Moolenaar071d4272004-06-13 20:20:40 +00002273 return FALSE;
2274}
2275
Bram Moolenaar071d4272004-06-13 20:20:40 +00002276/*
2277 * return non-zero if a character is available
2278 */
2279 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002280mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002281{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002282# ifdef VIMDLL
2283 if (gui.in_use)
2284 return TRUE;
2285# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002286 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002287}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002288
2289# if defined(FEAT_TERMINAL) || defined(PROTO)
2290/*
2291 * Check for any pending input or messages.
2292 */
2293 int
2294mch_check_messages(void)
2295{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002296# ifdef VIMDLL
2297 if (gui.in_use)
2298 return TRUE;
2299# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002300 return WaitForChar(0L, TRUE);
2301}
2302# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002303
2304/*
2305 * Create the console input. Used when reading stdin doesn't work.
2306 */
2307 static void
2308create_conin(void)
2309{
2310 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
2311 FILE_SHARE_READ|FILE_SHARE_WRITE,
2312 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002313 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002314 did_create_conin = TRUE;
2315}
2316
2317/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002318 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002319 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002320 static WCHAR
2321tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002322{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002323 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002324
2325 for (;;)
2326 {
2327 INPUT_RECORD ir;
2328 DWORD cRecords = 0;
2329
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002330# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002331 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002332 if (input_available())
2333 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002334 if (g_nMouseClick != -1)
2335 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002336# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002337 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002338 {
2339 if (did_create_conin)
2340 read_error_exit();
2341 create_conin();
2342 continue;
2343 }
2344
2345 if (ir.EventType == KEY_EVENT)
2346 {
2347 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
2348 pmodifiers, TRUE))
2349 return ch;
2350 }
2351 else if (ir.EventType == FOCUS_EVENT)
2352 handle_focus_event(ir);
2353 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
2354 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002355 else if (ir.EventType == MOUSE_EVENT)
2356 {
2357 if (decode_mouse_event(&ir.Event.MouseEvent))
2358 return 0;
2359 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002360 }
2361}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002362#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002363
2364
2365/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02002366 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002367 * Get one or more characters from the keyboard or the mouse.
2368 * If time == 0, do not wait for characters.
2369 * If time == n, wait a short time for characters.
2370 * If time == -1, wait forever for characters.
2371 * Returns the number of characters read into buf.
2372 */
2373 int
2374mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002375 char_u *buf UNUSED,
2376 int maxlen UNUSED,
2377 long time UNUSED,
2378 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002379{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002380#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002381
2382 int len;
2383 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002384# ifdef VIMDLL
2385// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
2386# define TYPEAHEADSPACE 6
2387# else
2388# define TYPEAHEADSPACE 0
2389# endif
2390# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002391 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002392 static int typeaheadlen = 0;
2393
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002394# ifdef VIMDLL
2395 if (gui.in_use)
2396 return 0;
2397# endif
2398
Bram Moolenaar0f873732019-12-05 20:28:46 +01002399 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002400 if (typeaheadlen > 0)
2401 goto theend;
2402
Bram Moolenaar071d4272004-06-13 20:20:40 +00002403 if (time >= 0)
2404 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002405 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00002406 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002407 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01002408 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00002409 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002410 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00002411
Bram Moolenaar3918c952005-03-15 22:34:55 +00002412 /*
2413 * If there is no character available within 2 seconds (default)
2414 * write the autoscript file to disk. Or cause the CursorHold event
2415 * to be triggered.
2416 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002417 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002418 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00002419 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002420 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00002421 buf[0] = K_SPECIAL;
2422 buf[1] = KS_EXTRA;
2423 buf[2] = (int)KE_CURSORHOLD;
2424 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002425 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00002426 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002427 }
2428 }
2429
2430 /*
2431 * Try to read as many characters as there are, until the buffer is full.
2432 */
2433
Bram Moolenaar0f873732019-12-05 20:28:46 +01002434 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002435 g_fCBrkPressed = FALSE;
2436
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002437# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002438 if (fdDump)
2439 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002440# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002441
Bram Moolenaar0f873732019-12-05 20:28:46 +01002442 // Keep looping until there is something in the typeahead buffer and more
2443 // to get and still room in the buffer (up to two bytes for a char and
2444 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002445 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01002446 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002447 {
2448 if (typebuf_changed(tb_change_cnt))
2449 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002450 // "buf" may be invalid now if a client put something in the
2451 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002452 typeaheadlen = 0;
2453 break;
2454 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002455 if (g_nMouseClick != -1)
2456 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002457# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002458 if (fdDump)
2459 fprintf(fdDump, "{%02x @ %d, %d}",
2460 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002461# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01002462 char_u modifiers = ((char_u *)(&g_nMouseClick))[0];
2463 char_u scroll_dir = ((char_u *)(&g_nMouseClick))[1];
2464
2465 if (scroll_dir == KE_MOUSEDOWN
2466 || scroll_dir == KE_MOUSEUP
2467 || scroll_dir == KE_MOUSELEFT
2468 || scroll_dir == KE_MOUSERIGHT)
2469 {
2470 if (modifiers > 0)
2471 {
Christopher Plewright03193062022-11-22 12:58:27 +00002472 // use K_SPECIAL instead of CSI to make mappings work
2473 typeahead[typeaheadlen++] = K_SPECIAL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002474 typeahead[typeaheadlen++] = KS_MODIFIER;
2475 typeahead[typeaheadlen++] = modifiers;
2476 }
2477 typeahead[typeaheadlen++] = CSI;
2478 typeahead[typeaheadlen++] = KS_EXTRA;
2479 typeahead[typeaheadlen++] = scroll_dir;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002480 }
2481 else
2482 {
2483 typeahead[typeaheadlen++] = ESC + 128;
2484 typeahead[typeaheadlen++] = 'M';
2485 typeahead[typeaheadlen++] = g_nMouseClick;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002486 }
Christopher Plewright36446bb2022-11-23 22:28:08 +00002487
2488 // Pass the pointer coordinates of the mouse event in 2 bytes,
2489 // allowing for > 223 columns. Both for click and scroll events.
2490 // This is the same as what is used for the GUI.
2491 typeahead[typeaheadlen++] = (char_u)(g_xMouse / 128 + ' ' + 1);
2492 typeahead[typeaheadlen++] = (char_u)(g_xMouse % 128 + ' ' + 1);
2493 typeahead[typeaheadlen++] = (char_u)(g_yMouse / 128 + ' ' + 1);
2494 typeahead[typeaheadlen++] = (char_u)(g_yMouse % 128 + ' ' + 1);
2495
2496 g_nMouseClick = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002497 }
2498 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002499 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002500 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002501 int modifiers = 0;
2502
2503 c = tgetch(&modifiers, &ch2);
2504
Christopher Plewrightc8b20492023-01-04 18:06:00 +00002505 c = simplify_key(c, &modifiers);
2506
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002507 // Some chars need adjustment when the Ctrl modifier is used.
2508 ++no_reduce_keys;
2509 c = may_adjust_key_for_ctrl(modifiers, c);
2510 --no_reduce_keys;
2511
2512 // remove the SHIFT modifier for keys where it's already included,
2513 // e.g., '(' and '*'
2514 modifiers = may_remove_shift_modifier(modifiers, c);
2515
Bram Moolenaar071d4272004-06-13 20:20:40 +00002516 if (typebuf_changed(tb_change_cnt))
2517 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002518 // "buf" may be invalid now if a client put something in the
2519 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002520 typeaheadlen = 0;
2521 break;
2522 }
2523
2524 if (c == Ctrl_C && ctrl_c_interrupts)
2525 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002526# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002527 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002528# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002529 got_int = TRUE;
2530 }
2531
Bram Moolenaar071d4272004-06-13 20:20:40 +00002532 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002533 {
2534 int n = 1;
2535
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002536 if (ch2 == NUL)
2537 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002538 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002539 char_u *p;
2540 WCHAR ch[2];
2541
2542 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002543 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002544 {
2545 ch[1] = tgetch(&modifiers, &ch2);
2546 n++;
2547 }
2548 p = utf16_to_enc(ch, &n);
2549 if (p != NULL)
2550 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002551 for (i = 0, j = 0; i < n; i++)
2552 {
2553 typeahead[typeaheadlen + j++] = p[i];
2554# ifdef VIMDLL
2555 if (p[i] == CSI)
2556 {
2557 typeahead[typeaheadlen + j++] = KS_EXTRA;
2558 typeahead[typeaheadlen + j++] = KE_CSI;
2559 }
2560# endif
2561 }
2562 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002563 vim_free(p);
2564 }
2565 }
2566 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002567 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002568 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002569# ifdef VIMDLL
2570 if (c == CSI)
2571 {
2572 typeahead[typeaheadlen + 1] = KS_EXTRA;
2573 typeahead[typeaheadlen + 2] = KE_CSI;
2574 n = 3;
2575 }
2576# endif
2577 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002578 if (ch2 != NUL)
2579 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002580 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002581 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002582 switch (ch2)
2583 {
2584 case (WCHAR)'\324': // SHIFT+Insert
2585 case (WCHAR)'\325': // CTRL+Insert
2586 case (WCHAR)'\327': // SHIFT+Delete
2587 case (WCHAR)'\330': // CTRL+Delete
2588 typeahead[typeaheadlen + n] = (char_u)ch2;
2589 n++;
2590 break;
2591
2592 default:
2593 typeahead[typeaheadlen + n] = 3;
2594 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2595 n += 2;
2596 break;
2597 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002598 }
2599 else
2600 {
2601 typeahead[typeaheadlen + n] = 3;
2602 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2603 n += 2;
2604 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002605 }
2606
Bram Moolenaar0f873732019-12-05 20:28:46 +01002607 // Use the ALT key to set the 8th bit of the character
2608 // when it's one byte, the 8th bit isn't set yet and not
2609 // using a double-byte encoding (would become a lead
2610 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002611 if ((modifiers & MOD_MASK_ALT)
2612 && n == 1
2613 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002614 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002615 )
2616 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002617 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2618 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002619 modifiers &= ~MOD_MASK_ALT;
2620 }
2621
2622 if (modifiers != 0)
2623 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002624 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002625 mch_memmove(typeahead + typeaheadlen + 3,
2626 typeahead + typeaheadlen, n);
2627 typeahead[typeaheadlen++] = K_SPECIAL;
2628 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2629 typeahead[typeaheadlen++] = modifiers;
2630 }
2631
2632 typeaheadlen += n;
2633
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002634# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002635 if (fdDump)
2636 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002637# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002638 }
2639 }
2640 }
2641
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002642# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002643 if (fdDump)
2644 {
2645 fputs("]\n", fdDump);
2646 fflush(fdDump);
2647 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002648# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002649
Bram Moolenaar071d4272004-06-13 20:20:40 +00002650theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002651 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002652 len = 0;
2653 while (len < maxlen && typeaheadlen > 0)
2654 {
2655 buf[len++] = typeahead[0];
2656 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2657 }
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00002658# ifdef FEAT_EVAL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002659 if (len > 0)
2660 {
2661 buf[len] = NUL;
2662 ch_log(NULL, "raw key input: \"%s\"", buf);
2663 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002664# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002665 return len;
2666
Bram Moolenaar0f873732019-12-05 20:28:46 +01002667#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002668 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002669#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002670}
2671
Bram Moolenaar82881492012-11-20 16:53:39 +01002672#ifndef PROTO
2673# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002674# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002675# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002676#endif
2677
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002678/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002679 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002680 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2681 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002682 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002683 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002684 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002685executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002686{
LemonBoy40fd7e62022-05-05 20:18:16 +01002687 int attrs = win32_getattrs((char_u *)name);
2688
2689 // The file doesn't exist or is a folder.
2690 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2691 return FALSE;
2692 // Check if the file is an AppExecLink, a special alias used by Windows
2693 // Store for its apps.
2694 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002695 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002696 char_u *res = resolve_appexeclink((char_u *)name);
2697 if (res == NULL)
2698 return FALSE;
2699 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002700 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002701 *path = res;
2702 else
2703 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002704 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002705 else if (path != NULL)
2706 *path = FullName_save((char_u *)name, FALSE);
2707 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002708}
2709
2710/*
2711 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2712 * If "use_path" is FALSE: Return TRUE if "name" exists.
2713 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2714 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2715 * the allocated memory.
2716 */
2717 static int
2718executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2719{
2720 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2721 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2722 // UTF-8.
2723 char_u buf[_MAX_PATH * 3];
2724 size_t len = STRLEN(name);
2725 size_t tmplen;
2726 char_u *p, *e, *e2;
2727 char_u *pathbuf = NULL;
2728 char_u *pathext = NULL;
2729 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002730 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002731 int noext = FALSE;
2732 int retval = FALSE;
2733
2734 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002735 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002736
2737 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002738 shname = gettail(p_sh);
2739 if (strstr((char *)shname, "sh") != NULL &&
2740 !(strstr((char *)shname, "powershell") != NULL
2741 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002742 noext = TRUE;
2743
2744 if (use_pathext)
2745 {
2746 pathext = mch_getenv("PATHEXT");
2747 if (pathext == NULL)
2748 pathext = (char_u *)".com;.exe;.bat;.cmd";
2749
2750 if (noext == FALSE)
2751 {
2752 /*
2753 * Loop over all extensions in $PATHEXT.
2754 * Check "name" ends with extension.
2755 */
2756 p = pathext;
2757 while (*p)
2758 {
2759 if (p[0] == ';'
2760 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2761 {
2762 // Skip empty or single ".".
2763 ++p;
2764 continue;
2765 }
2766 e = vim_strchr(p, ';');
2767 if (e == NULL)
2768 e = p + STRLEN(p);
2769 tmplen = e - p;
2770
2771 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2772 {
2773 noext = TRUE;
2774 break;
2775 }
2776
2777 p = e;
2778 }
2779 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002780 }
2781
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002782 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002783 if (pathext == NULL)
2784 pathext = (char_u *)".";
2785 else if (noext == TRUE)
2786 {
2787 if (pathextbuf == NULL)
2788 pathextbuf = alloc(STRLEN(pathext) + 3);
2789 if (pathextbuf == NULL)
2790 {
2791 retval = FALSE;
2792 goto theend;
2793 }
2794 STRCPY(pathextbuf, ".;");
2795 STRCAT(pathextbuf, pathext);
2796 pathext = pathextbuf;
2797 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002798
Bram Moolenaar95da1362020-05-30 18:37:55 +02002799 // Use $PATH when "use_path" is TRUE and "name" is basename.
2800 if (use_path && gettail((char_u *)name) == (char_u *)name)
2801 {
2802 p = mch_getenv("PATH");
2803 if (p != NULL)
2804 {
2805 pathbuf = alloc(STRLEN(p) + 3);
2806 if (pathbuf == NULL)
2807 {
2808 retval = FALSE;
2809 goto theend;
2810 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002811
2812 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2813 STRCPY(pathbuf, ".;");
2814 else
2815 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002816 STRCAT(pathbuf, p);
2817 }
2818 }
2819
2820 /*
2821 * Walk through all entries in $PATH to check if "name" exists there and
2822 * is an executable file.
2823 */
2824 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2825 while (*p)
2826 {
2827 if (*p == ';') // Skip empty entry
2828 {
2829 ++p;
2830 continue;
2831 }
2832 e = vim_strchr(p, ';');
2833 if (e == NULL)
2834 e = p + STRLEN(p);
2835
2836 if (e - p + len + 2 > sizeof(buf))
2837 {
2838 retval = FALSE;
2839 goto theend;
2840 }
2841 // A single "." that means current dir.
2842 if (e - p == 1 && *p == '.')
2843 STRCPY(buf, name);
2844 else
2845 {
2846 vim_strncpy(buf, p, e - p);
2847 add_pathsep(buf);
2848 STRCAT(buf, name);
2849 }
2850 tmplen = STRLEN(buf);
2851
2852 /*
2853 * Loop over all extensions in $PATHEXT.
2854 * Check "name" with extension added.
2855 */
2856 p = pathext;
2857 while (*p)
2858 {
2859 if (*p == ';')
2860 {
2861 // Skip empty entry
2862 ++p;
2863 continue;
2864 }
2865 e2 = vim_strchr(p, (int)';');
2866 if (e2 == NULL)
2867 e2 = p + STRLEN(p);
2868
2869 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2870 {
2871 // Not a single "." that means no extension is added.
2872 if (e2 - p + tmplen + 1 > sizeof(buf))
2873 {
2874 retval = FALSE;
2875 goto theend;
2876 }
2877 vim_strncpy(buf + tmplen, p, e2 - p);
2878 }
2879 if (executable_file((char *)buf, path))
2880 {
2881 retval = TRUE;
2882 goto theend;
2883 }
2884
2885 p = e2;
2886 }
2887
2888 p = e;
2889 }
2890
2891theend:
2892 free(pathextbuf);
2893 free(pathbuf);
2894 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002895}
2896
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002897#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2898 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002899/*
2900 * Bad parameter handler.
2901 *
2902 * Certain MS CRT functions will intentionally crash when passed invalid
2903 * parameters to highlight possible security holes. Setting this function as
2904 * the bad parameter handler will prevent the crash.
2905 *
2906 * In debug builds the parameters contain CRT information that might help track
2907 * down the source of a problem, but in non-debug builds the arguments are all
2908 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2909 * worth allowing these to make debugging of issues easier.
2910 */
2911 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002912bad_param_handler(const wchar_t *expression UNUSED,
2913 const wchar_t *function UNUSED,
2914 const wchar_t *file UNUSED,
2915 unsigned int line UNUSED,
2916 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002917{
2918}
2919
2920# define SET_INVALID_PARAM_HANDLER \
2921 ((void)_set_invalid_parameter_handler(bad_param_handler))
2922#else
2923# define SET_INVALID_PARAM_HANDLER
2924#endif
2925
Bram Moolenaar4f974752019-02-17 17:44:42 +01002926#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002927
2928/*
2929 * GUI version of mch_init().
2930 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002931 static void
2932mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002933{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002934# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002935 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002936# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002937
Bram Moolenaar0f873732019-12-05 20:28:46 +01002938 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002939 SET_INVALID_PARAM_HANDLER;
2940
Bram Moolenaar0f873732019-12-05 20:28:46 +01002941 // Let critical errors result in a failure, not in a dialog box. Required
2942 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002943 SetErrorMode(SEM_FAILCRITICALERRORS);
2944
Bram Moolenaar0f873732019-12-05 20:28:46 +01002945 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002946
Bram Moolenaar0f873732019-12-05 20:28:46 +01002947 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002948 Rows = 25;
2949 Columns = 80;
2950
Bram Moolenaar0f873732019-12-05 20:28:46 +01002951 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002952 {
2953 char_u vimrun_location[_MAX_PATH + 4];
2954
Bram Moolenaar0f873732019-12-05 20:28:46 +01002955 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002956 STRCPY(vimrun_location, exe_name);
2957 STRCPY(gettail(vimrun_location), "vimrun.exe");
2958 if (mch_getperm(vimrun_location) >= 0)
2959 {
2960 if (*skiptowhite(vimrun_location) != NUL)
2961 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002962 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002963 mch_memmove(vimrun_location + 1, vimrun_location,
2964 STRLEN(vimrun_location) + 1);
2965 *vimrun_location = '"';
2966 STRCPY(gettail(vimrun_location), "vimrun\" ");
2967 }
2968 else
2969 STRCPY(gettail(vimrun_location), "vimrun ");
2970
2971 vimrun_path = (char *)vim_strsave(vimrun_location);
2972 s_dont_use_vimrun = FALSE;
2973 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002974 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002975 s_dont_use_vimrun = FALSE;
2976
Bram Moolenaar0f873732019-12-05 20:28:46 +01002977 // Don't give the warning for a missing vimrun.exe right now, but only
2978 // when vimrun was supposed to be used. Don't bother people that do
2979 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002980 if (s_dont_use_vimrun)
2981 need_vimrun_warning = TRUE;
2982 }
2983
2984 /*
2985 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2986 * Otherwise the default "findstr /n" is used.
2987 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002988 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01002989 set_option_value_give_err((char_u *)"grepprg",
2990 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002991
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002992# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002993 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002994# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002995
2996 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002997}
2998
2999
Bram Moolenaar0f873732019-12-05 20:28:46 +01003000#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003001
3002#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003003
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003004# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
3005# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003006
3007/*
3008 * ClearConsoleBuffer()
3009 * Description:
3010 * Clears the entire contents of the console screen buffer, using the
3011 * specified attribute.
3012 * Returns:
3013 * TRUE on success
3014 */
3015 static BOOL
3016ClearConsoleBuffer(WORD wAttribute)
3017{
3018 CONSOLE_SCREEN_BUFFER_INFO csbi;
3019 COORD coord;
3020 DWORD NumCells, dummy;
3021
3022 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3023 return FALSE;
3024
3025 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
3026 coord.X = 0;
3027 coord.Y = 0;
3028 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
3029 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003030 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003031 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
3032 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003033 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003034
3035 return TRUE;
3036}
3037
3038/*
3039 * FitConsoleWindow()
3040 * Description:
3041 * Checks if the console window will fit within given buffer dimensions.
3042 * Also, if requested, will shrink the window to fit.
3043 * Returns:
3044 * TRUE on success
3045 */
3046 static BOOL
3047FitConsoleWindow(
3048 COORD dwBufferSize,
3049 BOOL WantAdjust)
3050{
3051 CONSOLE_SCREEN_BUFFER_INFO csbi;
3052 COORD dwWindowSize;
3053 BOOL NeedAdjust = FALSE;
3054
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003055 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3056 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003057
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003058 /*
3059 * A buffer resize will fail if the current console window does
3060 * not lie completely within that buffer. To avoid this, we might
3061 * have to move and possibly shrink the window.
3062 */
3063 if (csbi.srWindow.Right >= dwBufferSize.X)
3064 {
3065 dwWindowSize.X = SRWIDTH(csbi.srWindow);
3066 if (dwWindowSize.X > dwBufferSize.X)
3067 dwWindowSize.X = dwBufferSize.X;
3068 csbi.srWindow.Right = dwBufferSize.X - 1;
3069 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
3070 NeedAdjust = TRUE;
3071 }
3072 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
3073 {
3074 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
3075 if (dwWindowSize.Y > dwBufferSize.Y)
3076 dwWindowSize.Y = dwBufferSize.Y;
3077 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
3078 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
3079 NeedAdjust = TRUE;
3080 }
3081 if (NeedAdjust && WantAdjust)
3082 {
3083 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
3084 return FALSE;
3085 }
3086 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003087}
3088
3089typedef struct ConsoleBufferStruct
3090{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003091 BOOL IsValid;
3092 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003093 PCHAR_INFO Buffer;
3094 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003095 PSMALL_RECT Regions;
3096 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003097} ConsoleBuffer;
3098
3099/*
3100 * SaveConsoleBuffer()
3101 * Description:
3102 * Saves important information about the console buffer, including the
3103 * actual buffer contents. The saved information is suitable for later
3104 * restoration by RestoreConsoleBuffer().
3105 * Returns:
3106 * TRUE if all information was saved; FALSE otherwise
3107 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
3108 */
3109 static BOOL
3110SaveConsoleBuffer(
3111 ConsoleBuffer *cb)
3112{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003113 DWORD NumCells;
3114 COORD BufferCoord;
3115 SMALL_RECT ReadRegion;
3116 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003117 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003118
Bram Moolenaar071d4272004-06-13 20:20:40 +00003119 if (cb == NULL)
3120 return FALSE;
3121
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003122 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003123 {
3124 cb->IsValid = FALSE;
3125 return FALSE;
3126 }
3127 cb->IsValid = TRUE;
3128
Christopher Plewright1140b512022-11-12 18:46:05 +00003129 // VTP uses alternate screen buffer.
3130 // No need to save buffer contents for restoration.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003131 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003132 return TRUE;
3133
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003134 /*
3135 * Allocate a buffer large enough to hold the entire console screen
3136 * buffer. If this ConsoleBuffer structure has already been initialized
3137 * with a buffer of the correct size, then just use that one.
3138 */
3139 if (!cb->IsValid || cb->Buffer == NULL ||
3140 cb->BufferSize.X != cb->Info.dwSize.X ||
3141 cb->BufferSize.Y != cb->Info.dwSize.Y)
3142 {
3143 cb->BufferSize.X = cb->Info.dwSize.X;
3144 cb->BufferSize.Y = cb->Info.dwSize.Y;
3145 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
3146 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003147 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003148 if (cb->Buffer == NULL)
3149 return FALSE;
3150 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003151
3152 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003153 * We will now copy the console screen buffer into our buffer.
3154 * ReadConsoleOutput() seems to be limited as far as how much you
3155 * can read at a time. Empirically, this number seems to be about
3156 * 12000 cells (rows * columns). Start at position (0, 0) and copy
3157 * in chunks until it is all copied. The chunks will all have the
3158 * same horizontal characteristics, so initialize them now. The
3159 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003160 */
Bram Moolenaar61594242015-09-01 20:23:37 +02003161 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003162 ReadRegion.Left = 0;
3163 ReadRegion.Right = cb->Info.dwSize.X - 1;
3164 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003165
3166 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
3167 if (cb->Regions == NULL || numregions != cb->NumRegions)
3168 {
3169 cb->NumRegions = numregions;
3170 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003171 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003172 if (cb->Regions == NULL)
3173 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003174 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003175 return FALSE;
3176 }
3177 }
3178
3179 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003180 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003181 /*
3182 * Read into position (0, Y) in our buffer.
3183 */
3184 BufferCoord.Y = Y;
3185 /*
3186 * Read the region whose top left corner is (0, Y) and whose bottom
3187 * right corner is (width - 1, Y + Y_incr - 1). This should define
3188 * a region of size width by Y_incr. Don't worry if this region is
3189 * too large for the remaining buffer; it will be cropped.
3190 */
3191 ReadRegion.Top = Y;
3192 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003193 if (!ReadConsoleOutputW(g_hConOut, // output handle
3194 cb->Buffer, // our buffer
3195 cb->BufferSize, // dimensions of our buffer
3196 BufferCoord, // offset in our buffer
3197 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003198 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003199 VIM_CLEAR(cb->Buffer);
3200 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003201 return FALSE;
3202 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02003203 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003204 }
3205
3206 return TRUE;
3207}
3208
3209/*
3210 * RestoreConsoleBuffer()
3211 * Description:
3212 * Restores important information about the console buffer, including the
3213 * actual buffer contents, if desired. The information to restore is in
3214 * the same format used by SaveConsoleBuffer().
3215 * Returns:
3216 * TRUE on success
3217 */
3218 static BOOL
3219RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003220 ConsoleBuffer *cb,
3221 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003222{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003223 COORD BufferCoord;
3224 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003225 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003226
Christopher Plewright1140b512022-11-12 18:46:05 +00003227 // VTP uses alternate screen buffer.
3228 // No need to restore buffer contents.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003229 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003230 return TRUE;
3231
Bram Moolenaar071d4272004-06-13 20:20:40 +00003232 if (cb == NULL || !cb->IsValid)
3233 return FALSE;
3234
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003235 /*
3236 * Before restoring the buffer contents, clear the current buffer, and
3237 * restore the cursor position and window information. Doing this now
3238 * prevents old buffer contents from "flashing" onto the screen.
3239 */
3240 if (RestoreScreen)
3241 ClearConsoleBuffer(cb->Info.wAttributes);
3242
3243 FitConsoleWindow(cb->Info.dwSize, TRUE);
3244 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
3245 return FALSE;
3246 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
3247 return FALSE;
3248
3249 if (!RestoreScreen)
3250 {
3251 /*
3252 * No need to restore the screen buffer contents, so we're done.
3253 */
3254 return TRUE;
3255 }
3256
3257 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
3258 return FALSE;
3259 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
3260 return FALSE;
3261
3262 /*
3263 * Restore the screen buffer contents.
3264 */
3265 if (cb->Buffer != NULL)
3266 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003267 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003268 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003269 BufferCoord.X = cb->Regions[i].Left;
3270 BufferCoord.Y = cb->Regions[i].Top;
3271 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01003272 if (!WriteConsoleOutputW(g_hConOut, // output handle
3273 cb->Buffer, // our buffer
3274 cb->BufferSize, // dimensions of our buffer
3275 BufferCoord, // offset in our buffer
3276 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02003277 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003278 }
3279 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003280
3281 return TRUE;
3282}
3283
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003284# define FEAT_RESTORE_ORIG_SCREEN
3285# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003286static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003287# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003288static ConsoleBuffer g_cbNonTermcap = { 0 };
3289static ConsoleBuffer g_cbTermcap = { 0 };
3290
Bram Moolenaar071d4272004-06-13 20:20:40 +00003291char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01003292HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00003293static HICON g_hOrigIconSmall = NULL;
3294static HICON g_hOrigIcon = NULL;
3295static HICON g_hVimIcon = NULL;
3296static BOOL g_fCanChangeIcon = FALSE;
3297
Bram Moolenaar071d4272004-06-13 20:20:40 +00003298/*
3299 * GetConsoleIcon()
3300 * Description:
3301 * Attempts to retrieve the small icon and/or the big icon currently in
3302 * use by a given window.
3303 * Returns:
3304 * TRUE on success
3305 */
3306 static BOOL
3307GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003308 HWND hWnd,
3309 HICON *phIconSmall,
3310 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003311{
3312 if (hWnd == NULL)
3313 return FALSE;
3314
3315 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003316 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
3317 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003318 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003319 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
3320 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003321 return TRUE;
3322}
3323
3324/*
3325 * SetConsoleIcon()
3326 * Description:
3327 * Attempts to change the small icon and/or the big icon currently in
3328 * use by a given window.
3329 * Returns:
3330 * TRUE on success
3331 */
3332 static BOOL
3333SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003334 HWND hWnd,
3335 HICON hIconSmall,
3336 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003337{
Bram Moolenaar071d4272004-06-13 20:20:40 +00003338 if (hWnd == NULL)
3339 return FALSE;
3340
3341 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003342 SendMessage(hWnd, WM_SETICON,
3343 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003344 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003345 SendMessage(hWnd, WM_SETICON,
3346 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003347 return TRUE;
3348}
3349
3350/*
3351 * SaveConsoleTitleAndIcon()
3352 * Description:
3353 * Saves the current console window title in g_szOrigTitle, for later
3354 * restoration. Also, attempts to obtain a handle to the console window,
3355 * and use it to save the small and big icons currently in use by the
3356 * console window. This is not always possible on some versions of Windows;
3357 * nor is it possible when running Vim remotely using Telnet (since the
3358 * console window the user sees is owned by a remote process).
3359 */
3360 static void
3361SaveConsoleTitleAndIcon(void)
3362{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003363 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003364 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
3365 return;
3366
3367 /*
3368 * Obtain a handle to the console window using GetConsoleWindow() from
3369 * KERNEL32.DLL; we need to handle in order to change the window icon.
3370 * This function only exists on NT-based Windows, starting with Windows
3371 * 2000. On older operating systems, we can't change the window icon
3372 * anyway.
3373 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003374 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003375 if (g_hWnd == NULL)
3376 return;
3377
Bram Moolenaar0f873732019-12-05 20:28:46 +01003378 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003379 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
3380 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
3381 return;
3382
Bram Moolenaar0f873732019-12-05 20:28:46 +01003383 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01003384 if (
3385# ifdef FEAT_LIBCALL
3386 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
3387# endif
3388 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003389 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003390 if (g_hVimIcon != NULL)
3391 g_fCanChangeIcon = TRUE;
3392}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003393
3394static int g_fWindInitCalled = FALSE;
3395static int g_fTermcapMode = FALSE;
3396static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003397
3398/*
3399 * non-GUI version of mch_init().
3400 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003401 static void
3402mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003403{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003404# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003405 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003406# endif
3407# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00003408 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003409# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003410
Bram Moolenaar0f873732019-12-05 20:28:46 +01003411 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02003412 SET_INVALID_PARAM_HANDLER;
3413
Bram Moolenaar0f873732019-12-05 20:28:46 +01003414 // Let critical errors result in a failure, not in a dialog box. Required
3415 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003416 SetErrorMode(SEM_FAILCRITICALERRORS);
3417
Bram Moolenaar0f873732019-12-05 20:28:46 +01003418 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00003419 out_flush();
3420
Bram Moolenaar0f873732019-12-05 20:28:46 +01003421 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00003422 if (read_cmd_fd == 0)
3423 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
3424 else
3425 create_conin();
3426 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
3427
Christopher Plewright38804d62022-11-09 23:55:52 +00003428 wt_init();
3429 vtp_flag_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003430# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01003431 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003432 SaveConsoleBuffer(&g_cbOrig);
3433 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003434# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01003435 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003436 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
3437 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003438# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003439 if (cterm_normal_fg_color == 0)
3440 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
3441 if (cterm_normal_bg_color == 0)
3442 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
3443
Bram Moolenaarbdace832019-03-02 10:13:42 +01003444 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02003445 g_color_index_fg = g_attrDefault & 0xf;
3446 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
3447
Bram Moolenaar0f873732019-12-05 20:28:46 +01003448 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00003449 update_tcap(g_attrCurrent);
3450
3451 GetConsoleCursorInfo(g_hConOut, &g_cci);
3452 GetConsoleMode(g_hConIn, &g_cmodein);
3453 GetConsoleMode(g_hConOut, &g_cmodeout);
3454
Bram Moolenaar071d4272004-06-13 20:20:40 +00003455 SaveConsoleTitleAndIcon();
3456 /*
3457 * Set both the small and big icons of the console window to Vim's icon.
3458 * Note that Vim presently only has one size of icon (32x32), but it
3459 * automatically gets scaled down to 16x16 when setting the small icon.
3460 */
3461 if (g_fCanChangeIcon)
3462 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003463
3464 ui_get_shellsize();
3465
Christopher Plewrightd343c602023-01-22 18:58:30 +00003466 vtp_init();
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00003467 // Switch to a new alternate screen buffer.
3468 if (use_alternate_screen_buffer)
3469 vtp_printf("\033[?1049h");
Christopher Plewrightd343c602023-01-22 18:58:30 +00003470
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003471# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003472 fdDump = fopen("dump", "wt");
3473
3474 if (fdDump)
3475 {
3476 time_t t;
3477
3478 time(&t);
3479 fputs(ctime(&t), fdDump);
3480 fflush(fdDump);
3481 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003482# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003483
3484 g_fWindInitCalled = TRUE;
3485
Bram Moolenaar071d4272004-06-13 20:20:40 +00003486 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003487
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003488# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003489 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003490# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003491}
3492
3493/*
3494 * non-GUI version of mch_exit().
3495 * Shut down and exit with status `r'
3496 * Careful: mch_exit() may be called before mch_init()!
3497 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003498 static void
3499mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003500{
Bram Moolenaar955f1982017-02-05 15:10:51 +01003501 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003502
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003503 vtp_exit();
3504
Bram Moolenaar955f1982017-02-05 15:10:51 +01003505 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003506 if (g_fWindInitCalled)
3507 settmode(TMODE_COOK);
3508
Bram Moolenaar0f873732019-12-05 20:28:46 +01003509 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00003510
3511 if (g_fWindInitCalled)
3512 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02003513 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003514 /*
3515 * Restore both the small and big icons of the console window to
3516 * what they were at startup. Don't do this when the window is
3517 * closed, Vim would hang here.
3518 */
3519 if (g_fCanChangeIcon && !g_fForceExit)
3520 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003521
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003522# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003523 if (fdDump)
3524 {
3525 time_t t;
3526
3527 time(&t);
3528 fputs(ctime(&t), fdDump);
3529 fclose(fdDump);
3530 }
3531 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003532# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003533 }
3534
3535 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003536 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003537 SetConsoleMode(g_hConOut, g_cmodeout);
3538
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003539# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003540 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003541# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003542
3543 exit(r);
3544}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003545#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003546
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003547 void
3548mch_init(void)
3549{
3550#ifdef VIMDLL
3551 if (gui.starting)
3552 mch_init_g();
3553 else
3554 mch_init_c();
3555#elif defined(FEAT_GUI_MSWIN)
3556 mch_init_g();
3557#else
3558 mch_init_c();
3559#endif
3560}
3561
3562 void
3563mch_exit(int r)
3564{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003565#ifdef FEAT_NETBEANS_INTG
3566 netbeans_send_disconnect();
3567#endif
3568
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003569#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003570 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003571 mch_exit_g(r);
3572 else
3573 mch_exit_c(r);
3574#elif defined(FEAT_GUI_MSWIN)
3575 mch_exit_g(r);
3576#else
3577 mch_exit_c(r);
3578#endif
3579}
3580
Bram Moolenaar071d4272004-06-13 20:20:40 +00003581/*
3582 * Do we have an interactive window?
3583 */
3584 int
3585mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003586 int argc UNUSED,
3587 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003588{
3589 get_exe_name();
3590
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003591#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003592 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003593#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003594# ifdef VIMDLL
3595 if (gui.in_use)
3596 return OK;
3597# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003598 if (isatty(1))
3599 return OK;
3600 return FAIL;
3601#endif
3602}
3603
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003604/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003605 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003606 * When "len" is > 0, also expand short to long filenames.
3607 */
3608 void
3609fname_case(
3610 char_u *name,
3611 int len)
3612{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003613 int flen;
3614 WCHAR *p;
3615 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003616
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003617 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003618 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003619 return;
3620
3621 slash_adjust(name);
3622
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003623 p = enc_to_utf16(name, NULL);
3624 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003625 return;
3626
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003627 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003628 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003629 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003630
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003631 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003632 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003633 if (len > 0 || flen >= (int)STRLEN(q))
3634 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3635 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003636 }
3637 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003638 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003639}
3640
3641
3642/*
3643 * Insert user name in s[len].
3644 */
3645 int
3646mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003647 char_u *s,
3648 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003649{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003650 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003651 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003652
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003653 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003654 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003655 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003656
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003657 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003658 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003659 vim_strncpy(s, p, len - 1);
3660 vim_free(p);
3661 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003662 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003663 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003664 s[0] = NUL;
3665 return FAIL;
3666}
3667
3668
3669/*
3670 * Insert host name in s[len].
3671 */
3672 void
3673mch_get_host_name(
3674 char_u *s,
3675 int len)
3676{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003677 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003678 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003679
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003680 if (!GetComputerNameW(wszHostName, &wcch))
3681 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003682
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003683 char_u *p = utf16_to_enc(wszHostName, NULL);
3684 if (p == NULL)
3685 return;
3686
3687 vim_strncpy(s, p, len - 1);
3688 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003689}
3690
3691
3692/*
3693 * return process ID
3694 */
3695 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003696mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003697{
3698 return (long)GetCurrentProcessId();
3699}
3700
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003701/*
3702 * return TRUE if process "pid" is still running
3703 */
3704 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003705mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003706{
3707 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3708 DWORD status = 0;
3709 int ret = FALSE;
3710
3711 if (hProcess == NULL)
3712 return FALSE; // might not have access
3713 if (GetExitCodeProcess(hProcess, &status) )
3714 ret = status == STILL_ACTIVE;
3715 CloseHandle(hProcess);
3716 return ret;
3717}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003718
3719/*
3720 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3721 * Return OK for success, FAIL for failure.
3722 */
3723 int
3724mch_dirname(
3725 char_u *buf,
3726 int len)
3727{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003728 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003729
Bram Moolenaar071d4272004-06-13 20:20:40 +00003730 /*
3731 * Originally this was:
3732 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3733 * But the Win32s known bug list says that getcwd() doesn't work
3734 * so use the Win32 system call instead. <Negri>
3735 */
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003736 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) == 0)
3737 return FAIL;
3738
3739 WCHAR wcbuf[_MAX_PATH + 1];
3740 char_u *p = NULL;
3741
3742 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003743 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003744 p = utf16_to_enc(wcbuf, NULL);
3745 if (STRLEN(p) >= (size_t)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003746 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003747 // long path name is too long, fall back to short one
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003748 vim_free(p);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003749 p = NULL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003750 }
3751 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003752 if (p == NULL)
3753 p = utf16_to_enc(wbuf, NULL);
3754
3755 if (p == NULL)
3756 return FAIL;
3757
3758 vim_strncpy(buf, p, len - 1);
3759 vim_free(p);
3760 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003761}
3762
3763/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003764 * Get file permissions for "name".
3765 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003766 */
3767 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003768mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003769{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003770 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003771 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003772
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003773 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003774 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003775}
3776
3777
3778/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003779 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003780 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003781 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003782 */
3783 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003784mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003785{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003786 long n;
3787 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003788
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003789 p = enc_to_utf16(name, NULL);
3790 if (p == NULL)
3791 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003792
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003793 n = _wchmod(p, perm);
3794 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003795 if (n == -1)
3796 return FAIL;
3797
3798 win32_set_archive(name);
3799
3800 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003801}
3802
3803/*
3804 * Set hidden flag for "name".
3805 */
3806 void
3807mch_hide(char_u *name)
3808{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003809 int attrs = win32_getattrs(name);
3810 if (attrs == -1)
3811 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003812
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003813 attrs |= FILE_ATTRIBUTE_HIDDEN;
3814 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003815}
3816
3817/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003818 * Return TRUE if file "name" exists and is hidden.
3819 */
3820 int
3821mch_ishidden(char_u *name)
3822{
3823 int f = win32_getattrs(name);
3824
3825 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003826 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003827
3828 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3829}
3830
3831/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003832 * return TRUE if "name" is a directory
3833 * return FALSE if "name" is not a directory or upon error
3834 */
3835 int
3836mch_isdir(char_u *name)
3837{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003838 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003839
3840 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003841 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003842
3843 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3844}
3845
3846/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003847 * return TRUE if "name" is a directory, NOT a symlink to a directory
3848 * return FALSE if "name" is not a directory
3849 * return FALSE for error
3850 */
3851 int
3852mch_isrealdir(char_u *name)
3853{
3854 return mch_isdir(name) && !mch_is_symbolic_link(name);
3855}
3856
3857/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003858 * Create directory "name".
3859 * Return 0 on success, -1 on error.
3860 */
3861 int
3862mch_mkdir(char_u *name)
3863{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003864 WCHAR *p;
3865 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003866
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003867 p = enc_to_utf16(name, NULL);
3868 if (p == NULL)
3869 return -1;
3870 retval = _wmkdir(p);
3871 vim_free(p);
3872 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003873}
3874
3875/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003876 * Delete directory "name".
3877 * Return 0 on success, -1 on error.
3878 */
3879 int
3880mch_rmdir(char_u *name)
3881{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003882 WCHAR *p;
3883 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003884
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003885 p = enc_to_utf16(name, NULL);
3886 if (p == NULL)
3887 return -1;
3888 retval = _wrmdir(p);
3889 vim_free(p);
3890 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003891}
3892
3893/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003894 * Return TRUE if file "fname" has more than one link.
3895 */
3896 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003897mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003898{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003899 BY_HANDLE_FILE_INFORMATION info;
3900
3901 return win32_fileinfo(fname, &info) == FILEINFO_OK
3902 && info.nNumberOfLinks > 1;
3903}
3904
3905/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003906 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003907 */
3908 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003909mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003910{
3911 HANDLE hFind;
3912 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003913 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003914 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003915 WIN32_FIND_DATAW findDataW;
3916
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003917 wn = enc_to_utf16(name, NULL);
3918 if (wn == NULL)
3919 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003920
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003921 hFind = FindFirstFileW(wn, &findDataW);
3922 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003923 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003924 {
3925 fileFlags = findDataW.dwFileAttributes;
3926 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003927 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003928 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003929
3930 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003931 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3932 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003933 res = TRUE;
3934
3935 return res;
3936}
3937
3938/*
3939 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3940 * link.
3941 */
3942 int
3943mch_is_linked(char_u *fname)
3944{
3945 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3946 return TRUE;
3947 return FALSE;
3948}
3949
3950/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003951 * Get the by-handle-file-information for "fname".
3952 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003953 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003954 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3955 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3956 */
3957 int
3958win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3959{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003960 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003961 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003962 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003963
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003964 wn = enc_to_utf16(fname, NULL);
3965 if (wn == NULL)
3966 return FILEINFO_ENC_FAIL;
3967
3968 hFile = CreateFileW(wn, // file name
3969 GENERIC_READ, // access mode
3970 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3971 NULL, // security descriptor
3972 OPEN_EXISTING, // creation disposition
3973 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3974 NULL); // handle to template file
3975 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003976
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003977 if (hFile == INVALID_HANDLE_VALUE)
3978 return FILEINFO_READ_FAIL;
3979
3980 if (GetFileInformationByHandle(hFile, info) != 0)
3981 res = FILEINFO_OK;
3982 else
3983 res = FILEINFO_INFO_FAIL;
3984 CloseHandle(hFile);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003985
Bram Moolenaar03f48552006-02-28 23:52:23 +00003986 return res;
3987}
3988
3989/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003990 * get file attributes for `name'
3991 * -1 : error
3992 * else FILE_ATTRIBUTE_* defined in winnt.h
3993 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003994 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003995win32_getattrs(char_u *name)
3996{
3997 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003998 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003999
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004000 p = enc_to_utf16(name, NULL);
4001 if (p == NULL)
4002 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004003
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004004 attr = GetFileAttributesW(p);
4005 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004006
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004007 return attr;
4008}
4009
4010/*
4011 * set file attributes for `name' to `attrs'
4012 *
4013 * return -1 for failure, 0 otherwise
4014 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004015 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004016win32_setattrs(char_u *name, int attrs)
4017{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004018 int res;
4019 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004020
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004021 p = enc_to_utf16(name, NULL);
4022 if (p == NULL)
4023 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004024
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004025 res = SetFileAttributesW(p, attrs);
4026 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004027
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004028 return res ? 0 : -1;
4029}
4030
4031/*
4032 * Set archive flag for "name".
4033 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004034 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004035win32_set_archive(char_u *name)
4036{
4037 int attrs = win32_getattrs(name);
4038 if (attrs == -1)
4039 return -1;
4040
4041 attrs |= FILE_ATTRIBUTE_ARCHIVE;
4042 return win32_setattrs(name, attrs);
4043}
4044
4045/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004046 * Return TRUE if file or directory "name" is writable (not readonly).
4047 * Strange semantics of Win32: a readonly directory is writable, but you can't
4048 * delete a file. Let's say this means it is writable.
4049 */
4050 int
4051mch_writable(char_u *name)
4052{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004053 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004054
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004055 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
4056 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004057}
4058
Bram Moolenaar071d4272004-06-13 20:20:40 +00004059/*
Bram Moolenaar43663192017-03-05 14:29:12 +01004060 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01004061 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01004062 * When returning TRUE and "path" is not NULL save the path and set "*path" to
4063 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004064 */
4065 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01004066mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004067{
Bram Moolenaar95da1362020-05-30 18:37:55 +02004068 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004069}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004070
4071/*
4072 * Check what "name" is:
4073 * NODE_NORMAL: file or directory (or doesn't exist)
4074 * NODE_WRITABLE: writable device, socket, fifo, etc.
4075 * NODE_OTHER: non-writable things
4076 */
4077 int
4078mch_nodetype(char_u *name)
4079{
4080 HANDLE hFile;
4081 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004082 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004083
Bram Moolenaar0f873732019-12-05 20:28:46 +01004084 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
4085 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
4086 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00004087 if (STRNCMP(name, "\\\\.\\", 4) == 0)
4088 return NODE_WRITABLE;
4089
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004090 wn = enc_to_utf16(name, NULL);
4091 if (wn == NULL)
4092 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004093
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004094 hFile = CreateFileW(wn, // file name
4095 GENERIC_WRITE, // access mode
4096 0, // share mode
4097 NULL, // security descriptor
4098 OPEN_EXISTING, // creation disposition
4099 0, // file attributes
4100 NULL); // handle to template file
4101 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004102 if (hFile == INVALID_HANDLE_VALUE)
4103 return NODE_NORMAL;
4104
4105 type = GetFileType(hFile);
4106 CloseHandle(hFile);
4107 if (type == FILE_TYPE_CHAR)
4108 return NODE_WRITABLE;
4109 if (type == FILE_TYPE_DISK)
4110 return NODE_NORMAL;
4111 return NODE_OTHER;
4112}
4113
4114#ifdef HAVE_ACL
4115struct my_acl
4116{
4117 PSECURITY_DESCRIPTOR pSecurityDescriptor;
4118 PSID pSidOwner;
4119 PSID pSidGroup;
4120 PACL pDacl;
4121 PACL pSacl;
4122};
4123#endif
4124
4125/*
4126 * Return a pointer to the ACL of file "fname" in allocated memory.
4127 * Return NULL if the ACL is not available for whatever reason.
4128 */
4129 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004130mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004131{
4132#ifndef HAVE_ACL
4133 return (vim_acl_T)NULL;
4134#else
4135 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02004136 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004137
Bram Moolenaarc799fe22019-05-28 23:08:19 +02004138 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004139 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004140 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004141 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02004142
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004143 wn = enc_to_utf16(fname, NULL);
4144 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004145 {
4146 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004147 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004148 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004149
4150 // Try to retrieve the entire security descriptor.
4151 err = GetNamedSecurityInfoW(
4152 wn, // Abstract filename
4153 SE_FILE_OBJECT, // File Object
4154 OWNER_SECURITY_INFORMATION |
4155 GROUP_SECURITY_INFORMATION |
4156 DACL_SECURITY_INFORMATION |
4157 SACL_SECURITY_INFORMATION,
4158 &p->pSidOwner, // Ownership information.
4159 &p->pSidGroup, // Group membership.
4160 &p->pDacl, // Discretionary information.
4161 &p->pSacl, // For auditing purposes.
4162 &p->pSecurityDescriptor);
4163 if (err == ERROR_ACCESS_DENIED ||
4164 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004165 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004166 // Retrieve only DACL.
4167 (void)GetNamedSecurityInfoW(
4168 wn,
4169 SE_FILE_OBJECT,
4170 DACL_SECURITY_INFORMATION,
4171 NULL,
4172 NULL,
4173 &p->pDacl,
4174 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004175 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004176 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004177 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004178 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004179 mch_free_acl((vim_acl_T)p);
4180 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004181 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004182 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004183 }
4184
4185 return (vim_acl_T)p;
4186#endif
4187}
4188
Bram Moolenaar27515922013-06-29 15:36:26 +02004189#ifdef HAVE_ACL
4190/*
4191 * Check if "acl" contains inherited ACE.
4192 */
4193 static BOOL
4194is_acl_inherited(PACL acl)
4195{
4196 DWORD i;
4197 ACL_SIZE_INFORMATION acl_info;
4198 PACCESS_ALLOWED_ACE ace;
4199
4200 acl_info.AceCount = 0;
4201 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
4202 for (i = 0; i < acl_info.AceCount; i++)
4203 {
4204 GetAce(acl, i, (LPVOID *)&ace);
4205 if (ace->Header.AceFlags & INHERITED_ACE)
4206 return TRUE;
4207 }
4208 return FALSE;
4209}
4210#endif
4211
Bram Moolenaar071d4272004-06-13 20:20:40 +00004212/*
4213 * Set the ACL of file "fname" to "acl" (unless it's NULL).
4214 * Errors are ignored.
4215 * This must only be called with "acl" equal to what mch_get_acl() returned.
4216 */
4217 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004218mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004219{
4220#ifdef HAVE_ACL
4221 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02004222 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004223 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004224
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004225 if (p == NULL)
4226 return;
4227
4228 wn = enc_to_utf16(fname, NULL);
4229 if (wn == NULL)
4230 return;
4231
4232 // Set security flags
4233 if (p->pSidOwner)
4234 sec_info |= OWNER_SECURITY_INFORMATION;
4235 if (p->pSidGroup)
4236 sec_info |= GROUP_SECURITY_INFORMATION;
4237 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02004238 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004239 sec_info |= DACL_SECURITY_INFORMATION;
4240 // Do not inherit its parent's DACL.
4241 // If the DACL is inherited, Cygwin permissions would be changed.
4242 if (!is_acl_inherited(p->pDacl))
4243 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02004244 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004245 if (p->pSacl)
4246 sec_info |= SACL_SECURITY_INFORMATION;
4247
4248 (void)SetNamedSecurityInfoW(
4249 wn, // Abstract filename
4250 SE_FILE_OBJECT, // File Object
4251 sec_info,
4252 p->pSidOwner, // Ownership information.
4253 p->pSidGroup, // Group membership.
4254 p->pDacl, // Discretionary information.
4255 p->pSacl // For auditing purposes.
4256 );
4257 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004258#endif
4259}
4260
4261 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004262mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004263{
4264#ifdef HAVE_ACL
4265 struct my_acl *p = (struct my_acl *)acl;
4266
4267 if (p != NULL)
4268 {
4269 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
4270 vim_free(p);
4271 }
4272#endif
4273}
4274
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004275#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004276
4277/*
4278 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
4279 */
4280 static BOOL WINAPI
4281handler_routine(
4282 DWORD dwCtrlType)
4283{
Bram Moolenaar589b1102017-08-12 16:39:05 +02004284 INPUT_RECORD ir;
4285 DWORD out;
4286
Bram Moolenaar071d4272004-06-13 20:20:40 +00004287 switch (dwCtrlType)
4288 {
4289 case CTRL_C_EVENT:
4290 if (ctrl_c_interrupts)
4291 g_fCtrlCPressed = TRUE;
4292 return TRUE;
4293
4294 case CTRL_BREAK_EVENT:
4295 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02004296 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004297 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02004298 ir.EventType = KEY_EVENT;
4299 ir.Event.KeyEvent.bKeyDown = TRUE;
4300 ir.Event.KeyEvent.wRepeatCount = 1;
4301 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
4302 ir.Event.KeyEvent.wVirtualScanCode = 0;
4303 ir.Event.KeyEvent.dwControlKeyState = 0;
4304 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
4305 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004306 return TRUE;
4307
Bram Moolenaar0f873732019-12-05 20:28:46 +01004308 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00004309 case CTRL_CLOSE_EVENT:
4310 case CTRL_LOGOFF_EVENT:
4311 case CTRL_SHUTDOWN_EVENT:
4312 windgoto((int)Rows - 1, 0);
4313 g_fForceExit = TRUE;
4314
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004315 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004316 (dwCtrlType == CTRL_CLOSE_EVENT
4317 ? _("close")
4318 : dwCtrlType == CTRL_LOGOFF_EVENT
4319 ? _("logoff")
4320 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004321# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00004322 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004323# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004324
Bram Moolenaar0f873732019-12-05 20:28:46 +01004325 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00004326
Bram Moolenaar0f873732019-12-05 20:28:46 +01004327 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00004328
4329 default:
4330 return FALSE;
4331 }
4332}
4333
4334
4335/*
4336 * set the tty in (raw) ? "raw" : "cooked" mode
4337 */
4338 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02004339mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004340{
4341 DWORD cmodein;
4342 DWORD cmodeout;
4343 BOOL bEnableHandler;
4344
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004345# ifdef VIMDLL
4346 if (gui.in_use)
4347 return;
4348# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004349 GetConsoleMode(g_hConIn, &cmodein);
4350 GetConsoleMode(g_hConOut, &cmodeout);
4351 if (tmode == TMODE_RAW)
4352 {
4353 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4354 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004355 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004356 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004357 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004358 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
4359 }
4360 else
4361 {
4362 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
4363 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004364 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004365# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01004366 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
4367 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004368 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004369# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004370 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004371# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004372 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004373 bEnableHandler = TRUE;
4374 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004375 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00004376 {
4377 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4378 ENABLE_ECHO_INPUT);
4379 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
4380 bEnableHandler = FALSE;
4381 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004382 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004383 SetConsoleMode(g_hConOut, cmodeout);
4384 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
4385
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004386# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004387 if (fdDump)
4388 {
4389 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
4390 tmode == TMODE_RAW ? "raw" :
4391 tmode == TMODE_COOK ? "cooked" : "normal",
4392 cmodein, cmodeout);
4393 fflush(fdDump);
4394 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004395# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004396}
4397
4398
4399/*
4400 * Get the size of the current window in `Rows' and `Columns'
4401 * Return OK when size could be determined, FAIL otherwise.
4402 */
4403 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004404mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004405{
4406 CONSOLE_SCREEN_BUFFER_INFO csbi;
4407
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004408# ifdef VIMDLL
4409 if (gui.in_use)
4410 return OK;
4411# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004412 if (!g_fTermcapMode && g_cbTermcap.IsValid)
4413 {
4414 /*
4415 * For some reason, we are trying to get the screen dimensions
4416 * even though we are not in termcap mode. The 'Rows' and 'Columns'
4417 * variables are really intended to mean the size of Vim screen
4418 * while in termcap mode.
4419 */
4420 Rows = g_cbTermcap.Info.dwSize.Y;
4421 Columns = g_cbTermcap.Info.dwSize.X;
4422 }
4423 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4424 {
4425 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4426 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4427 }
4428 else
4429 {
4430 Rows = 25;
4431 Columns = 80;
4432 }
4433 return OK;
4434}
4435
4436/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004437 * Resize console buffer to 'COORD'
4438 */
4439 static void
4440ResizeConBuf(
4441 HANDLE hConsole,
4442 COORD coordScreen)
4443{
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00004444 if (use_alternate_screen_buffer)
4445 return;
4446
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004447 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4448 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004449# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004450 if (fdDump)
4451 {
4452 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4453 GetLastError());
4454 fflush(fdDump);
4455 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004456# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004457 }
4458}
4459
4460/*
4461 * Resize console window size to 'srWindowRect'
4462 */
4463 static void
4464ResizeWindow(
4465 HANDLE hConsole,
4466 SMALL_RECT srWindowRect)
4467{
4468 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4469 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004470# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004471 if (fdDump)
4472 {
4473 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4474 GetLastError());
4475 fflush(fdDump);
4476 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004477# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004478 }
4479}
4480
4481/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004482 * Set a console window to `xSize' * `ySize'
4483 */
4484 static void
4485ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004486 HANDLE hConsole,
4487 int xSize,
4488 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004489{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004490 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
4491 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004492 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004493 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004494 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004495
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004496# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004497 if (fdDump)
4498 {
4499 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4500 fflush(fdDump);
4501 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004502# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004503
Bram Moolenaar0f873732019-12-05 20:28:46 +01004504 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00004505 coordScreen = GetLargestConsoleWindowSize(hConsole);
4506
Bram Moolenaar0f873732019-12-05 20:28:46 +01004507 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00004508 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4509 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4510 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4511
4512 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4513 {
4514 int sx, sy;
4515
4516 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4517 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4518 if (sy < ySize || sx < xSize)
4519 {
4520 /*
4521 * Increasing number of lines/columns, do buffer first.
4522 * Use the maximal size in x and y direction.
4523 */
4524 if (sy < ySize)
4525 coordScreen.Y = ySize;
4526 else
4527 coordScreen.Y = sy;
4528 if (sx < xSize)
4529 coordScreen.X = xSize;
4530 else
4531 coordScreen.X = sx;
4532 SetConsoleScreenBufferSize(hConsole, coordScreen);
4533 }
4534 }
4535
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004536 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004537 coordScreen.X = xSize;
4538 coordScreen.Y = ySize;
4539
Bram Moolenaar2551c032018-08-23 22:38:31 +02004540 // In the new console call API, only the first time in reverse order
4541 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004542 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004543 ResizeWindow(hConsole, srWindowRect);
4544 ResizeConBuf(hConsole, coordScreen);
4545 }
4546 else
4547 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004548 // Workaround for a Windows 10 bug
4549 cursor.X = srWindowRect.Left;
4550 cursor.Y = srWindowRect.Top;
4551 SetConsoleCursorPosition(hConsole, cursor);
4552
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004553 ResizeConBuf(hConsole, coordScreen);
4554 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004555 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004556 }
4557}
4558
4559
4560/*
4561 * Set the console window to `Rows' * `Columns'
4562 */
4563 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004564mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004565{
4566 COORD coordScreen;
4567
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004568# ifdef VIMDLL
4569 if (gui.in_use)
4570 return;
4571# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004572 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004573 if (suppress_winsize != 0)
4574 {
4575 suppress_winsize = 2;
4576 return;
4577 }
4578
4579 if (term_console)
4580 {
4581 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4582
Bram Moolenaar0f873732019-12-05 20:28:46 +01004583 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004584 if (Rows > coordScreen.Y)
4585 Rows = coordScreen.Y;
4586 if (Columns > coordScreen.X)
4587 Columns = coordScreen.X;
4588
4589 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4590 }
4591}
4592
4593/*
4594 * Rows and/or Columns has changed.
4595 */
4596 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004597mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004598{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004599# ifdef VIMDLL
4600 if (gui.in_use)
4601 return;
4602# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004603 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4604}
4605
4606
4607/*
4608 * Called when started up, to set the winsize that was delayed.
4609 */
4610 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004611mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004612{
4613 if (suppress_winsize == 2)
4614 {
4615 suppress_winsize = 0;
4616 mch_set_shellsize();
4617 shell_resized();
4618 }
4619 suppress_winsize = 0;
4620}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004621#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004622
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004623 static BOOL
4624vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004625 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004626 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004627 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004628 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004629 PROCESS_INFORMATION *pi,
4630 LPVOID *env,
4631 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004632{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004633 BOOL ret = FALSE;
4634 WCHAR *wcmd, *wcwd = NULL;
4635
4636 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4637 if (wcmd == NULL)
4638 return FALSE;
4639 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004640 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004641 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4642 if (wcwd == NULL)
4643 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004644 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004645
4646 ret = CreateProcessW(
4647 NULL, // Executable name
4648 wcmd, // Command to execute
4649 NULL, // Process security attributes
4650 NULL, // Thread security attributes
4651 inherit_handles, // Inherit handles
4652 flags, // Creation flags
4653 env, // Environment
4654 wcwd, // Current directory
4655 (LPSTARTUPINFOW)si, // Startup information
4656 pi); // Process information
4657theend:
4658 vim_free(wcmd);
4659 vim_free(wcwd);
4660 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004661}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004662
4663
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004664 static HINSTANCE
4665vim_shell_execute(
4666 char *cmd,
4667 INT n_show_cmd)
4668{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004669 HINSTANCE ret;
4670 WCHAR *wcmd;
4671
4672 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4673 if (wcmd == NULL)
4674 return (HINSTANCE) 0;
4675
4676 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4677 vim_free(wcmd);
4678 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004679}
4680
4681
Bram Moolenaar4f974752019-02-17 17:44:42 +01004682#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004683
4684/*
4685 * Specialised version of system() for Win32 GUI mode.
4686 * This version proceeds as follows:
4687 * 1. Create a console window for use by the subprocess
4688 * 2. Run the subprocess (it gets the allocated console by default)
4689 * 3. Wait for the subprocess to terminate and get its exit code
4690 * 4. Prompt the user to press a key to close the console window
4691 */
4692 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004693mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004694{
4695 STARTUPINFO si;
4696 PROCESS_INFORMATION pi;
4697 DWORD ret = 0;
4698 HWND hwnd = GetFocus();
4699
4700 si.cb = sizeof(si);
4701 si.lpReserved = NULL;
4702 si.lpDesktop = NULL;
4703 si.lpTitle = NULL;
4704 si.dwFlags = STARTF_USESHOWWINDOW;
4705 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004706 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004707 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004708 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004709 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004710 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004711 else
4712 si.wShowWindow = SW_SHOWNORMAL;
4713 si.cbReserved2 = 0;
4714 si.lpReserved2 = NULL;
4715
Bram Moolenaar0f873732019-12-05 20:28:46 +01004716 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004717 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004718 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4719 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004720
Bram Moolenaar0f873732019-12-05 20:28:46 +01004721 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004722 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004723# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004724 int delay = 1;
4725
Bram Moolenaar0f873732019-12-05 20:28:46 +01004726 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004727 for (;;)
4728 {
4729 MSG msg;
4730
K.Takatab7057bd2022-01-21 11:37:07 +00004731 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004732 {
4733 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004734 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004735 delay = 1;
4736 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004737 }
4738 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4739 break;
4740
Bram Moolenaar0f873732019-12-05 20:28:46 +01004741 // We start waiting for a very short time and then increase it, so
4742 // that we respond quickly when the process is quick, and don't
4743 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004744 if (delay < 50)
4745 delay += 10;
4746 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004747# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004748 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004749# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004750
Bram Moolenaar0f873732019-12-05 20:28:46 +01004751 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004752 GetExitCodeProcess(pi.hProcess, &ret);
4753 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004754
Bram Moolenaar0f873732019-12-05 20:28:46 +01004755 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004756 CloseHandle(pi.hThread);
4757 CloseHandle(pi.hProcess);
4758
Bram Moolenaar0f873732019-12-05 20:28:46 +01004759 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004760 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4761
4762 return ret;
4763}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004764
4765/*
4766 * Thread launched by the gui to send the current buffer data to the
4767 * process. This way avoid to hang up vim totally if the children
4768 * process take a long time to process the lines.
4769 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004770 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004771sub_process_writer(LPVOID param)
4772{
4773 HANDLE g_hChildStd_IN_Wr = param;
4774 linenr_T lnum = curbuf->b_op_start.lnum;
4775 DWORD len = 0;
4776 DWORD l;
4777 char_u *lp = ml_get(lnum);
4778 char_u *s;
4779 int written = 0;
4780
4781 for (;;)
4782 {
4783 l = (DWORD)STRLEN(lp + written);
4784 if (l == 0)
4785 len = 0;
4786 else if (lp[written] == NL)
4787 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004788 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004789 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4790 }
4791 else
4792 {
4793 s = vim_strchr(lp + written, NL);
4794 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4795 s == NULL ? l : (DWORD)(s - (lp + written)),
4796 &len, NULL);
4797 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004798 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004799 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004800 // Finished a line, add a NL, unless this line should not have
4801 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004802 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004803 || (!curbuf->b_p_bin
4804 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004805 || (lnum != curbuf->b_no_eol_lnum
4806 && (lnum != curbuf->b_ml.ml_line_count
4807 || curbuf->b_p_eol)))
4808 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004809 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4810 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004811 }
4812
4813 ++lnum;
4814 if (lnum > curbuf->b_op_end.lnum)
4815 break;
4816
4817 lp = ml_get(lnum);
4818 written = 0;
4819 }
4820 else if (len > 0)
4821 written += len;
4822 }
4823
Bram Moolenaar0f873732019-12-05 20:28:46 +01004824 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004825 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004826 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004827}
4828
4829
Bram Moolenaar0f873732019-12-05 20:28:46 +01004830# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004831
4832/*
4833 * This function read from the children's stdout and write the
4834 * data on screen or in the buffer accordingly.
4835 */
4836 static void
4837dump_pipe(int options,
4838 HANDLE g_hChildStd_OUT_Rd,
4839 garray_T *ga,
4840 char_u buffer[],
4841 DWORD *buffer_off)
4842{
4843 DWORD availableBytes = 0;
4844 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004845 int ret;
4846 DWORD len;
4847 DWORD toRead;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004848
Bram Moolenaar0f873732019-12-05 20:28:46 +01004849 // we query the pipe to see if there is any data to read
4850 // to avoid to perform a blocking read
4851 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4852 NULL, // optional buffer
4853 0, // buffer size
4854 NULL, // number of read bytes
4855 &availableBytes, // available bytes total
4856 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004857
Bram Moolenaar0f873732019-12-05 20:28:46 +01004858 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004859 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004860 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01004861 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004862 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004863 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004864
Bram Moolenaar0f873732019-12-05 20:28:46 +01004865 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004866 if (len == 0)
4867 break;
4868
4869 availableBytes -= len;
4870
4871 if (options & SHELL_READ)
4872 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004873 // Do NUL -> NL translation, append NL separated
4874 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004875 for (i = 0; i < len; ++i)
4876 {
4877 if (buffer[i] == NL)
4878 append_ga_line(ga);
4879 else if (buffer[i] == NUL)
4880 ga_append(ga, NL);
4881 else
4882 ga_append(ga, buffer[i]);
4883 }
4884 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004885 else if (has_mbyte)
4886 {
4887 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004888 int c;
4889 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004890
4891 len += *buffer_off;
4892 buffer[len] = NUL;
4893
Bram Moolenaar0f873732019-12-05 20:28:46 +01004894 // Check if the last character in buffer[] is
4895 // incomplete, keep these bytes for the next
4896 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004897 for (p = buffer; p < buffer + len; p += l)
4898 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004899 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004900 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004901 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004902 else if (MB_BYTE2LEN(*p) != l)
4903 break;
4904 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004905 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004906 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004907 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004908 if (len >= 12)
4909 ++p;
4910 else
4911 {
4912 *buffer_off = len;
4913 return;
4914 }
4915 }
4916 c = *p;
4917 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004918 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004919 if (p < buffer + len)
4920 {
4921 *p = c;
4922 *buffer_off = (DWORD)((buffer + len) - p);
4923 mch_memmove(buffer, p, *buffer_off);
4924 return;
4925 }
4926 *buffer_off = 0;
4927 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004928 else
4929 {
4930 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004931 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004932 }
4933
4934 windgoto(msg_row, msg_col);
4935 cursor_on();
4936 out_flush();
4937 }
4938}
4939
4940/*
4941 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4942 * for communication and doesn't open any new window.
4943 */
4944 static int
4945mch_system_piped(char *cmd, int options)
4946{
4947 STARTUPINFO si;
4948 PROCESS_INFORMATION pi;
4949 DWORD ret = 0;
4950
4951 HANDLE g_hChildStd_IN_Rd = NULL;
4952 HANDLE g_hChildStd_IN_Wr = NULL;
4953 HANDLE g_hChildStd_OUT_Rd = NULL;
4954 HANDLE g_hChildStd_OUT_Wr = NULL;
4955
Bram Moolenaar0f873732019-12-05 20:28:46 +01004956 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004957 DWORD len;
4958
Bram Moolenaar0f873732019-12-05 20:28:46 +01004959 // buffer used to receive keys
4960 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4961 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004962
4963 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004964 int noread_cnt = 0;
4965 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004966 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004967 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004968 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004969
4970 SECURITY_ATTRIBUTES saAttr;
4971
Bram Moolenaar0f873732019-12-05 20:28:46 +01004972 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004973 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4974 saAttr.bInheritHandle = TRUE;
4975 saAttr.lpSecurityDescriptor = NULL;
4976
4977 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004978 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004979 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004980 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004981 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004982 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004983 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004984 {
4985 CloseHandle(g_hChildStd_IN_Rd);
4986 CloseHandle(g_hChildStd_IN_Wr);
4987 CloseHandle(g_hChildStd_OUT_Rd);
4988 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004989 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004990 }
4991
4992 si.cb = sizeof(si);
4993 si.lpReserved = NULL;
4994 si.lpDesktop = NULL;
4995 si.lpTitle = NULL;
4996 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4997
Bram Moolenaar0f873732019-12-05 20:28:46 +01004998 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004999 si.hStdError = g_hChildStd_OUT_Wr;
5000 si.hStdOutput = g_hChildStd_OUT_Wr;
5001 si.hStdInput = g_hChildStd_IN_Rd;
5002 si.wShowWindow = SW_HIDE;
5003 si.cbReserved2 = 0;
5004 si.lpReserved2 = NULL;
5005
5006 if (options & SHELL_READ)
5007 ga_init2(&ga, 1, BUFLEN);
5008
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005009 if (cmd != NULL)
5010 {
5011 p = (char *)vim_strsave((char_u *)cmd);
5012 if (p != NULL)
5013 unescape_shellxquote((char_u *)p, p_sxe);
5014 else
5015 p = cmd;
5016 }
5017
Bram Moolenaar0f873732019-12-05 20:28:46 +01005018 // Now, run the command.
5019 // About "Inherit handles" being TRUE: this command can be litigious,
5020 // handle inheritance was deactivated for pending temp file, but, if we
5021 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005022 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
5023 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005024
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005025 if (p != cmd)
5026 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005027
Bram Moolenaar0f873732019-12-05 20:28:46 +01005028 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005029 CloseHandle(g_hChildStd_IN_Rd);
5030 CloseHandle(g_hChildStd_OUT_Wr);
5031
5032 if (options & SHELL_WRITE)
5033 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02005034 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005035 _beginthreadex(NULL, // security attributes
5036 0, // default stack size
5037 sub_process_writer, // function to be executed
5038 g_hChildStd_IN_Wr, // parameter
5039 0, // creation flag, start immediately
5040 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005041 CloseHandle(thread);
5042 g_hChildStd_IN_Wr = NULL;
5043 }
5044
Bram Moolenaar0f873732019-12-05 20:28:46 +01005045 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005046 for (;;)
5047 {
5048 MSG msg;
5049
K.Takatab7057bd2022-01-21 11:37:07 +00005050 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005051 {
5052 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00005053 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005054 }
5055
Bram Moolenaar0f873732019-12-05 20:28:46 +01005056 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005057 if ((options & (SHELL_READ|SHELL_WRITE))
5058# ifdef FEAT_GUI
5059 || gui.in_use
5060# endif
5061 )
5062 {
5063 len = 0;
5064 if (!(options & SHELL_EXPAND)
5065 && ((options &
5066 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
5067 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
5068# ifdef FEAT_GUI
5069 || gui.in_use
5070# endif
5071 )
5072 && (ta_len > 0 || noread_cnt > 4))
5073 {
5074 if (ta_len == 0)
5075 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005076 // Get extra characters when we don't have any. Reset the
5077 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005078 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005079 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
5080 }
5081 if (ta_len > 0 || len > 0)
5082 {
5083 /*
5084 * For pipes: Check for CTRL-C: send interrupt signal to
5085 * child. Check for CTRL-D: EOF, close pipe to child.
5086 */
5087 if (len == 1 && cmd != NULL)
5088 {
5089 if (ta_buf[ta_len] == Ctrl_C)
5090 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005091 // Learn what exit code is expected, for
5092 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005093 TerminateProcess(pi.hProcess, 9);
5094 }
5095 if (ta_buf[ta_len] == Ctrl_D)
5096 {
5097 CloseHandle(g_hChildStd_IN_Wr);
5098 g_hChildStd_IN_Wr = NULL;
5099 }
5100 }
5101
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01005102 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005103
5104 /*
5105 * For pipes: echo the typed characters. For a pty this
5106 * does not seem to work.
5107 */
5108 for (i = ta_len; i < ta_len + len; ++i)
5109 {
5110 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
5111 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005112 else if (has_mbyte)
5113 {
5114 int l = (*mb_ptr2len)(ta_buf + i);
5115
5116 msg_outtrans_len(ta_buf + i, l);
5117 i += l - 1;
5118 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005119 else
5120 msg_outtrans_len(ta_buf + i, 1);
5121 }
5122 windgoto(msg_row, msg_col);
5123 out_flush();
5124
5125 ta_len += len;
5126
5127 /*
5128 * Write the characters to the child, unless EOF has been
5129 * typed for pipes. Write one character at a time, to
5130 * avoid losing too much typeahead. When writing buffer
5131 * lines, drop the typed characters (only check for
5132 * CTRL-C).
5133 */
5134 if (options & SHELL_WRITE)
5135 ta_len = 0;
5136 else if (g_hChildStd_IN_Wr != NULL)
5137 {
5138 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
5139 1, &len, NULL);
5140 // if we are typing in, we want to keep things reactive
5141 delay = 1;
5142 if (len > 0)
5143 {
5144 ta_len -= len;
5145 mch_memmove(ta_buf, ta_buf + len, ta_len);
5146 }
5147 }
5148 }
5149 }
5150 }
5151
5152 if (ta_len)
5153 ui_inchar_undo(ta_buf, ta_len);
5154
5155 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
5156 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005157 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005158 break;
5159 }
5160
5161 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005162 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005163
Bram Moolenaar0f873732019-12-05 20:28:46 +01005164 // We start waiting for a very short time and then increase it, so
5165 // that we respond quickly when the process is quick, and don't
5166 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005167 if (delay < 50)
5168 delay += 10;
5169 }
5170
Bram Moolenaar0f873732019-12-05 20:28:46 +01005171 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005172 CloseHandle(g_hChildStd_OUT_Rd);
5173 if (g_hChildStd_IN_Wr != NULL)
5174 CloseHandle(g_hChildStd_IN_Wr);
5175
5176 WaitForSingleObject(pi.hProcess, INFINITE);
5177
Bram Moolenaar0f873732019-12-05 20:28:46 +01005178 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005179 GetExitCodeProcess(pi.hProcess, &ret);
5180
5181 if (options & SHELL_READ)
5182 {
5183 if (ga.ga_len > 0)
5184 {
5185 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01005186 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005187 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
5188 }
5189 else
5190 curbuf->b_no_eol_lnum = 0;
5191 ga_clear(&ga);
5192 }
5193
Bram Moolenaar0f873732019-12-05 20:28:46 +01005194 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005195 CloseHandle(pi.hThread);
5196 CloseHandle(pi.hProcess);
5197
5198 return ret;
5199}
5200
5201 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005202mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005203{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005204 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005205 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005206 return mch_system_piped(cmd, options);
5207 else
5208 return mch_system_classic(cmd, options);
5209}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005210#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005211
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005212#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005213 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02005214mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005215{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005216 int ret;
5217 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005218 char_u *buf;
5219 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005220
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005221 // If the command starts and ends with double quotes, enclose the command
5222 // in parentheses.
5223 len = STRLEN(cmd);
5224 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
5225 {
5226 len += 3;
5227 buf = alloc(len);
5228 if (buf == NULL)
5229 return -1;
5230 vim_snprintf((char *)buf, len, "(%s)", cmd);
5231 wcmd = enc_to_utf16(buf, NULL);
5232 free(buf);
5233 }
5234 else
5235 wcmd = enc_to_utf16((char_u *)cmd, NULL);
5236
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005237 if (wcmd == NULL)
5238 return -1;
5239
5240 ret = _wsystem(wcmd);
5241 vim_free(wcmd);
5242 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005243}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005244
5245#endif
5246
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005247 static int
5248mch_system(char *cmd, int options)
5249{
5250#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005251 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005252 return mch_system_g(cmd, options);
5253 else
5254 return mch_system_c(cmd, options);
5255#elif defined(FEAT_GUI_MSWIN)
5256 return mch_system_g(cmd, options);
5257#else
5258 return mch_system_c(cmd, options);
5259#endif
5260}
5261
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005262#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
5263/*
5264 * Use a terminal window to run a shell command in.
5265 */
5266 static int
5267mch_call_shell_terminal(
5268 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005269 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005270{
5271 jobopt_T opt;
5272 char_u *newcmd = NULL;
5273 typval_T argvar[2];
5274 long_u cmdlen;
5275 int retval = -1;
5276 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005277 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005278 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005279 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005280
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005281 if (cmd == NULL)
5282 cmdlen = STRLEN(p_sh) + 1;
5283 else
5284 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005285 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005286 if (newcmd == NULL)
5287 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005288 if (cmd == NULL)
5289 {
5290 STRCPY(newcmd, p_sh);
5291 ch_log(NULL, "starting terminal to run a shell");
5292 }
5293 else
5294 {
5295 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
5296 ch_log(NULL, "starting terminal for system command '%s'", cmd);
5297 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005298
5299 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005300
5301 argvar[0].v_type = VAR_STRING;
5302 argvar[0].vval.v_string = newcmd;
5303 argvar[1].v_type = VAR_UNKNOWN;
5304 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005305 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01005306 {
5307 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005308 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01005309 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005310
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005311 job = term_getjob(buf->b_term);
5312 ++job->jv_refcount;
5313
Bram Moolenaar0f873732019-12-05 20:28:46 +01005314 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005315 aucmd_prepbuf(&aco, buf);
Bram Moolenaare76062c2022-11-28 18:51:43 +00005316 if (curbuf == buf)
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005317 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005318 // Only do this when a window was found for "buf".
5319 clear_oparg(&oa);
5320 while (term_use_loop())
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005321 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005322 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
5323 {
5324 // If terminal_loop() returns OK we got a key that is handled
5325 // in Normal model. We don't do redrawing anyway.
5326 if (terminal_loop(TRUE) == OK)
5327 normal_cmd(&oa, TRUE);
5328 }
5329 else
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005330 normal_cmd(&oa, TRUE);
5331 }
Bram Moolenaare76062c2022-11-28 18:51:43 +00005332 retval = job->jv_exitval;
5333 ch_log(NULL, "system command finished");
5334
5335 job_unref(job);
5336
5337 // restore curwin/curbuf and a few other things
5338 aucmd_restbuf(&aco);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005339 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005340
5341 wait_return(TRUE);
5342 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
5343
5344 vim_free(newcmd);
5345 return retval;
5346}
5347#endif
5348
Bram Moolenaar071d4272004-06-13 20:20:40 +00005349/*
5350 * Either execute a command by calling the shell or start a new shell
5351 */
5352 int
5353mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005354 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005355 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00005356{
5357 int x = 0;
5358 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005359 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02005360
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00005361#ifdef FEAT_EVAL
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01005362 ch_log(NULL, "executing shell command: %s", cmd);
5363#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01005364 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02005365 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005366 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005367 if (cmd == NULL)
5368 wcscat(szShellTitle, L" :sh");
5369 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005370 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005371 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005372
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005373 if (wn != NULL)
5374 {
5375 wcscat(szShellTitle, L" - !");
5376 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02005377 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005378 wcscat(szShellTitle, wn);
5379 SetConsoleTitleW(szShellTitle);
5380 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005381 }
5382 }
5383 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005384
5385 out_flush();
5386
5387#ifdef MCH_WRITE_DUMP
5388 if (fdDump)
5389 {
5390 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
5391 fflush(fdDump);
5392 }
5393#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005394#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005395 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005396 if (
5397# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005398 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005399# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005400 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005401 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
5402 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005403 char_u *cmdbase = cmd;
5404
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02005405 if (cmdbase != NULL)
5406 // Skip a leading quote and (.
5407 while (*cmdbase == '"' || *cmdbase == '(')
5408 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005409
5410 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01005411 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
5412 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005413 {
5414 // Use a terminal window to run the command in.
5415 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005416 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005417 return x;
5418 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005419 }
5420#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005421
5422 /*
5423 * Catch all deadly signals while running the external command, because a
5424 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5425 */
5426 signal(SIGINT, SIG_IGN);
5427#if defined(__GNUC__) && !defined(__MINGW32__)
5428 signal(SIGKILL, SIG_IGN);
5429#else
5430 signal(SIGBREAK, SIG_IGN);
5431#endif
5432 signal(SIGILL, SIG_IGN);
5433 signal(SIGFPE, SIG_IGN);
5434 signal(SIGSEGV, SIG_IGN);
5435 signal(SIGTERM, SIG_IGN);
5436 signal(SIGABRT, SIG_IGN);
5437
5438 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005439 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00005440
5441 if (cmd == NULL)
5442 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005443 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005444 }
5445 else
5446 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005447 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005448 char_u *newcmd = NULL;
5449 char_u *cmdbase = cmd;
5450 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005451
Bram Moolenaar0f873732019-12-05 20:28:46 +01005452 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005453 if (*cmdbase == '"' )
5454 ++cmdbase;
5455 if (*cmdbase == '(')
5456 ++cmdbase;
5457
Bram Moolenaar1c465442017-03-12 20:10:05 +01005458 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005459 {
5460 STARTUPINFO si;
5461 PROCESS_INFORMATION pi;
5462 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005463 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005464 char_u *p;
5465
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005466 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005467 si.cb = sizeof(si);
5468 si.lpReserved = NULL;
5469 si.lpDesktop = NULL;
5470 si.lpTitle = NULL;
5471 si.dwFlags = 0;
5472 si.cbReserved2 = 0;
5473 si.lpReserved2 = NULL;
5474
5475 cmdbase = skipwhite(cmdbase + 5);
5476 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005477 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005478 {
5479 cmdbase = skipwhite(cmdbase + 4);
5480 si.dwFlags = STARTF_USESHOWWINDOW;
5481 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005482 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005483 }
5484 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005485 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005486 {
5487 cmdbase = skipwhite(cmdbase + 2);
5488 flags = CREATE_NO_WINDOW;
5489 si.dwFlags = STARTF_USESTDHANDLES;
5490 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005491 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005492 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005493 NULL, // Security att.
5494 OPEN_EXISTING, // Open flags
5495 FILE_ATTRIBUTE_NORMAL, // File att.
5496 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005497 si.hStdOutput = si.hStdInput;
5498 si.hStdError = si.hStdInput;
5499 }
5500
Bram Moolenaar0f873732019-12-05 20:28:46 +01005501 // Remove a trailing ", ) and )" if they have a match
5502 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005503 if (cmdbase > cmd)
5504 {
5505 p = cmdbase + STRLEN(cmdbase);
5506 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5507 *--p = NUL;
5508 if (p > cmdbase && p[-1] == ')'
5509 && (*cmd =='(' || cmd[1] == '('))
5510 *--p = NUL;
5511 }
5512
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005513 newcmd = cmdbase;
5514 unescape_shellxquote(cmdbase, p_sxe);
5515
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005516 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005517 * If creating new console, arguments are passed to the
5518 * 'cmd.exe' as-is. If it's not, arguments are not treated
5519 * correctly for current 'cmd.exe'. So unescape characters in
5520 * shellxescape except '|' for avoiding to be treated as
5521 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005522 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005523 if (flags != CREATE_NEW_CONSOLE)
5524 {
5525 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005526 char_u *cmd_shell = mch_getenv("COMSPEC");
5527
5528 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005529 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005530
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005531 subcmd = vim_strsave_escaped_ext(cmdbase,
5532 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005533 if (subcmd != NULL)
5534 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005535 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005536 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005537 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005538 if (newcmd != NULL)
5539 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005540 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005541 else
5542 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005543 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005544 }
5545 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005546
5547 /*
5548 * Now, start the command as a process, so that it doesn't
5549 * inherit our handles which causes unpleasant dangling swap
5550 * files if we exit before the spawned process
5551 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005552 if (vim_create_process((char *)newcmd, FALSE, flags,
5553 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005554 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005555 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5556 > (HINSTANCE)32)
5557 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005558 else
5559 {
5560 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005561#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005562# ifdef VIMDLL
5563 if (gui.in_use)
5564# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005565 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005566#endif
5567 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005568
5569 if (newcmd != cmdbase)
5570 vim_free(newcmd);
5571
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005572 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005573 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005574 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005575 CloseHandle(si.hStdInput);
5576 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005577 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005578 CloseHandle(pi.hThread);
5579 CloseHandle(pi.hProcess);
5580 }
5581 else
5582 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005583 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005584#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005585 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005586 (!s_dont_use_vimrun && p_stmp ?
5587 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5588 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005589#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005590 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005591
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005592 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005593 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005594 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005595#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005596 if (
5597# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005598 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005599# endif
5600 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005601 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005602 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5603 "External commands will not pause after completion.\n"
5604 "See :help win32-vimrun for more information.");
5605 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005606 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5607 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005608
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005609 if (wmsg != NULL && wtitle != NULL)
5610 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5611 vim_free(wmsg);
5612 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005613 need_vimrun_warning = FALSE;
5614 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005615 if (
5616# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005617 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005618# endif
5619 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005620 // Use vimrun to execute the command. It opens a console
5621 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005622 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005623 vimrun_path,
5624 (msg_silent != 0 || (options & SHELL_DOOUT))
5625 ? "-s " : "",
5626 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005627 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005628# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005629 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005630# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005631 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005632 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005633 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5634 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005635 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005636#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005637 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005638 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005639 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005640 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005641 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005642 }
5643 }
5644
5645 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005646 {
5647 // The shell may have messed with the mode, always set it.
5648 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005649 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005650 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005651
Bram Moolenaar0f873732019-12-05 20:28:46 +01005652 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005653 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005654#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005655 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005656 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005657#endif
5658 )
5659 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005660 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005661 msg_putchar('\n');
5662 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005663 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005664
5665 signal(SIGINT, SIG_DFL);
5666#if defined(__GNUC__) && !defined(__MINGW32__)
5667 signal(SIGKILL, SIG_DFL);
5668#else
5669 signal(SIGBREAK, SIG_DFL);
5670#endif
5671 signal(SIGILL, SIG_DFL);
5672 signal(SIGFPE, SIG_DFL);
5673 signal(SIGSEGV, SIG_DFL);
5674 signal(SIGTERM, SIG_DFL);
5675 signal(SIGABRT, SIG_DFL);
5676
5677 return x;
5678}
5679
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005680#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005681 static HANDLE
5682job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005683 char_u *fname,
5684 DWORD dwDesiredAccess,
5685 DWORD dwShareMode,
5686 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5687 DWORD dwCreationDisposition,
5688 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005689{
5690 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005691 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005692
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005693 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005694 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005695 return INVALID_HANDLE_VALUE;
5696
5697 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5698 lpSecurityAttributes, dwCreationDisposition,
5699 dwFlagsAndAttributes, NULL);
5700 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005701 return h;
5702}
5703
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005704/*
5705 * Turn the dictionary "env" into a NUL separated list that can be used as the
5706 * environment argument of vim_create_process().
5707 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005708 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005709win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005710{
5711 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005712 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005713 LPVOID base = GetEnvironmentStringsW();
5714
Bram Moolenaar0f873732019-12-05 20:28:46 +01005715 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005716 if (ga_grow(gap, 1) == FAIL)
5717 return;
5718
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005719 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005720 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005721 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005722 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005723 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005724 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005725 typval_T *item = &dict_lookup(hi)->di_tv;
5726 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005727 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005728 --todo;
5729 if (wkey != NULL && wval != NULL)
5730 {
5731 size_t n;
5732 size_t lkey = wcslen(wkey);
5733 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005734
Yegappan Lakshmananfadc02a2023-01-27 21:03:12 +00005735 if (ga_grow(gap, (int)(lkey + lval + 2)) == FAIL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005736 continue;
5737 for (n = 0; n < lkey; n++)
5738 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5739 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5740 for (n = 0; n < lval; n++)
5741 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5742 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5743 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005744 vim_free(wkey);
5745 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005746 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005747 }
5748 }
5749
Bram Moolenaar355757a2020-02-10 22:06:32 +01005750 if (base)
5751 {
5752 WCHAR *p = (WCHAR*) base;
5753
5754 // for last \0
5755 if (ga_grow(gap, 1) == FAIL)
5756 return;
5757
5758 while (*p != 0 || *(p + 1) != 0)
5759 {
5760 if (ga_grow(gap, 1) == OK)
5761 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5762 p++;
5763 }
5764 FreeEnvironmentStrings(base);
5765 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5766 }
5767
Bram Moolenaar493359e2018-06-12 20:25:52 +02005768# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005769 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005770# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005771 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005772 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005773# endif
5774# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005775 char_u *version = get_vim_var_str(VV_VERSION);
5776 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005777# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005778 // size of "VIM_SERVERNAME=" and value,
5779 // plus "VIM_TERMINAL=" and value,
5780 // plus two terminating NULs
5781 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005782# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005783 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005784# endif
5785# ifdef FEAT_TERMINAL
5786 + 13 + version_len + 2
5787# endif
5788 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005789
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005790 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005791 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005792# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005793 for (n = 0; n < 15; n++)
5794 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5795 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005796 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005797 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5798 (WCHAR)servername[n];
5799 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005800# endif
5801# ifdef FEAT_TERMINAL
5802 if (is_terminal)
5803 {
5804 for (n = 0; n < 13; n++)
5805 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5806 (WCHAR)"VIM_TERMINAL="[n];
5807 for (n = 0; n < version_len; n++)
5808 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5809 (WCHAR)version[n];
5810 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5811 }
5812# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005813 }
5814 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005815# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005816}
5817
Bram Moolenaarb091f302019-01-19 14:37:00 +01005818/*
5819 * Create a pair of pipes.
5820 * Return TRUE for success, FALSE for failure.
5821 */
5822 static BOOL
5823create_pipe_pair(HANDLE handles[2])
5824{
5825 static LONG s;
5826 char name[64];
5827 SECURITY_ATTRIBUTES sa;
5828
5829 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5830 GetCurrentProcessId(),
5831 InterlockedIncrement(&s));
5832
5833 // Create named pipe. Max size of named pipe is 65535.
5834 handles[1] = CreateNamedPipe(
5835 name,
5836 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5837 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005838 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005839
5840 if (handles[1] == INVALID_HANDLE_VALUE)
5841 return FALSE;
5842
5843 sa.nLength = sizeof(sa);
5844 sa.bInheritHandle = TRUE;
5845 sa.lpSecurityDescriptor = NULL;
5846
5847 handles[0] = CreateFile(name,
5848 FILE_GENERIC_READ,
5849 FILE_SHARE_READ, &sa,
5850 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5851
5852 if (handles[0] == INVALID_HANDLE_VALUE)
5853 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005854 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005855 return FALSE;
5856 }
5857
5858 return TRUE;
5859}
5860
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005861 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005862mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005863{
5864 STARTUPINFO si;
5865 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005866 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005867 SECURITY_ATTRIBUTES saAttr;
5868 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005869 HANDLE ifd[2];
5870 HANDLE ofd[2];
5871 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005872 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005873
5874 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5875 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5876 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5877 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5878 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5879 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5880 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5881
5882 if (use_out_for_err && use_null_for_out)
5883 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005884
5885 ifd[0] = INVALID_HANDLE_VALUE;
5886 ifd[1] = INVALID_HANDLE_VALUE;
5887 ofd[0] = INVALID_HANDLE_VALUE;
5888 ofd[1] = INVALID_HANDLE_VALUE;
5889 efd[0] = INVALID_HANDLE_VALUE;
5890 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005891 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005892
Bram Moolenaar14207f42016-10-27 21:13:10 +02005893 jo = CreateJobObject(NULL, NULL);
5894 if (jo == NULL)
5895 {
5896 job->jv_status = JOB_FAILED;
5897 goto failed;
5898 }
5899
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005900 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005901 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005902
Bram Moolenaar76467df2016-02-12 19:30:26 +01005903 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005904 ZeroMemory(&si, sizeof(si));
5905 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005906 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005907 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005908
Bram Moolenaard8070362016-02-15 21:56:54 +01005909 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5910 saAttr.bInheritHandle = TRUE;
5911 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005912
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005913 if (use_file_for_in)
5914 {
5915 char_u *fname = options->jo_io_name[PART_IN];
5916
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005917 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5918 FILE_SHARE_READ | FILE_SHARE_WRITE,
5919 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5920 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005921 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005922 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005923 goto failed;
5924 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005925 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005926 else if (!use_null_for_in
5927 && (!create_pipe_pair(ifd)
5928 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005929 goto failed;
5930
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005931 if (use_file_for_out)
5932 {
5933 char_u *fname = options->jo_io_name[PART_OUT];
5934
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005935 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5936 FILE_SHARE_READ | FILE_SHARE_WRITE,
5937 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5938 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005939 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005940 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005941 goto failed;
5942 }
5943 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005944 else if (!use_null_for_out &&
5945 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005946 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005947 goto failed;
5948
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005949 if (use_file_for_err)
5950 {
5951 char_u *fname = options->jo_io_name[PART_ERR];
5952
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005953 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5954 FILE_SHARE_READ | FILE_SHARE_WRITE,
5955 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5956 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005957 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005958 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005959 goto failed;
5960 }
5961 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005962 else if (!use_out_for_err && !use_null_for_err &&
5963 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005964 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005965 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005966
Bram Moolenaard8070362016-02-15 21:56:54 +01005967 si.dwFlags |= STARTF_USESTDHANDLES;
5968 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005969 si.hStdOutput = ofd[1];
5970 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5971
5972 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5973 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005974 if (options->jo_set & JO_CHANNEL)
5975 {
5976 channel = options->jo_channel;
5977 if (channel != NULL)
5978 ++channel->ch_refcount;
5979 }
5980 else
5981 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005982 if (channel == NULL)
5983 goto failed;
5984 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005985
5986 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005987 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005988 CREATE_DEFAULT_ERROR_MODE |
5989 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005990 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005991 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005992 &si, &pi,
5993 ga.ga_data,
5994 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005995 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005996 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005997 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005998 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005999 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006000
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006001 ga_clear(&ga);
6002
Bram Moolenaar14207f42016-10-27 21:13:10 +02006003 if (!AssignProcessToJobObject(jo, pi.hProcess))
6004 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006005 // if failing, switch the way to terminate
6006 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02006007 CloseHandle(jo);
6008 jo = NULL;
6009 }
6010 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01006011 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006012 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02006013 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006014 job->jv_status = JOB_STARTED;
6015
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02006016 CloseHandle(ifd[0]);
6017 CloseHandle(ofd[1]);
6018 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01006019 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01006020
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006021 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006022 if (channel != NULL)
6023 {
6024 channel_set_pipes(channel,
6025 use_file_for_in || use_null_for_in
6026 ? INVALID_FD : (sock_T)ifd[1],
6027 use_file_for_out || use_null_for_out
6028 ? INVALID_FD : (sock_T)ofd[0],
6029 use_out_for_err || use_file_for_err || use_null_for_err
6030 ? INVALID_FD : (sock_T)efd[0]);
6031 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006032 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006033 return;
6034
6035failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01006036 CloseHandle(ifd[0]);
6037 CloseHandle(ofd[0]);
6038 CloseHandle(efd[0]);
6039 CloseHandle(ifd[1]);
6040 CloseHandle(ofd[1]);
6041 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01006042 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006043 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006044}
6045
6046 char *
6047mch_job_status(job_T *job)
6048{
6049 DWORD dwExitCode = 0;
6050
Bram Moolenaar76467df2016-02-12 19:30:26 +01006051 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
6052 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006053 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01006054 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01006055 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02006056 {
6057 ch_log(job->jv_channel, "Job ended");
6058 job->jv_status = JOB_ENDED;
6059 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006060 return "dead";
6061 }
6062 return "run";
6063}
6064
Bram Moolenaar97792de2016-10-15 18:36:49 +02006065 job_T *
6066mch_detect_ended_job(job_T *job_list)
6067{
6068 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
6069 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
6070 job_T *job = job_list;
6071
6072 while (job != NULL)
6073 {
6074 DWORD n;
6075 DWORD result;
6076
6077 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
6078 && job != NULL; job = job->jv_next)
6079 {
6080 if (job->jv_status == JOB_STARTED)
6081 {
6082 jobHandles[n] = job->jv_proc_info.hProcess;
6083 jobArray[n] = job;
6084 ++n;
6085 }
6086 }
6087 if (n == 0)
6088 continue;
6089 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
6090 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
6091 {
6092 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
6093
6094 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
6095 return wait_job;
6096 }
6097 }
6098 return NULL;
6099}
6100
Bram Moolenaarfb630902016-10-29 14:55:00 +02006101 static BOOL
6102terminate_all(HANDLE process, int code)
6103{
6104 PROCESSENTRY32 pe;
6105 HANDLE h = INVALID_HANDLE_VALUE;
6106 DWORD pid = GetProcessId(process);
6107
6108 if (pid != 0)
6109 {
6110 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
6111 if (h != INVALID_HANDLE_VALUE)
6112 {
6113 pe.dwSize = sizeof(PROCESSENTRY32);
6114 if (!Process32First(h, &pe))
6115 goto theend;
6116
6117 do
6118 {
6119 if (pe.th32ParentProcessID == pid)
6120 {
6121 HANDLE ph = OpenProcess(
6122 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
6123 if (ph != NULL)
6124 {
6125 terminate_all(ph, code);
6126 CloseHandle(ph);
6127 }
6128 }
6129 } while (Process32Next(h, &pe));
6130
6131 CloseHandle(h);
6132 }
6133 }
6134
6135theend:
6136 return TerminateProcess(process, code);
6137}
6138
6139/*
6140 * Send a (deadly) signal to "job".
6141 * Return FAIL if it didn't work.
6142 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006143 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02006144mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006145{
Bram Moolenaar923d9262016-02-25 20:56:01 +01006146 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006147
Bram Moolenaar923d9262016-02-25 20:56:01 +01006148 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01006149 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006150 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02006151 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006152 {
6153 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
6154 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00006155 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006156 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01006157 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006158 }
6159
6160 if (!AttachConsole(job->jv_proc_info.dwProcessId))
6161 return FAIL;
6162 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01006163 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
6164 job->jv_proc_info.dwProcessId)
6165 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006166 FreeConsole();
6167 return ret;
6168}
6169
6170/*
6171 * Clear the data related to "job".
6172 */
6173 void
6174mch_clear_job(job_T *job)
6175{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00006176 if (job->jv_status == JOB_FAILED)
6177 return;
6178
6179 if (job->jv_job_object != NULL)
6180 CloseHandle(job->jv_job_object);
6181 CloseHandle(job->jv_proc_info.hProcess);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006182}
6183#endif
6184
Bram Moolenaar071d4272004-06-13 20:20:40 +00006185
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006186#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006187
6188/*
6189 * Start termcap mode
6190 */
6191 static void
6192termcap_mode_start(void)
6193{
6194 DWORD cmodein;
6195
6196 if (g_fTermcapMode)
6197 return;
6198
6199 SaveConsoleBuffer(&g_cbNonTermcap);
6200
6201 if (g_cbTermcap.IsValid)
6202 {
6203 /*
6204 * We've been in termcap mode before. Restore certain screen
6205 * characteristics, including the buffer size and the window
6206 * size. Since we will be redrawing the screen, we don't need
6207 * to restore the actual contents of the buffer.
6208 */
6209 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006210 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006211 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
6212 Rows = g_cbTermcap.Info.dwSize.Y;
6213 Columns = g_cbTermcap.Info.dwSize.X;
6214 }
6215 else
6216 {
6217 /*
6218 * This is our first time entering termcap mode. Clear the console
6219 * screen buffer, and resize the buffer to match the current window
6220 * size. We will use this as the size of our editing environment.
6221 */
6222 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006223 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006224 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
6225 }
6226
Bram Moolenaar071d4272004-06-13 20:20:40 +00006227 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006228
6229 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006230 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006231 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006232 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006233 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
6234 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006235 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006236 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006237 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006238 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6239 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006240 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006241 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006242
6243 redraw_later_clear();
6244 g_fTermcapMode = TRUE;
6245}
6246
6247
6248/*
6249 * End termcap mode
6250 */
6251 static void
6252termcap_mode_end(void)
6253{
6254 DWORD cmodein;
6255 ConsoleBuffer *cb;
6256 COORD coord;
6257 DWORD dwDummy;
6258
6259 if (!g_fTermcapMode)
6260 return;
6261
6262 SaveConsoleBuffer(&g_cbTermcap);
6263
6264 GetConsoleMode(g_hConIn, &cmodein);
6265 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006266 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6267 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006268
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006269# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01006270 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006271# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006272 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006273# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006274 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01006275 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006276
Christopher Plewright1140b512022-11-12 18:46:05 +00006277 // Switch back to main screen buffer.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00006278 if (exiting && use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00006279 vtp_printf("\033[?1049l");
6280
6281 if (!USE_WT && (p_rs || exiting))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006282 {
6283 /*
6284 * Clear anything that happens to be on the current line.
6285 */
6286 coord.X = 0;
6287 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006288 FillConsoleOutputCharacter(g_hConOut, ' ',
6289 cb->Info.dwSize.X, coord, &dwDummy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006290 /*
6291 * The following is just for aesthetics. If we are exiting without
6292 * restoring the screen, then we want to have a prompt string
6293 * appear at the bottom line. However, the command interpreter
6294 * seems to always advance the cursor one line before displaying
6295 * the prompt string, which causes the screen to scroll. To
6296 * counter this, move the cursor up one line before exiting.
6297 */
6298 if (exiting && !p_rs)
6299 coord.Y--;
6300 /*
6301 * Position the cursor at the leftmost column of the desired row.
6302 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006303 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006304 }
Christopher Plewright1140b512022-11-12 18:46:05 +00006305 SetConsoleCursorInfo(g_hConOut, &g_cci);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006306 g_fTermcapMode = FALSE;
6307}
Christopher Plewright38804d62022-11-09 23:55:52 +00006308#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006309
6310
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006311#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006312 void
6313mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01006314 char_u *s UNUSED,
6315 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006316{
Bram Moolenaar0f873732019-12-05 20:28:46 +01006317 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00006318}
6319
6320#else
6321
6322/*
6323 * clear `n' chars, starting from `coord'
6324 */
6325 static void
6326clear_chars(
6327 COORD coord,
6328 DWORD n)
6329{
Christopher Plewright38804d62022-11-09 23:55:52 +00006330 if (!vtp_working)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006331 {
6332 DWORD dwDummy;
6333
6334 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
6335 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
6336 &dwDummy);
6337 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006338 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02006339 {
6340 set_console_color_rgb();
6341 gotoxy(coord.X + 1, coord.Y + 1);
6342 vtp_printf("\033[%dX", n);
6343 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006344}
6345
6346
6347/*
6348 * Clear the screen
6349 */
6350 static void
6351clear_screen(void)
6352{
6353 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006354
Christopher Plewright38804d62022-11-09 23:55:52 +00006355 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006356 clear_chars(g_coord, Rows * Columns);
6357 else
6358 {
6359 set_console_color_rgb();
6360 gotoxy(1, 1);
6361 vtp_printf("\033[2J");
6362 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006363}
6364
6365
6366/*
6367 * Clear to end of display
6368 */
6369 static void
6370clear_to_end_of_display(void)
6371{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006372 COORD save = g_coord;
6373
Christopher Plewright38804d62022-11-09 23:55:52 +00006374 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006375 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006376 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006377 else
6378 {
6379 set_console_color_rgb();
6380 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6381 vtp_printf("\033[0J");
6382
6383 gotoxy(save.X + 1, save.Y + 1);
6384 g_coord = save;
6385 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006386}
6387
6388
6389/*
6390 * Clear to end of line
6391 */
6392 static void
6393clear_to_end_of_line(void)
6394{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006395 COORD save = g_coord;
6396
Christopher Plewright38804d62022-11-09 23:55:52 +00006397 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006398 clear_chars(g_coord, Columns - g_coord.X);
6399 else
6400 {
6401 set_console_color_rgb();
6402 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6403 vtp_printf("\033[0K");
6404
6405 gotoxy(save.X + 1, save.Y + 1);
6406 g_coord = save;
6407 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006408}
6409
6410
6411/*
6412 * Scroll the scroll region up by `cLines' lines
6413 */
6414 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006415scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006416{
6417 COORD oldcoord = g_coord;
6418
6419 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6420 delete_lines(cLines);
6421
6422 g_coord = oldcoord;
6423}
6424
6425
6426/*
6427 * Set the scroll region
6428 */
6429 static void
6430set_scroll_region(
6431 unsigned left,
6432 unsigned top,
6433 unsigned right,
6434 unsigned bottom)
6435{
6436 if (left >= right
6437 || top >= bottom
6438 || right > (unsigned) Columns - 1
6439 || bottom > (unsigned) Rows - 1)
6440 return;
6441
6442 g_srScrollRegion.Left = left;
6443 g_srScrollRegion.Top = top;
6444 g_srScrollRegion.Right = right;
6445 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006446}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006447
Bram Moolenaar6982f422019-02-16 16:48:01 +01006448 static void
6449set_scroll_region_tb(
6450 unsigned top,
6451 unsigned bottom)
6452{
6453 if (top >= bottom || bottom > (unsigned)Rows - 1)
6454 return;
6455
6456 g_srScrollRegion.Top = top;
6457 g_srScrollRegion.Bottom = bottom;
6458}
6459
6460 static void
6461set_scroll_region_lr(
6462 unsigned left,
6463 unsigned right)
6464{
6465 if (left >= right || right > (unsigned)Columns - 1)
6466 return;
6467
6468 g_srScrollRegion.Left = left;
6469 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006470}
6471
6472
6473/*
6474 * Insert `cLines' lines at the current cursor position
6475 */
6476 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006477insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006478{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006479 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006480 COORD dest;
6481 CHAR_INFO fill;
6482
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006483 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6484
Bram Moolenaar6982f422019-02-16 16:48:01 +01006485 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006486 dest.Y = g_coord.Y + cLines;
6487
Bram Moolenaar6982f422019-02-16 16:48:01 +01006488 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006489 source.Top = g_coord.Y;
6490 source.Right = g_srScrollRegion.Right;
6491 source.Bottom = g_srScrollRegion.Bottom - cLines;
6492
Bram Moolenaar6982f422019-02-16 16:48:01 +01006493 clip.Left = g_srScrollRegion.Left;
6494 clip.Top = g_coord.Y;
6495 clip.Right = g_srScrollRegion.Right;
6496 clip.Bottom = g_srScrollRegion.Bottom;
6497
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006498 fill.Char.AsciiChar = ' ';
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006499 if (!USE_VTP)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006500 fill.Attributes = g_attrCurrent;
6501 else
6502 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006503
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006504 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006505
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006506 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6507
Bram Moolenaar6982f422019-02-16 16:48:01 +01006508 // Here we have to deal with a win32 console flake: If the scroll
6509 // region looks like abc and we scroll c to a and fill with d we get
6510 // cbd... if we scroll block c one line at a time to a, we get cdd...
6511 // vim expects cdd consistently... So we have to deal with that
6512 // here... (this also occurs scrolling the same way in the other
6513 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006514
6515 if (source.Bottom < dest.Y)
6516 {
6517 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006518 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006519
Bram Moolenaar6982f422019-02-16 16:48:01 +01006520 coord.X = source.Left;
6521 for (i = clip.Top; i < dest.Y; ++i)
6522 {
6523 coord.Y = i;
6524 clear_chars(coord, source.Right - source.Left + 1);
6525 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006526 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006527
Christopher Plewright38804d62022-11-09 23:55:52 +00006528 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006529 {
6530 COORD coord;
6531 int i;
6532
6533 coord.X = source.Left;
6534 for (i = source.Top; i < dest.Y; ++i)
6535 {
6536 coord.Y = i;
6537 clear_chars(coord, source.Right - source.Left + 1);
6538 }
6539 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006540}
6541
6542
6543/*
6544 * Delete `cLines' lines at the current cursor position
6545 */
6546 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006547delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006548{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006549 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006550 COORD dest;
6551 CHAR_INFO fill;
6552 int nb;
6553
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006554 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6555
Bram Moolenaar6982f422019-02-16 16:48:01 +01006556 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006557 dest.Y = g_coord.Y;
6558
Bram Moolenaar6982f422019-02-16 16:48:01 +01006559 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006560 source.Top = g_coord.Y + cLines;
6561 source.Right = g_srScrollRegion.Right;
6562 source.Bottom = g_srScrollRegion.Bottom;
6563
Bram Moolenaar6982f422019-02-16 16:48:01 +01006564 clip.Left = g_srScrollRegion.Left;
6565 clip.Top = g_coord.Y;
6566 clip.Right = g_srScrollRegion.Right;
6567 clip.Bottom = g_srScrollRegion.Bottom;
6568
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006569 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006570 if (!vtp_working)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006571 fill.Attributes = g_attrCurrent;
6572 else
6573 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006574
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006575 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006576
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006577 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6578
Bram Moolenaar6982f422019-02-16 16:48:01 +01006579 // Here we have to deal with a win32 console flake; See insert_lines()
6580 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006581
6582 nb = dest.Y + (source.Bottom - source.Top) + 1;
6583
6584 if (nb < source.Top)
6585 {
6586 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006587 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006588
Bram Moolenaar6982f422019-02-16 16:48:01 +01006589 coord.X = source.Left;
6590 for (i = nb; i < clip.Bottom; ++i)
6591 {
6592 coord.Y = i;
6593 clear_chars(coord, source.Right - source.Left + 1);
6594 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006595 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006596
Christopher Plewright38804d62022-11-09 23:55:52 +00006597 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006598 {
6599 COORD coord;
6600 int i;
6601
6602 coord.X = source.Left;
6603 for (i = nb; i <= source.Bottom; ++i)
6604 {
6605 coord.Y = i;
6606 clear_chars(coord, source.Right - source.Left + 1);
6607 }
6608 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006609}
6610
6611
6612/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006613 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006614 */
6615 static void
6616gotoxy(
6617 unsigned x,
6618 unsigned y)
6619{
6620 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6621 return;
6622
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006623 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006624 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006625 // There are reports of double-width characters not displayed
6626 // correctly. This workaround should fix it, similar to how it's done
6627 // for VTP.
6628 g_coord.X = 0;
6629 SetConsoleCursorPosition(g_hConOut, g_coord);
6630
Bram Moolenaar2313b612019-09-27 14:14:32 +02006631 // external cursor coords are 1-based; internal are 0-based
6632 g_coord.X = x - 1;
6633 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006634 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006635 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006636 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006637 {
6638 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006639 // destruction. Insider build bug. Always enabled because it's cheap
6640 // and avoids mistakes with recognizing the build.
6641 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006642
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006643 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006644
6645 g_coord.X = x - 1;
6646 g_coord.Y = y - 1;
6647 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006648}
6649
6650
6651/*
6652 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006653 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006654 */
6655 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006656textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006657{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006658 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006659
6660 SetConsoleTextAttribute(g_hConOut, wAttr);
6661}
6662
6663
6664 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006665textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006666{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006667 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006668
Christopher Plewright38804d62022-11-09 23:55:52 +00006669 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006670 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6671 else
6672 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006673}
6674
6675
6676 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006677textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006678{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006679 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006680
Christopher Plewright38804d62022-11-09 23:55:52 +00006681 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006682 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6683 else
6684 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006685}
6686
6687
6688/*
6689 * restore the default text attribute (whatever we started with)
6690 */
6691 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006692normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006693{
Christopher Plewright38804d62022-11-09 23:55:52 +00006694 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006695 textattr(g_attrDefault);
6696 else
6697 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006698}
6699
6700
6701static WORD g_attrPreStandout = 0;
6702
6703/*
6704 * Make the text standout, by brightening it
6705 */
6706 static void
6707standout(void)
6708{
6709 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006710
Bram Moolenaar071d4272004-06-13 20:20:40 +00006711 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6712}
6713
6714
6715/*
6716 * Turn off standout mode
6717 */
6718 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006719standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006720{
6721 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006722 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006723
6724 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006725}
6726
6727
6728/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006729 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006730 */
6731 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006732mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006733{
6734 char_u *p;
6735 int n;
6736
6737 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6738 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006739 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006740# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006741 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006742# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006743 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006744 {
6745 p = T_ME + 2;
6746 n = getdigits(&p);
6747 if (*p == 'm' && n > 0)
6748 {
6749 cterm_normal_fg_color = (n & 0xf) + 1;
6750 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6751 }
6752 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006753# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006754 cterm_normal_fg_gui_color = INVALCOLOR;
6755 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006756# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006757}
6758
6759
6760/*
6761 * visual bell: flash the screen
6762 */
6763 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006764visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006765{
6766 COORD coordOrigin = {0, 0};
6767 WORD attrFlash = ~g_attrCurrent & 0xff;
6768
6769 DWORD dwDummy;
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006770 LPWORD oldattrs = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006771
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006772# ifdef FEAT_TERMGUICOLORS
6773 if (!(p_tgc || t_colors >= 256))
6774# endif
6775 {
6776 oldattrs = ALLOC_MULT(WORD, Rows * Columns);
6777 if (oldattrs == NULL)
6778 return;
6779 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006780 coordOrigin, &dwDummy);
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006781 }
6782
Bram Moolenaar071d4272004-06-13 20:20:40 +00006783 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6784 coordOrigin, &dwDummy);
6785
Bram Moolenaar0f873732019-12-05 20:28:46 +01006786 Sleep(15); // wait for 15 msec
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006787
6788 if (oldattrs != NULL)
6789 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006790 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006791 coordOrigin, &dwDummy);
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006792 vim_free(oldattrs);
6793 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006794}
6795
6796
6797/*
6798 * Make the cursor visible or invisible
6799 */
6800 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006801cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006802{
6803 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006804
Christopher Plewright38804d62022-11-09 23:55:52 +00006805 if (vtp_working)
Bram Moolenaar2695de62020-04-17 21:13:01 +02006806 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6807
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006808# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006809 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006810# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006811}
6812
6813
6814/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006815 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006816 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006817 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006818 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006819write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006820 char_u *pchBuf,
6821 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006822{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006823 COORD coord = g_coord;
6824 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006825 DWORD n, cchwritten;
6826 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006827 static WCHAR *unicodebuf = NULL;
6828 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006829 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006830 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006831 static WCHAR *utf8spbuf = NULL;
6832 static int utf8splength;
6833 static DWORD utf8spcells;
6834 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006835
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006836 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006837 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006838 utf8usingbuf = &unicodebuf;
6839 do
6840 {
6841 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6842 unicodebuf, unibuflen);
6843 if (length && length <= unibuflen)
6844 break;
6845 vim_free(unicodebuf);
6846 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6847 unibuflen = unibuflen ? 0 : length;
6848 } while(1);
6849 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006850 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006851 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6852 {
6853 if (utf8usingbuf != &utf8spbuf)
6854 {
6855 if (utf8spbuf == NULL)
6856 {
6857 cells = mb_string2cells((char_u *)" ", 1);
6858 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6859 utf8spbuf = LALLOC_MULT(WCHAR, length);
6860 if (utf8spbuf != NULL)
6861 {
6862 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6863 utf8usingbuf = &utf8spbuf;
6864 utf8splength = length;
6865 utf8spcells = cells;
6866 }
6867 }
6868 else
6869 {
6870 utf8usingbuf = &utf8spbuf;
6871 length = utf8splength;
6872 cells = utf8spcells;
6873 }
6874 }
6875 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006876
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006877 if (!USE_VTP)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006878 {
6879 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6880 coord, &written);
6881 // When writing fails or didn't write a single character, pretend one
6882 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006883 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006884 coord, &cchwritten) == 0
6885 || cchwritten == 0 || cchwritten == (DWORD)-1)
6886 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006887 }
6888 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006889 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006890 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006891 NULL) == 0 || cchwritten == 0)
6892 cchwritten = 1;
6893 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006894
K.Takata135e1522022-01-29 15:27:58 +00006895 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006896 {
6897 written = cbToWrite;
6898 g_coord.X += (SHORT)cells;
6899 }
6900 else
6901 {
6902 char_u *p = pchBuf;
6903 for (n = 0; n < cchwritten; n++)
6904 MB_CPTR_ADV(p);
6905 written = p - pchBuf;
6906 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006907 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006908
6909 while (g_coord.X > g_srScrollRegion.Right)
6910 {
6911 g_coord.X -= (SHORT) Columns;
6912 if (g_coord.Y < g_srScrollRegion.Bottom)
6913 g_coord.Y++;
6914 }
6915
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006916 // Cursor under VTP is always in the correct position, no need to reset.
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006917 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006918 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006919
6920 return written;
6921}
6922
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006923 static char_u *
6924get_seq(
6925 int *args,
6926 int *count,
6927 char_u *head)
6928{
6929 int argc;
6930 char_u *p;
6931
6932 if (head == NULL || *head != '\033')
6933 return NULL;
6934
6935 argc = 0;
6936 p = head;
6937 ++p;
6938 do
6939 {
6940 ++p;
6941 args[argc] = getdigits(&p);
6942 argc += (argc < 15) ? 1 : 0;
6943 } while (*p == ';');
6944 *count = argc;
6945
6946 return p;
6947}
6948
6949 static char_u *
6950get_sgr(
6951 int *args,
6952 int *count,
6953 char_u *head)
6954{
6955 char_u *p = get_seq(args, count, head);
6956
6957 return (p && *p == 'm') ? ++p : NULL;
6958}
6959
6960/*
6961 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6962 */
6963 static char_u *
6964sgrn2(
6965 char_u *head,
6966 int n)
6967{
6968 int argc;
6969 int args[16];
6970 char_u *p = get_sgr(args, &argc, head);
6971
6972 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6973}
6974
6975/*
6976 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6977 */
6978 static char_u *
6979sgrnc(
6980 char_u *head,
6981 int n)
6982{
6983 int argc;
6984 int args[16];
6985 char_u *p = get_sgr(args, &argc, head);
6986
6987 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6988 ? p : NULL;
6989}
6990
6991 static char_u *
6992skipblank(char_u *q)
6993{
6994 char_u *p = q;
6995
6996 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6997 ++p;
6998 return p;
6999}
7000
7001/*
7002 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
7003 * NULL.
7004 */
7005 static char_u *
7006sgrn2c(
7007 char_u *head,
7008 int n)
7009{
7010 char_u *p = sgrn2(head, n);
7011
7012 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
7013}
7014
7015/*
7016 * If there is only a newline between the sequence immediately following it,
7017 * a pointer to the character following the newline is returned.
7018 * Otherwise NULL.
7019 */
7020 static char_u *
7021sgrn2cn(
7022 char_u *head,
7023 int n)
7024{
7025 char_u *p = sgrn2(head, n);
7026
7027 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
7028}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007029
7030/*
7031 * mch_write(): write the output buffer to the screen, translating ESC
7032 * sequences into calls to console output routines.
7033 */
7034 void
7035mch_write(
7036 char_u *s,
7037 int len)
7038{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007039 char_u *end = s + len;
7040
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007041# ifdef VIMDLL
7042 if (gui.in_use)
7043 return;
7044# endif
7045
Bram Moolenaar071d4272004-06-13 20:20:40 +00007046 if (!term_console)
7047 {
7048 write(1, s, (unsigned)len);
7049 return;
7050 }
7051
Bram Moolenaar0f873732019-12-05 20:28:46 +01007052 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00007053 while (len--)
7054 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007055 int prefix = -1;
7056 char_u ch;
7057
7058 // While processing a sequence, on rare occasions it seems that another
7059 // sequence may be inserted asynchronously.
7060 if (len < 0)
7061 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01007062 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007063 return;
7064 }
7065
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007066 while (s + ++prefix < end)
7067 {
7068 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007069 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
7070 && ch != '\a' && ch != '\033'))
7071 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007072 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007073
7074 if (p_wd)
7075 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007076 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007077 if (prefix != 0)
7078 prefix = 1;
7079 }
7080
7081 if (prefix != 0)
7082 {
7083 DWORD nWritten;
7084
7085 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007086# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007087 if (fdDump)
7088 {
7089 fputc('>', fdDump);
7090 fwrite(s, sizeof(char_u), nWritten, fdDump);
7091 fputs("<\n", fdDump);
7092 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007093# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007094 len -= (nWritten - 1);
7095 s += nWritten;
7096 }
7097 else if (s[0] == '\n')
7098 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007099 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00007100 if (g_coord.Y == g_srScrollRegion.Bottom)
7101 {
7102 scroll(1);
7103 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
7104 }
7105 else
7106 {
7107 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
7108 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007109# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007110 if (fdDump)
7111 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007112# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007113 s++;
7114 }
7115 else if (s[0] == '\r')
7116 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007117 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00007118 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007119# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007120 if (fdDump)
7121 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007122# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007123 s++;
7124 }
7125 else if (s[0] == '\b')
7126 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007127 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00007128 if (g_coord.X > g_srScrollRegion.Left)
7129 g_coord.X--;
7130 else if (g_coord.Y > g_srScrollRegion.Top)
7131 {
7132 g_coord.X = g_srScrollRegion.Right;
7133 g_coord.Y--;
7134 }
7135 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007136# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007137 if (fdDump)
7138 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007139# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007140 s++;
7141 }
7142 else if (s[0] == '\a')
7143 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007144 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00007145 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007146# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007147 if (fdDump)
7148 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007149# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007150 s++;
7151 }
7152 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
7153 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007154# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007155 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007156# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007157 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007158 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007159 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007160
7161 switch (s[2])
7162 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007163 case '0': case '1': case '2': case '3': case '4':
7164 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007165 if (*(p = get_seq(args, &argc, s)) != 'm')
7166 goto notsgr;
7167
7168 p = s;
7169
7170 // Handling frequent optional sequences. Output to the screen
7171 // takes too long, so do not output as much as possible.
7172
7173 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
7174 // resetFG,FG,BG are omitted.
7175 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007176 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007177 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
7178 len = len + 1 - (int)(p - s);
7179 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007180 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007181 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007182
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007183 // If FG,BG,BG,FG of SGR are connected, the first FG can be
7184 // omitted.
7185 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
7186 p = sp;
7187
7188 // If FG,BG,FG,BG of SGR are connected, the first FG can be
7189 // omitted.
7190 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
7191 p = sp;
7192
7193 // If BG,BG of SGR are connected, the first BG can be omitted.
7194 if (sgrn2((sp = sgrn2(p, 48)), 48))
7195 p = sp;
7196
7197 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007198 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007199 if (sgrn2((sp = sgrnc(p, 39)), 38))
7200 p = sp;
7201
7202 p = get_seq(args, &argc, p);
7203
7204notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007205 arg1 = args[0];
7206 arg2 = args[1];
7207 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007208 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007209 if (argc == 1 && args[0] == 0)
7210 normvideo();
7211 else if (argc == 1)
7212 {
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00007213 if (USE_VTP)
Christopher Plewright38804d62022-11-09 23:55:52 +00007214 textcolor((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007215 else
Christopher Plewright38804d62022-11-09 23:55:52 +00007216 textattr((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007217 }
Christopher Plewright38804d62022-11-09 23:55:52 +00007218 else if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007219 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007220 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007221 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007222 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007223 gotoxy(arg2, arg1);
7224 }
7225 else if (argc == 2 && *p == 'r')
7226 {
7227 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
7228 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01007229 else if (argc == 2 && *p == 'R')
7230 {
7231 set_scroll_region_tb(arg1, arg2);
7232 }
7233 else if (argc == 2 && *p == 'V')
7234 {
7235 set_scroll_region_lr(arg1, arg2);
7236 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007237 else if (argc == 1 && *p == 'A')
7238 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007239 gotoxy(g_coord.X + 1,
7240 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
7241 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007242 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007243 {
7244 textbackground((WORD) arg1);
7245 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007246 else if (argc == 1 && *p == 'C')
7247 {
7248 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
7249 g_coord.Y + 1);
7250 }
7251 else if (argc == 1 && *p == 'f')
7252 {
7253 textcolor((WORD) arg1);
7254 }
7255 else if (argc == 1 && *p == 'H')
7256 {
7257 gotoxy(1, arg1);
7258 }
7259 else if (argc == 1 && *p == 'L')
7260 {
7261 insert_lines(arg1);
7262 }
7263 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007264 {
7265 delete_lines(arg1);
7266 }
7267
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007268 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007269 s = p + 1;
7270 break;
7271
Bram Moolenaar071d4272004-06-13 20:20:40 +00007272 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007273 gotoxy(g_coord.X + 1,
7274 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
7275 goto got3;
7276
7277 case 'B':
7278 visual_bell();
7279 goto got3;
7280
7281 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007282 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
7283 g_coord.Y + 1);
7284 goto got3;
7285
7286 case 'E':
7287 termcap_mode_end();
7288 goto got3;
7289
7290 case 'F':
7291 standout();
7292 goto got3;
7293
7294 case 'f':
7295 standend();
7296 goto got3;
7297
7298 case 'H':
7299 gotoxy(1, 1);
7300 goto got3;
7301
7302 case 'j':
7303 clear_to_end_of_display();
7304 goto got3;
7305
7306 case 'J':
7307 clear_screen();
7308 goto got3;
7309
7310 case 'K':
7311 clear_to_end_of_line();
7312 goto got3;
7313
7314 case 'L':
7315 insert_lines(1);
7316 goto got3;
7317
7318 case 'M':
7319 delete_lines(1);
7320 goto got3;
7321
7322 case 'S':
7323 termcap_mode_start();
7324 goto got3;
7325
7326 case 'V':
7327 cursor_visible(TRUE);
7328 goto got3;
7329
7330 case 'v':
7331 cursor_visible(FALSE);
7332 goto got3;
7333
7334 got3:
7335 s += 3;
7336 len -= 2;
7337 }
7338
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007339# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007340 if (fdDump)
7341 {
7342 fputs("ESC | ", fdDump);
7343 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
7344 fputc('\n', fdDump);
7345 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007346# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007347 }
K.Takatadf5320c2022-09-01 13:20:16 +01007348 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
7349 {
7350 int l = 2;
7351
7352 if (isdigit(s[l]))
7353 l++;
7354 if (s[l] == ' ' && s[l + 1] == 'q')
7355 {
7356 // DECSCUSR (cursor style) sequences
Christopher Plewright38804d62022-11-09 23:55:52 +00007357 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01007358 vtp_printf("%.*s", l + 2, s); // Pass through
7359 s += l + 2;
7360 len -= l + 1;
7361 }
7362 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007363 else
7364 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007365 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00007366 DWORD nWritten;
7367
7368 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007369# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007370 if (fdDump)
7371 {
7372 fputc('>', fdDump);
7373 fwrite(s, sizeof(char_u), nWritten, fdDump);
7374 fputs("<\n", fdDump);
7375 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007376# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007377
7378 len -= (nWritten - 1);
7379 s += nWritten;
7380 }
7381 }
7382
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007383# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007384 if (fdDump)
7385 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007386# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007387}
7388
Bram Moolenaar0f873732019-12-05 20:28:46 +01007389#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00007390
7391
7392/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01007393 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007394 */
7395 void
7396mch_delay(
7397 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02007398 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007399{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007400#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007401 Sleep((int)msec); // never wait for input
7402#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007403# ifdef VIMDLL
7404 if (gui.in_use)
7405 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007406 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007407 return;
7408 }
7409# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02007410 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007411# ifdef FEAT_MZSCHEME
7412 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
7413 {
7414 int towait = p_mzq;
7415
Bram Moolenaar0f873732019-12-05 20:28:46 +01007416 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007417 while (msec > 0)
7418 {
7419 mzvim_check_threads();
7420 if (msec < towait)
7421 towait = msec;
7422 Sleep(towait);
7423 msec -= towait;
7424 }
7425 }
7426 else
7427# endif
7428 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007429 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007430 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007431#endif
7432}
7433
7434
7435/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01007436 * This version of remove is not scared by a readonly (backup) file.
7437 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007438 * Return 0 for success, -1 for failure.
7439 */
7440 int
7441mch_remove(char_u *name)
7442{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007443 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007444 int n;
7445
Bram Moolenaar203258c2016-01-17 22:15:16 +01007446 /*
7447 * On Windows, deleting a directory's symbolic link is done by
7448 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
7449 */
7450 if (mch_isdir(name) && mch_is_symbolic_link(name))
7451 return mch_rmdir(name);
7452
Bram Moolenaar12b559e2013-06-12 22:41:37 +02007453 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
7454
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007455 wn = enc_to_utf16(name, NULL);
7456 if (wn == NULL)
7457 return -1;
7458
7459 n = DeleteFileW(wn) ? 0 : -1;
7460 vim_free(wn);
7461 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007462}
7463
7464
7465/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007466 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007467 */
7468 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007469mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007470{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007471#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7472# ifdef VIMDLL
7473 if (!gui.in_use)
7474# endif
7475 if (g_fCtrlCPressed || g_fCBrkPressed)
7476 {
7477 ctrl_break_was_pressed = g_fCBrkPressed;
7478 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7479 got_int = TRUE;
7480 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007481#endif
7482}
7483
Bram Moolenaar0f873732019-12-05 20:28:46 +01007484// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007485#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007486
7487/*
7488 * How much main memory in KiB that can be used by VIM.
7489 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007490 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007491mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007492{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007493 MEMORYSTATUSEX ms;
7494
Bram Moolenaar0f873732019-12-05 20:28:46 +01007495 // Need to use GlobalMemoryStatusEx() when there is more memory than
7496 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007497 ms.dwLength = sizeof(MEMORYSTATUSEX);
7498 GlobalMemoryStatusEx(&ms);
7499 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007500 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007501 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007502 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007503 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007504 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007505 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007506 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007507 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007508 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007509 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007510 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007511}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007512
Bram Moolenaar071d4272004-06-13 20:20:40 +00007513/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007514 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00007515 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
7516 * file whose short file name is "FOO.BAR" (its long file name will
7517 * be correct: "foo.bar~"). Because a file can be accessed by
7518 * either its SFN or its LFN, "foo.bar" has effectively been
7519 * renamed to "foo.bar", which is not at all what was wanted. This
7520 * seems to happen only when renaming files with three-character
7521 * extensions by appending a suffix that does not include ".".
7522 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
7523 *
7524 * There is another problem, which isn't really a bug but isn't right either:
7525 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
7526 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
7527 * service pack 6. Doesn't seem to happen on Windows 98.
7528 *
7529 * Like rename(), returns 0 upon success, non-zero upon failure.
7530 * Should probably set errno appropriately when errors occur.
7531 */
7532 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007533mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007534{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007535 WCHAR *p;
7536 int i;
7537 WCHAR szTempFile[_MAX_PATH + 1];
7538 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007539 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007540
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007541 // No need to play tricks unless the file name contains a "~" as the
7542 // seventh character.
7543 p = wold;
7544 for (i = 0; wold[i] != NUL; ++i)
7545 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
7546 && wold[i + 1] != 0)
7547 p = wold + i + 1;
7548 if ((int)(wold + i - p) < 8 || p[6] != '~')
7549 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007550
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007551 // Get base path of new file name. Undocumented feature: If pszNewFile is
7552 // a directory, no error is returned and pszFilePart will be NULL.
7553 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007554 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007555 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007556
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007557 // Get (and create) a unique temporary file name in directory of new file
7558 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007559 return -2;
7560
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007561 // blow the temp file away
7562 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007563 return -3;
7564
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007565 // rename old file to the temp file
7566 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007567 return -4;
7568
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007569 // now create an empty file called pszOldFile; this prevents the operating
7570 // system using pszOldFile as an alias (SFN) if we're renaming within the
7571 // same directory. For example, we're editing a file called
7572 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7573 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7574 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7575 // cause all sorts of problems later in buf_write(). So, we create an
7576 // empty file called filena~1.txt and the system will have to find some
7577 // other SFN for filena~1.txt~, such as filena~2.txt
7578 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007579 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7580 return -5;
7581 if (!CloseHandle(hf))
7582 return -6;
7583
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007584 // rename the temp file to the new file
7585 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007586 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007587 // Renaming failed. Rename the file back to its old name, so that it
7588 // looks like nothing happened.
7589 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007590 return -7;
7591 }
7592
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007593 // Seems to be left around on Novell filesystems
7594 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007595
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007596 // finally, remove the empty old file
7597 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007598 return -8;
7599
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007600 return 0;
7601}
7602
7603
7604/*
7605 * Converts the filenames to UTF-16, then call mch_wrename().
7606 * Like rename(), returns 0 upon success, non-zero upon failure.
7607 */
7608 int
7609mch_rename(
7610 const char *pszOldFile,
7611 const char *pszNewFile)
7612{
7613 WCHAR *wold = NULL;
7614 WCHAR *wnew = NULL;
7615 int retval = -1;
7616
7617 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7618 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7619 if (wold != NULL && wnew != NULL)
7620 retval = mch_wrename(wold, wnew);
7621 vim_free(wold);
7622 vim_free(wnew);
7623 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007624}
7625
7626/*
7627 * Get the default shell for the current hardware platform
7628 */
7629 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007630default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007631{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007632 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007633}
7634
7635/*
7636 * mch_access() extends access() to do more detailed check on network drives.
7637 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7638 */
7639 int
7640mch_access(char *n, int p)
7641{
7642 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007643 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007644 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007645
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007646 wn = enc_to_utf16((char_u *)n, NULL);
7647 if (wn == NULL)
7648 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007649
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007650 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007651 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007652 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007653
7654 if (p & R_OK)
7655 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007656 // Read check is performed by seeing if we can do a find file on
7657 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007658 int i;
7659 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007660
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007661 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7662 TempNameW[i] = wn[i];
7663 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7664 TempNameW[i++] = '\\';
7665 TempNameW[i++] = '*';
7666 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007667
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007668 hFile = FindFirstFileW(TempNameW, &d);
7669 if (hFile == INVALID_HANDLE_VALUE)
7670 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007671 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007672 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007673 }
7674
7675 if (p & W_OK)
7676 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007677 // Trying to create a temporary file in the directory should catch
7678 // directories on read-only network shares. However, in
7679 // directories whose ACL allows writes but denies deletes will end
7680 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007681 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7682 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007683 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007684 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007685 }
7686 }
7687 else
7688 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007689 // Don't consider a file read-only if another process has opened it.
7690 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7691
Bram Moolenaar0f873732019-12-05 20:28:46 +01007692 // Trying to open the file for the required access does ACL, read-only
7693 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007694 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7695 | ((p & R_OK) ? GENERIC_READ : 0);
7696
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007697 hFile = CreateFileW(wn, access_mode, share_mode,
7698 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007699 if (hFile == INVALID_HANDLE_VALUE)
7700 goto getout;
7701 CloseHandle(hFile);
7702 }
7703
Bram Moolenaar0f873732019-12-05 20:28:46 +01007704 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007705getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007706 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007707 return retval;
7708}
7709
Bram Moolenaar071d4272004-06-13 20:20:40 +00007710/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007711 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007712 */
7713 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007714mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007715{
7716 WCHAR *wn;
7717 int f;
7718
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007719 wn = enc_to_utf16((char_u *)name, NULL);
7720 if (wn == NULL)
7721 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007722
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007723 f = _wopen(wn, flags, mode);
7724 vim_free(wn);
7725 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007726}
7727
7728/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007729 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007730 */
7731 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007732mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007733{
7734 WCHAR *wn, *wm;
7735 FILE *f = NULL;
7736
Bram Moolenaara12a1612019-01-24 16:39:02 +01007737#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007738 // Work around an annoying assertion in the Microsoft debug CRT
7739 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007740 char newMode = mode[strlen(mode) - 1];
7741 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007742
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007743 _get_fmode(&oldMode);
7744 if (newMode == 't')
7745 _set_fmode(_O_TEXT);
7746 else if (newMode == 'b')
7747 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007748#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007749 wn = enc_to_utf16((char_u *)name, NULL);
7750 wm = enc_to_utf16((char_u *)mode, NULL);
7751 if (wn != NULL && wm != NULL)
7752 f = _wfopen(wn, wm);
7753 vim_free(wn);
7754 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007755
Bram Moolenaara12a1612019-01-24 16:39:02 +01007756#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007757 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007758#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007759 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007760}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007761
Bram Moolenaar071d4272004-06-13 20:20:40 +00007762/*
7763 * SUB STREAM (aka info stream) handling:
7764 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007765 * NTFS can have sub streams for each file. The normal contents of a file is
7766 * stored in the main stream, and extra contents (author information, title and
7767 * so on) can be stored in a sub stream. After Windows 2000, the user can
7768 * access and store this information in sub streams via an explorer's property
7769 * menu item in the right click menu. This information in sub streams was lost
7770 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007771 *
7772 * Incomplete explanation:
7773 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7774 * More useful info and an example:
7775 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7776 */
7777
7778/*
7779 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7780 * and write to stream "substream" of file "to".
7781 * Errors are ignored.
7782 */
7783 static void
7784copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7785{
7786 HANDLE hTo;
7787 WCHAR *to_name;
7788
7789 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7790 wcscpy(to_name, to);
7791 wcscat(to_name, substream);
7792
7793 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7794 FILE_ATTRIBUTE_NORMAL, NULL);
7795 if (hTo != INVALID_HANDLE_VALUE)
7796 {
7797 long done;
7798 DWORD todo;
7799 DWORD readcnt, written;
7800 char buf[4096];
7801
Bram Moolenaar0f873732019-12-05 20:28:46 +01007802 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007803 for (done = 0; done < len; done += written)
7804 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007805 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007806 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7807 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007808 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7809 FALSE, FALSE, context)
7810 || readcnt != todo
7811 || !WriteFile(hTo, buf, todo, &written, NULL)
7812 || written != todo)
7813 break;
7814 }
7815 CloseHandle(hTo);
7816 }
7817
7818 free(to_name);
7819}
7820
7821/*
7822 * Copy info streams from file "from" to file "to".
7823 */
7824 static void
7825copy_infostreams(char_u *from, char_u *to)
7826{
7827 WCHAR *fromw;
7828 WCHAR *tow;
7829 HANDLE sh;
7830 WIN32_STREAM_ID sid;
7831 int headersize;
7832 WCHAR streamname[_MAX_PATH];
7833 DWORD readcount;
7834 void *context = NULL;
7835 DWORD lo, hi;
7836 int len;
7837
Bram Moolenaar0f873732019-12-05 20:28:46 +01007838 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007839 fromw = enc_to_utf16(from, NULL);
7840 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007841 if (fromw != NULL && tow != NULL)
7842 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007843 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007844 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7845 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7846 if (sh != INVALID_HANDLE_VALUE)
7847 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007848 // Use BackupRead() to find the info streams. Repeat until we
7849 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007850 for (;;)
7851 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007852 // Get the header to find the length of the stream name. If
7853 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007854 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007855 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007856 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7857 &readcount, FALSE, FALSE, &context)
7858 || readcount == 0)
7859 break;
7860
Bram Moolenaar0f873732019-12-05 20:28:46 +01007861 // We only deal with streams that have a name. The normal
7862 // file data appears to be without a name, even though docs
7863 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007864 if (sid.dwStreamNameSize > 0)
7865 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007866 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007867 if (!BackupRead(sh, (LPBYTE)streamname,
7868 sid.dwStreamNameSize,
7869 &readcount, FALSE, FALSE, &context))
7870 break;
7871
Bram Moolenaar0f873732019-12-05 20:28:46 +01007872 // Copy an info stream with a name ":anything:$DATA".
7873 // Skip "::$DATA", it has no stream name (examples suggest
7874 // it might be used for the normal file contents).
7875 // Note that BackupRead() counts bytes, but the name is in
7876 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007877 len = readcount / sizeof(WCHAR);
7878 streamname[len] = 0;
7879 if (len > 7 && wcsicmp(streamname + len - 6,
7880 L":$DATA") == 0)
7881 {
7882 streamname[len - 6] = 0;
7883 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007884 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007885 }
7886 }
7887
Bram Moolenaar0f873732019-12-05 20:28:46 +01007888 // Advance to the next stream. We might try seeking too far,
7889 // but BackupSeek() doesn't skip over stream borders, thus
7890 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007891 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007892 &lo, &hi, &context);
7893 }
7894
Bram Moolenaar0f873732019-12-05 20:28:46 +01007895 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007896 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7897
7898 CloseHandle(sh);
7899 }
7900 }
7901 vim_free(fromw);
7902 vim_free(tow);
7903}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007904
7905/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007906 * ntdll.dll definitions
7907 */
7908#define FileEaInformation 7
7909#ifndef STATUS_SUCCESS
7910# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7911#endif
7912
7913typedef struct _FILE_FULL_EA_INFORMATION_ {
7914 ULONG NextEntryOffset;
7915 UCHAR Flags;
7916 UCHAR EaNameLength;
7917 USHORT EaValueLength;
7918 CHAR EaName[1];
7919} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7920
7921typedef struct _FILE_EA_INFORMATION_ {
7922 ULONG EaSize;
7923} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7924
Paul Ollis65745772022-06-05 16:55:54 +01007925#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007926typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7927 PHANDLE FileHandle,
7928 ACCESS_MASK DesiredAccess,
7929 POBJECT_ATTRIBUTES ObjectAttributes,
7930 PIO_STATUS_BLOCK IoStatusBlock,
7931 ULONG ShareAccess,
7932 ULONG OpenOptions);
7933typedef NTSTATUS (NTAPI *PfnNtClose)(
7934 HANDLE Handle);
7935typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007936 HANDLE FileHandle,
7937 PIO_STATUS_BLOCK IoStatusBlock,
7938 PVOID Buffer,
7939 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007940typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7941 HANDLE FileHandle,
7942 PIO_STATUS_BLOCK IoStatusBlock,
7943 PVOID Buffer,
7944 ULONG Length,
7945 BOOLEAN ReturnSingleEntry,
7946 PVOID EaList,
7947 ULONG EaListLength,
7948 PULONG EaIndex,
7949 BOOLEAN RestartScan);
7950typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007951 HANDLE FileHandle,
7952 PIO_STATUS_BLOCK IoStatusBlock,
7953 PVOID FileInformation,
7954 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007955 FILE_INFORMATION_CLASS FileInformationClass);
7956typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7957 PUNICODE_STRING DestinationString,
7958 PCWSTR SourceString);
7959
7960PfnNtOpenFile pNtOpenFile = NULL;
7961PfnNtClose pNtClose = NULL;
7962PfnNtSetEaFile pNtSetEaFile = NULL;
7963PfnNtQueryEaFile pNtQueryEaFile = NULL;
7964PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7965PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01007966#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007967
7968/*
7969 * Load ntdll.dll functions.
7970 */
7971 static BOOL
7972load_ntdll(void)
7973{
7974 static int loaded = -1;
7975
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00007976 if (loaded != -1)
7977 return (BOOL) loaded;
7978
7979 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7980 if (hNtdll != NULL)
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007981 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00007982 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7983 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7984 pNtSetEaFile = (PfnNtSetEaFile)
7985 GetProcAddress(hNtdll, "NtSetEaFile");
7986 pNtQueryEaFile = (PfnNtQueryEaFile)
7987 GetProcAddress(hNtdll, "NtQueryEaFile");
7988 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7989 GetProcAddress(hNtdll, "NtQueryInformationFile");
7990 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7991 GetProcAddress(hNtdll, "RtlInitUnicodeString");
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007992 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00007993 if (pNtOpenFile == NULL
7994 || pNtClose == NULL
7995 || pNtSetEaFile == NULL
7996 || pNtQueryEaFile == NULL
7997 || pNtQueryInformationFile == NULL
7998 || pRtlInitUnicodeString == NULL)
7999 loaded = FALSE;
8000 else
8001 loaded = TRUE;
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008002 return (BOOL) loaded;
8003}
8004
8005/*
8006 * Copy extended attributes (EA) from file "from" to file "to".
8007 */
8008 static void
8009copy_extattr(char_u *from, char_u *to)
8010{
8011 char_u *fromf = NULL;
8012 char_u *tof = NULL;
8013 WCHAR *fromw = NULL;
8014 WCHAR *tow = NULL;
8015 UNICODE_STRING u;
8016 HANDLE h;
8017 OBJECT_ATTRIBUTES oa;
8018 IO_STATUS_BLOCK iosb;
8019 FILE_EA_INFORMATION_ eainfo = {0};
8020 void *ea = NULL;
8021
8022 if (!load_ntdll())
8023 return;
8024
8025 // Convert the file names to the fully qualified object names.
8026 fromf = alloc(STRLEN(from) + 5);
8027 tof = alloc(STRLEN(to) + 5);
8028 if (fromf == NULL || tof == NULL)
8029 goto theend;
8030 STRCPY(fromf, "\\??\\");
8031 STRCAT(fromf, from);
8032 STRCPY(tof, "\\??\\");
8033 STRCAT(tof, to);
8034
8035 // Convert the names to wide characters.
8036 fromw = enc_to_utf16(fromf, NULL);
8037 tow = enc_to_utf16(tof, NULL);
8038 if (fromw == NULL || tow == NULL)
8039 goto theend;
8040
8041 // Get the EA.
8042 pRtlInitUnicodeString(&u, fromw);
8043 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8044 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
8045 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8046 goto theend;
8047 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
8048 FileEaInformation);
8049 if (eainfo.EaSize != 0)
8050 {
8051 ea = alloc(eainfo.EaSize);
8052 if (ea != NULL)
8053 {
8054 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
8055 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
8056 {
8057 vim_free(ea);
8058 ea = NULL;
8059 }
8060 }
8061 }
8062 pNtClose(h);
8063
8064 // Set the EA.
8065 if (ea != NULL)
8066 {
8067 pRtlInitUnicodeString(&u, tow);
8068 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8069 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
8070 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8071 goto theend;
8072
8073 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
8074 pNtClose(h);
8075 }
8076
8077theend:
8078 vim_free(fromf);
8079 vim_free(tof);
8080 vim_free(fromw);
8081 vim_free(tow);
8082 vim_free(ea);
8083}
8084
8085/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008086 * Copy file attributes from file "from" to file "to".
8087 * For Windows NT and later we copy info streams.
8088 * Always returns zero, errors are ignored.
8089 */
8090 int
8091mch_copy_file_attribute(char_u *from, char_u *to)
8092{
Bram Moolenaar0f873732019-12-05 20:28:46 +01008093 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02008094 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008095 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008096 return 0;
8097}
8098
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008099
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008100/*
K.Takatadc73b4b2021-06-08 18:32:36 +02008101 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008102 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008103static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008104static LPWSTR *ArglistW = NULL;
8105static int global_argc = 0;
8106static char **global_argv;
8107
Bram Moolenaar0f873732019-12-05 20:28:46 +01008108static int used_file_argc = 0; // last argument in global_argv[] used
8109 // for the argument list.
8110static int *used_file_indexes = NULL; // indexes in global_argv[] for
8111 // command line arguments added to
8112 // the argument list
8113static int used_file_count = 0; // nr of entries in used_file_indexes
8114static int used_file_literal = FALSE; // take file names literally
8115static int used_file_full_path = FALSE; // file name was full path
8116static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008117static int used_alist_count = 0;
8118
8119
8120/*
8121 * Get the command line arguments. Unicode version.
8122 * Returns argc. Zero when something fails.
8123 */
8124 int
8125get_cmd_argsW(char ***argvp)
8126{
8127 char **argv = NULL;
8128 int argc = 0;
8129 int i;
8130
Bram Moolenaar14993322014-09-09 12:25:33 +02008131 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008132 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
8133 if (ArglistW != NULL)
8134 {
8135 argv = malloc((nArgsW + 1) * sizeof(char *));
8136 if (argv != NULL)
8137 {
8138 argc = nArgsW;
8139 argv[argc] = NULL;
8140 for (i = 0; i < argc; ++i)
8141 {
8142 int len;
8143
K.Takatadc73b4b2021-06-08 18:32:36 +02008144 // Convert each Unicode argument to UTF-8.
8145 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008146 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008147 (LPSTR *)&argv[i], &len, 0, 0);
8148 if (argv[i] == NULL)
8149 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008150 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008151 while (i > 0)
8152 free(argv[--i]);
8153 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01008154 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008155 argc = 0;
8156 }
8157 }
8158 }
8159 }
8160
8161 global_argc = argc;
8162 global_argv = argv;
8163 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02008164 {
8165 if (used_file_indexes != NULL)
8166 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008167 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02008168 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008169
8170 if (argvp != NULL)
8171 *argvp = argv;
8172 return argc;
8173}
8174
8175 void
8176free_cmd_argsW(void)
8177{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008178 if (ArglistW == NULL)
8179 return;
8180
8181 GlobalFree(ArglistW);
8182 ArglistW = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008183}
8184
8185/*
8186 * Remember "name" is an argument that was added to the argument list.
8187 * This avoids that we have to re-parse the argument list when fix_arg_enc()
8188 * is called.
8189 */
8190 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008191used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008192{
8193 int i;
8194
8195 if (used_file_indexes == NULL)
8196 return;
8197 for (i = used_file_argc + 1; i < global_argc; ++i)
8198 if (STRCMP(global_argv[i], name) == 0)
8199 {
8200 used_file_argc = i;
8201 used_file_indexes[used_file_count++] = i;
8202 break;
8203 }
8204 used_file_literal = literal;
8205 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008206 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008207}
8208
8209/*
8210 * Remember the length of the argument list as it was. If it changes then we
8211 * leave it alone when 'encoding' is set.
8212 */
8213 void
8214set_alist_count(void)
8215{
8216 used_alist_count = GARGCOUNT;
8217}
8218
8219/*
8220 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02008221 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008222 * and convert them to 'encoding'.
8223 */
8224 void
8225fix_arg_enc(void)
8226{
8227 int i;
8228 int idx;
8229 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00008230 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008231
Bram Moolenaar0f873732019-12-05 20:28:46 +01008232 // Safety checks:
8233 // - if argument count differs between the wide and non-wide argument
8234 // list, something must be wrong.
8235 // - the file name arguments must have been located.
8236 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008237 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008238 || ArglistW == NULL
8239 || used_file_indexes == NULL
8240 || used_file_count == 0
8241 || used_alist_count != GARGCOUNT)
8242 return;
8243
Bram Moolenaar0f873732019-12-05 20:28:46 +01008244 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02008245 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008246 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008247 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00008248 for (i = 0; i < GARGCOUNT; ++i)
8249 fnum_list[i] = GARGLIST[i].ae_fnum;
8250
Bram Moolenaar0f873732019-12-05 20:28:46 +01008251 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008252 alist_clear(&global_alist);
8253 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008254 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008255
8256 for (i = 0; i < used_file_count; ++i)
8257 {
8258 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008259 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008260 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00008261 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008262 int literal = used_file_literal;
8263
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008264#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01008265 // When using diff mode may need to concatenate file name to
8266 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008267 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
8268 && !mch_isdir(alist_name(&GARGLIST[0])))
8269 {
8270 char_u *r;
8271
8272 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
8273 if (r != NULL)
8274 {
8275 vim_free(str);
8276 str = r;
8277 }
8278 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008279#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01008280 // Re-use the old buffer by renaming it. When not using literal
8281 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00008282 if (used_file_literal)
8283 buf_set_name(fnum_list[i], str);
8284
Bram Moolenaar0f873732019-12-05 20:28:46 +01008285 // Check backtick literal. backtick literal is already expanded in
8286 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008287 if (literal == FALSE)
8288 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02008289 size_t len = STRLEN(str);
8290
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008291 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
8292 literal = TRUE;
8293 }
8294 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008295 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008296 }
8297
8298 if (!used_file_literal)
8299 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008300 // Now expand wildcards in the arguments.
8301 // Temporarily add '(' and ')' to 'isfname'. These are valid
8302 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00008303 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01008304 // Also, unset wildignore to not be influenced by this option.
8305 // The arguments specified in command-line should be kept even if
8306 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00008307 // Use :legacy so that it also works when in Vim9 script.
8308 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
8309 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00008310 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00008311 do_cmdline_cmd(
8312 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
8313 do_cmdline_cmd(
8314 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008315 }
8316
Bram Moolenaar0f873732019-12-05 20:28:46 +01008317 // If wildcard expansion failed, we are editing the first file of the
8318 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008319 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
8320 {
8321 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00008322 if (GARGCOUNT == 1 && used_file_full_path
8323 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
8324 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008325 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00008326
8327 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008328}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008329
8330 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02008331mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008332{
8333 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008334 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008335
Bram Moolenaar964b3742019-05-24 18:54:09 +02008336 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008337 if (envbuf == NULL)
8338 return -1;
8339
8340 sprintf((char *)envbuf, "%s=%s", var, value);
8341
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008342 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008343
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008344 vim_free(envbuf);
8345 if (p == NULL)
8346 return -1;
8347 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008348#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008349 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008350#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008351 // Unlike Un*x systems, we can free the string for _wputenv().
8352 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008353
8354 return 0;
8355}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008356
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008357/*
8358 * Support for 256 colors and 24-bit colors was added in Windows 10
8359 * version 1703 (Creators update).
8360 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008361#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
8362
8363/*
8364 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02008365 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008366 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008367#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008368
8369/*
8370 * ConPTY differences between versions, need different logic.
8371 * version 1903 (May 2019 update).
8372 */
8373#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
8374
8375/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008376 * version 1909 (November 2019 update).
8377 */
8378#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
8379
8380/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008381 * Stay ahead of the next update, and when it's done, fix this.
8382 * version ? (2020 update, temporarily use the build number of insider preview)
8383 */
8384#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
8385
8386/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02008387 * Confirm until this version. Also the logic changes.
8388 * insider preview.
8389 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02008390#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008391
8392/*
8393 * Not stable now.
8394 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008395#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Christopher Plewright1140b512022-11-12 18:46:05 +00008396// Notes:
8397// Win 10 22H2 Final is build 19045, it's conpty is widely used.
8398// Strangely, 19045 is newer but is a lower build number than the 2020 insider
8399// preview which had a build 19587. And, not sure how stable that was?
8400// Win Server 2022 (May 10, 2022) is build 20348, its conpty is widely used.
8401// Win 11 starts from build 22000, even though the major version says 10!
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008402
8403 static void
8404vtp_flag_init(void)
8405{
8406 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008407#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008408 DWORD mode;
8409 HANDLE out;
8410
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008411# ifdef VIMDLL
8412 if (!gui.in_use)
8413# endif
8414 {
8415 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008416
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008417 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
8418 GetConsoleMode(out, &mode);
8419 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
8420 if (SetConsoleMode(out, mode) == 0)
8421 vtp_working = 0;
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008422
8423 // VTP uses alternate screen buffer.
8424 // But, not if running in a nested terminal
8425 use_alternate_screen_buffer = win10_22H2_or_later && p_rs && vtp_working
8426 && !mch_getenv("VIM_TERMINAL");
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008427 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008428#endif
8429
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008430 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008431 conpty_working = 1;
8432 if (ver >= CONPTY_STABLE_BUILD)
8433 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008434
Bram Moolenaar57da6982019-09-13 22:30:11 +02008435 if (ver <= CONPTY_INSIDER_BUILD)
8436 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008437 if (ver <= CONPTY_1909_BUILD)
8438 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02008439 if (ver <= CONPTY_1903_BUILD)
8440 conpty_type = 2;
8441 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
8442 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008443
8444 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
8445 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008446}
8447
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008448#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008449
8450 static void
8451vtp_init(void)
8452{
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008453# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightd343c602023-01-22 18:58:30 +00008454 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8455 csbi.cbSize = sizeof(csbi);
8456 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8457 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
8458 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
8459 store_console_bg_rgb = save_console_bg_rgb;
8460 store_console_fg_rgb = save_console_fg_rgb;
Christopher Plewright38804d62022-11-09 23:55:52 +00008461
Christopher Plewrightd343c602023-01-22 18:58:30 +00008462 COLORREF bg;
8463 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
8464 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8465 default_console_color_bg = bg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008466
Christopher Plewrightd343c602023-01-22 18:58:30 +00008467 COLORREF fg;
8468 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
8469 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8470 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008471# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008472 set_console_color_rgb();
8473}
8474
8475 static void
8476vtp_exit(void)
8477{
Bram Moolenaardf543822020-01-30 11:53:59 +01008478 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008479}
8480
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008481 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008482vtp_printf(
8483 char *format,
8484 ...)
8485{
8486 char_u buf[100];
8487 va_list list;
8488 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008489 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008490
8491 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008492 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008493 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008494 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008495 return (int)result;
8496}
8497
8498 static void
8499vtp_sgr_bulk(
8500 int arg)
8501{
8502 int args[1];
8503
8504 args[0] = arg;
8505 vtp_sgr_bulks(1, args);
8506}
8507
K.Takata6e1d31e2022-02-03 13:05:32 +00008508# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008509 if ((*p-- = "0123456789"[(n = x % 10)]) \
8510 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8511 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8512
K.Takata6e1d31e2022-02-03 13:05:32 +00008513# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008514 case x: \
8515 FAST256(newargs[x - 1]);
8516
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008517 static void
8518vtp_sgr_bulks(
8519 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008520 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008521{
K.Takata6e1d31e2022-02-03 13:05:32 +00008522# define MAXSGR 16
8523# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008524 char_u buf[SGRBUFSIZE];
8525 char_u *p;
8526 int in, out;
8527 int newargs[16];
8528 static int sgrfgr = -1, sgrfgg, sgrfgb;
8529 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008530
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008531 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008532 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008533 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008534 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008535 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008536 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008537
8538 in = out = 0;
8539 while (in < argc)
8540 {
8541 int s = args[in];
8542 int copylen = 1;
8543
8544 if (s == 38)
8545 {
8546 if (argc - in >= 5 && args[in + 1] == 2)
8547 {
8548 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8549 && sgrfgb == args[in + 4])
8550 {
8551 in += 5;
8552 copylen = 0;
8553 }
8554 else
8555 {
8556 sgrfgr = args[in + 2];
8557 sgrfgg = args[in + 3];
8558 sgrfgb = args[in + 4];
8559 copylen = 5;
8560 }
8561 }
8562 else if (argc - in >= 3 && args[in + 1] == 5)
8563 {
8564 sgrfgr = -1;
8565 copylen = 3;
8566 }
8567 }
8568 else if (s == 48)
8569 {
8570 if (argc - in >= 5 && args[in + 1] == 2)
8571 {
8572 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8573 && sgrbgb == args[in + 4])
8574 {
8575 in += 5;
8576 copylen = 0;
8577 }
8578 else
8579 {
8580 sgrbgr = args[in + 2];
8581 sgrbgg = args[in + 3];
8582 sgrbgb = args[in + 4];
8583 copylen = 5;
8584 }
8585 }
8586 else if (argc - in >= 3 && args[in + 1] == 5)
8587 {
8588 sgrbgr = -1;
8589 copylen = 3;
8590 }
8591 }
8592 else if (30 <= s && s <= 39)
8593 sgrfgr = -1;
8594 else if (90 <= s && s <= 97)
8595 sgrfgr = -1;
8596 else if (40 <= s && s <= 49)
8597 sgrbgr = -1;
8598 else if (100 <= s && s <= 107)
8599 sgrbgr = -1;
8600 else if (s == 0)
8601 sgrfgr = sgrbgr = -1;
8602
8603 while (copylen--)
8604 newargs[out++] = args[in++];
8605 }
8606
8607 p = &buf[sizeof(buf) - 1];
8608 *p-- = 'm';
8609
8610 switch (out)
8611 {
8612 int n, m;
8613 DWORD r;
8614
8615 FAST256CASE(16);
8616 *p-- = ';';
8617 FAST256CASE(15);
8618 *p-- = ';';
8619 FAST256CASE(14);
8620 *p-- = ';';
8621 FAST256CASE(13);
8622 *p-- = ';';
8623 FAST256CASE(12);
8624 *p-- = ';';
8625 FAST256CASE(11);
8626 *p-- = ';';
8627 FAST256CASE(10);
8628 *p-- = ';';
8629 FAST256CASE(9);
8630 *p-- = ';';
8631 FAST256CASE(8);
8632 *p-- = ';';
8633 FAST256CASE(7);
8634 *p-- = ';';
8635 FAST256CASE(6);
8636 *p-- = ';';
8637 FAST256CASE(5);
8638 *p-- = ';';
8639 FAST256CASE(4);
8640 *p-- = ';';
8641 FAST256CASE(3);
8642 *p-- = ';';
8643 FAST256CASE(2);
8644 *p-- = ';';
8645 FAST256CASE(1);
8646 *p-- = '[';
8647 *p = '\033';
8648 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8649 default:
8650 break;
8651 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008652}
8653
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008654 static void
8655wt_init(void)
8656{
Christopher Plewright1140b512022-11-12 18:46:05 +00008657 wt_working = mch_getenv("WT_SESSION") != NULL;
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008658}
8659
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008660# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008661 static int
8662ctermtoxterm(
8663 int cterm)
8664{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008665 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008666
8667 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8668 return (((int)r << 16) | ((int)g << 8) | (int)b);
8669}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008670# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008671
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008672 static void
8673set_console_color_rgb(void)
8674{
8675# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008676 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008677 guicolor_T fg, bg;
8678 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008679
Christopher Plewright38804d62022-11-09 23:55:52 +00008680 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008681 return;
8682
Bram Moolenaara050b942019-12-02 21:35:31 +01008683 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8684
Christopher Plewright38804d62022-11-09 23:55:52 +00008685 if (p_tgc || t_colors >= 256)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008686 {
8687 term_fg_rgb_color(fg);
8688 term_bg_rgb_color(bg);
8689 return;
8690 }
8691
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008692 if (use_alternate_screen_buffer)
8693 return;
8694
Christopher Plewrightd343c602023-01-22 18:58:30 +00008695 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8696 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008697
Christopher Plewrightd343c602023-01-22 18:58:30 +00008698 csbi.cbSize = sizeof(csbi);
8699 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008700
Christopher Plewrightd343c602023-01-22 18:58:30 +00008701 csbi.cbSize = sizeof(csbi);
8702 csbi.srWindow.Right += 1;
8703 csbi.srWindow.Bottom += 1;
8704 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8705 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
8706 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8707 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
8708 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008709# endif
8710}
8711
Bram Moolenaara050b942019-12-02 21:35:31 +01008712# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8713 void
8714get_default_console_color(
8715 int *cterm_fg,
8716 int *cterm_bg,
8717 guicolor_T *gui_fg,
8718 guicolor_T *gui_bg)
8719{
8720 int id;
8721 guicolor_T guifg = INVALCOLOR;
8722 guicolor_T guibg = INVALCOLOR;
8723 int ctermfg = 0;
8724 int ctermbg = 0;
Christopher Plewright38804d62022-11-09 23:55:52 +00008725 int dummynull = 0;
Bram Moolenaara050b942019-12-02 21:35:31 +01008726
8727 id = syn_name2id((char_u *)"Normal");
8728 if (id > 0 && p_tgc)
8729 syn_id2colors(id, &guifg, &guibg);
8730 if (guifg == INVALCOLOR)
8731 {
8732 ctermfg = -1;
8733 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008734 syn_id2cterm_bg(id, &ctermfg, &dummynull);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008735 if (ctermfg != -1)
8736 guifg = ctermtoxterm(ctermfg);
Christopher Plewright38804d62022-11-09 23:55:52 +00008737 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008738 guifg = USE_WT ? INVALCOLOR : default_console_color_fg;
8739 cterm_normal_fg_gui_color = guifg;
8740 ctermfg = ctermfg < 0 ? 0 : ctermfg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008741 }
8742 if (guibg == INVALCOLOR)
8743 {
8744 ctermbg = -1;
8745 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008746 syn_id2cterm_bg(id, &dummynull, &ctermbg);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008747 if (ctermbg != -1)
8748 guibg = ctermtoxterm(ctermbg);
K.Takatae53a0d42022-09-05 21:45:11 +01008749 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008750 guibg = USE_WT ? INVALCOLOR : default_console_color_bg;
8751 cterm_normal_bg_gui_color = guibg;
8752 ctermbg = ctermbg < 0 ? 0 : ctermbg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008753 }
8754
8755 *cterm_fg = ctermfg;
8756 *cterm_bg = ctermbg;
8757 *gui_fg = guifg;
8758 *gui_bg = guibg;
8759}
8760# endif
8761
Bram Moolenaardf543822020-01-30 11:53:59 +01008762/*
8763 * Set the console colors to the original colors or the last set colors.
8764 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008765 static void
8766reset_console_color_rgb(void)
8767{
8768# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008769 if (use_alternate_screen_buffer)
8770 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008771
Christopher Plewright38804d62022-11-09 23:55:52 +00008772 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8773
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008774 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008775 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008776
8777 csbi.cbSize = sizeof(csbi);
8778 csbi.srWindow.Right += 1;
8779 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008780 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8781 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008782 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008783# endif
8784}
8785
8786/*
8787 * Set the console colors to the original colors.
8788 */
8789 static void
8790restore_console_color_rgb(void)
8791{
8792# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008793 if (use_alternate_screen_buffer)
8794 return;
Christopher Plewright38804d62022-11-09 23:55:52 +00008795
K.Takata27b53be2022-09-18 12:25:49 +01008796 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008797
8798 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008799 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008800
8801 csbi.cbSize = sizeof(csbi);
8802 csbi.srWindow.Right += 1;
8803 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008804 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8805 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008806 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008807# endif
8808}
8809
8810 void
8811control_console_color_rgb(void)
8812{
Christopher Plewright38804d62022-11-09 23:55:52 +00008813 if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008814 set_console_color_rgb();
8815 else
8816 reset_console_color_rgb();
8817}
8818
8819 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008820use_vtp(void)
8821{
8822 return USE_VTP;
8823}
8824
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008825 int
8826is_term_win32(void)
8827{
8828 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8829}
8830
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008831 int
8832has_vtp_working(void)
8833{
8834 return vtp_working;
8835}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008836
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008837#endif
8838
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008839 int
8840has_conpty_working(void)
8841{
8842 return conpty_working;
8843}
8844
8845 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008846get_conpty_type(void)
8847{
8848 return conpty_type;
8849}
8850
8851 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008852is_conpty_stable(void)
8853{
8854 return conpty_stable;
8855}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008856
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008857 int
8858get_conpty_fix_type(void)
8859{
8860 return conpty_fix_type;
8861}
8862
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008863#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008864 void
8865resize_console_buf(void)
8866{
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008867 if (use_alternate_screen_buffer)
8868 return;
8869
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008870 CONSOLE_SCREEN_BUFFER_INFO csbi;
8871 COORD coord;
8872 SMALL_RECT newsize;
8873
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008874 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8875 return;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008876
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008877 coord.X = SRWIDTH(csbi.srWindow);
8878 coord.Y = SRHEIGHT(csbi.srWindow);
8879 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008880
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008881 newsize.Left = 0;
8882 newsize.Top = 0;
8883 newsize.Right = coord.X - 1;
8884 newsize.Bottom = coord.Y - 1;
8885 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8886
8887 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008888}
8889#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008890
8891 char *
8892GetWin32Error(void)
8893{
K.Takatad68b2fc2022-02-12 11:18:37 +00008894 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008895 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008896
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008897 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8898 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008899 if (oldmsg != NULL)
8900 LocalFree(oldmsg);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008901 if (msg == NULL)
8902 return NULL;
8903
8904 // remove trailing \r\n
8905 char *pcrlf = strstr(msg, "\r\n");
8906 if (pcrlf != NULL)
8907 *pcrlf = '\0';
8908 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008909 return msg;
8910}
Paul Ollis65745772022-06-05 16:55:54 +01008911
8912#if defined(FEAT_RELTIME) || defined(PROTO)
8913static HANDLE timer_handle;
8914static int timer_active = FALSE;
8915
8916/*
8917 * Calls to start_timeout alternate the return value pointer between the two
8918 * entries in timeout_flags. If the previously active timeout is very close to
8919 * expiring when start_timeout() is called then a race condition means that the
8920 * set_flag() function may still be invoked after the previous timer is
8921 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8922 * timeouts.
8923 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008924static sig_atomic_t timeout_flags[2];
8925static int timeout_flag_idx = 0;
8926static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01008927
8928
8929 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01008930set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01008931{
8932 int *timeout_flag = (int *)param;
8933
8934 *timeout_flag = TRUE;
8935}
8936
8937/*
8938 * Stop any active timeout.
8939 */
8940 void
8941stop_timeout(void)
8942{
8943 if (timer_active)
8944 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01008945 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01008946 timer_active = FALSE;
8947 if (!ret && GetLastError() != ERROR_IO_PENDING)
8948 {
8949 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
8950 }
8951 }
8952 *timeout_flag = FALSE;
8953}
8954
8955/*
8956 * Start the timeout timer.
8957 *
8958 * The period is defined in milliseconds.
8959 *
8960 * The return value is a pointer to a flag that is initialised to 0. If the
8961 * timeout expires, the flag is set to 1. This will only return pointers to
8962 * static memory; i.e. any pointer returned by this function may always be
8963 * safely dereferenced.
8964 *
8965 * This function is not expected to fail, but if it does it still returns a
8966 * valid flag pointer; the flag will remain stuck at zero.
8967 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008968 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01008969start_timeout(long msec)
8970{
Paul Ollis65745772022-06-05 16:55:54 +01008971 BOOL ret;
8972
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008973 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01008974
8975 stop_timeout();
8976 ret = CreateTimerQueueTimer(
8977 &timer_handle, NULL, set_flag, timeout_flag,
8978 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
8979 if (!ret)
8980 {
8981 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
8982 }
8983 else
8984 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008985 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01008986 timer_active = TRUE;
8987 *timeout_flag = FALSE;
8988 }
8989 return timeout_flag;
8990}
8991#endif