blob: 20ec8adeb21735ff3ac770cadc19bf789e02b03a [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 Plewright38804d62022-11-09 23:55:52 +0000235# define USE_VTP (vtp_working && is_term_win32())
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200236# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100237# else
238# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200239# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100240# endif
241
242static void set_console_color_rgb(void);
243static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100244static void restore_console_color_rgb(void);
Christopher Plewright20b795e2022-12-20 20:01:58 +0000245#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100246
Bram Moolenaar0f873732019-12-05 20:28:46 +0100247// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100248#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
249# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
250#endif
251
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200252#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100253static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000254#endif
255
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200256static char_u *exe_path = NULL;
257
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100258static BOOL win8_or_later = FALSE;
Christopher Plewright1140b512022-11-12 18:46:05 +0000259static BOOL win11_or_later = FALSE;
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100260
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100261/*
262 * Get version number including build number
263 */
264typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100265#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100266 (((major) << 24) | ((minor) << 16) | (build))
267
268 static DWORD
269get_build_number(void)
270{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100271 OSVERSIONINFOW osver;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100272 HMODULE hNtdll;
273 PfnRtlGetVersion pRtlGetVersion;
274 DWORD ver = MAKE_VER(0, 0, 0);
275
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100276 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100277 hNtdll = GetModuleHandle("ntdll.dll");
278 if (hNtdll != NULL)
279 {
280 pRtlGetVersion =
281 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
282 pRtlGetVersion(&osver);
283 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
284 min(osver.dwMinorVersion, 255),
285 min(osver.dwBuildNumber, 32767));
286 }
287 return ver;
288}
289
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200290#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200291 static BOOL
292is_ambiwidth_event(
293 INPUT_RECORD *ir)
294{
295 return ir->EventType == KEY_EVENT
296 && ir->Event.KeyEvent.bKeyDown
297 && ir->Event.KeyEvent.wRepeatCount == 1
298 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
299 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000300 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200301 && ir->Event.KeyEvent.dwControlKeyState == 2;
302}
303
304 static void
305make_ambiwidth_event(
306 INPUT_RECORD *down,
307 INPUT_RECORD *up)
308{
309 down->Event.KeyEvent.wVirtualKeyCode = 0;
310 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000311 down->Event.KeyEvent.uChar.UnicodeChar
312 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200313 down->Event.KeyEvent.dwControlKeyState = 0;
314}
315
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100316/*
317 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100318 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100319 */
320 static BOOL
321read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100322 HANDLE hInput,
323 INPUT_RECORD *lpBuffer,
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100324 int nLength,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100325 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100326{
327 enum
328 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100329 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100330 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100331 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100332 static DWORD s_dwIndex = 0;
333 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100334 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100335 int head;
336 int tail;
337 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200338 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100339
Christopher Plewright20b795e2022-12-20 20:01:58 +0000340 if (s_dwMax == 0 && input_record_buffer.length > 0)
341 {
342 dwEvents = read_input_record_buffer(s_irCache, IRSIZE);
343 s_dwIndex = 0;
344 s_dwMax = dwEvents;
345 }
346
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200347 if (nLength == -2)
348 return (s_dwMax > 0) ? TRUE : FALSE;
349
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100350 if (!win8_or_later)
351 {
352 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200353 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
354 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100355 }
356
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100357 if (s_dwMax == 0)
358 {
Christopher Plewright38804d62022-11-09 23:55:52 +0000359 if (!vtp_working && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200360 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200361 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
362 if (dwEvents == 0 && nLength == -1)
363 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
364 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100365 s_dwIndex = 0;
366 s_dwMax = dwEvents;
367 if (dwEvents == 0)
368 {
369 *lpEvents = 0;
370 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100371 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100372
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200373 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
374 if (is_ambiwidth_event(&s_irCache[i]))
375 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
376
Bram Moolenaardd415a62014-02-05 14:02:27 +0100377 if (s_dwMax > 1)
378 {
379 head = 0;
380 tail = s_dwMax - 1;
381 while (head != tail)
382 {
383 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
384 && s_irCache[head + 1].EventType
385 == WINDOW_BUFFER_SIZE_EVENT)
386 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100387 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100388 for (i = head; i < tail; ++i)
389 s_irCache[i] = s_irCache[i + 1];
390 --tail;
391 continue;
392 }
393 head++;
394 }
395 s_dwMax = tail + 1;
396 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100397 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100398
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200399 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
400 {
401 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
402 {
403 s_irPseudo = s_irCache[s_dwIndex];
404 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
405 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
406 *lpBuffer = s_irPseudo;
407 *lpEvents = 1;
408 return TRUE;
409 }
410 }
411
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100412 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200413 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100414 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100415 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100416 return TRUE;
417}
418
419/*
420 * Version of PeekConsoleInput() that works with IME.
421 */
422 static BOOL
423peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100424 HANDLE hInput,
425 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200426 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100427 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100428{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100429 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100430}
431
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100432# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200433 static DWORD
434msg_wait_for_multiple_objects(
435 DWORD nCount,
436 LPHANDLE pHandles,
437 BOOL fWaitAll,
438 DWORD dwMilliseconds,
439 DWORD dwWakeMask)
440{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100441 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200442 return WAIT_OBJECT_0;
443 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
444 dwMilliseconds, dwWakeMask);
445}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100446# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200447
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100448# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200449 static DWORD
450wait_for_single_object(
451 HANDLE hHandle,
452 DWORD dwMilliseconds)
453{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100454 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200455 return WAIT_OBJECT_0;
456 return WaitForSingleObject(hHandle, dwMilliseconds);
457}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100458# endif
Christopher Plewright20b795e2022-12-20 20:01:58 +0000459#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200460
Bram Moolenaar071d4272004-06-13 20:20:40 +0000461 static void
462get_exe_name(void)
463{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100464 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
465 // as the maximum length that works (plus a NUL byte).
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100466#define MAX_ENV_PATH_LEN 8192
467 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200468 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000469
470 if (exe_name == NULL)
471 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100472 // store the name of the executable, may be used for $VIM
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100473 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000474 if (*temp != NUL)
475 exe_name = FullName_save((char_u *)temp, FALSE);
476 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000477
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200478 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000479 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200480 exe_path = vim_strnsave(exe_name, gettail_sep(exe_name) - exe_name);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200481 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000482 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100483 // Append our starting directory to $PATH, so that when doing
484 // "!xxd" it's found in our starting directory. Needed because
485 // SearchPath() also looks there.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200486 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100487 if (p == NULL
488 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200489 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100490 if (p == NULL || *p == NUL)
491 temp[0] = NUL;
492 else
493 {
494 STRCPY(temp, p);
495 STRCAT(temp, ";");
496 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200497 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100498 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200499 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000500 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000501 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000502}
503
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200504/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100505 * Unescape characters in "p" that appear in "escaped".
506 */
507 static void
508unescape_shellxquote(char_u *p, char_u *escaped)
509{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100510 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100511 int n;
512
513 while (*p != NUL)
514 {
515 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
516 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100517 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100518 p += n;
519 l -= n;
520 }
521}
522
523/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200524 * Load library "name".
525 */
526 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000527vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200528{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200529 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200530
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200531 // No need to load any library when registering OLE.
532 if (found_register_arg)
533 return dll;
534
Bram Moolenaar0f873732019-12-05 20:28:46 +0100535 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
536 // vimLoadLib() recursively, which causes a stack overflow.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200537 if (exe_path == NULL)
538 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200539 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200540 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200541 WCHAR old_dirw[MAXPATHL];
542
543 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
544 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100545 // Change directory to where the executable is, both to make
546 // sure we find a .dll there and to avoid looking for a .dll
547 // in the current directory.
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100548 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200549 dll = LoadLibrary(name);
550 SetCurrentDirectoryW(old_dirw);
551 return dll;
552 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200553 }
554 return dll;
555}
556
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200557#if defined(VIMDLL) || defined(PROTO)
558/*
559 * Check if the current executable file is for the GUI subsystem.
560 */
561 int
562mch_is_gui_executable(void)
563{
564 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
565 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
566 PIMAGE_NT_HEADERS pPE;
567
568 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
569 return FALSE;
570 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
571 if (pPE->Signature != IMAGE_NT_SIGNATURE)
572 return FALSE;
573 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
574 return TRUE;
575 return FALSE;
576}
577#endif
578
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000579#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
580 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100581/*
582 * Get related information about 'funcname' which is imported by 'hInst'.
583 * If 'info' is 0, return the function address.
584 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000585 * If 'info' is 2, hook the function with 'ptr', and return the original
586 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100587 */
588 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000589get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
590 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100591{
592 PBYTE pImage = (PBYTE)hInst;
593 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
594 PIMAGE_NT_HEADERS pPE;
595 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100596 PIMAGE_THUNK_DATA pIAT; // Import Address Table
597 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100598 PIMAGE_IMPORT_BY_NAME pImpName;
599
600 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
601 return NULL;
602 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
603 if (pPE->Signature != IMAGE_NT_SIGNATURE)
604 return NULL;
605 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
606 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
607 .VirtualAddress);
608 for (; pImpDesc->FirstThunk; ++pImpDesc)
609 {
610 if (!pImpDesc->OriginalFirstThunk)
611 continue;
612 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
613 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
614 for (; pIAT->u1.Function; ++pIAT, ++pINT)
615 {
616 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
617 continue;
618 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
619 + (UINT_PTR)(pINT->u1.AddressOfData));
620 if (strcmp((char *)pImpName->Name, funcname) == 0)
621 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000622 void *original;
623 DWORD old, new = PAGE_READWRITE;
624
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100625 switch (info)
626 {
627 case 0:
628 return (void *)pIAT->u1.Function;
629 case 1:
630 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000631 case 2:
632 original = (void *)pIAT->u1.Function;
633 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
634 new, &old);
635 pIAT->u1.Function = (UINT_PTR)ptr;
636 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
637 old, &new);
638 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100639 default:
640 return NULL;
641 }
642 }
643 }
644 }
645 return NULL;
646}
647
648/*
649 * Get the module handle which 'funcname' in 'hInst' is imported from.
650 */
651 HINSTANCE
652find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
653{
654 char *modulename;
655
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000656 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100657 if (modulename != NULL)
658 return GetModuleHandleA(modulename);
659 return NULL;
660}
661
662/*
663 * Get the address of 'funcname' which is imported by 'hInst' DLL.
664 */
665 void *
666get_dll_import_func(HINSTANCE hInst, const char *funcname)
667{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000668 return get_imported_func_info(hInst, funcname, 0, NULL);
669}
670
671/*
672 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
673 * and return the original function address.
674 */
675 void *
676hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
677{
678 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100679}
680#endif
681
Bram Moolenaar071d4272004-06-13 20:20:40 +0000682#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
683# ifndef GETTEXT_DLL
684# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200685# define GETTEXT_DLL_ALT1 "libintl-8.dll"
686# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000687# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100688// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000689static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200690static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000691static char *null_libintl_textdomain(const char *);
692static char *null_libintl_bindtextdomain(const char *, const char *);
693static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100694static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000695
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200696static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000697char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200698char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
699 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000700char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
701char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000702 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000703char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
704 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100705int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000706
707 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100708dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000709{
710 int i;
711 static struct
712 {
713 char *name;
714 FARPROC *ptr;
715 } libintl_entry[] =
716 {
717 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200718 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000719 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
720 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
721 {NULL, NULL}
722 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100723 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000724
Bram Moolenaar7554c542018-10-06 15:03:15 +0200725 // No need to initialize twice.
726 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000727 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200728 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100729 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100730# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100731 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200732 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100733# endif
734# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200735 if (!hLibintlDLL)
736 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100737# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100738 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000739 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200740 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000741 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200742 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000743 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200744 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000745 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200746 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000747 }
748 for (i = 0; libintl_entry[i].name != NULL
749 && libintl_entry[i].ptr != NULL; ++i)
750 {
K.Takata54119102022-02-03 13:33:03 +0000751 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000752 libintl_entry[i].name)) == NULL)
753 {
754 dyn_libintl_end();
755 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000756 {
757 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000758 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000759 verbose_leave();
760 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000761 return 0;
762 }
763 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000764
Bram Moolenaar0f873732019-12-05 20:28:46 +0100765 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100766 dyn_libintl_bind_textdomain_codeset = (char *(*)(const char *, const char *))
767 GetProcAddress(hLibintlDLL, "bind_textdomain_codeset");
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000768 if (dyn_libintl_bind_textdomain_codeset == NULL)
769 dyn_libintl_bind_textdomain_codeset =
770 null_libintl_bind_textdomain_codeset;
771
Bram Moolenaar0f873732019-12-05 20:28:46 +0100772 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100773 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
774 if (hmsvcrt != NULL)
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100775 dyn_libintl_wputenv = (int (*)(const wchar_t *))
776 GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100777 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
778 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100779
Bram Moolenaar071d4272004-06-13 20:20:40 +0000780 return 1;
781}
782
783 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100784dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000785{
786 if (hLibintlDLL)
787 FreeLibrary(hLibintlDLL);
788 hLibintlDLL = NULL;
789 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200790 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000791 dyn_libintl_textdomain = null_libintl_textdomain;
792 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000793 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100794 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000795}
796
797 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000798null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000799{
800 return (char*)msgid;
801}
802
803 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200804null_libintl_ngettext(
805 const char *msgid,
806 const char *msgid_plural,
807 unsigned long n)
808{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200809 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200810}
811
Bram Moolenaaree695f72016-08-03 22:08:45 +0200812 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100813null_libintl_bindtextdomain(
814 const char *domainname UNUSED,
815 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000816{
817 return NULL;
818}
819
820 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100821null_libintl_bind_textdomain_codeset(
822 const char *domainname UNUSED,
823 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000824{
825 return NULL;
826}
827
828 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100829null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000830{
831 return NULL;
832}
833
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200834 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100835null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100836{
837 return 0;
838}
839
Bram Moolenaar0f873732019-12-05 20:28:46 +0100840#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000841
Bram Moolenaar0f873732019-12-05 20:28:46 +0100842// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000843
844#ifndef VER_PLATFORM_WIN32_WINDOWS
845# define VER_PLATFORM_WIN32_WINDOWS 1
846#endif
847
Bram Moolenaar071d4272004-06-13 20:20:40 +0000848#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100849# ifndef PROTO
850# include <aclapi.h>
851# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200852# ifndef PROTECTED_DACL_SECURITY_INFORMATION
853# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
854# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000855#endif
856
Bram Moolenaar27515922013-06-29 15:36:26 +0200857#ifdef HAVE_ACL
858/*
859 * Enables or disables the specified privilege.
860 */
861 static BOOL
862win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
863{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100864 BOOL bResult;
865 LUID luid;
866 HANDLE hToken;
867 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200868
869 if (!OpenProcessToken(GetCurrentProcess(),
870 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
871 return FALSE;
872
873 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
874 {
875 CloseHandle(hToken);
876 return FALSE;
877 }
878
Bram Moolenaar45500912014-07-09 20:51:07 +0200879 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200880 tokenPrivileges.Privileges[0].Luid = luid;
881 tokenPrivileges.Privileges[0].Attributes = bEnable ?
882 SE_PRIVILEGE_ENABLED : 0;
883
884 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
885 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
886
887 CloseHandle(hToken);
888
889 return bResult && GetLastError() == ERROR_SUCCESS;
890}
891#endif
892
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100893#ifdef _MSC_VER
894// Suppress the deprecation warning for using GetVersionEx().
895// It is needed for implementing "windowsversion()".
896# pragma warning(push)
897# pragma warning(disable: 4996)
898#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000899/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200900 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000901 */
902 void
903PlatformId(void)
904{
905 static int done = FALSE;
906
907 if (!done)
908 {
909 OSVERSIONINFO ovi;
910
911 ovi.dwOSVersionInfoSize = sizeof(ovi);
912 GetVersionEx(&ovi);
913
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200914#ifdef FEAT_EVAL
Bram Moolenaar0c1e3742019-12-27 13:49:24 +0100915 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
916 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200917#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100918 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
919 || ovi.dwMajorVersion > 6)
920 win8_or_later = TRUE;
921
Christopher Plewright1140b512022-11-12 18:46:05 +0000922 if ((ovi.dwMajorVersion == 10 && ovi.dwBuildNumber >= 22000)
923 || ovi.dwMajorVersion > 10)
924 win11_or_later = TRUE;
925
Bram Moolenaar071d4272004-06-13 20:20:40 +0000926#ifdef HAVE_ACL
Bram Moolenaar0f873732019-12-05 20:28:46 +0100927 // Enable privilege for getting or setting SACLs.
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200928 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000929#endif
930 done = TRUE;
931 }
932}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100933#ifdef _MSC_VER
934# pragma warning(pop)
935#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000936
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200937#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000938
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100939# define SHIFT (SHIFT_PRESSED)
940# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
941# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
942# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000943
944
Bram Moolenaar0f873732019-12-05 20:28:46 +0100945// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
946// We map function keys to their ANSI terminal equivalents, as produced
947// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
948// ANSI key with a value >= '\300' is nonstandard, but provided anyway
949// so that the user can have access to all SHIFT-, CTRL-, and ALT-
950// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000951
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000952static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000953{
954 WORD wVirtKey;
955 BOOL fAnsiKey;
956 int chAlone;
957 int chShift;
958 int chCtrl;
959 int chAlt;
960} VirtKeyMap[] =
961{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200962// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000963 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
964
965 { VK_F1, TRUE, ';', 'T', '^', 'h', },
966 { VK_F2, TRUE, '<', 'U', '_', 'i', },
967 { VK_F3, TRUE, '=', 'V', '`', 'j', },
968 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
969 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
970 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
971 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
972 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
973 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
974 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200975 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
976 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000977
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200978 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
979 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
980 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
981 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
982 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
983 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
984 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
985 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
986 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
987 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100988 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000989
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200990 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000991
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100992# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200993 // Most people don't have F13-F20, but what the hell...
994 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
995 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
996 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
997 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
998 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
999 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
1000 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
1001 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001002# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001003 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
1004 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
1005 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
1006 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001007
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001008 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
1009 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
1010 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
1011 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
1012 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
1013 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
1014 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
1015 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
1016 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
1017 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001018 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001019};
1020
1021
Bram Moolenaar0f873732019-12-05 20:28:46 +01001022/*
1023 * The return code indicates key code size.
1024 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001025 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001026win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001027 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001028{
1029 UINT uMods = pker->dwControlKeyState;
1030 static int s_iIsDead = 0;
1031 static WORD awAnsiCode[2];
1032 static BYTE abKeystate[256];
1033
1034
1035 if (s_iIsDead == 2)
1036 {
K.Takata972db232022-02-04 10:45:38 +00001037 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001038 s_iIsDead = 0;
1039 return 1;
1040 }
1041
Christopher Plewright20b795e2022-12-20 20:01:58 +00001042 if (pker->uChar.UnicodeChar > 0 && pker->uChar.UnicodeChar < 0xfffd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001043 return 1;
1044
Bram Moolenaara80faa82020-04-12 19:37:17 +02001045 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001046
Bram Moolenaar0f873732019-12-05 20:28:46 +01001047 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001048 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001049
1050 if (uMods & SHIFT_PRESSED)
1051 abKeystate[VK_SHIFT] = 0x80;
1052 if (uMods & CAPSLOCK_ON)
1053 abKeystate[VK_CAPITAL] = 1;
1054
1055 if ((uMods & ALT_GR) == ALT_GR)
1056 {
1057 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1058 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1059 }
1060
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001061 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1062 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001063
1064 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001065 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001066
1067 return s_iIsDead;
1068}
1069
Bram Moolenaar071d4272004-06-13 20:20:40 +00001070static BOOL g_fJustGotFocus = FALSE;
1071
1072/*
1073 * Decode a KEY_EVENT into one or two keystrokes
1074 */
1075 static BOOL
1076decode_key_event(
1077 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001078 WCHAR *pch,
1079 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001080 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001081 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001082{
1083 int i;
1084 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1085
1086 *pch = *pch2 = NUL;
1087 g_fJustGotFocus = FALSE;
1088
Bram Moolenaar0f873732019-12-05 20:28:46 +01001089 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001090 if (!pker->bKeyDown)
1091 return FALSE;
1092
Bram Moolenaar0f873732019-12-05 20:28:46 +01001093 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001094 switch (pker->wVirtualKeyCode)
1095 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001096 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001097 case VK_SHIFT:
1098 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001099 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001100 return FALSE;
1101
1102 default:
1103 break;
1104 }
1105
Bram Moolenaar0f873732019-12-05 20:28:46 +01001106 // special cases
K.Takata972db232022-02-04 10:45:38 +00001107 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0
Christopher Plewright20b795e2022-12-20 20:01:58 +00001108 && (pker->uChar.UnicodeChar == NUL
1109 || pker->uChar.UnicodeChar == 0xfffd))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001110 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001111 // Ctrl-6 is Ctrl-^
Bram Moolenaar071d4272004-06-13 20:20:40 +00001112 if (pker->wVirtualKeyCode == '6')
1113 {
1114 *pch = Ctrl_HAT;
1115 return TRUE;
1116 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001117 // Ctrl-2 is Ctrl-@
Bram Moolenaar071d4272004-06-13 20:20:40 +00001118 else if (pker->wVirtualKeyCode == '2')
1119 {
1120 *pch = NUL;
1121 return TRUE;
1122 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001123 // Ctrl-- is Ctrl-_
Bram Moolenaar071d4272004-06-13 20:20:40 +00001124 else if (pker->wVirtualKeyCode == 0xBD)
1125 {
1126 *pch = Ctrl__;
1127 return TRUE;
1128 }
1129 }
1130
Bram Moolenaar0f873732019-12-05 20:28:46 +01001131 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001132 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1133 {
1134 *pch = K_NUL;
1135 *pch2 = '\017';
1136 return TRUE;
1137 }
1138
K.Takataeeec2542021-06-02 13:28:16 +02001139 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001140 {
1141 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1142 {
1143 if (nModifs == 0)
1144 *pch = VirtKeyMap[i].chAlone;
1145 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1146 *pch = VirtKeyMap[i].chShift;
1147 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1148 *pch = VirtKeyMap[i].chCtrl;
1149 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1150 *pch = VirtKeyMap[i].chAlt;
1151
1152 if (*pch != 0)
1153 {
1154 if (VirtKeyMap[i].fAnsiKey)
1155 {
1156 *pch2 = *pch;
1157 *pch = K_NUL;
1158 }
1159
1160 return TRUE;
1161 }
1162 }
1163 }
1164
1165 i = win32_kbd_patch_key(pker);
1166
1167 if (i < 0)
1168 *pch = NUL;
1169 else
1170 {
K.Takata972db232022-02-04 10:45:38 +00001171 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001172
1173 if (pmodifiers != NULL)
1174 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001175 // Pass on the ALT key as a modifier, but only when not combined
1176 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001177 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1178 *pmodifiers |= MOD_MASK_ALT;
1179
Bram Moolenaar0f873732019-12-05 20:28:46 +01001180 // Pass on SHIFT only for special keys, because we don't know when
1181 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001182 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1183 *pmodifiers |= MOD_MASK_SHIFT;
1184
Bram Moolenaar0f873732019-12-05 20:28:46 +01001185 // Pass on CTRL only for non-special keys, because we don't know
1186 // when it's already included with the character. And not when
1187 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001188 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1189 && *pch >= 0x20 && *pch < 0x80)
1190 *pmodifiers |= MOD_MASK_CTRL;
1191 }
1192 }
1193
1194 return (*pch != NUL);
1195}
1196
Christopher Plewright20b795e2022-12-20 20:01:58 +00001197# if defined(FEAT_EVAL)
1198 static int
1199encode_key_event(dict_T *args, INPUT_RECORD *ir)
1200{
1201 static int s_dwMods = 0;
1202
1203 char_u *event = dict_get_string(args, "event", TRUE);
1204 if (event && (STRICMP(event, "keydown") == 0
1205 || STRICMP(event, "keyup") == 0))
1206 {
1207 WORD vkCode = dict_get_number_def(args, "keycode", 0);
1208 if (vkCode <= 0 || vkCode >= 0xFF)
1209 {
1210 semsg(_(e_invalid_argument_nr), (long)vkCode);
1211 return FALSE;
1212 }
1213
1214 ir->EventType = KEY_EVENT;
1215 KEY_EVENT_RECORD ker;
1216 ZeroMemory(&ker, sizeof(ker));
1217 ker.bKeyDown = STRICMP(event, "keydown") == 0;
1218 ker.wRepeatCount = 1;
1219 ker.wVirtualScanCode = 0;
1220 ker.dwControlKeyState = 0;
1221 int mods = (int)dict_get_number(args, "modifiers");
1222 // Encode the win32 console key modifiers from Vim keyboard modifiers.
1223 if (mods)
1224 {
1225 // If "modifiers" is explicitly set in the args, then we reset any
1226 // remembered modifer key state that may have been set from earlier
1227 // mod-key-down events, even if they are not yet unset by earlier
1228 // mod-key-up events.
1229 s_dwMods = 0;
1230 if (mods & MOD_MASK_SHIFT)
1231 ker.dwControlKeyState |= SHIFT_PRESSED;
1232 if (mods & MOD_MASK_CTRL)
1233 ker.dwControlKeyState |= LEFT_CTRL_PRESSED;
1234 if (mods & MOD_MASK_ALT)
1235 ker.dwControlKeyState |= LEFT_ALT_PRESSED;
1236 }
1237
1238 if (vkCode == VK_LSHIFT || vkCode == VK_RSHIFT || vkCode == VK_SHIFT)
1239 {
1240 if (STRICMP(event, "keydown") == 0)
1241 s_dwMods |= SHIFT_PRESSED;
1242 else
1243 s_dwMods &= ~SHIFT_PRESSED;
1244 }
1245 else if (vkCode == VK_LCONTROL || vkCode == VK_CONTROL)
1246 {
1247 if (STRICMP(event, "keydown") == 0)
1248 s_dwMods |= LEFT_CTRL_PRESSED;
1249 else
1250 s_dwMods &= ~LEFT_CTRL_PRESSED;
1251 }
1252 else if (vkCode == VK_RCONTROL)
1253 {
1254 if (STRICMP(event, "keydown") == 0)
1255 s_dwMods |= RIGHT_CTRL_PRESSED;
1256 else
1257 s_dwMods &= ~RIGHT_CTRL_PRESSED;
1258 }
1259 else if (vkCode == VK_LMENU || vkCode == VK_MENU)
1260 {
1261 if (STRICMP(event, "keydown") == 0)
1262 s_dwMods |= LEFT_ALT_PRESSED;
1263 else
1264 s_dwMods &= ~LEFT_ALT_PRESSED;
1265 }
1266 else if (vkCode == VK_RMENU)
1267 {
1268 if (STRICMP(event, "keydown") == 0)
1269 s_dwMods |= RIGHT_ALT_PRESSED;
1270 else
1271 s_dwMods &= ~RIGHT_ALT_PRESSED;
1272 }
1273 ker.dwControlKeyState |= s_dwMods;
1274 ker.wVirtualKeyCode = vkCode;
1275 win32_kbd_patch_key(&ker);
1276
1277 for (int i = ARRAY_LENGTH(VirtKeyMap);
1278 --i >= 0 && !ker.uChar.UnicodeChar; )
1279 {
1280 if (VirtKeyMap[i].wVirtKey == vkCode)
1281 ker.uChar.UnicodeChar = 0xfffd; // REPLACEMENT CHARACTER
1282 }
1283
1284 ir->Event.KeyEvent = ker;
1285 vim_free(event);
1286 }
1287 else
1288 {
1289 if (event == NULL)
1290 {
1291 semsg(_(e_missing_argument_str), "event");
1292 }
1293 else
1294 {
1295 semsg(_(e_invalid_value_for_argument_str_str), "event", event);
1296 vim_free(event);
1297 }
1298 return FALSE;
1299 }
1300 return TRUE;
1301}
1302# endif // FEAT_EVAL
1303#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00001304
1305
Bram Moolenaar071d4272004-06-13 20:20:40 +00001306/*
1307 * For the GUI the mouse handling is in gui_w32.c.
1308 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001309#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001310 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001311mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001312{
1313}
Christopher Plewright20b795e2022-12-20 20:01:58 +00001314#else // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar0f873732019-12-05 20:28:46 +01001315static int g_fMouseAvail = FALSE; // mouse present
1316static int g_fMouseActive = FALSE; // mouse enabled
1317static int g_nMouseClick = -1; // mouse status
1318static int g_xMouse; // mouse x coordinate
1319static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001320static DWORD g_cmodein = 0; // Original console input mode
1321static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001322
1323/*
1324 * Enable or disable mouse input
1325 */
1326 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001327mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001328{
1329 DWORD cmodein;
1330
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001331# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001332 if (gui.in_use)
1333 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001334# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001335 if (!g_fMouseAvail)
1336 return;
1337
1338 g_fMouseActive = on;
1339 GetConsoleMode(g_hConIn, &cmodein);
1340
1341 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001342 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001343 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001344 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1345 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001346 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001347 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001348 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001349 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1350 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001351
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001352 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001353}
1354
Bram Moolenaar157d8132018-03-06 17:09:20 +01001355
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001356# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001357/*
1358 * Called when 'balloonevalterm' changed.
1359 */
1360 void
1361mch_bevalterm_changed(void)
1362{
1363 mch_setmouse(g_fMouseActive);
1364}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001365# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001366
Christopher Plewright2a46f812022-10-16 19:47:45 +01001367/*
1368 * Win32 console mouse scroll event handler.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001369 * Console version of the _OnMouseWheel() function in gui_w32.c
Christopher Plewright2a46f812022-10-16 19:47:45 +01001370 *
1371 * This encodes the mouse scroll direction and keyboard modifiers into
1372 * g_nMouseClick, and the mouse position into g_xMouse and g_yMouse
1373 *
1374 * The direction of the scroll is decoded from two fields of the win32 console
1375 * mouse event record;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001376 * 1. The orientation - vertical or horizontal flag - from dwEventFlags
Christopher Plewright2a46f812022-10-16 19:47:45 +01001377 * 2. The sign - positive or negative (aka delta flag) - from dwButtonState
1378 *
Christopher Plewright20b795e2022-12-20 20:01:58 +00001379 * When scroll orientation is HORIZONTAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001380 * - If the high word of the dwButtonState member contains a positive
1381 * value, the wheel was rotated to the right.
1382 * - Otherwise, the wheel was rotated to the left.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001383 * When scroll orientation is VERTICAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001384 * - If the high word of the dwButtonState member contains a positive value,
1385 * the wheel was rotated forward, away from the user.
1386 * - Otherwise, the wheel was rotated backward, toward the user.
1387 */
1388 static void
1389decode_mouse_wheel(MOUSE_EVENT_RECORD *pmer)
1390{
Christopher Plewright2a46f812022-10-16 19:47:45 +01001391 int horizontal = (pmer->dwEventFlags == MOUSE_HWHEELED);
1392 int zDelta = pmer->dwButtonState;
1393
1394 g_xMouse = pmer->dwMousePosition.X;
1395 g_yMouse = pmer->dwMousePosition.Y;
1396
K.Takata161b6ac2022-11-14 15:31:07 +00001397# ifdef FEAT_PROP_POPUP
Christopher Plewright605d02a2022-10-19 11:54:46 +01001398 int lcol = g_xMouse;
1399 int lrow = g_yMouse;
Christopher Plewright38804d62022-11-09 23:55:52 +00001400 win_T *wp = mouse_find_win(&lrow, &lcol, FIND_POPUP);
Christopher Plewright2a46f812022-10-16 19:47:45 +01001401 if (wp != NULL && popup_is_popup(wp))
1402 {
1403 g_nMouseClick = -1;
1404 cmdarg_T cap;
1405 oparg_T oa;
1406 CLEAR_FIELD(cap);
1407 clear_oparg(&oa);
1408 cap.oap = &oa;
1409 if (horizontal)
1410 {
1411 cap.arg = zDelta < 0 ? MSCR_LEFT : MSCR_RIGHT;
1412 cap.cmdchar = zDelta < 0 ? K_MOUSELEFT : K_MOUSERIGHT;
1413 }
1414 else
1415 {
1416 cap.cmdchar = zDelta < 0 ? K_MOUSEUP : K_MOUSEDOWN;
1417 cap.arg = zDelta < 0 ? MSCR_UP : MSCR_DOWN;
1418 }
1419
1420 // Mouse hovers over popup window, scroll it if possible.
1421 mouse_row = wp->w_winrow;
1422 mouse_col = wp->w_wincol;
1423 nv_mousescroll(&cap);
1424 update_screen(0);
1425 setcursor();
1426 out_flush();
1427 return;
1428 }
K.Takata161b6ac2022-11-14 15:31:07 +00001429# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01001430 mouse_col = g_xMouse;
1431 mouse_row = g_yMouse;
1432
1433 char_u modifiers = 0;
1434 char_u direction = 0;
1435
1436 // Decode the direction into an event that Vim can process
1437 if (horizontal)
1438 direction = zDelta >= 0 ? KE_MOUSELEFT : KE_MOUSERIGHT;
1439 else
1440 direction = zDelta >= 0 ? KE_MOUSEDOWN : KE_MOUSEUP;
1441
dundargocc57b5bc2022-11-02 13:30:51 +00001442 // Decode the win32 console key modifiers into Vim mouse modifiers.
Christopher Plewright2a46f812022-10-16 19:47:45 +01001443 if (pmer->dwControlKeyState & SHIFT_PRESSED)
Christopher Plewright605d02a2022-10-19 11:54:46 +01001444 modifiers |= MOD_MASK_SHIFT; // MOUSE_SHIFT;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001445 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
Christopher Plewright605d02a2022-10-19 11:54:46 +01001446 modifiers |= MOD_MASK_CTRL; // MOUSE_CTRL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001447 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1448 modifiers |= MOD_MASK_ALT; // MOUSE_ALT;
1449
1450 // add (bitwise or) the scroll direction and the key modifier chars
1451 // together.
1452 g_nMouseClick = ((direction << 8) | modifiers);
1453
1454 return;
1455}
1456
Bram Moolenaar071d4272004-06-13 20:20:40 +00001457/*
1458 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1459 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1460 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1461 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1462 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1463 * and we return the mouse position in g_xMouse and g_yMouse.
1464 *
1465 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1466 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1467 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1468 *
1469 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1470 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1471 *
1472 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1473 * moves, even if it stays within the same character cell. We ignore
1474 * all MOUSE_MOVED messages if the position hasn't really changed, and
1475 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1476 * we're only interested in MOUSE_DRAG).
1477 *
1478 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1479 * 2-button mouses by pressing the left & right buttons simultaneously.
1480 * In practice, it's almost impossible to click both at the same time,
1481 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1482 * in such cases, if the user is clicking quickly.
1483 */
1484 static BOOL
1485decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001486 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001487{
1488 static int s_nOldButton = -1;
1489 static int s_nOldMouseClick = -1;
1490 static int s_xOldMouse = -1;
1491 static int s_yOldMouse = -1;
1492 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001493# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001494 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001495# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001496 static int s_cClicks = 1;
1497 static BOOL s_fReleased = TRUE;
1498 static DWORD s_dwLastClickTime = 0;
1499 static BOOL s_fNextIsMiddle = FALSE;
1500
Bram Moolenaar0f873732019-12-05 20:28:46 +01001501 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001502
1503 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1504 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1505 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1506 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1507
1508 int nButton;
1509
1510 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1511 cButtons = 2;
1512
1513 if (!g_fMouseAvail || !g_fMouseActive)
1514 {
1515 g_nMouseClick = -1;
1516 return FALSE;
1517 }
1518
Bram Moolenaar0f873732019-12-05 20:28:46 +01001519 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001520 if (g_fJustGotFocus)
1521 {
1522 g_fJustGotFocus = FALSE;
1523 return FALSE;
1524 }
1525
Christopher Plewright605d02a2022-10-19 11:54:46 +01001526 // If there is an unprocessed mouse click drop this one.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001527 if (g_nMouseClick != -1)
1528 return TRUE;
Christopher Plewright605d02a2022-10-19 11:54:46 +01001529
Christopher Plewright2a46f812022-10-16 19:47:45 +01001530 if (pmer->dwEventFlags == MOUSE_WHEELED
1531 || pmer->dwEventFlags == MOUSE_HWHEELED)
1532 {
1533 decode_mouse_wheel(pmer);
1534 return TRUE; // we now should have a mouse scroll in g_nMouseClick
1535 }
Christopher Plewright605d02a2022-10-19 11:54:46 +01001536
Bram Moolenaar071d4272004-06-13 20:20:40 +00001537 nButton = -1;
1538 g_xMouse = pmer->dwMousePosition.X;
1539 g_yMouse = pmer->dwMousePosition.Y;
1540
1541 if (pmer->dwEventFlags == MOUSE_MOVED)
1542 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001543 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1544 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001545 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1546 return FALSE;
1547 }
1548
Bram Moolenaar0f873732019-12-05 20:28:46 +01001549 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001550 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1551 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001552 nButton = MOUSE_RELEASE;
1553
Bram Moolenaar0f873732019-12-05 20:28:46 +01001554 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001555 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001556 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001557# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001558 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001559 if (p_bevalterm)
1560 nButton = MOUSE_DRAG;
1561 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001562# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001563 return FALSE;
1564 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001565
Bram Moolenaar071d4272004-06-13 20:20:40 +00001566 s_fReleased = TRUE;
1567 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001568 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001569 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001570 // on a 2-button mouse, hold down left and right buttons
1571 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001572
1573 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1574 {
1575 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1576
Bram Moolenaar0f873732019-12-05 20:28:46 +01001577 // if either left or right button only is pressed, see if the
1578 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001579 if (dwLR == LEFT || dwLR == RIGHT)
1580 {
1581 for (;;)
1582 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001583 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001584 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1585 != WAIT_OBJECT_0)
1586 break;
1587 else
1588 {
1589 DWORD cRecords = 0;
1590 INPUT_RECORD ir;
1591 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1592
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001593 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001594
1595 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1596 || !(pmer2->dwButtonState & LEFT_RIGHT))
1597 break;
1598 else
1599 {
1600 if (pmer2->dwEventFlags != MOUSE_MOVED)
1601 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001602 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001603
1604 return decode_mouse_event(pmer2);
1605 }
1606 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1607 s_yOldMouse == pmer2->dwMousePosition.Y)
1608 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001609 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001610 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001611
Bram Moolenaar0f873732019-12-05 20:28:46 +01001612 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001613 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001614
1615 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1616 break;
1617 }
1618 else
1619 break;
1620 }
1621 }
1622 }
1623 }
1624 }
1625
1626 if (s_fNextIsMiddle)
1627 {
1628 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1629 ? MOUSE_DRAG : MOUSE_MIDDLE;
1630 s_fNextIsMiddle = FALSE;
1631 }
1632 else if (cButtons == 2 &&
1633 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1634 {
1635 nButton = MOUSE_MIDDLE;
1636
1637 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1638 {
1639 s_fNextIsMiddle = TRUE;
1640 nButton = MOUSE_RELEASE;
1641 }
1642 }
1643 else if ((pmer->dwButtonState & LEFT) == LEFT)
1644 nButton = MOUSE_LEFT;
1645 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1646 nButton = MOUSE_MIDDLE;
1647 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1648 nButton = MOUSE_RIGHT;
1649
1650 if (! s_fReleased && ! s_fNextIsMiddle
1651 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1652 return FALSE;
1653
1654 s_fReleased = s_fNextIsMiddle;
1655 }
1656
1657 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1658 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001659 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001660 if (nButton != -1 && nButton != MOUSE_RELEASE)
1661 {
1662 DWORD dwCurrentTime = GetTickCount();
1663
1664 if (s_xOldMouse != g_xMouse
1665 || s_yOldMouse != g_yMouse
1666 || s_nOldButton != nButton
1667 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001668# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001669 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001670# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001671 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1672 {
1673 s_cClicks = 1;
1674 }
1675 else if (++s_cClicks > 4)
1676 {
1677 s_cClicks = 1;
1678 }
1679
1680 s_dwLastClickTime = dwCurrentTime;
1681 }
1682 }
1683 else if (pmer->dwEventFlags == MOUSE_MOVED)
1684 {
1685 if (nButton != -1 && nButton != MOUSE_RELEASE)
1686 nButton = MOUSE_DRAG;
1687
1688 s_cClicks = 1;
1689 }
1690
1691 if (nButton == -1)
1692 return FALSE;
1693
1694 if (nButton != MOUSE_RELEASE)
1695 s_nOldButton = nButton;
1696
1697 g_nMouseClick = nButton;
1698
1699 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1700 g_nMouseClick |= MOUSE_SHIFT;
1701 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1702 g_nMouseClick |= MOUSE_CTRL;
1703 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1704 g_nMouseClick |= MOUSE_ALT;
1705
1706 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1707 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1708
Bram Moolenaar0f873732019-12-05 20:28:46 +01001709 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001710 if (s_xOldMouse == g_xMouse
1711 && s_yOldMouse == g_yMouse
1712 && s_nOldMouseClick == g_nMouseClick)
1713 {
1714 g_nMouseClick = -1;
1715 return FALSE;
1716 }
1717
1718 s_xOldMouse = g_xMouse;
1719 s_yOldMouse = g_yMouse;
1720 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001721# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001722 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001723# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001724 s_nOldMouseClick = g_nMouseClick;
1725
1726 return TRUE;
1727}
1728
Christopher Plewright20b795e2022-12-20 20:01:58 +00001729# ifdef FEAT_EVAL
1730 static int
1731encode_mouse_event(dict_T *args, INPUT_RECORD *ir)
1732{
1733 int button;
1734 int row;
1735 int col;
1736 int repeated_click;
Bram Moolenaar9b8a3652022-12-20 20:47:28 +00001737 int_u mods = 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001738 int move;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001739
Christopher Plewright20b795e2022-12-20 20:01:58 +00001740 if (!dict_has_key(args, "row") || !dict_has_key(args, "col"))
1741 return FALSE;
1742
1743 // Note: "move" is optional, requires fewer arguments
1744 move = (int)dict_get_bool(args, "move", FALSE);
1745 if (!move && (!dict_has_key(args, "button")
1746 || !dict_has_key(args, "multiclick")
1747 || !dict_has_key(args, "modifiers")))
1748 return FALSE;
1749
1750 row = (int)dict_get_number(args, "row") - 1;
1751 col = (int)dict_get_number(args, "col") - 1;
1752
1753 ir->EventType = MOUSE_EVENT;
1754 MOUSE_EVENT_RECORD mer;
1755 ZeroMemory(&mer, sizeof(mer));
1756 mer.dwMousePosition.X = col;
1757 mer.dwMousePosition.Y = row;
1758
1759 if (move)
1760 {
1761 mer.dwButtonState = 0;
1762 mer.dwEventFlags = MOUSE_MOVED;
1763 }
1764 else
1765 {
1766 button = (int)dict_get_number(args, "button");
1767 repeated_click = (int)dict_get_number(args, "multiclick");
1768 mods = (int)dict_get_number(args, "modifiers");
1769 // Reset the scroll values to known values.
1770 // XXX: Remove this when/if the scroll step is made configurable.
1771 mouse_set_hor_scroll_step(6);
1772 mouse_set_vert_scroll_step(3);
1773
1774 switch (button)
1775 {
1776 case MOUSE_LEFT:
1777 mer.dwButtonState = FROM_LEFT_1ST_BUTTON_PRESSED;
1778 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1779 break;
1780 case MOUSE_MIDDLE:
1781 mer.dwButtonState = FROM_LEFT_2ND_BUTTON_PRESSED;
1782 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1783 break;
1784 case MOUSE_RIGHT:
1785 mer.dwButtonState = RIGHTMOST_BUTTON_PRESSED;
1786 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1787 break;
1788 case MOUSE_RELEASE:
1789 // umm? Assume Left Release?
1790 mer.dwEventFlags = 0;
1791
1792 case MOUSE_MOVE:
1793 mer.dwButtonState = 0;
1794 mer.dwEventFlags = MOUSE_MOVED;
1795 break;
1796 case MOUSE_X1:
1797 mer.dwButtonState = FROM_LEFT_3RD_BUTTON_PRESSED;
1798 break;
1799 case MOUSE_X2:
1800 mer.dwButtonState = FROM_LEFT_4TH_BUTTON_PRESSED;
1801 break;
1802 case MOUSE_4: // KE_MOUSEDOWN;
1803 mer.dwButtonState = -1;
1804 mer.dwEventFlags = MOUSE_WHEELED;
1805 break;
1806 case MOUSE_5: // KE_MOUSEUP;
1807 mer.dwButtonState = +1;
1808 mer.dwEventFlags = MOUSE_WHEELED;
1809 break;
1810 case MOUSE_6: // KE_MOUSELEFT;
1811 mer.dwButtonState = -1;
1812 mer.dwEventFlags = MOUSE_HWHEELED;
1813 break;
1814 case MOUSE_7: // KE_MOUSERIGHT;
1815 mer.dwButtonState = +1;
1816 mer.dwEventFlags = MOUSE_HWHEELED;
1817 break;
1818 default:
1819 semsg(_(e_invalid_argument_str), "button");
1820 return FALSE;
1821 }
1822 }
1823
1824 mer.dwControlKeyState = 0;
1825 if (mods != 0)
1826 {
1827 // Encode the win32 console key modifiers from Vim MOUSE modifiers.
1828 if (mods & MOUSE_SHIFT)
1829 mer.dwControlKeyState |= SHIFT_PRESSED;
1830 if (mods & MOUSE_CTRL)
1831 mer.dwControlKeyState |= LEFT_CTRL_PRESSED;
1832 if (mods & MOUSE_ALT)
1833 mer.dwControlKeyState |= LEFT_ALT_PRESSED;
1834 }
1835 ir->Event.MouseEvent = mer;
1836 return TRUE;
1837}
1838# endif // FEAT_EVAL
1839
1840 static int
1841write_input_record_buffer(INPUT_RECORD* irEvents, int nLength)
1842{
1843 int nCount = 0;
1844 while (nCount < nLength)
1845 {
1846 input_record_buffer.length++;
1847 input_record_buffer_node_T *event_node =
1848 malloc(sizeof(input_record_buffer_node_T));
1849 event_node->ir = irEvents[nCount++];
1850 event_node->next = NULL;
1851 if (input_record_buffer.tail == NULL)
1852 {
1853 input_record_buffer.head = event_node;
1854 input_record_buffer.tail = event_node;
1855 }
1856 else
1857 {
1858 input_record_buffer.tail->next = event_node;
1859 input_record_buffer.tail = input_record_buffer.tail->next;
1860 }
1861 }
1862 return nCount;
1863}
1864
1865 static int
1866read_input_record_buffer(INPUT_RECORD* irEvents, int nMaxLength)
1867{
1868 int nCount = 0;
1869 while (nCount < nMaxLength && input_record_buffer.head != NULL)
1870 {
1871 input_record_buffer.length--;
1872 input_record_buffer_node_T *pop_head = input_record_buffer.head;
1873 irEvents[nCount++] = pop_head->ir;
1874 input_record_buffer.head = pop_head->next;
1875 vim_free(pop_head);
1876 if (input_record_buffer.length == 0)
1877 input_record_buffer.tail = NULL;
1878 }
1879 return nCount;
1880}
Christopher Plewright20b795e2022-12-20 20:01:58 +00001881#endif // !FEAT_GUI_MSWIN || VIMDLL
1882
1883#ifdef FEAT_EVAL
1884/*
1885 * The 'test_mswin_event' function is for testing Vim's low-level handling of
1886 * user input events. ie, this manages the encoding of INPUT_RECORD events
1887 * so that we have a way to test how Vim decodes INPUT_RECORD events in Windows
1888 * consoles.
1889 *
1890 * The 'test_mswin_event' function is based on 'test_gui_event'. In fact, when
1891 * the Windows GUI is running, the arguments; 'event' and 'args', are the same.
1892 * So, it acts as an alias for 'test_gui_event' for the Windows GUI.
1893 *
1894 * When the Windows console is running, the arguments; 'event' and 'args', are
1895 * a subset of what 'test_gui_event' handles, ie, only "key" and "mouse"
1896 * events are encoded as INPUT_RECORD events.
1897 *
1898 * Note: INPUT_RECORDs are only used by the Windows console, not the GUI. The
1899 * GUI sends MSG structs instead.
1900 */
1901 int
1902test_mswin_event(char_u *event, dict_T *args)
1903{
1904 int lpEventsWritten = 0;
1905
1906# if defined(VIMDLL) || defined(FEAT_GUI_MSWIN)
1907 if (gui.in_use)
1908 return test_gui_w32_sendevent(event, args);
1909# endif
1910
1911# if defined(VIMDLL) || !defined(FEAT_GUI_MSWIN)
1912
1913// Currently implemented event record types are; KEY_EVENT and MOUSE_EVENT
1914// Potentially could also implement: FOCUS_EVENT and WINDOW_BUFFER_SIZE_EVENT
1915// Maybe also: MENU_EVENT
1916
1917 INPUT_RECORD ir;
1918 BOOL input_encoded = FALSE;
1919 if (STRCMP(event, "key") == 0)
1920 input_encoded = encode_key_event(args, &ir);
1921 else if (STRCMP(event, "mouse") == 0)
1922 input_encoded = encode_mouse_event(args, &ir);
1923 else
1924 {
1925 semsg(_(e_invalid_value_for_argument_str_str), "event", event);
1926 return FALSE;
1927 }
1928
1929 // Ideally, WriteConsoleInput would be used to inject these low-level
1930 // events. But, this doesnt work well in the CI test environment. So
1931 // implementing an input_record_buffer instead.
1932 if (input_encoded)
1933 lpEventsWritten = write_input_record_buffer(&ir, 1);
1934
1935 if (STRCMP(event, "mouse") == 0)
1936 exec_normal(TRUE, TRUE, TRUE);
1937
1938# endif
1939 return lpEventsWritten;
1940}
1941#endif // FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00001942
1943#ifdef MCH_CURSOR_SHAPE
1944/*
1945 * Set the shape of the cursor.
1946 * 'thickness' can be from 1 (thin) to 99 (block)
1947 */
1948 static void
1949mch_set_cursor_shape(int thickness)
1950{
Christopher Plewright38804d62022-11-09 23:55:52 +00001951 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01001952 {
1953 if (*T_CSI == NUL)
1954 {
1955 // If 't_SI' is not set, use the default cursor styles.
1956 if (thickness < 50)
1957 vtp_printf("\033[3 q"); // underline
1958 else
1959 vtp_printf("\033[0 q"); // default
1960 }
1961 }
1962 else
1963 {
1964 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1965 ConsoleCursorInfo.dwSize = thickness;
1966 ConsoleCursorInfo.bVisible = s_cursor_visible;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001967
K.Takatadf5320c2022-09-01 13:20:16 +01001968 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1969 if (s_cursor_visible)
1970 SetConsoleCursorPosition(g_hConOut, g_coord);
1971 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001972}
1973
1974 void
1975mch_update_cursor(void)
1976{
1977 int idx;
1978 int thickness;
1979
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001980# ifdef VIMDLL
1981 if (gui.in_use)
1982 return;
1983# endif
1984
Bram Moolenaar071d4272004-06-13 20:20:40 +00001985 /*
1986 * How the cursor is drawn depends on the current mode.
1987 */
1988 idx = get_shape_idx(FALSE);
1989
1990 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001991 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00001992 else
1993 thickness = shape_table[idx].percentage;
1994 mch_set_cursor_shape(thickness);
1995}
1996#endif
1997
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001998#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001999/*
2000 * Handle FOCUS_EVENT.
2001 */
2002 static void
2003handle_focus_event(INPUT_RECORD ir)
2004{
2005 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
2006 ui_focus_change((int)g_fJustGotFocus);
2007}
2008
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002009static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
2010
Bram Moolenaar071d4272004-06-13 20:20:40 +00002011/*
2012 * Wait until console input from keyboard or mouse is available,
2013 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002014 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002015 * Return TRUE if something is available FALSE if not.
2016 */
2017 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002018WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002019{
2020 DWORD dwNow = 0, dwEndTime = 0;
2021 INPUT_RECORD ir;
2022 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002023 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002024# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02002025 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002026# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002027
2028 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002029 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002030 dwEndTime = GetTickCount() + msec;
2031 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002032 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002033 dwEndTime = INFINITE;
2034
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002035 // We need to loop until the end of the time period, because
2036 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002037 for (;;)
2038 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002039 // Only process messages when waiting.
2040 if (msec != 0)
2041 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002042# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002043 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002044# endif
2045# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002046 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002047# endif
2048# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002049 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002050# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002051 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002052
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02002053 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002054# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002055 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002056# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057 )
2058 return TRUE;
2059
2060 if (msec > 0)
2061 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002062 // If the specified wait time has passed, return. Beware that
2063 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002064 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02002065 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002066 break;
2067 }
2068 if (msec != 0)
2069 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00002070 DWORD dwWaitTime = dwEndTime - dwNow;
2071
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002072 // Don't wait for more than 11 msec to avoid dropping characters,
2073 // check channel while waiting for input and handle a callback from
2074 // 'balloonexpr'.
2075 if (dwWaitTime > 11)
2076 dwWaitTime = 11;
2077
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002078# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002079 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002080 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002081# endif
2082# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002083 // When waiting very briefly don't trigger timers.
2084 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002085 {
2086 long due_time;
2087
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002088 // Trigger timers and then get the time in msec until the next
2089 // one is due. Wait up to that time.
2090 due_time = check_due_timer();
2091 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002092 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002093 // timer may have used feedkeys().
2094 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002095 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002096 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
2097 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002098 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002099# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002100 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002101# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002102 // Wait for either an event on the console input or a
2103 // message in the client-server window.
2104 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
2105 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002106# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002107 wait_for_single_object(g_hConIn, dwWaitTime)
2108 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002109# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002110 )
2111 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002112 }
2113
2114 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002115 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002116
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002117# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02002118 // May have to redraw if the cursor ends up in the wrong place.
2119 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01002120 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002121 {
2122 CONSOLE_SCREEN_BUFFER_INFO csbi;
2123
2124 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2125 {
2126 if (csbi.dwCursorPosition.Y != msg_row)
2127 {
matveyte08795e2021-05-07 15:00:17 +02002128 // The screen is now messed up, must redraw the command
2129 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002130 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02002131 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002132 redrawcmd();
2133 }
2134 }
2135 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002136# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002137
2138 if (cRecords > 0)
2139 {
2140 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
2141 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002142# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01002143 // Windows IME sends two '\n's with only one 'ENTER'. First:
2144 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00002145 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002146 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
2147 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002148 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002149 continue;
2150 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002151# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002152 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
2153 NULL, FALSE))
2154 return TRUE;
2155 }
2156
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002157 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002158
2159 if (ir.EventType == FOCUS_EVENT)
2160 handle_focus_event(ir);
2161 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002162 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002163 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
2164
Bram Moolenaar36698e32019-12-11 22:57:40 +01002165 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002166 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002167 if (dwSize.X != Columns || dwSize.Y != Rows)
2168 {
2169 CONSOLE_SCREEN_BUFFER_INFO csbi;
2170 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01002171 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002172 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01002173 if (dwSize.X != Columns || dwSize.Y != Rows)
2174 {
2175 ResizeConBuf(g_hConOut, dwSize);
2176 shell_resized();
2177 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002178 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002179 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002180 else if (ir.EventType == MOUSE_EVENT
2181 && decode_mouse_event(&ir.Event.MouseEvent))
2182 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002183 }
2184 else if (msec == 0)
2185 break;
2186 }
2187
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002188# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01002189 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002190 if (input_available())
2191 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002192# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002193
Bram Moolenaar071d4272004-06-13 20:20:40 +00002194 return FALSE;
2195}
2196
Bram Moolenaar071d4272004-06-13 20:20:40 +00002197/*
2198 * return non-zero if a character is available
2199 */
2200 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002201mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002202{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002203# ifdef VIMDLL
2204 if (gui.in_use)
2205 return TRUE;
2206# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002207 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002208}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002209
2210# if defined(FEAT_TERMINAL) || defined(PROTO)
2211/*
2212 * Check for any pending input or messages.
2213 */
2214 int
2215mch_check_messages(void)
2216{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002217# ifdef VIMDLL
2218 if (gui.in_use)
2219 return TRUE;
2220# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002221 return WaitForChar(0L, TRUE);
2222}
2223# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002224
2225/*
2226 * Create the console input. Used when reading stdin doesn't work.
2227 */
2228 static void
2229create_conin(void)
2230{
2231 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
2232 FILE_SHARE_READ|FILE_SHARE_WRITE,
2233 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002234 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002235 did_create_conin = TRUE;
2236}
2237
2238/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002239 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002240 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002241 static WCHAR
2242tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002243{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002244 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002245
2246 for (;;)
2247 {
2248 INPUT_RECORD ir;
2249 DWORD cRecords = 0;
2250
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002251# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002252 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002253 if (input_available())
2254 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002255 if (g_nMouseClick != -1)
2256 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002257# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002258 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002259 {
2260 if (did_create_conin)
2261 read_error_exit();
2262 create_conin();
2263 continue;
2264 }
2265
2266 if (ir.EventType == KEY_EVENT)
2267 {
2268 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
2269 pmodifiers, TRUE))
2270 return ch;
2271 }
2272 else if (ir.EventType == FOCUS_EVENT)
2273 handle_focus_event(ir);
2274 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
2275 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002276 else if (ir.EventType == MOUSE_EVENT)
2277 {
2278 if (decode_mouse_event(&ir.Event.MouseEvent))
2279 return 0;
2280 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002281 }
2282}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002283#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002284
2285
2286/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02002287 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002288 * Get one or more characters from the keyboard or the mouse.
2289 * If time == 0, do not wait for characters.
2290 * If time == n, wait a short time for characters.
2291 * If time == -1, wait forever for characters.
2292 * Returns the number of characters read into buf.
2293 */
2294 int
2295mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002296 char_u *buf UNUSED,
2297 int maxlen UNUSED,
2298 long time UNUSED,
2299 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002300{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002301#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002302
2303 int len;
2304 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002305# ifdef VIMDLL
2306// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
2307# define TYPEAHEADSPACE 6
2308# else
2309# define TYPEAHEADSPACE 0
2310# endif
2311# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002312 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002313 static int typeaheadlen = 0;
2314
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002315# ifdef VIMDLL
2316 if (gui.in_use)
2317 return 0;
2318# endif
2319
Bram Moolenaar0f873732019-12-05 20:28:46 +01002320 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002321 if (typeaheadlen > 0)
2322 goto theend;
2323
Bram Moolenaar071d4272004-06-13 20:20:40 +00002324 if (time >= 0)
2325 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002326 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00002327 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002328 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01002329 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00002330 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002331 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00002332
Bram Moolenaar3918c952005-03-15 22:34:55 +00002333 /*
2334 * If there is no character available within 2 seconds (default)
2335 * write the autoscript file to disk. Or cause the CursorHold event
2336 * to be triggered.
2337 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002338 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002339 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00002340 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002341 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00002342 buf[0] = K_SPECIAL;
2343 buf[1] = KS_EXTRA;
2344 buf[2] = (int)KE_CURSORHOLD;
2345 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002346 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00002347 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002348 }
2349 }
2350
2351 /*
2352 * Try to read as many characters as there are, until the buffer is full.
2353 */
2354
Bram Moolenaar0f873732019-12-05 20:28:46 +01002355 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002356 g_fCBrkPressed = FALSE;
2357
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002358# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002359 if (fdDump)
2360 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002361# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002362
Bram Moolenaar0f873732019-12-05 20:28:46 +01002363 // Keep looping until there is something in the typeahead buffer and more
2364 // to get and still room in the buffer (up to two bytes for a char and
2365 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002366 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01002367 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002368 {
2369 if (typebuf_changed(tb_change_cnt))
2370 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002371 // "buf" may be invalid now if a client put something in the
2372 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002373 typeaheadlen = 0;
2374 break;
2375 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002376 if (g_nMouseClick != -1)
2377 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002378# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002379 if (fdDump)
2380 fprintf(fdDump, "{%02x @ %d, %d}",
2381 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002382# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01002383 char_u modifiers = ((char_u *)(&g_nMouseClick))[0];
2384 char_u scroll_dir = ((char_u *)(&g_nMouseClick))[1];
2385
2386 if (scroll_dir == KE_MOUSEDOWN
2387 || scroll_dir == KE_MOUSEUP
2388 || scroll_dir == KE_MOUSELEFT
2389 || scroll_dir == KE_MOUSERIGHT)
2390 {
2391 if (modifiers > 0)
2392 {
Christopher Plewright03193062022-11-22 12:58:27 +00002393 // use K_SPECIAL instead of CSI to make mappings work
2394 typeahead[typeaheadlen++] = K_SPECIAL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002395 typeahead[typeaheadlen++] = KS_MODIFIER;
2396 typeahead[typeaheadlen++] = modifiers;
2397 }
2398 typeahead[typeaheadlen++] = CSI;
2399 typeahead[typeaheadlen++] = KS_EXTRA;
2400 typeahead[typeaheadlen++] = scroll_dir;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002401 }
2402 else
2403 {
2404 typeahead[typeaheadlen++] = ESC + 128;
2405 typeahead[typeaheadlen++] = 'M';
2406 typeahead[typeaheadlen++] = g_nMouseClick;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002407 }
Christopher Plewright36446bb2022-11-23 22:28:08 +00002408
2409 // Pass the pointer coordinates of the mouse event in 2 bytes,
2410 // allowing for > 223 columns. Both for click and scroll events.
2411 // This is the same as what is used for the GUI.
2412 typeahead[typeaheadlen++] = (char_u)(g_xMouse / 128 + ' ' + 1);
2413 typeahead[typeaheadlen++] = (char_u)(g_xMouse % 128 + ' ' + 1);
2414 typeahead[typeaheadlen++] = (char_u)(g_yMouse / 128 + ' ' + 1);
2415 typeahead[typeaheadlen++] = (char_u)(g_yMouse % 128 + ' ' + 1);
2416
2417 g_nMouseClick = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002418 }
2419 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002420 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002421 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002422 int modifiers = 0;
2423
2424 c = tgetch(&modifiers, &ch2);
2425
2426 if (typebuf_changed(tb_change_cnt))
2427 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002428 // "buf" may be invalid now if a client put something in the
2429 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002430 typeaheadlen = 0;
2431 break;
2432 }
2433
2434 if (c == Ctrl_C && ctrl_c_interrupts)
2435 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002436# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002437 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002438# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002439 got_int = TRUE;
2440 }
2441
Bram Moolenaar071d4272004-06-13 20:20:40 +00002442 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002443 {
2444 int n = 1;
2445
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002446 if (ch2 == NUL)
2447 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002448 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002449 char_u *p;
2450 WCHAR ch[2];
2451
2452 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002453 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002454 {
2455 ch[1] = tgetch(&modifiers, &ch2);
2456 n++;
2457 }
2458 p = utf16_to_enc(ch, &n);
2459 if (p != NULL)
2460 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002461 for (i = 0, j = 0; i < n; i++)
2462 {
2463 typeahead[typeaheadlen + j++] = p[i];
2464# ifdef VIMDLL
2465 if (p[i] == CSI)
2466 {
2467 typeahead[typeaheadlen + j++] = KS_EXTRA;
2468 typeahead[typeaheadlen + j++] = KE_CSI;
2469 }
2470# endif
2471 }
2472 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002473 vim_free(p);
2474 }
2475 }
2476 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002477 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002478 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002479# ifdef VIMDLL
2480 if (c == CSI)
2481 {
2482 typeahead[typeaheadlen + 1] = KS_EXTRA;
2483 typeahead[typeaheadlen + 2] = KE_CSI;
2484 n = 3;
2485 }
2486# endif
2487 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002488 if (ch2 != NUL)
2489 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002490 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002491 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002492 switch (ch2)
2493 {
2494 case (WCHAR)'\324': // SHIFT+Insert
2495 case (WCHAR)'\325': // CTRL+Insert
2496 case (WCHAR)'\327': // SHIFT+Delete
2497 case (WCHAR)'\330': // CTRL+Delete
2498 typeahead[typeaheadlen + n] = (char_u)ch2;
2499 n++;
2500 break;
2501
2502 default:
2503 typeahead[typeaheadlen + n] = 3;
2504 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2505 n += 2;
2506 break;
2507 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002508 }
2509 else
2510 {
2511 typeahead[typeaheadlen + n] = 3;
2512 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2513 n += 2;
2514 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002515 }
2516
Bram Moolenaar0f873732019-12-05 20:28:46 +01002517 // Use the ALT key to set the 8th bit of the character
2518 // when it's one byte, the 8th bit isn't set yet and not
2519 // using a double-byte encoding (would become a lead
2520 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002521 if ((modifiers & MOD_MASK_ALT)
2522 && n == 1
2523 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002524 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002525 )
2526 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002527 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2528 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002529 modifiers &= ~MOD_MASK_ALT;
2530 }
2531
2532 if (modifiers != 0)
2533 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002534 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002535 mch_memmove(typeahead + typeaheadlen + 3,
2536 typeahead + typeaheadlen, n);
2537 typeahead[typeaheadlen++] = K_SPECIAL;
2538 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2539 typeahead[typeaheadlen++] = modifiers;
2540 }
2541
2542 typeaheadlen += n;
2543
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002544# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002545 if (fdDump)
2546 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002547# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002548 }
2549 }
2550 }
2551
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002552# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002553 if (fdDump)
2554 {
2555 fputs("]\n", fdDump);
2556 fflush(fdDump);
2557 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002558# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002559
Bram Moolenaar071d4272004-06-13 20:20:40 +00002560theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002561 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002562 len = 0;
2563 while (len < maxlen && typeaheadlen > 0)
2564 {
2565 buf[len++] = typeahead[0];
2566 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2567 }
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00002568# ifdef FEAT_EVAL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002569 if (len > 0)
2570 {
2571 buf[len] = NUL;
2572 ch_log(NULL, "raw key input: \"%s\"", buf);
2573 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002574# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002575 return len;
2576
Bram Moolenaar0f873732019-12-05 20:28:46 +01002577#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002578 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002579#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002580}
2581
Bram Moolenaar82881492012-11-20 16:53:39 +01002582#ifndef PROTO
2583# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002584# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002585# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002586#endif
2587
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002588/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002589 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002590 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2591 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002592 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002593 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002594 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002595executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002596{
LemonBoy40fd7e62022-05-05 20:18:16 +01002597 int attrs = win32_getattrs((char_u *)name);
2598
2599 // The file doesn't exist or is a folder.
2600 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2601 return FALSE;
2602 // Check if the file is an AppExecLink, a special alias used by Windows
2603 // Store for its apps.
2604 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002605 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002606 char_u *res = resolve_appexeclink((char_u *)name);
2607 if (res == NULL)
2608 return FALSE;
2609 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002610 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002611 *path = res;
2612 else
2613 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002614 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002615 else if (path != NULL)
2616 *path = FullName_save((char_u *)name, FALSE);
2617 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002618}
2619
2620/*
2621 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2622 * If "use_path" is FALSE: Return TRUE if "name" exists.
2623 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2624 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2625 * the allocated memory.
2626 */
2627 static int
2628executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2629{
2630 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2631 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2632 // UTF-8.
2633 char_u buf[_MAX_PATH * 3];
2634 size_t len = STRLEN(name);
2635 size_t tmplen;
2636 char_u *p, *e, *e2;
2637 char_u *pathbuf = NULL;
2638 char_u *pathext = NULL;
2639 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002640 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002641 int noext = FALSE;
2642 int retval = FALSE;
2643
2644 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002645 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002646
2647 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002648 shname = gettail(p_sh);
2649 if (strstr((char *)shname, "sh") != NULL &&
2650 !(strstr((char *)shname, "powershell") != NULL
2651 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002652 noext = TRUE;
2653
2654 if (use_pathext)
2655 {
2656 pathext = mch_getenv("PATHEXT");
2657 if (pathext == NULL)
2658 pathext = (char_u *)".com;.exe;.bat;.cmd";
2659
2660 if (noext == FALSE)
2661 {
2662 /*
2663 * Loop over all extensions in $PATHEXT.
2664 * Check "name" ends with extension.
2665 */
2666 p = pathext;
2667 while (*p)
2668 {
2669 if (p[0] == ';'
2670 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2671 {
2672 // Skip empty or single ".".
2673 ++p;
2674 continue;
2675 }
2676 e = vim_strchr(p, ';');
2677 if (e == NULL)
2678 e = p + STRLEN(p);
2679 tmplen = e - p;
2680
2681 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2682 {
2683 noext = TRUE;
2684 break;
2685 }
2686
2687 p = e;
2688 }
2689 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002690 }
2691
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002692 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002693 if (pathext == NULL)
2694 pathext = (char_u *)".";
2695 else if (noext == TRUE)
2696 {
2697 if (pathextbuf == NULL)
2698 pathextbuf = alloc(STRLEN(pathext) + 3);
2699 if (pathextbuf == NULL)
2700 {
2701 retval = FALSE;
2702 goto theend;
2703 }
2704 STRCPY(pathextbuf, ".;");
2705 STRCAT(pathextbuf, pathext);
2706 pathext = pathextbuf;
2707 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002708
Bram Moolenaar95da1362020-05-30 18:37:55 +02002709 // Use $PATH when "use_path" is TRUE and "name" is basename.
2710 if (use_path && gettail((char_u *)name) == (char_u *)name)
2711 {
2712 p = mch_getenv("PATH");
2713 if (p != NULL)
2714 {
2715 pathbuf = alloc(STRLEN(p) + 3);
2716 if (pathbuf == NULL)
2717 {
2718 retval = FALSE;
2719 goto theend;
2720 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002721
2722 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2723 STRCPY(pathbuf, ".;");
2724 else
2725 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002726 STRCAT(pathbuf, p);
2727 }
2728 }
2729
2730 /*
2731 * Walk through all entries in $PATH to check if "name" exists there and
2732 * is an executable file.
2733 */
2734 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2735 while (*p)
2736 {
2737 if (*p == ';') // Skip empty entry
2738 {
2739 ++p;
2740 continue;
2741 }
2742 e = vim_strchr(p, ';');
2743 if (e == NULL)
2744 e = p + STRLEN(p);
2745
2746 if (e - p + len + 2 > sizeof(buf))
2747 {
2748 retval = FALSE;
2749 goto theend;
2750 }
2751 // A single "." that means current dir.
2752 if (e - p == 1 && *p == '.')
2753 STRCPY(buf, name);
2754 else
2755 {
2756 vim_strncpy(buf, p, e - p);
2757 add_pathsep(buf);
2758 STRCAT(buf, name);
2759 }
2760 tmplen = STRLEN(buf);
2761
2762 /*
2763 * Loop over all extensions in $PATHEXT.
2764 * Check "name" with extension added.
2765 */
2766 p = pathext;
2767 while (*p)
2768 {
2769 if (*p == ';')
2770 {
2771 // Skip empty entry
2772 ++p;
2773 continue;
2774 }
2775 e2 = vim_strchr(p, (int)';');
2776 if (e2 == NULL)
2777 e2 = p + STRLEN(p);
2778
2779 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2780 {
2781 // Not a single "." that means no extension is added.
2782 if (e2 - p + tmplen + 1 > sizeof(buf))
2783 {
2784 retval = FALSE;
2785 goto theend;
2786 }
2787 vim_strncpy(buf + tmplen, p, e2 - p);
2788 }
2789 if (executable_file((char *)buf, path))
2790 {
2791 retval = TRUE;
2792 goto theend;
2793 }
2794
2795 p = e2;
2796 }
2797
2798 p = e;
2799 }
2800
2801theend:
2802 free(pathextbuf);
2803 free(pathbuf);
2804 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002805}
2806
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002807#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2808 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002809/*
2810 * Bad parameter handler.
2811 *
2812 * Certain MS CRT functions will intentionally crash when passed invalid
2813 * parameters to highlight possible security holes. Setting this function as
2814 * the bad parameter handler will prevent the crash.
2815 *
2816 * In debug builds the parameters contain CRT information that might help track
2817 * down the source of a problem, but in non-debug builds the arguments are all
2818 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2819 * worth allowing these to make debugging of issues easier.
2820 */
2821 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002822bad_param_handler(const wchar_t *expression UNUSED,
2823 const wchar_t *function UNUSED,
2824 const wchar_t *file UNUSED,
2825 unsigned int line UNUSED,
2826 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002827{
2828}
2829
2830# define SET_INVALID_PARAM_HANDLER \
2831 ((void)_set_invalid_parameter_handler(bad_param_handler))
2832#else
2833# define SET_INVALID_PARAM_HANDLER
2834#endif
2835
Bram Moolenaar4f974752019-02-17 17:44:42 +01002836#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002837
2838/*
2839 * GUI version of mch_init().
2840 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002841 static void
2842mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002843{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002844# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002845 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002846# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002847
Bram Moolenaar0f873732019-12-05 20:28:46 +01002848 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002849 SET_INVALID_PARAM_HANDLER;
2850
Bram Moolenaar0f873732019-12-05 20:28:46 +01002851 // Let critical errors result in a failure, not in a dialog box. Required
2852 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002853 SetErrorMode(SEM_FAILCRITICALERRORS);
2854
Bram Moolenaar0f873732019-12-05 20:28:46 +01002855 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002856
Bram Moolenaar0f873732019-12-05 20:28:46 +01002857 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002858 Rows = 25;
2859 Columns = 80;
2860
Bram Moolenaar0f873732019-12-05 20:28:46 +01002861 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002862 {
2863 char_u vimrun_location[_MAX_PATH + 4];
2864
Bram Moolenaar0f873732019-12-05 20:28:46 +01002865 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002866 STRCPY(vimrun_location, exe_name);
2867 STRCPY(gettail(vimrun_location), "vimrun.exe");
2868 if (mch_getperm(vimrun_location) >= 0)
2869 {
2870 if (*skiptowhite(vimrun_location) != NUL)
2871 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002872 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002873 mch_memmove(vimrun_location + 1, vimrun_location,
2874 STRLEN(vimrun_location) + 1);
2875 *vimrun_location = '"';
2876 STRCPY(gettail(vimrun_location), "vimrun\" ");
2877 }
2878 else
2879 STRCPY(gettail(vimrun_location), "vimrun ");
2880
2881 vimrun_path = (char *)vim_strsave(vimrun_location);
2882 s_dont_use_vimrun = FALSE;
2883 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002884 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002885 s_dont_use_vimrun = FALSE;
2886
Bram Moolenaar0f873732019-12-05 20:28:46 +01002887 // Don't give the warning for a missing vimrun.exe right now, but only
2888 // when vimrun was supposed to be used. Don't bother people that do
2889 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002890 if (s_dont_use_vimrun)
2891 need_vimrun_warning = TRUE;
2892 }
2893
2894 /*
2895 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2896 * Otherwise the default "findstr /n" is used.
2897 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002898 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01002899 set_option_value_give_err((char_u *)"grepprg",
2900 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002901
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002902# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002903 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002904# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002905
2906 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002907}
2908
2909
Bram Moolenaar0f873732019-12-05 20:28:46 +01002910#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002911
2912#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002913
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002914# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2915# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002916
2917/*
2918 * ClearConsoleBuffer()
2919 * Description:
2920 * Clears the entire contents of the console screen buffer, using the
2921 * specified attribute.
2922 * Returns:
2923 * TRUE on success
2924 */
2925 static BOOL
2926ClearConsoleBuffer(WORD wAttribute)
2927{
2928 CONSOLE_SCREEN_BUFFER_INFO csbi;
2929 COORD coord;
2930 DWORD NumCells, dummy;
2931
2932 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2933 return FALSE;
2934
2935 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2936 coord.X = 0;
2937 coord.Y = 0;
2938 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2939 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002940 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002941 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2942 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002943 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002944
2945 return TRUE;
2946}
2947
2948/*
2949 * FitConsoleWindow()
2950 * Description:
2951 * Checks if the console window will fit within given buffer dimensions.
2952 * Also, if requested, will shrink the window to fit.
2953 * Returns:
2954 * TRUE on success
2955 */
2956 static BOOL
2957FitConsoleWindow(
2958 COORD dwBufferSize,
2959 BOOL WantAdjust)
2960{
2961 CONSOLE_SCREEN_BUFFER_INFO csbi;
2962 COORD dwWindowSize;
2963 BOOL NeedAdjust = FALSE;
2964
2965 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2966 {
2967 /*
2968 * A buffer resize will fail if the current console window does
2969 * not lie completely within that buffer. To avoid this, we might
2970 * have to move and possibly shrink the window.
2971 */
2972 if (csbi.srWindow.Right >= dwBufferSize.X)
2973 {
2974 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2975 if (dwWindowSize.X > dwBufferSize.X)
2976 dwWindowSize.X = dwBufferSize.X;
2977 csbi.srWindow.Right = dwBufferSize.X - 1;
2978 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2979 NeedAdjust = TRUE;
2980 }
2981 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2982 {
2983 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2984 if (dwWindowSize.Y > dwBufferSize.Y)
2985 dwWindowSize.Y = dwBufferSize.Y;
2986 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2987 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2988 NeedAdjust = TRUE;
2989 }
2990 if (NeedAdjust && WantAdjust)
2991 {
2992 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2993 return FALSE;
2994 }
2995 return TRUE;
2996 }
2997
2998 return FALSE;
2999}
3000
3001typedef struct ConsoleBufferStruct
3002{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003003 BOOL IsValid;
3004 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003005 PCHAR_INFO Buffer;
3006 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003007 PSMALL_RECT Regions;
3008 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003009} ConsoleBuffer;
3010
3011/*
3012 * SaveConsoleBuffer()
3013 * Description:
3014 * Saves important information about the console buffer, including the
3015 * actual buffer contents. The saved information is suitable for later
3016 * restoration by RestoreConsoleBuffer().
3017 * Returns:
3018 * TRUE if all information was saved; FALSE otherwise
3019 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
3020 */
3021 static BOOL
3022SaveConsoleBuffer(
3023 ConsoleBuffer *cb)
3024{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003025 DWORD NumCells;
3026 COORD BufferCoord;
3027 SMALL_RECT ReadRegion;
3028 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003029 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003030
Bram Moolenaar071d4272004-06-13 20:20:40 +00003031 if (cb == NULL)
3032 return FALSE;
3033
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003034 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003035 {
3036 cb->IsValid = FALSE;
3037 return FALSE;
3038 }
3039 cb->IsValid = TRUE;
3040
Christopher Plewright1140b512022-11-12 18:46:05 +00003041 // VTP uses alternate screen buffer.
3042 // No need to save buffer contents for restoration.
3043 if (win11_or_later && vtp_working)
3044 return TRUE;
3045
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003046 /*
3047 * Allocate a buffer large enough to hold the entire console screen
3048 * buffer. If this ConsoleBuffer structure has already been initialized
3049 * with a buffer of the correct size, then just use that one.
3050 */
3051 if (!cb->IsValid || cb->Buffer == NULL ||
3052 cb->BufferSize.X != cb->Info.dwSize.X ||
3053 cb->BufferSize.Y != cb->Info.dwSize.Y)
3054 {
3055 cb->BufferSize.X = cb->Info.dwSize.X;
3056 cb->BufferSize.Y = cb->Info.dwSize.Y;
3057 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
3058 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003059 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003060 if (cb->Buffer == NULL)
3061 return FALSE;
3062 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003063
3064 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003065 * We will now copy the console screen buffer into our buffer.
3066 * ReadConsoleOutput() seems to be limited as far as how much you
3067 * can read at a time. Empirically, this number seems to be about
3068 * 12000 cells (rows * columns). Start at position (0, 0) and copy
3069 * in chunks until it is all copied. The chunks will all have the
3070 * same horizontal characteristics, so initialize them now. The
3071 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003072 */
Bram Moolenaar61594242015-09-01 20:23:37 +02003073 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003074 ReadRegion.Left = 0;
3075 ReadRegion.Right = cb->Info.dwSize.X - 1;
3076 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003077
3078 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
3079 if (cb->Regions == NULL || numregions != cb->NumRegions)
3080 {
3081 cb->NumRegions = numregions;
3082 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003083 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003084 if (cb->Regions == NULL)
3085 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003086 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003087 return FALSE;
3088 }
3089 }
3090
3091 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003092 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003093 /*
3094 * Read into position (0, Y) in our buffer.
3095 */
3096 BufferCoord.Y = Y;
3097 /*
3098 * Read the region whose top left corner is (0, Y) and whose bottom
3099 * right corner is (width - 1, Y + Y_incr - 1). This should define
3100 * a region of size width by Y_incr. Don't worry if this region is
3101 * too large for the remaining buffer; it will be cropped.
3102 */
3103 ReadRegion.Top = Y;
3104 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003105 if (!ReadConsoleOutputW(g_hConOut, // output handle
3106 cb->Buffer, // our buffer
3107 cb->BufferSize, // dimensions of our buffer
3108 BufferCoord, // offset in our buffer
3109 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003110 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003111 VIM_CLEAR(cb->Buffer);
3112 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003113 return FALSE;
3114 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02003115 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003116 }
3117
3118 return TRUE;
3119}
3120
3121/*
3122 * RestoreConsoleBuffer()
3123 * Description:
3124 * Restores important information about the console buffer, including the
3125 * actual buffer contents, if desired. The information to restore is in
3126 * the same format used by SaveConsoleBuffer().
3127 * Returns:
3128 * TRUE on success
3129 */
3130 static BOOL
3131RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003132 ConsoleBuffer *cb,
3133 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003134{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003135 COORD BufferCoord;
3136 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003137 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003138
Christopher Plewright1140b512022-11-12 18:46:05 +00003139 // VTP uses alternate screen buffer.
3140 // No need to restore buffer contents.
3141 if (win11_or_later && vtp_working)
3142 return TRUE;
3143
Bram Moolenaar071d4272004-06-13 20:20:40 +00003144 if (cb == NULL || !cb->IsValid)
3145 return FALSE;
3146
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003147 /*
3148 * Before restoring the buffer contents, clear the current buffer, and
3149 * restore the cursor position and window information. Doing this now
3150 * prevents old buffer contents from "flashing" onto the screen.
3151 */
3152 if (RestoreScreen)
3153 ClearConsoleBuffer(cb->Info.wAttributes);
3154
3155 FitConsoleWindow(cb->Info.dwSize, TRUE);
3156 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
3157 return FALSE;
3158 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
3159 return FALSE;
3160
3161 if (!RestoreScreen)
3162 {
3163 /*
3164 * No need to restore the screen buffer contents, so we're done.
3165 */
3166 return TRUE;
3167 }
3168
3169 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
3170 return FALSE;
3171 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
3172 return FALSE;
3173
3174 /*
3175 * Restore the screen buffer contents.
3176 */
3177 if (cb->Buffer != NULL)
3178 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003179 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003180 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003181 BufferCoord.X = cb->Regions[i].Left;
3182 BufferCoord.Y = cb->Regions[i].Top;
3183 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01003184 if (!WriteConsoleOutputW(g_hConOut, // output handle
3185 cb->Buffer, // our buffer
3186 cb->BufferSize, // dimensions of our buffer
3187 BufferCoord, // offset in our buffer
3188 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02003189 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003190 }
3191 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003192
3193 return TRUE;
3194}
3195
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003196# define FEAT_RESTORE_ORIG_SCREEN
3197# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003198static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003199# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003200static ConsoleBuffer g_cbNonTermcap = { 0 };
3201static ConsoleBuffer g_cbTermcap = { 0 };
3202
Bram Moolenaar071d4272004-06-13 20:20:40 +00003203char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01003204HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00003205static HICON g_hOrigIconSmall = NULL;
3206static HICON g_hOrigIcon = NULL;
3207static HICON g_hVimIcon = NULL;
3208static BOOL g_fCanChangeIcon = FALSE;
3209
Bram Moolenaar071d4272004-06-13 20:20:40 +00003210/*
3211 * GetConsoleIcon()
3212 * Description:
3213 * Attempts to retrieve the small icon and/or the big icon currently in
3214 * use by a given window.
3215 * Returns:
3216 * TRUE on success
3217 */
3218 static BOOL
3219GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003220 HWND hWnd,
3221 HICON *phIconSmall,
3222 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003223{
3224 if (hWnd == NULL)
3225 return FALSE;
3226
3227 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003228 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
3229 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003230 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003231 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
3232 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003233 return TRUE;
3234}
3235
3236/*
3237 * SetConsoleIcon()
3238 * Description:
3239 * Attempts to change the small icon and/or the big icon currently in
3240 * use by a given window.
3241 * Returns:
3242 * TRUE on success
3243 */
3244 static BOOL
3245SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003246 HWND hWnd,
3247 HICON hIconSmall,
3248 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003249{
Bram Moolenaar071d4272004-06-13 20:20:40 +00003250 if (hWnd == NULL)
3251 return FALSE;
3252
3253 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003254 SendMessage(hWnd, WM_SETICON,
3255 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003256 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003257 SendMessage(hWnd, WM_SETICON,
3258 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003259 return TRUE;
3260}
3261
3262/*
3263 * SaveConsoleTitleAndIcon()
3264 * Description:
3265 * Saves the current console window title in g_szOrigTitle, for later
3266 * restoration. Also, attempts to obtain a handle to the console window,
3267 * and use it to save the small and big icons currently in use by the
3268 * console window. This is not always possible on some versions of Windows;
3269 * nor is it possible when running Vim remotely using Telnet (since the
3270 * console window the user sees is owned by a remote process).
3271 */
3272 static void
3273SaveConsoleTitleAndIcon(void)
3274{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003275 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003276 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
3277 return;
3278
3279 /*
3280 * Obtain a handle to the console window using GetConsoleWindow() from
3281 * KERNEL32.DLL; we need to handle in order to change the window icon.
3282 * This function only exists on NT-based Windows, starting with Windows
3283 * 2000. On older operating systems, we can't change the window icon
3284 * anyway.
3285 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003286 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003287 if (g_hWnd == NULL)
3288 return;
3289
Bram Moolenaar0f873732019-12-05 20:28:46 +01003290 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003291 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
3292 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
3293 return;
3294
Bram Moolenaar0f873732019-12-05 20:28:46 +01003295 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01003296 if (
3297# ifdef FEAT_LIBCALL
3298 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
3299# endif
3300 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003301 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003302 if (g_hVimIcon != NULL)
3303 g_fCanChangeIcon = TRUE;
3304}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003305
3306static int g_fWindInitCalled = FALSE;
3307static int g_fTermcapMode = FALSE;
3308static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003309
3310/*
3311 * non-GUI version of mch_init().
3312 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003313 static void
3314mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003315{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003316# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003317 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003318# endif
3319# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00003320 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003321# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003322
Bram Moolenaar0f873732019-12-05 20:28:46 +01003323 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02003324 SET_INVALID_PARAM_HANDLER;
3325
Bram Moolenaar0f873732019-12-05 20:28:46 +01003326 // Let critical errors result in a failure, not in a dialog box. Required
3327 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003328 SetErrorMode(SEM_FAILCRITICALERRORS);
3329
Bram Moolenaar0f873732019-12-05 20:28:46 +01003330 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00003331 out_flush();
3332
Bram Moolenaar0f873732019-12-05 20:28:46 +01003333 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00003334 if (read_cmd_fd == 0)
3335 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
3336 else
3337 create_conin();
3338 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
3339
Christopher Plewright38804d62022-11-09 23:55:52 +00003340 wt_init();
3341 vtp_flag_init();
3342 vtp_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003343# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01003344 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003345 SaveConsoleBuffer(&g_cbOrig);
3346 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003347# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01003348 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003349 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
3350 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003351# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003352 if (cterm_normal_fg_color == 0)
3353 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
3354 if (cterm_normal_bg_color == 0)
3355 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
3356
Bram Moolenaarbdace832019-03-02 10:13:42 +01003357 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02003358 g_color_index_fg = g_attrDefault & 0xf;
3359 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
3360
Bram Moolenaar0f873732019-12-05 20:28:46 +01003361 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00003362 update_tcap(g_attrCurrent);
3363
3364 GetConsoleCursorInfo(g_hConOut, &g_cci);
3365 GetConsoleMode(g_hConIn, &g_cmodein);
3366 GetConsoleMode(g_hConOut, &g_cmodeout);
3367
Bram Moolenaar071d4272004-06-13 20:20:40 +00003368 SaveConsoleTitleAndIcon();
3369 /*
3370 * Set both the small and big icons of the console window to Vim's icon.
3371 * Note that Vim presently only has one size of icon (32x32), but it
3372 * automatically gets scaled down to 16x16 when setting the small icon.
3373 */
3374 if (g_fCanChangeIcon)
3375 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003376
3377 ui_get_shellsize();
3378
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003379# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003380 fdDump = fopen("dump", "wt");
3381
3382 if (fdDump)
3383 {
3384 time_t t;
3385
3386 time(&t);
3387 fputs(ctime(&t), fdDump);
3388 fflush(fdDump);
3389 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003390# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003391
3392 g_fWindInitCalled = TRUE;
3393
Bram Moolenaar071d4272004-06-13 20:20:40 +00003394 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003395
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003396# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003397 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003398# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003399}
3400
3401/*
3402 * non-GUI version of mch_exit().
3403 * Shut down and exit with status `r'
3404 * Careful: mch_exit() may be called before mch_init()!
3405 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003406 static void
3407mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003408{
Bram Moolenaar955f1982017-02-05 15:10:51 +01003409 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003410
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003411 vtp_exit();
3412
Bram Moolenaar955f1982017-02-05 15:10:51 +01003413 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003414 if (g_fWindInitCalled)
3415 settmode(TMODE_COOK);
3416
Bram Moolenaar0f873732019-12-05 20:28:46 +01003417 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00003418
3419 if (g_fWindInitCalled)
3420 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02003421 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003422 /*
3423 * Restore both the small and big icons of the console window to
3424 * what they were at startup. Don't do this when the window is
3425 * closed, Vim would hang here.
3426 */
3427 if (g_fCanChangeIcon && !g_fForceExit)
3428 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003429
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003430# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003431 if (fdDump)
3432 {
3433 time_t t;
3434
3435 time(&t);
3436 fputs(ctime(&t), fdDump);
3437 fclose(fdDump);
3438 }
3439 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003440# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003441 }
3442
3443 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003444 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003445 SetConsoleMode(g_hConOut, g_cmodeout);
3446
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003447# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003448 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003449# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003450
3451 exit(r);
3452}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003453#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003454
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003455 void
3456mch_init(void)
3457{
3458#ifdef VIMDLL
3459 if (gui.starting)
3460 mch_init_g();
3461 else
3462 mch_init_c();
3463#elif defined(FEAT_GUI_MSWIN)
3464 mch_init_g();
3465#else
3466 mch_init_c();
3467#endif
3468}
3469
3470 void
3471mch_exit(int r)
3472{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003473#ifdef FEAT_NETBEANS_INTG
3474 netbeans_send_disconnect();
3475#endif
3476
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003477#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003478 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003479 mch_exit_g(r);
3480 else
3481 mch_exit_c(r);
3482#elif defined(FEAT_GUI_MSWIN)
3483 mch_exit_g(r);
3484#else
3485 mch_exit_c(r);
3486#endif
3487}
3488
Bram Moolenaar071d4272004-06-13 20:20:40 +00003489/*
3490 * Do we have an interactive window?
3491 */
3492 int
3493mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003494 int argc UNUSED,
3495 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003496{
3497 get_exe_name();
3498
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003499#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003500 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003501#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003502# ifdef VIMDLL
3503 if (gui.in_use)
3504 return OK;
3505# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003506 if (isatty(1))
3507 return OK;
3508 return FAIL;
3509#endif
3510}
3511
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003512/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003513 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003514 * When "len" is > 0, also expand short to long filenames.
3515 */
3516 void
3517fname_case(
3518 char_u *name,
3519 int len)
3520{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003521 int flen;
3522 WCHAR *p;
3523 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003524
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003525 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003526 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003527 return;
3528
3529 slash_adjust(name);
3530
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003531 p = enc_to_utf16(name, NULL);
3532 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003533 return;
3534
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003535 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003536 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003537 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003538
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003539 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003540 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003541 if (len > 0 || flen >= (int)STRLEN(q))
3542 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3543 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003544 }
3545 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003546 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003547}
3548
3549
3550/*
3551 * Insert user name in s[len].
3552 */
3553 int
3554mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003555 char_u *s,
3556 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003557{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003558 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003559 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003560
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003561 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003562 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003563 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003564
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003565 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003566 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003567 vim_strncpy(s, p, len - 1);
3568 vim_free(p);
3569 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003570 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003571 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003572 s[0] = NUL;
3573 return FAIL;
3574}
3575
3576
3577/*
3578 * Insert host name in s[len].
3579 */
3580 void
3581mch_get_host_name(
3582 char_u *s,
3583 int len)
3584{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003585 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003586 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003587
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003588 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003589 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003590 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003591
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003592 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003593 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003594 vim_strncpy(s, p, len - 1);
3595 vim_free(p);
3596 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003597 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003598 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003599}
3600
3601
3602/*
3603 * return process ID
3604 */
3605 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003606mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003607{
3608 return (long)GetCurrentProcessId();
3609}
3610
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003611/*
3612 * return TRUE if process "pid" is still running
3613 */
3614 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003615mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003616{
3617 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3618 DWORD status = 0;
3619 int ret = FALSE;
3620
3621 if (hProcess == NULL)
3622 return FALSE; // might not have access
3623 if (GetExitCodeProcess(hProcess, &status) )
3624 ret = status == STILL_ACTIVE;
3625 CloseHandle(hProcess);
3626 return ret;
3627}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003628
3629/*
3630 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3631 * Return OK for success, FAIL for failure.
3632 */
3633 int
3634mch_dirname(
3635 char_u *buf,
3636 int len)
3637{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003638 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003639
Bram Moolenaar071d4272004-06-13 20:20:40 +00003640 /*
3641 * Originally this was:
3642 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3643 * But the Win32s known bug list says that getcwd() doesn't work
3644 * so use the Win32 system call instead. <Negri>
3645 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003646 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003647 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003648 WCHAR wcbuf[_MAX_PATH + 1];
3649 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003650
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003651 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003652 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003653 p = utf16_to_enc(wcbuf, NULL);
3654 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003655 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003656 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003657 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003658 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003659 }
3660 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003661 if (p == NULL)
3662 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003663
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003664 if (p != NULL)
3665 {
3666 vim_strncpy(buf, p, len - 1);
3667 vim_free(p);
3668 return OK;
3669 }
3670 }
3671 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003672}
3673
3674/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003675 * Get file permissions for "name".
3676 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003677 */
3678 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003679mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003680{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003681 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003682 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003683
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003684 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003685 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003686}
3687
3688
3689/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003690 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003691 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003692 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003693 */
3694 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003695mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003696{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003697 long n;
3698 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003699
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003700 p = enc_to_utf16(name, NULL);
3701 if (p == NULL)
3702 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003703
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003704 n = _wchmod(p, perm);
3705 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003706 if (n == -1)
3707 return FAIL;
3708
3709 win32_set_archive(name);
3710
3711 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003712}
3713
3714/*
3715 * Set hidden flag for "name".
3716 */
3717 void
3718mch_hide(char_u *name)
3719{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003720 int attrs = win32_getattrs(name);
3721 if (attrs == -1)
3722 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003723
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003724 attrs |= FILE_ATTRIBUTE_HIDDEN;
3725 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003726}
3727
3728/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003729 * Return TRUE if file "name" exists and is hidden.
3730 */
3731 int
3732mch_ishidden(char_u *name)
3733{
3734 int f = win32_getattrs(name);
3735
3736 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003737 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003738
3739 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3740}
3741
3742/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003743 * return TRUE if "name" is a directory
3744 * return FALSE if "name" is not a directory or upon error
3745 */
3746 int
3747mch_isdir(char_u *name)
3748{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003749 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003750
3751 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003752 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003753
3754 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3755}
3756
3757/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003758 * return TRUE if "name" is a directory, NOT a symlink to a directory
3759 * return FALSE if "name" is not a directory
3760 * return FALSE for error
3761 */
3762 int
3763mch_isrealdir(char_u *name)
3764{
3765 return mch_isdir(name) && !mch_is_symbolic_link(name);
3766}
3767
3768/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003769 * Create directory "name".
3770 * Return 0 on success, -1 on error.
3771 */
3772 int
3773mch_mkdir(char_u *name)
3774{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003775 WCHAR *p;
3776 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003777
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003778 p = enc_to_utf16(name, NULL);
3779 if (p == NULL)
3780 return -1;
3781 retval = _wmkdir(p);
3782 vim_free(p);
3783 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003784}
3785
3786/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003787 * Delete directory "name".
3788 * Return 0 on success, -1 on error.
3789 */
3790 int
3791mch_rmdir(char_u *name)
3792{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003793 WCHAR *p;
3794 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003795
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003796 p = enc_to_utf16(name, NULL);
3797 if (p == NULL)
3798 return -1;
3799 retval = _wrmdir(p);
3800 vim_free(p);
3801 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003802}
3803
3804/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003805 * Return TRUE if file "fname" has more than one link.
3806 */
3807 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003808mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003809{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003810 BY_HANDLE_FILE_INFORMATION info;
3811
3812 return win32_fileinfo(fname, &info) == FILEINFO_OK
3813 && info.nNumberOfLinks > 1;
3814}
3815
3816/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003817 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003818 */
3819 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003820mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003821{
3822 HANDLE hFind;
3823 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003824 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003825 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003826 WIN32_FIND_DATAW findDataW;
3827
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003828 wn = enc_to_utf16(name, NULL);
3829 if (wn == NULL)
3830 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003831
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003832 hFind = FindFirstFileW(wn, &findDataW);
3833 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003834 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003835 {
3836 fileFlags = findDataW.dwFileAttributes;
3837 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003838 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003839 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003840
3841 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003842 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3843 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003844 res = TRUE;
3845
3846 return res;
3847}
3848
3849/*
3850 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3851 * link.
3852 */
3853 int
3854mch_is_linked(char_u *fname)
3855{
3856 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3857 return TRUE;
3858 return FALSE;
3859}
3860
3861/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003862 * Get the by-handle-file-information for "fname".
3863 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003864 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003865 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3866 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3867 */
3868 int
3869win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3870{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003871 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003872 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003873 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003874
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003875 wn = enc_to_utf16(fname, NULL);
3876 if (wn == NULL)
3877 return FILEINFO_ENC_FAIL;
3878
3879 hFile = CreateFileW(wn, // file name
3880 GENERIC_READ, // access mode
3881 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3882 NULL, // security descriptor
3883 OPEN_EXISTING, // creation disposition
3884 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3885 NULL); // handle to template file
3886 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003887
3888 if (hFile != INVALID_HANDLE_VALUE)
3889 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003890 if (GetFileInformationByHandle(hFile, info) != 0)
3891 res = FILEINFO_OK;
3892 else
3893 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003894 CloseHandle(hFile);
3895 }
3896
Bram Moolenaar03f48552006-02-28 23:52:23 +00003897 return res;
3898}
3899
3900/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003901 * get file attributes for `name'
3902 * -1 : error
3903 * else FILE_ATTRIBUTE_* defined in winnt.h
3904 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003905 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003906win32_getattrs(char_u *name)
3907{
3908 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003909 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003910
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003911 p = enc_to_utf16(name, NULL);
3912 if (p == NULL)
3913 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003914
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003915 attr = GetFileAttributesW(p);
3916 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003917
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003918 return attr;
3919}
3920
3921/*
3922 * set file attributes for `name' to `attrs'
3923 *
3924 * return -1 for failure, 0 otherwise
3925 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003926 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003927win32_setattrs(char_u *name, int attrs)
3928{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003929 int res;
3930 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003931
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003932 p = enc_to_utf16(name, NULL);
3933 if (p == NULL)
3934 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003935
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003936 res = SetFileAttributesW(p, attrs);
3937 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003938
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003939 return res ? 0 : -1;
3940}
3941
3942/*
3943 * Set archive flag for "name".
3944 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003945 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003946win32_set_archive(char_u *name)
3947{
3948 int attrs = win32_getattrs(name);
3949 if (attrs == -1)
3950 return -1;
3951
3952 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3953 return win32_setattrs(name, attrs);
3954}
3955
3956/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003957 * Return TRUE if file or directory "name" is writable (not readonly).
3958 * Strange semantics of Win32: a readonly directory is writable, but you can't
3959 * delete a file. Let's say this means it is writable.
3960 */
3961 int
3962mch_writable(char_u *name)
3963{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003964 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003965
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003966 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3967 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003968}
3969
Bram Moolenaar071d4272004-06-13 20:20:40 +00003970/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003971 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003972 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003973 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3974 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003975 */
3976 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01003977mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003978{
Bram Moolenaar95da1362020-05-30 18:37:55 +02003979 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003980}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003981
3982/*
3983 * Check what "name" is:
3984 * NODE_NORMAL: file or directory (or doesn't exist)
3985 * NODE_WRITABLE: writable device, socket, fifo, etc.
3986 * NODE_OTHER: non-writable things
3987 */
3988 int
3989mch_nodetype(char_u *name)
3990{
3991 HANDLE hFile;
3992 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003993 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003994
Bram Moolenaar0f873732019-12-05 20:28:46 +01003995 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3996 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3997 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00003998 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3999 return NODE_WRITABLE;
4000
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004001 wn = enc_to_utf16(name, NULL);
4002 if (wn == NULL)
4003 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004004
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004005 hFile = CreateFileW(wn, // file name
4006 GENERIC_WRITE, // access mode
4007 0, // share mode
4008 NULL, // security descriptor
4009 OPEN_EXISTING, // creation disposition
4010 0, // file attributes
4011 NULL); // handle to template file
4012 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004013 if (hFile == INVALID_HANDLE_VALUE)
4014 return NODE_NORMAL;
4015
4016 type = GetFileType(hFile);
4017 CloseHandle(hFile);
4018 if (type == FILE_TYPE_CHAR)
4019 return NODE_WRITABLE;
4020 if (type == FILE_TYPE_DISK)
4021 return NODE_NORMAL;
4022 return NODE_OTHER;
4023}
4024
4025#ifdef HAVE_ACL
4026struct my_acl
4027{
4028 PSECURITY_DESCRIPTOR pSecurityDescriptor;
4029 PSID pSidOwner;
4030 PSID pSidGroup;
4031 PACL pDacl;
4032 PACL pSacl;
4033};
4034#endif
4035
4036/*
4037 * Return a pointer to the ACL of file "fname" in allocated memory.
4038 * Return NULL if the ACL is not available for whatever reason.
4039 */
4040 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004041mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004042{
4043#ifndef HAVE_ACL
4044 return (vim_acl_T)NULL;
4045#else
4046 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02004047 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004048
Bram Moolenaarc799fe22019-05-28 23:08:19 +02004049 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004050 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004051 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004052 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02004053
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004054 wn = enc_to_utf16(fname, NULL);
4055 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004056 {
4057 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004058 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004059 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004060
4061 // Try to retrieve the entire security descriptor.
4062 err = GetNamedSecurityInfoW(
4063 wn, // Abstract filename
4064 SE_FILE_OBJECT, // File Object
4065 OWNER_SECURITY_INFORMATION |
4066 GROUP_SECURITY_INFORMATION |
4067 DACL_SECURITY_INFORMATION |
4068 SACL_SECURITY_INFORMATION,
4069 &p->pSidOwner, // Ownership information.
4070 &p->pSidGroup, // Group membership.
4071 &p->pDacl, // Discretionary information.
4072 &p->pSacl, // For auditing purposes.
4073 &p->pSecurityDescriptor);
4074 if (err == ERROR_ACCESS_DENIED ||
4075 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004076 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004077 // Retrieve only DACL.
4078 (void)GetNamedSecurityInfoW(
4079 wn,
4080 SE_FILE_OBJECT,
4081 DACL_SECURITY_INFORMATION,
4082 NULL,
4083 NULL,
4084 &p->pDacl,
4085 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004086 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004087 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004088 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004089 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004090 mch_free_acl((vim_acl_T)p);
4091 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004092 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004093 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004094 }
4095
4096 return (vim_acl_T)p;
4097#endif
4098}
4099
Bram Moolenaar27515922013-06-29 15:36:26 +02004100#ifdef HAVE_ACL
4101/*
4102 * Check if "acl" contains inherited ACE.
4103 */
4104 static BOOL
4105is_acl_inherited(PACL acl)
4106{
4107 DWORD i;
4108 ACL_SIZE_INFORMATION acl_info;
4109 PACCESS_ALLOWED_ACE ace;
4110
4111 acl_info.AceCount = 0;
4112 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
4113 for (i = 0; i < acl_info.AceCount; i++)
4114 {
4115 GetAce(acl, i, (LPVOID *)&ace);
4116 if (ace->Header.AceFlags & INHERITED_ACE)
4117 return TRUE;
4118 }
4119 return FALSE;
4120}
4121#endif
4122
Bram Moolenaar071d4272004-06-13 20:20:40 +00004123/*
4124 * Set the ACL of file "fname" to "acl" (unless it's NULL).
4125 * Errors are ignored.
4126 * This must only be called with "acl" equal to what mch_get_acl() returned.
4127 */
4128 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004129mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004130{
4131#ifdef HAVE_ACL
4132 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02004133 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004134 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004135
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004136 if (p == NULL)
4137 return;
4138
4139 wn = enc_to_utf16(fname, NULL);
4140 if (wn == NULL)
4141 return;
4142
4143 // Set security flags
4144 if (p->pSidOwner)
4145 sec_info |= OWNER_SECURITY_INFORMATION;
4146 if (p->pSidGroup)
4147 sec_info |= GROUP_SECURITY_INFORMATION;
4148 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02004149 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004150 sec_info |= DACL_SECURITY_INFORMATION;
4151 // Do not inherit its parent's DACL.
4152 // If the DACL is inherited, Cygwin permissions would be changed.
4153 if (!is_acl_inherited(p->pDacl))
4154 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02004155 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004156 if (p->pSacl)
4157 sec_info |= SACL_SECURITY_INFORMATION;
4158
4159 (void)SetNamedSecurityInfoW(
4160 wn, // Abstract filename
4161 SE_FILE_OBJECT, // File Object
4162 sec_info,
4163 p->pSidOwner, // Ownership information.
4164 p->pSidGroup, // Group membership.
4165 p->pDacl, // Discretionary information.
4166 p->pSacl // For auditing purposes.
4167 );
4168 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004169#endif
4170}
4171
4172 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004173mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004174{
4175#ifdef HAVE_ACL
4176 struct my_acl *p = (struct my_acl *)acl;
4177
4178 if (p != NULL)
4179 {
4180 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
4181 vim_free(p);
4182 }
4183#endif
4184}
4185
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004186#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004187
4188/*
4189 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
4190 */
4191 static BOOL WINAPI
4192handler_routine(
4193 DWORD dwCtrlType)
4194{
Bram Moolenaar589b1102017-08-12 16:39:05 +02004195 INPUT_RECORD ir;
4196 DWORD out;
4197
Bram Moolenaar071d4272004-06-13 20:20:40 +00004198 switch (dwCtrlType)
4199 {
4200 case CTRL_C_EVENT:
4201 if (ctrl_c_interrupts)
4202 g_fCtrlCPressed = TRUE;
4203 return TRUE;
4204
4205 case CTRL_BREAK_EVENT:
4206 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02004207 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004208 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02004209 ir.EventType = KEY_EVENT;
4210 ir.Event.KeyEvent.bKeyDown = TRUE;
4211 ir.Event.KeyEvent.wRepeatCount = 1;
4212 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
4213 ir.Event.KeyEvent.wVirtualScanCode = 0;
4214 ir.Event.KeyEvent.dwControlKeyState = 0;
4215 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
4216 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004217 return TRUE;
4218
Bram Moolenaar0f873732019-12-05 20:28:46 +01004219 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00004220 case CTRL_CLOSE_EVENT:
4221 case CTRL_LOGOFF_EVENT:
4222 case CTRL_SHUTDOWN_EVENT:
4223 windgoto((int)Rows - 1, 0);
4224 g_fForceExit = TRUE;
4225
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004226 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004227 (dwCtrlType == CTRL_CLOSE_EVENT
4228 ? _("close")
4229 : dwCtrlType == CTRL_LOGOFF_EVENT
4230 ? _("logoff")
4231 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004232# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00004233 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004234# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004235
Bram Moolenaar0f873732019-12-05 20:28:46 +01004236 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00004237
Bram Moolenaar0f873732019-12-05 20:28:46 +01004238 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00004239
4240 default:
4241 return FALSE;
4242 }
4243}
4244
4245
4246/*
4247 * set the tty in (raw) ? "raw" : "cooked" mode
4248 */
4249 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02004250mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004251{
4252 DWORD cmodein;
4253 DWORD cmodeout;
4254 BOOL bEnableHandler;
4255
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004256# ifdef VIMDLL
4257 if (gui.in_use)
4258 return;
4259# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004260 GetConsoleMode(g_hConIn, &cmodein);
4261 GetConsoleMode(g_hConOut, &cmodeout);
4262 if (tmode == TMODE_RAW)
4263 {
4264 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4265 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004266 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004267 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004268 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004269 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
4270 }
4271 else
4272 {
4273 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
4274 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004275 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004276# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01004277 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
4278 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004279 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004280# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004281 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004282# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004283 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004284 bEnableHandler = TRUE;
4285 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004286 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00004287 {
4288 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4289 ENABLE_ECHO_INPUT);
4290 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
4291 bEnableHandler = FALSE;
4292 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004293 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004294 SetConsoleMode(g_hConOut, cmodeout);
4295 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
4296
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004297# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004298 if (fdDump)
4299 {
4300 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
4301 tmode == TMODE_RAW ? "raw" :
4302 tmode == TMODE_COOK ? "cooked" : "normal",
4303 cmodein, cmodeout);
4304 fflush(fdDump);
4305 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004306# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004307}
4308
4309
4310/*
4311 * Get the size of the current window in `Rows' and `Columns'
4312 * Return OK when size could be determined, FAIL otherwise.
4313 */
4314 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004315mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004316{
4317 CONSOLE_SCREEN_BUFFER_INFO csbi;
4318
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004319# ifdef VIMDLL
4320 if (gui.in_use)
4321 return OK;
4322# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004323 if (!g_fTermcapMode && g_cbTermcap.IsValid)
4324 {
4325 /*
4326 * For some reason, we are trying to get the screen dimensions
4327 * even though we are not in termcap mode. The 'Rows' and 'Columns'
4328 * variables are really intended to mean the size of Vim screen
4329 * while in termcap mode.
4330 */
4331 Rows = g_cbTermcap.Info.dwSize.Y;
4332 Columns = g_cbTermcap.Info.dwSize.X;
4333 }
4334 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4335 {
4336 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4337 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4338 }
4339 else
4340 {
4341 Rows = 25;
4342 Columns = 80;
4343 }
4344 return OK;
4345}
4346
4347/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004348 * Resize console buffer to 'COORD'
4349 */
4350 static void
4351ResizeConBuf(
4352 HANDLE hConsole,
4353 COORD coordScreen)
4354{
4355 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4356 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004357# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004358 if (fdDump)
4359 {
4360 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4361 GetLastError());
4362 fflush(fdDump);
4363 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004364# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004365 }
4366}
4367
4368/*
4369 * Resize console window size to 'srWindowRect'
4370 */
4371 static void
4372ResizeWindow(
4373 HANDLE hConsole,
4374 SMALL_RECT srWindowRect)
4375{
4376 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4377 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004378# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004379 if (fdDump)
4380 {
4381 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4382 GetLastError());
4383 fflush(fdDump);
4384 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004385# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004386 }
4387}
4388
4389/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004390 * Set a console window to `xSize' * `ySize'
4391 */
4392 static void
4393ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004394 HANDLE hConsole,
4395 int xSize,
4396 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004397{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004398 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
4399 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004400 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004401 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004402 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004403
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004404# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004405 if (fdDump)
4406 {
4407 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4408 fflush(fdDump);
4409 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004410# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004411
Bram Moolenaar0f873732019-12-05 20:28:46 +01004412 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00004413 coordScreen = GetLargestConsoleWindowSize(hConsole);
4414
Bram Moolenaar0f873732019-12-05 20:28:46 +01004415 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00004416 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4417 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4418 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4419
4420 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4421 {
4422 int sx, sy;
4423
4424 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4425 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4426 if (sy < ySize || sx < xSize)
4427 {
4428 /*
4429 * Increasing number of lines/columns, do buffer first.
4430 * Use the maximal size in x and y direction.
4431 */
4432 if (sy < ySize)
4433 coordScreen.Y = ySize;
4434 else
4435 coordScreen.Y = sy;
4436 if (sx < xSize)
4437 coordScreen.X = xSize;
4438 else
4439 coordScreen.X = sx;
4440 SetConsoleScreenBufferSize(hConsole, coordScreen);
4441 }
4442 }
4443
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004444 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004445 coordScreen.X = xSize;
4446 coordScreen.Y = ySize;
4447
Bram Moolenaar2551c032018-08-23 22:38:31 +02004448 // In the new console call API, only the first time in reverse order
4449 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004450 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004451 ResizeWindow(hConsole, srWindowRect);
4452 ResizeConBuf(hConsole, coordScreen);
4453 }
4454 else
4455 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004456 // Workaround for a Windows 10 bug
4457 cursor.X = srWindowRect.Left;
4458 cursor.Y = srWindowRect.Top;
4459 SetConsoleCursorPosition(hConsole, cursor);
4460
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004461 ResizeConBuf(hConsole, coordScreen);
4462 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004463 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004464 }
4465}
4466
4467
4468/*
4469 * Set the console window to `Rows' * `Columns'
4470 */
4471 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004472mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004473{
4474 COORD coordScreen;
4475
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004476# ifdef VIMDLL
4477 if (gui.in_use)
4478 return;
4479# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004480 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004481 if (suppress_winsize != 0)
4482 {
4483 suppress_winsize = 2;
4484 return;
4485 }
4486
4487 if (term_console)
4488 {
4489 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4490
Bram Moolenaar0f873732019-12-05 20:28:46 +01004491 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004492 if (Rows > coordScreen.Y)
4493 Rows = coordScreen.Y;
4494 if (Columns > coordScreen.X)
4495 Columns = coordScreen.X;
4496
4497 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4498 }
4499}
4500
4501/*
4502 * Rows and/or Columns has changed.
4503 */
4504 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004505mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004506{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004507# ifdef VIMDLL
4508 if (gui.in_use)
4509 return;
4510# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004511 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4512}
4513
4514
4515/*
4516 * Called when started up, to set the winsize that was delayed.
4517 */
4518 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004519mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004520{
4521 if (suppress_winsize == 2)
4522 {
4523 suppress_winsize = 0;
4524 mch_set_shellsize();
4525 shell_resized();
4526 }
4527 suppress_winsize = 0;
4528}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004529#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004530
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004531 static BOOL
4532vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004533 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004534 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004535 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004536 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004537 PROCESS_INFORMATION *pi,
4538 LPVOID *env,
4539 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004540{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004541 BOOL ret = FALSE;
4542 WCHAR *wcmd, *wcwd = NULL;
4543
4544 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4545 if (wcmd == NULL)
4546 return FALSE;
4547 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004548 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004549 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4550 if (wcwd == NULL)
4551 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004552 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004553
4554 ret = CreateProcessW(
4555 NULL, // Executable name
4556 wcmd, // Command to execute
4557 NULL, // Process security attributes
4558 NULL, // Thread security attributes
4559 inherit_handles, // Inherit handles
4560 flags, // Creation flags
4561 env, // Environment
4562 wcwd, // Current directory
4563 (LPSTARTUPINFOW)si, // Startup information
4564 pi); // Process information
4565theend:
4566 vim_free(wcmd);
4567 vim_free(wcwd);
4568 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004569}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004570
4571
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004572 static HINSTANCE
4573vim_shell_execute(
4574 char *cmd,
4575 INT n_show_cmd)
4576{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004577 HINSTANCE ret;
4578 WCHAR *wcmd;
4579
4580 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4581 if (wcmd == NULL)
4582 return (HINSTANCE) 0;
4583
4584 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4585 vim_free(wcmd);
4586 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004587}
4588
4589
Bram Moolenaar4f974752019-02-17 17:44:42 +01004590#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004591
4592/*
4593 * Specialised version of system() for Win32 GUI mode.
4594 * This version proceeds as follows:
4595 * 1. Create a console window for use by the subprocess
4596 * 2. Run the subprocess (it gets the allocated console by default)
4597 * 3. Wait for the subprocess to terminate and get its exit code
4598 * 4. Prompt the user to press a key to close the console window
4599 */
4600 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004601mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004602{
4603 STARTUPINFO si;
4604 PROCESS_INFORMATION pi;
4605 DWORD ret = 0;
4606 HWND hwnd = GetFocus();
4607
4608 si.cb = sizeof(si);
4609 si.lpReserved = NULL;
4610 si.lpDesktop = NULL;
4611 si.lpTitle = NULL;
4612 si.dwFlags = STARTF_USESHOWWINDOW;
4613 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004614 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004615 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004616 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004617 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004618 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004619 else
4620 si.wShowWindow = SW_SHOWNORMAL;
4621 si.cbReserved2 = 0;
4622 si.lpReserved2 = NULL;
4623
Bram Moolenaar0f873732019-12-05 20:28:46 +01004624 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004625 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004626 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4627 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004628
Bram Moolenaar0f873732019-12-05 20:28:46 +01004629 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004630 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004631# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004632 int delay = 1;
4633
Bram Moolenaar0f873732019-12-05 20:28:46 +01004634 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004635 for (;;)
4636 {
4637 MSG msg;
4638
K.Takatab7057bd2022-01-21 11:37:07 +00004639 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004640 {
4641 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004642 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004643 delay = 1;
4644 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004645 }
4646 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4647 break;
4648
Bram Moolenaar0f873732019-12-05 20:28:46 +01004649 // We start waiting for a very short time and then increase it, so
4650 // that we respond quickly when the process is quick, and don't
4651 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004652 if (delay < 50)
4653 delay += 10;
4654 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004655# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004656 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004657# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004658
Bram Moolenaar0f873732019-12-05 20:28:46 +01004659 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004660 GetExitCodeProcess(pi.hProcess, &ret);
4661 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004662
Bram Moolenaar0f873732019-12-05 20:28:46 +01004663 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004664 CloseHandle(pi.hThread);
4665 CloseHandle(pi.hProcess);
4666
Bram Moolenaar0f873732019-12-05 20:28:46 +01004667 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004668 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4669
4670 return ret;
4671}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004672
4673/*
4674 * Thread launched by the gui to send the current buffer data to the
4675 * process. This way avoid to hang up vim totally if the children
4676 * process take a long time to process the lines.
4677 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004678 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004679sub_process_writer(LPVOID param)
4680{
4681 HANDLE g_hChildStd_IN_Wr = param;
4682 linenr_T lnum = curbuf->b_op_start.lnum;
4683 DWORD len = 0;
4684 DWORD l;
4685 char_u *lp = ml_get(lnum);
4686 char_u *s;
4687 int written = 0;
4688
4689 for (;;)
4690 {
4691 l = (DWORD)STRLEN(lp + written);
4692 if (l == 0)
4693 len = 0;
4694 else if (lp[written] == NL)
4695 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004696 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004697 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4698 }
4699 else
4700 {
4701 s = vim_strchr(lp + written, NL);
4702 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4703 s == NULL ? l : (DWORD)(s - (lp + written)),
4704 &len, NULL);
4705 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004706 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004707 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004708 // Finished a line, add a NL, unless this line should not have
4709 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004710 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004711 || (!curbuf->b_p_bin
4712 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004713 || (lnum != curbuf->b_no_eol_lnum
4714 && (lnum != curbuf->b_ml.ml_line_count
4715 || curbuf->b_p_eol)))
4716 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004717 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4718 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004719 }
4720
4721 ++lnum;
4722 if (lnum > curbuf->b_op_end.lnum)
4723 break;
4724
4725 lp = ml_get(lnum);
4726 written = 0;
4727 }
4728 else if (len > 0)
4729 written += len;
4730 }
4731
Bram Moolenaar0f873732019-12-05 20:28:46 +01004732 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004733 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004734 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004735}
4736
4737
Bram Moolenaar0f873732019-12-05 20:28:46 +01004738# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004739
4740/*
4741 * This function read from the children's stdout and write the
4742 * data on screen or in the buffer accordingly.
4743 */
4744 static void
4745dump_pipe(int options,
4746 HANDLE g_hChildStd_OUT_Rd,
4747 garray_T *ga,
4748 char_u buffer[],
4749 DWORD *buffer_off)
4750{
4751 DWORD availableBytes = 0;
4752 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004753 int ret;
4754 DWORD len;
4755 DWORD toRead;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004756
Bram Moolenaar0f873732019-12-05 20:28:46 +01004757 // we query the pipe to see if there is any data to read
4758 // to avoid to perform a blocking read
4759 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4760 NULL, // optional buffer
4761 0, // buffer size
4762 NULL, // number of read bytes
4763 &availableBytes, // available bytes total
4764 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004765
Bram Moolenaar0f873732019-12-05 20:28:46 +01004766 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004767 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004768 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01004769 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004770 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004771 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004772
Bram Moolenaar0f873732019-12-05 20:28:46 +01004773 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004774 if (len == 0)
4775 break;
4776
4777 availableBytes -= len;
4778
4779 if (options & SHELL_READ)
4780 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004781 // Do NUL -> NL translation, append NL separated
4782 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004783 for (i = 0; i < len; ++i)
4784 {
4785 if (buffer[i] == NL)
4786 append_ga_line(ga);
4787 else if (buffer[i] == NUL)
4788 ga_append(ga, NL);
4789 else
4790 ga_append(ga, buffer[i]);
4791 }
4792 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004793 else if (has_mbyte)
4794 {
4795 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004796 int c;
4797 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004798
4799 len += *buffer_off;
4800 buffer[len] = NUL;
4801
Bram Moolenaar0f873732019-12-05 20:28:46 +01004802 // Check if the last character in buffer[] is
4803 // incomplete, keep these bytes for the next
4804 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004805 for (p = buffer; p < buffer + len; p += l)
4806 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004807 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004808 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004809 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004810 else if (MB_BYTE2LEN(*p) != l)
4811 break;
4812 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004813 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004814 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004815 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004816 if (len >= 12)
4817 ++p;
4818 else
4819 {
4820 *buffer_off = len;
4821 return;
4822 }
4823 }
4824 c = *p;
4825 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004826 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004827 if (p < buffer + len)
4828 {
4829 *p = c;
4830 *buffer_off = (DWORD)((buffer + len) - p);
4831 mch_memmove(buffer, p, *buffer_off);
4832 return;
4833 }
4834 *buffer_off = 0;
4835 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004836 else
4837 {
4838 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004839 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004840 }
4841
4842 windgoto(msg_row, msg_col);
4843 cursor_on();
4844 out_flush();
4845 }
4846}
4847
4848/*
4849 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4850 * for communication and doesn't open any new window.
4851 */
4852 static int
4853mch_system_piped(char *cmd, int options)
4854{
4855 STARTUPINFO si;
4856 PROCESS_INFORMATION pi;
4857 DWORD ret = 0;
4858
4859 HANDLE g_hChildStd_IN_Rd = NULL;
4860 HANDLE g_hChildStd_IN_Wr = NULL;
4861 HANDLE g_hChildStd_OUT_Rd = NULL;
4862 HANDLE g_hChildStd_OUT_Wr = NULL;
4863
Bram Moolenaar0f873732019-12-05 20:28:46 +01004864 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004865 DWORD len;
4866
Bram Moolenaar0f873732019-12-05 20:28:46 +01004867 // buffer used to receive keys
4868 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4869 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004870
4871 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004872 int noread_cnt = 0;
4873 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004874 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004875 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004876 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004877
4878 SECURITY_ATTRIBUTES saAttr;
4879
Bram Moolenaar0f873732019-12-05 20:28:46 +01004880 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004881 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4882 saAttr.bInheritHandle = TRUE;
4883 saAttr.lpSecurityDescriptor = NULL;
4884
4885 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004886 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004887 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004888 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004889 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004890 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004891 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004892 {
4893 CloseHandle(g_hChildStd_IN_Rd);
4894 CloseHandle(g_hChildStd_IN_Wr);
4895 CloseHandle(g_hChildStd_OUT_Rd);
4896 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004897 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004898 }
4899
4900 si.cb = sizeof(si);
4901 si.lpReserved = NULL;
4902 si.lpDesktop = NULL;
4903 si.lpTitle = NULL;
4904 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4905
Bram Moolenaar0f873732019-12-05 20:28:46 +01004906 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004907 si.hStdError = g_hChildStd_OUT_Wr;
4908 si.hStdOutput = g_hChildStd_OUT_Wr;
4909 si.hStdInput = g_hChildStd_IN_Rd;
4910 si.wShowWindow = SW_HIDE;
4911 si.cbReserved2 = 0;
4912 si.lpReserved2 = NULL;
4913
4914 if (options & SHELL_READ)
4915 ga_init2(&ga, 1, BUFLEN);
4916
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004917 if (cmd != NULL)
4918 {
4919 p = (char *)vim_strsave((char_u *)cmd);
4920 if (p != NULL)
4921 unescape_shellxquote((char_u *)p, p_sxe);
4922 else
4923 p = cmd;
4924 }
4925
Bram Moolenaar0f873732019-12-05 20:28:46 +01004926 // Now, run the command.
4927 // About "Inherit handles" being TRUE: this command can be litigious,
4928 // handle inheritance was deactivated for pending temp file, but, if we
4929 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004930 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4931 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004932
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004933 if (p != cmd)
4934 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004935
Bram Moolenaar0f873732019-12-05 20:28:46 +01004936 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004937 CloseHandle(g_hChildStd_IN_Rd);
4938 CloseHandle(g_hChildStd_OUT_Wr);
4939
4940 if (options & SHELL_WRITE)
4941 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004942 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004943 _beginthreadex(NULL, // security attributes
4944 0, // default stack size
4945 sub_process_writer, // function to be executed
4946 g_hChildStd_IN_Wr, // parameter
4947 0, // creation flag, start immediately
4948 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004949 CloseHandle(thread);
4950 g_hChildStd_IN_Wr = NULL;
4951 }
4952
Bram Moolenaar0f873732019-12-05 20:28:46 +01004953 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004954 for (;;)
4955 {
4956 MSG msg;
4957
K.Takatab7057bd2022-01-21 11:37:07 +00004958 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004959 {
4960 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004961 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004962 }
4963
Bram Moolenaar0f873732019-12-05 20:28:46 +01004964 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004965 if ((options & (SHELL_READ|SHELL_WRITE))
4966# ifdef FEAT_GUI
4967 || gui.in_use
4968# endif
4969 )
4970 {
4971 len = 0;
4972 if (!(options & SHELL_EXPAND)
4973 && ((options &
4974 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4975 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4976# ifdef FEAT_GUI
4977 || gui.in_use
4978# endif
4979 )
4980 && (ta_len > 0 || noread_cnt > 4))
4981 {
4982 if (ta_len == 0)
4983 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004984 // Get extra characters when we don't have any. Reset the
4985 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004986 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004987 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4988 }
4989 if (ta_len > 0 || len > 0)
4990 {
4991 /*
4992 * For pipes: Check for CTRL-C: send interrupt signal to
4993 * child. Check for CTRL-D: EOF, close pipe to child.
4994 */
4995 if (len == 1 && cmd != NULL)
4996 {
4997 if (ta_buf[ta_len] == Ctrl_C)
4998 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004999 // Learn what exit code is expected, for
5000 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005001 TerminateProcess(pi.hProcess, 9);
5002 }
5003 if (ta_buf[ta_len] == Ctrl_D)
5004 {
5005 CloseHandle(g_hChildStd_IN_Wr);
5006 g_hChildStd_IN_Wr = NULL;
5007 }
5008 }
5009
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01005010 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005011
5012 /*
5013 * For pipes: echo the typed characters. For a pty this
5014 * does not seem to work.
5015 */
5016 for (i = ta_len; i < ta_len + len; ++i)
5017 {
5018 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
5019 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005020 else if (has_mbyte)
5021 {
5022 int l = (*mb_ptr2len)(ta_buf + i);
5023
5024 msg_outtrans_len(ta_buf + i, l);
5025 i += l - 1;
5026 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005027 else
5028 msg_outtrans_len(ta_buf + i, 1);
5029 }
5030 windgoto(msg_row, msg_col);
5031 out_flush();
5032
5033 ta_len += len;
5034
5035 /*
5036 * Write the characters to the child, unless EOF has been
5037 * typed for pipes. Write one character at a time, to
5038 * avoid losing too much typeahead. When writing buffer
5039 * lines, drop the typed characters (only check for
5040 * CTRL-C).
5041 */
5042 if (options & SHELL_WRITE)
5043 ta_len = 0;
5044 else if (g_hChildStd_IN_Wr != NULL)
5045 {
5046 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
5047 1, &len, NULL);
5048 // if we are typing in, we want to keep things reactive
5049 delay = 1;
5050 if (len > 0)
5051 {
5052 ta_len -= len;
5053 mch_memmove(ta_buf, ta_buf + len, ta_len);
5054 }
5055 }
5056 }
5057 }
5058 }
5059
5060 if (ta_len)
5061 ui_inchar_undo(ta_buf, ta_len);
5062
5063 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
5064 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005065 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005066 break;
5067 }
5068
5069 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005070 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005071
Bram Moolenaar0f873732019-12-05 20:28:46 +01005072 // We start waiting for a very short time and then increase it, so
5073 // that we respond quickly when the process is quick, and don't
5074 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005075 if (delay < 50)
5076 delay += 10;
5077 }
5078
Bram Moolenaar0f873732019-12-05 20:28:46 +01005079 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005080 CloseHandle(g_hChildStd_OUT_Rd);
5081 if (g_hChildStd_IN_Wr != NULL)
5082 CloseHandle(g_hChildStd_IN_Wr);
5083
5084 WaitForSingleObject(pi.hProcess, INFINITE);
5085
Bram Moolenaar0f873732019-12-05 20:28:46 +01005086 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005087 GetExitCodeProcess(pi.hProcess, &ret);
5088
5089 if (options & SHELL_READ)
5090 {
5091 if (ga.ga_len > 0)
5092 {
5093 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01005094 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005095 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
5096 }
5097 else
5098 curbuf->b_no_eol_lnum = 0;
5099 ga_clear(&ga);
5100 }
5101
Bram Moolenaar0f873732019-12-05 20:28:46 +01005102 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005103 CloseHandle(pi.hThread);
5104 CloseHandle(pi.hProcess);
5105
5106 return ret;
5107}
5108
5109 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005110mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005111{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005112 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005113 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005114 return mch_system_piped(cmd, options);
5115 else
5116 return mch_system_classic(cmd, options);
5117}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005118#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005119
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005120#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005121 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02005122mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005123{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005124 int ret;
5125 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005126 char_u *buf;
5127 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005128
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005129 // If the command starts and ends with double quotes, enclose the command
5130 // in parentheses.
5131 len = STRLEN(cmd);
5132 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
5133 {
5134 len += 3;
5135 buf = alloc(len);
5136 if (buf == NULL)
5137 return -1;
5138 vim_snprintf((char *)buf, len, "(%s)", cmd);
5139 wcmd = enc_to_utf16(buf, NULL);
5140 free(buf);
5141 }
5142 else
5143 wcmd = enc_to_utf16((char_u *)cmd, NULL);
5144
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005145 if (wcmd == NULL)
5146 return -1;
5147
5148 ret = _wsystem(wcmd);
5149 vim_free(wcmd);
5150 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005151}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005152
5153#endif
5154
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005155 static int
5156mch_system(char *cmd, int options)
5157{
5158#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005159 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005160 return mch_system_g(cmd, options);
5161 else
5162 return mch_system_c(cmd, options);
5163#elif defined(FEAT_GUI_MSWIN)
5164 return mch_system_g(cmd, options);
5165#else
5166 return mch_system_c(cmd, options);
5167#endif
5168}
5169
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005170#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
5171/*
5172 * Use a terminal window to run a shell command in.
5173 */
5174 static int
5175mch_call_shell_terminal(
5176 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005177 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005178{
5179 jobopt_T opt;
5180 char_u *newcmd = NULL;
5181 typval_T argvar[2];
5182 long_u cmdlen;
5183 int retval = -1;
5184 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005185 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005186 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005187 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005188
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005189 if (cmd == NULL)
5190 cmdlen = STRLEN(p_sh) + 1;
5191 else
5192 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005193 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005194 if (newcmd == NULL)
5195 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005196 if (cmd == NULL)
5197 {
5198 STRCPY(newcmd, p_sh);
5199 ch_log(NULL, "starting terminal to run a shell");
5200 }
5201 else
5202 {
5203 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
5204 ch_log(NULL, "starting terminal for system command '%s'", cmd);
5205 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005206
5207 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005208
5209 argvar[0].v_type = VAR_STRING;
5210 argvar[0].vval.v_string = newcmd;
5211 argvar[1].v_type = VAR_UNKNOWN;
5212 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005213 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01005214 {
5215 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005216 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01005217 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005218
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005219 job = term_getjob(buf->b_term);
5220 ++job->jv_refcount;
5221
Bram Moolenaar0f873732019-12-05 20:28:46 +01005222 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005223 aucmd_prepbuf(&aco, buf);
Bram Moolenaare76062c2022-11-28 18:51:43 +00005224 if (curbuf == buf)
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005225 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005226 // Only do this when a window was found for "buf".
5227 clear_oparg(&oa);
5228 while (term_use_loop())
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005229 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005230 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
5231 {
5232 // If terminal_loop() returns OK we got a key that is handled
5233 // in Normal model. We don't do redrawing anyway.
5234 if (terminal_loop(TRUE) == OK)
5235 normal_cmd(&oa, TRUE);
5236 }
5237 else
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005238 normal_cmd(&oa, TRUE);
5239 }
Bram Moolenaare76062c2022-11-28 18:51:43 +00005240 retval = job->jv_exitval;
5241 ch_log(NULL, "system command finished");
5242
5243 job_unref(job);
5244
5245 // restore curwin/curbuf and a few other things
5246 aucmd_restbuf(&aco);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005247 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005248
5249 wait_return(TRUE);
5250 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
5251
5252 vim_free(newcmd);
5253 return retval;
5254}
5255#endif
5256
Bram Moolenaar071d4272004-06-13 20:20:40 +00005257/*
5258 * Either execute a command by calling the shell or start a new shell
5259 */
5260 int
5261mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005262 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005263 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00005264{
5265 int x = 0;
5266 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005267 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02005268
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00005269#ifdef FEAT_EVAL
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01005270 ch_log(NULL, "executing shell command: %s", cmd);
5271#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01005272 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02005273 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005274 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005275 if (cmd == NULL)
5276 wcscat(szShellTitle, L" :sh");
5277 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005278 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005279 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005280
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005281 if (wn != NULL)
5282 {
5283 wcscat(szShellTitle, L" - !");
5284 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02005285 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005286 wcscat(szShellTitle, wn);
5287 SetConsoleTitleW(szShellTitle);
5288 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005289 }
5290 }
5291 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005292
5293 out_flush();
5294
5295#ifdef MCH_WRITE_DUMP
5296 if (fdDump)
5297 {
5298 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
5299 fflush(fdDump);
5300 }
5301#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005302#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005303 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005304 if (
5305# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005306 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005307# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005308 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005309 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
5310 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005311 char_u *cmdbase = cmd;
5312
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02005313 if (cmdbase != NULL)
5314 // Skip a leading quote and (.
5315 while (*cmdbase == '"' || *cmdbase == '(')
5316 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005317
5318 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01005319 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
5320 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005321 {
5322 // Use a terminal window to run the command in.
5323 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005324 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005325 return x;
5326 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005327 }
5328#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005329
5330 /*
5331 * Catch all deadly signals while running the external command, because a
5332 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5333 */
5334 signal(SIGINT, SIG_IGN);
5335#if defined(__GNUC__) && !defined(__MINGW32__)
5336 signal(SIGKILL, SIG_IGN);
5337#else
5338 signal(SIGBREAK, SIG_IGN);
5339#endif
5340 signal(SIGILL, SIG_IGN);
5341 signal(SIGFPE, SIG_IGN);
5342 signal(SIGSEGV, SIG_IGN);
5343 signal(SIGTERM, SIG_IGN);
5344 signal(SIGABRT, SIG_IGN);
5345
5346 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005347 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00005348
5349 if (cmd == NULL)
5350 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005351 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005352 }
5353 else
5354 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005355 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005356 char_u *newcmd = NULL;
5357 char_u *cmdbase = cmd;
5358 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005359
Bram Moolenaar0f873732019-12-05 20:28:46 +01005360 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005361 if (*cmdbase == '"' )
5362 ++cmdbase;
5363 if (*cmdbase == '(')
5364 ++cmdbase;
5365
Bram Moolenaar1c465442017-03-12 20:10:05 +01005366 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005367 {
5368 STARTUPINFO si;
5369 PROCESS_INFORMATION pi;
5370 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005371 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005372 char_u *p;
5373
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005374 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005375 si.cb = sizeof(si);
5376 si.lpReserved = NULL;
5377 si.lpDesktop = NULL;
5378 si.lpTitle = NULL;
5379 si.dwFlags = 0;
5380 si.cbReserved2 = 0;
5381 si.lpReserved2 = NULL;
5382
5383 cmdbase = skipwhite(cmdbase + 5);
5384 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005385 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005386 {
5387 cmdbase = skipwhite(cmdbase + 4);
5388 si.dwFlags = STARTF_USESHOWWINDOW;
5389 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005390 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005391 }
5392 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005393 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005394 {
5395 cmdbase = skipwhite(cmdbase + 2);
5396 flags = CREATE_NO_WINDOW;
5397 si.dwFlags = STARTF_USESTDHANDLES;
5398 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005399 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005400 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005401 NULL, // Security att.
5402 OPEN_EXISTING, // Open flags
5403 FILE_ATTRIBUTE_NORMAL, // File att.
5404 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005405 si.hStdOutput = si.hStdInput;
5406 si.hStdError = si.hStdInput;
5407 }
5408
Bram Moolenaar0f873732019-12-05 20:28:46 +01005409 // Remove a trailing ", ) and )" if they have a match
5410 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005411 if (cmdbase > cmd)
5412 {
5413 p = cmdbase + STRLEN(cmdbase);
5414 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5415 *--p = NUL;
5416 if (p > cmdbase && p[-1] == ')'
5417 && (*cmd =='(' || cmd[1] == '('))
5418 *--p = NUL;
5419 }
5420
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005421 newcmd = cmdbase;
5422 unescape_shellxquote(cmdbase, p_sxe);
5423
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005424 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005425 * If creating new console, arguments are passed to the
5426 * 'cmd.exe' as-is. If it's not, arguments are not treated
5427 * correctly for current 'cmd.exe'. So unescape characters in
5428 * shellxescape except '|' for avoiding to be treated as
5429 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005430 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005431 if (flags != CREATE_NEW_CONSOLE)
5432 {
5433 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005434 char_u *cmd_shell = mch_getenv("COMSPEC");
5435
5436 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005437 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005438
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005439 subcmd = vim_strsave_escaped_ext(cmdbase,
5440 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005441 if (subcmd != NULL)
5442 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005443 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005444 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005445 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005446 if (newcmd != NULL)
5447 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005448 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005449 else
5450 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005451 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005452 }
5453 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005454
5455 /*
5456 * Now, start the command as a process, so that it doesn't
5457 * inherit our handles which causes unpleasant dangling swap
5458 * files if we exit before the spawned process
5459 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005460 if (vim_create_process((char *)newcmd, FALSE, flags,
5461 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005462 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005463 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5464 > (HINSTANCE)32)
5465 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005466 else
5467 {
5468 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005469#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005470# ifdef VIMDLL
5471 if (gui.in_use)
5472# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005473 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005474#endif
5475 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005476
5477 if (newcmd != cmdbase)
5478 vim_free(newcmd);
5479
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005480 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005481 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005482 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005483 CloseHandle(si.hStdInput);
5484 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005485 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005486 CloseHandle(pi.hThread);
5487 CloseHandle(pi.hProcess);
5488 }
5489 else
5490 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005491 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005492#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005493 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005494 (!s_dont_use_vimrun && p_stmp ?
5495 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5496 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005497#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005498 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005499
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005500 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005501 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005502 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005503#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005504 if (
5505# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005506 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005507# endif
5508 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005509 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005510 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5511 "External commands will not pause after completion.\n"
5512 "See :help win32-vimrun for more information.");
5513 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005514 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5515 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005516
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005517 if (wmsg != NULL && wtitle != NULL)
5518 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5519 vim_free(wmsg);
5520 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005521 need_vimrun_warning = FALSE;
5522 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005523 if (
5524# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005525 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005526# endif
5527 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005528 // Use vimrun to execute the command. It opens a console
5529 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005530 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005531 vimrun_path,
5532 (msg_silent != 0 || (options & SHELL_DOOUT))
5533 ? "-s " : "",
5534 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005535 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005536# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005537 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005538# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005539 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005540 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005541 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5542 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005543 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005544#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005545 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005546 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005547 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005548 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005549 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005550 }
5551 }
5552
5553 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005554 {
5555 // The shell may have messed with the mode, always set it.
5556 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005557 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005558 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005559
Bram Moolenaar0f873732019-12-05 20:28:46 +01005560 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005561 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005562#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005563 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005564 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005565#endif
5566 )
5567 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005568 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005569 msg_putchar('\n');
5570 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005571 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005572
5573 signal(SIGINT, SIG_DFL);
5574#if defined(__GNUC__) && !defined(__MINGW32__)
5575 signal(SIGKILL, SIG_DFL);
5576#else
5577 signal(SIGBREAK, SIG_DFL);
5578#endif
5579 signal(SIGILL, SIG_DFL);
5580 signal(SIGFPE, SIG_DFL);
5581 signal(SIGSEGV, SIG_DFL);
5582 signal(SIGTERM, SIG_DFL);
5583 signal(SIGABRT, SIG_DFL);
5584
5585 return x;
5586}
5587
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005588#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005589 static HANDLE
5590job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005591 char_u *fname,
5592 DWORD dwDesiredAccess,
5593 DWORD dwShareMode,
5594 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5595 DWORD dwCreationDisposition,
5596 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005597{
5598 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005599 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005600
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005601 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005602 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005603 return INVALID_HANDLE_VALUE;
5604
5605 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5606 lpSecurityAttributes, dwCreationDisposition,
5607 dwFlagsAndAttributes, NULL);
5608 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005609 return h;
5610}
5611
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005612/*
5613 * Turn the dictionary "env" into a NUL separated list that can be used as the
5614 * environment argument of vim_create_process().
5615 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005616 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005617win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005618{
5619 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005620 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005621 LPVOID base = GetEnvironmentStringsW();
5622
Bram Moolenaar0f873732019-12-05 20:28:46 +01005623 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005624 if (ga_grow(gap, 1) == FAIL)
5625 return;
5626
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005627 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005628 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005629 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005630 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005631 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005632 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005633 typval_T *item = &dict_lookup(hi)->di_tv;
5634 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005635 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005636 --todo;
5637 if (wkey != NULL && wval != NULL)
5638 {
5639 size_t n;
5640 size_t lkey = wcslen(wkey);
5641 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005642
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005643 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5644 continue;
5645 for (n = 0; n < lkey; n++)
5646 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5647 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5648 for (n = 0; n < lval; n++)
5649 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5650 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5651 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005652 vim_free(wkey);
5653 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005654 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005655 }
5656 }
5657
Bram Moolenaar355757a2020-02-10 22:06:32 +01005658 if (base)
5659 {
5660 WCHAR *p = (WCHAR*) base;
5661
5662 // for last \0
5663 if (ga_grow(gap, 1) == FAIL)
5664 return;
5665
5666 while (*p != 0 || *(p + 1) != 0)
5667 {
5668 if (ga_grow(gap, 1) == OK)
5669 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5670 p++;
5671 }
5672 FreeEnvironmentStrings(base);
5673 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5674 }
5675
Bram Moolenaar493359e2018-06-12 20:25:52 +02005676# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005677 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005678# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005679 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005680 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005681# endif
5682# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005683 char_u *version = get_vim_var_str(VV_VERSION);
5684 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005685# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005686 // size of "VIM_SERVERNAME=" and value,
5687 // plus "VIM_TERMINAL=" and value,
5688 // plus two terminating NULs
5689 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005690# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005691 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005692# endif
5693# ifdef FEAT_TERMINAL
5694 + 13 + version_len + 2
5695# endif
5696 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005697
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005698 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005699 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005700# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005701 for (n = 0; n < 15; n++)
5702 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5703 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005704 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005705 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5706 (WCHAR)servername[n];
5707 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005708# endif
5709# ifdef FEAT_TERMINAL
5710 if (is_terminal)
5711 {
5712 for (n = 0; n < 13; n++)
5713 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5714 (WCHAR)"VIM_TERMINAL="[n];
5715 for (n = 0; n < version_len; n++)
5716 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5717 (WCHAR)version[n];
5718 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5719 }
5720# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005721 }
5722 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005723# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005724}
5725
Bram Moolenaarb091f302019-01-19 14:37:00 +01005726/*
5727 * Create a pair of pipes.
5728 * Return TRUE for success, FALSE for failure.
5729 */
5730 static BOOL
5731create_pipe_pair(HANDLE handles[2])
5732{
5733 static LONG s;
5734 char name[64];
5735 SECURITY_ATTRIBUTES sa;
5736
5737 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5738 GetCurrentProcessId(),
5739 InterlockedIncrement(&s));
5740
5741 // Create named pipe. Max size of named pipe is 65535.
5742 handles[1] = CreateNamedPipe(
5743 name,
5744 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5745 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005746 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005747
5748 if (handles[1] == INVALID_HANDLE_VALUE)
5749 return FALSE;
5750
5751 sa.nLength = sizeof(sa);
5752 sa.bInheritHandle = TRUE;
5753 sa.lpSecurityDescriptor = NULL;
5754
5755 handles[0] = CreateFile(name,
5756 FILE_GENERIC_READ,
5757 FILE_SHARE_READ, &sa,
5758 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5759
5760 if (handles[0] == INVALID_HANDLE_VALUE)
5761 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005762 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005763 return FALSE;
5764 }
5765
5766 return TRUE;
5767}
5768
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005769 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005770mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005771{
5772 STARTUPINFO si;
5773 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005774 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005775 SECURITY_ATTRIBUTES saAttr;
5776 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005777 HANDLE ifd[2];
5778 HANDLE ofd[2];
5779 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005780 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005781
5782 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5783 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5784 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5785 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5786 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5787 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5788 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5789
5790 if (use_out_for_err && use_null_for_out)
5791 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005792
5793 ifd[0] = INVALID_HANDLE_VALUE;
5794 ifd[1] = INVALID_HANDLE_VALUE;
5795 ofd[0] = INVALID_HANDLE_VALUE;
5796 ofd[1] = INVALID_HANDLE_VALUE;
5797 efd[0] = INVALID_HANDLE_VALUE;
5798 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005799 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005800
Bram Moolenaar14207f42016-10-27 21:13:10 +02005801 jo = CreateJobObject(NULL, NULL);
5802 if (jo == NULL)
5803 {
5804 job->jv_status = JOB_FAILED;
5805 goto failed;
5806 }
5807
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005808 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005809 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005810
Bram Moolenaar76467df2016-02-12 19:30:26 +01005811 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005812 ZeroMemory(&si, sizeof(si));
5813 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005814 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005815 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005816
Bram Moolenaard8070362016-02-15 21:56:54 +01005817 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5818 saAttr.bInheritHandle = TRUE;
5819 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005820
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005821 if (use_file_for_in)
5822 {
5823 char_u *fname = options->jo_io_name[PART_IN];
5824
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005825 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5826 FILE_SHARE_READ | FILE_SHARE_WRITE,
5827 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5828 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005829 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005830 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005831 goto failed;
5832 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005833 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005834 else if (!use_null_for_in
5835 && (!create_pipe_pair(ifd)
5836 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005837 goto failed;
5838
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005839 if (use_file_for_out)
5840 {
5841 char_u *fname = options->jo_io_name[PART_OUT];
5842
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005843 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5844 FILE_SHARE_READ | FILE_SHARE_WRITE,
5845 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5846 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005847 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005848 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005849 goto failed;
5850 }
5851 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005852 else if (!use_null_for_out &&
5853 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005854 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005855 goto failed;
5856
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005857 if (use_file_for_err)
5858 {
5859 char_u *fname = options->jo_io_name[PART_ERR];
5860
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005861 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5862 FILE_SHARE_READ | FILE_SHARE_WRITE,
5863 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5864 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005865 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005866 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005867 goto failed;
5868 }
5869 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005870 else if (!use_out_for_err && !use_null_for_err &&
5871 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005872 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005873 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005874
Bram Moolenaard8070362016-02-15 21:56:54 +01005875 si.dwFlags |= STARTF_USESTDHANDLES;
5876 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005877 si.hStdOutput = ofd[1];
5878 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5879
5880 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5881 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005882 if (options->jo_set & JO_CHANNEL)
5883 {
5884 channel = options->jo_channel;
5885 if (channel != NULL)
5886 ++channel->ch_refcount;
5887 }
5888 else
5889 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005890 if (channel == NULL)
5891 goto failed;
5892 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005893
5894 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005895 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005896 CREATE_DEFAULT_ERROR_MODE |
5897 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005898 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005899 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005900 &si, &pi,
5901 ga.ga_data,
5902 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005903 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005904 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005905 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005906 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005907 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005908
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005909 ga_clear(&ga);
5910
Bram Moolenaar14207f42016-10-27 21:13:10 +02005911 if (!AssignProcessToJobObject(jo, pi.hProcess))
5912 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005913 // if failing, switch the way to terminate
5914 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005915 CloseHandle(jo);
5916 jo = NULL;
5917 }
5918 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005919 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005920 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005921 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005922 job->jv_status = JOB_STARTED;
5923
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005924 CloseHandle(ifd[0]);
5925 CloseHandle(ofd[1]);
5926 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005927 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005928
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005929 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005930 if (channel != NULL)
5931 {
5932 channel_set_pipes(channel,
5933 use_file_for_in || use_null_for_in
5934 ? INVALID_FD : (sock_T)ifd[1],
5935 use_file_for_out || use_null_for_out
5936 ? INVALID_FD : (sock_T)ofd[0],
5937 use_out_for_err || use_file_for_err || use_null_for_err
5938 ? INVALID_FD : (sock_T)efd[0]);
5939 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005940 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005941 return;
5942
5943failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005944 CloseHandle(ifd[0]);
5945 CloseHandle(ofd[0]);
5946 CloseHandle(efd[0]);
5947 CloseHandle(ifd[1]);
5948 CloseHandle(ofd[1]);
5949 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005950 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005951 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005952}
5953
5954 char *
5955mch_job_status(job_T *job)
5956{
5957 DWORD dwExitCode = 0;
5958
Bram Moolenaar76467df2016-02-12 19:30:26 +01005959 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5960 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005961 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005962 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005963 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005964 {
5965 ch_log(job->jv_channel, "Job ended");
5966 job->jv_status = JOB_ENDED;
5967 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005968 return "dead";
5969 }
5970 return "run";
5971}
5972
Bram Moolenaar97792de2016-10-15 18:36:49 +02005973 job_T *
5974mch_detect_ended_job(job_T *job_list)
5975{
5976 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5977 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5978 job_T *job = job_list;
5979
5980 while (job != NULL)
5981 {
5982 DWORD n;
5983 DWORD result;
5984
5985 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5986 && job != NULL; job = job->jv_next)
5987 {
5988 if (job->jv_status == JOB_STARTED)
5989 {
5990 jobHandles[n] = job->jv_proc_info.hProcess;
5991 jobArray[n] = job;
5992 ++n;
5993 }
5994 }
5995 if (n == 0)
5996 continue;
5997 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5998 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5999 {
6000 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
6001
6002 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
6003 return wait_job;
6004 }
6005 }
6006 return NULL;
6007}
6008
Bram Moolenaarfb630902016-10-29 14:55:00 +02006009 static BOOL
6010terminate_all(HANDLE process, int code)
6011{
6012 PROCESSENTRY32 pe;
6013 HANDLE h = INVALID_HANDLE_VALUE;
6014 DWORD pid = GetProcessId(process);
6015
6016 if (pid != 0)
6017 {
6018 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
6019 if (h != INVALID_HANDLE_VALUE)
6020 {
6021 pe.dwSize = sizeof(PROCESSENTRY32);
6022 if (!Process32First(h, &pe))
6023 goto theend;
6024
6025 do
6026 {
6027 if (pe.th32ParentProcessID == pid)
6028 {
6029 HANDLE ph = OpenProcess(
6030 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
6031 if (ph != NULL)
6032 {
6033 terminate_all(ph, code);
6034 CloseHandle(ph);
6035 }
6036 }
6037 } while (Process32Next(h, &pe));
6038
6039 CloseHandle(h);
6040 }
6041 }
6042
6043theend:
6044 return TerminateProcess(process, code);
6045}
6046
6047/*
6048 * Send a (deadly) signal to "job".
6049 * Return FAIL if it didn't work.
6050 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006051 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02006052mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006053{
Bram Moolenaar923d9262016-02-25 20:56:01 +01006054 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006055
Bram Moolenaar923d9262016-02-25 20:56:01 +01006056 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01006057 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006058 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02006059 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006060 {
6061 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
6062 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00006063 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006064 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01006065 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006066 }
6067
6068 if (!AttachConsole(job->jv_proc_info.dwProcessId))
6069 return FAIL;
6070 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01006071 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
6072 job->jv_proc_info.dwProcessId)
6073 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006074 FreeConsole();
6075 return ret;
6076}
6077
6078/*
6079 * Clear the data related to "job".
6080 */
6081 void
6082mch_clear_job(job_T *job)
6083{
6084 if (job->jv_status != JOB_FAILED)
6085 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02006086 if (job->jv_job_object != NULL)
6087 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01006088 CloseHandle(job->jv_proc_info.hProcess);
6089 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006090}
6091#endif
6092
Bram Moolenaar071d4272004-06-13 20:20:40 +00006093
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006094#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006095
6096/*
6097 * Start termcap mode
6098 */
6099 static void
6100termcap_mode_start(void)
6101{
6102 DWORD cmodein;
6103
6104 if (g_fTermcapMode)
6105 return;
6106
Christopher Plewright1140b512022-11-12 18:46:05 +00006107 // VTP uses alternate screen buffer.
6108 // Switch to a new alternate screen buffer.
6109 if (win11_or_later && p_rs && vtp_working)
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006110 vtp_printf("\033[?1049h");
6111
Bram Moolenaar071d4272004-06-13 20:20:40 +00006112 SaveConsoleBuffer(&g_cbNonTermcap);
6113
6114 if (g_cbTermcap.IsValid)
6115 {
6116 /*
6117 * We've been in termcap mode before. Restore certain screen
6118 * characteristics, including the buffer size and the window
6119 * size. Since we will be redrawing the screen, we don't need
6120 * to restore the actual contents of the buffer.
6121 */
6122 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006123 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006124 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
6125 Rows = g_cbTermcap.Info.dwSize.Y;
6126 Columns = g_cbTermcap.Info.dwSize.X;
6127 }
6128 else
6129 {
6130 /*
6131 * This is our first time entering termcap mode. Clear the console
6132 * screen buffer, and resize the buffer to match the current window
6133 * size. We will use this as the size of our editing environment.
6134 */
6135 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006136 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006137 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
6138 }
6139
Bram Moolenaar071d4272004-06-13 20:20:40 +00006140 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006141
6142 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006143 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006144 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006145 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006146 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
6147 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006148 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006149 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006150 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006151 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6152 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006153 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006154 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006155
6156 redraw_later_clear();
6157 g_fTermcapMode = TRUE;
6158}
6159
6160
6161/*
6162 * End termcap mode
6163 */
6164 static void
6165termcap_mode_end(void)
6166{
6167 DWORD cmodein;
6168 ConsoleBuffer *cb;
6169 COORD coord;
6170 DWORD dwDummy;
6171
6172 if (!g_fTermcapMode)
6173 return;
6174
6175 SaveConsoleBuffer(&g_cbTermcap);
6176
6177 GetConsoleMode(g_hConIn, &cmodein);
6178 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006179 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6180 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006181
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006182# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01006183 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006184# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006185 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006186# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006187 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01006188 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006189
Christopher Plewright1140b512022-11-12 18:46:05 +00006190 // VTP uses alternate screen buffer.
6191 // Switch back to main screen buffer.
6192 if (exiting && win11_or_later && p_rs && vtp_working)
6193 vtp_printf("\033[?1049l");
6194
6195 if (!USE_WT && (p_rs || exiting))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006196 {
6197 /*
6198 * Clear anything that happens to be on the current line.
6199 */
6200 coord.X = 0;
6201 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
Christopher Plewright1140b512022-11-12 18:46:05 +00006202 if (!vtp_working)
6203 FillConsoleOutputCharacter(g_hConOut, ' ',
6204 cb->Info.dwSize.X, coord, &dwDummy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006205 /*
6206 * The following is just for aesthetics. If we are exiting without
6207 * restoring the screen, then we want to have a prompt string
6208 * appear at the bottom line. However, the command interpreter
6209 * seems to always advance the cursor one line before displaying
6210 * the prompt string, which causes the screen to scroll. To
6211 * counter this, move the cursor up one line before exiting.
6212 */
6213 if (exiting && !p_rs)
6214 coord.Y--;
6215 /*
6216 * Position the cursor at the leftmost column of the desired row.
6217 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006218 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006219 }
Christopher Plewright1140b512022-11-12 18:46:05 +00006220 SetConsoleCursorInfo(g_hConOut, &g_cci);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006221 g_fTermcapMode = FALSE;
6222}
Christopher Plewright38804d62022-11-09 23:55:52 +00006223#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006224
6225
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006226#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006227 void
6228mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01006229 char_u *s UNUSED,
6230 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006231{
Bram Moolenaar0f873732019-12-05 20:28:46 +01006232 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00006233}
6234
6235#else
6236
6237/*
6238 * clear `n' chars, starting from `coord'
6239 */
6240 static void
6241clear_chars(
6242 COORD coord,
6243 DWORD n)
6244{
Christopher Plewright38804d62022-11-09 23:55:52 +00006245 if (!vtp_working)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006246 {
6247 DWORD dwDummy;
6248
6249 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
6250 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
6251 &dwDummy);
6252 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006253 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02006254 {
6255 set_console_color_rgb();
6256 gotoxy(coord.X + 1, coord.Y + 1);
6257 vtp_printf("\033[%dX", n);
6258 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006259}
6260
6261
6262/*
6263 * Clear the screen
6264 */
6265 static void
6266clear_screen(void)
6267{
6268 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006269
Christopher Plewright38804d62022-11-09 23:55:52 +00006270 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006271 clear_chars(g_coord, Rows * Columns);
6272 else
6273 {
6274 set_console_color_rgb();
6275 gotoxy(1, 1);
6276 vtp_printf("\033[2J");
6277 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006278}
6279
6280
6281/*
6282 * Clear to end of display
6283 */
6284 static void
6285clear_to_end_of_display(void)
6286{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006287 COORD save = g_coord;
6288
Christopher Plewright38804d62022-11-09 23:55:52 +00006289 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006290 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006291 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006292 else
6293 {
6294 set_console_color_rgb();
6295 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6296 vtp_printf("\033[0J");
6297
6298 gotoxy(save.X + 1, save.Y + 1);
6299 g_coord = save;
6300 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006301}
6302
6303
6304/*
6305 * Clear to end of line
6306 */
6307 static void
6308clear_to_end_of_line(void)
6309{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006310 COORD save = g_coord;
6311
Christopher Plewright38804d62022-11-09 23:55:52 +00006312 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006313 clear_chars(g_coord, Columns - g_coord.X);
6314 else
6315 {
6316 set_console_color_rgb();
6317 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6318 vtp_printf("\033[0K");
6319
6320 gotoxy(save.X + 1, save.Y + 1);
6321 g_coord = save;
6322 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006323}
6324
6325
6326/*
6327 * Scroll the scroll region up by `cLines' lines
6328 */
6329 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006330scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006331{
6332 COORD oldcoord = g_coord;
6333
6334 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6335 delete_lines(cLines);
6336
6337 g_coord = oldcoord;
6338}
6339
6340
6341/*
6342 * Set the scroll region
6343 */
6344 static void
6345set_scroll_region(
6346 unsigned left,
6347 unsigned top,
6348 unsigned right,
6349 unsigned bottom)
6350{
6351 if (left >= right
6352 || top >= bottom
6353 || right > (unsigned) Columns - 1
6354 || bottom > (unsigned) Rows - 1)
6355 return;
6356
6357 g_srScrollRegion.Left = left;
6358 g_srScrollRegion.Top = top;
6359 g_srScrollRegion.Right = right;
6360 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006361}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006362
Bram Moolenaar6982f422019-02-16 16:48:01 +01006363 static void
6364set_scroll_region_tb(
6365 unsigned top,
6366 unsigned bottom)
6367{
6368 if (top >= bottom || bottom > (unsigned)Rows - 1)
6369 return;
6370
6371 g_srScrollRegion.Top = top;
6372 g_srScrollRegion.Bottom = bottom;
6373}
6374
6375 static void
6376set_scroll_region_lr(
6377 unsigned left,
6378 unsigned right)
6379{
6380 if (left >= right || right > (unsigned)Columns - 1)
6381 return;
6382
6383 g_srScrollRegion.Left = left;
6384 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006385}
6386
6387
6388/*
6389 * Insert `cLines' lines at the current cursor position
6390 */
6391 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006392insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006393{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006394 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006395 COORD dest;
6396 CHAR_INFO fill;
6397
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006398 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6399
Bram Moolenaar6982f422019-02-16 16:48:01 +01006400 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006401 dest.Y = g_coord.Y + cLines;
6402
Bram Moolenaar6982f422019-02-16 16:48:01 +01006403 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006404 source.Top = g_coord.Y;
6405 source.Right = g_srScrollRegion.Right;
6406 source.Bottom = g_srScrollRegion.Bottom - cLines;
6407
Bram Moolenaar6982f422019-02-16 16:48:01 +01006408 clip.Left = g_srScrollRegion.Left;
6409 clip.Top = g_coord.Y;
6410 clip.Right = g_srScrollRegion.Right;
6411 clip.Bottom = g_srScrollRegion.Bottom;
6412
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006413 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006414 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006415# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006416 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006417# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006418 ))
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006419 fill.Attributes = g_attrCurrent;
6420 else
6421 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006422
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006423 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006424
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006425 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6426
Bram Moolenaar6982f422019-02-16 16:48:01 +01006427 // Here we have to deal with a win32 console flake: If the scroll
6428 // region looks like abc and we scroll c to a and fill with d we get
6429 // cbd... if we scroll block c one line at a time to a, we get cdd...
6430 // vim expects cdd consistently... So we have to deal with that
6431 // here... (this also occurs scrolling the same way in the other
6432 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006433
6434 if (source.Bottom < dest.Y)
6435 {
6436 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006437 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006438
Bram Moolenaar6982f422019-02-16 16:48:01 +01006439 coord.X = source.Left;
6440 for (i = clip.Top; i < dest.Y; ++i)
6441 {
6442 coord.Y = i;
6443 clear_chars(coord, source.Right - source.Left + 1);
6444 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006445 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006446
Christopher Plewright38804d62022-11-09 23:55:52 +00006447 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006448 {
6449 COORD coord;
6450 int i;
6451
6452 coord.X = source.Left;
6453 for (i = source.Top; i < dest.Y; ++i)
6454 {
6455 coord.Y = i;
6456 clear_chars(coord, source.Right - source.Left + 1);
6457 }
6458 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006459}
6460
6461
6462/*
6463 * Delete `cLines' lines at the current cursor position
6464 */
6465 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006466delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006467{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006468 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006469 COORD dest;
6470 CHAR_INFO fill;
6471 int nb;
6472
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006473 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6474
Bram Moolenaar6982f422019-02-16 16:48:01 +01006475 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006476 dest.Y = g_coord.Y;
6477
Bram Moolenaar6982f422019-02-16 16:48:01 +01006478 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006479 source.Top = g_coord.Y + cLines;
6480 source.Right = g_srScrollRegion.Right;
6481 source.Bottom = g_srScrollRegion.Bottom;
6482
Bram Moolenaar6982f422019-02-16 16:48:01 +01006483 clip.Left = g_srScrollRegion.Left;
6484 clip.Top = g_coord.Y;
6485 clip.Right = g_srScrollRegion.Right;
6486 clip.Bottom = g_srScrollRegion.Bottom;
6487
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006488 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006489 if (!vtp_working)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006490 fill.Attributes = g_attrCurrent;
6491 else
6492 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006493
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006494 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006495
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006496 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6497
Bram Moolenaar6982f422019-02-16 16:48:01 +01006498 // Here we have to deal with a win32 console flake; See insert_lines()
6499 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006500
6501 nb = dest.Y + (source.Bottom - source.Top) + 1;
6502
6503 if (nb < source.Top)
6504 {
6505 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006506 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006507
Bram Moolenaar6982f422019-02-16 16:48:01 +01006508 coord.X = source.Left;
6509 for (i = nb; i < clip.Bottom; ++i)
6510 {
6511 coord.Y = i;
6512 clear_chars(coord, source.Right - source.Left + 1);
6513 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006514 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006515
Christopher Plewright38804d62022-11-09 23:55:52 +00006516 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006517 {
6518 COORD coord;
6519 int i;
6520
6521 coord.X = source.Left;
6522 for (i = nb; i <= source.Bottom; ++i)
6523 {
6524 coord.Y = i;
6525 clear_chars(coord, source.Right - source.Left + 1);
6526 }
6527 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006528}
6529
6530
6531/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006532 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006533 */
6534 static void
6535gotoxy(
6536 unsigned x,
6537 unsigned y)
6538{
6539 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6540 return;
6541
Christopher Plewright38804d62022-11-09 23:55:52 +00006542 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006543# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006544 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006545# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006546 ))
Bram Moolenaar2313b612019-09-27 14:14:32 +02006547 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006548 // There are reports of double-width characters not displayed
6549 // correctly. This workaround should fix it, similar to how it's done
6550 // for VTP.
6551 g_coord.X = 0;
6552 SetConsoleCursorPosition(g_hConOut, g_coord);
6553
Bram Moolenaar2313b612019-09-27 14:14:32 +02006554 // external cursor coords are 1-based; internal are 0-based
6555 g_coord.X = x - 1;
6556 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006557 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006558 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006559 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006560 {
6561 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006562 // destruction. Insider build bug. Always enabled because it's cheap
6563 // and avoids mistakes with recognizing the build.
6564 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006565
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006566 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006567
6568 g_coord.X = x - 1;
6569 g_coord.Y = y - 1;
6570 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006571}
6572
6573
6574/*
6575 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006576 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006577 */
6578 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006579textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006580{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006581 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006582
6583 SetConsoleTextAttribute(g_hConOut, wAttr);
6584}
6585
6586
6587 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006588textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006589{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006590 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006591
Christopher Plewright38804d62022-11-09 23:55:52 +00006592 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006593 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6594 else
6595 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006596}
6597
6598
6599 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006600textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006601{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006602 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006603
Christopher Plewright38804d62022-11-09 23:55:52 +00006604 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006605 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6606 else
6607 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006608}
6609
6610
6611/*
6612 * restore the default text attribute (whatever we started with)
6613 */
6614 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006615normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006616{
Christopher Plewright38804d62022-11-09 23:55:52 +00006617 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006618 textattr(g_attrDefault);
6619 else
6620 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006621}
6622
6623
6624static WORD g_attrPreStandout = 0;
6625
6626/*
6627 * Make the text standout, by brightening it
6628 */
6629 static void
6630standout(void)
6631{
6632 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006633
Bram Moolenaar071d4272004-06-13 20:20:40 +00006634 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6635}
6636
6637
6638/*
6639 * Turn off standout mode
6640 */
6641 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006642standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006643{
6644 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006645 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006646
6647 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006648}
6649
6650
6651/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006652 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006653 */
6654 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006655mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006656{
6657 char_u *p;
6658 int n;
6659
6660 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6661 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006662 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006663# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006664 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006665# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006666 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006667 {
6668 p = T_ME + 2;
6669 n = getdigits(&p);
6670 if (*p == 'm' && n > 0)
6671 {
6672 cterm_normal_fg_color = (n & 0xf) + 1;
6673 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6674 }
6675 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006676# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006677 cterm_normal_fg_gui_color = INVALCOLOR;
6678 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006679# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006680}
6681
6682
6683/*
6684 * visual bell: flash the screen
6685 */
6686 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006687visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006688{
6689 COORD coordOrigin = {0, 0};
6690 WORD attrFlash = ~g_attrCurrent & 0xff;
6691
6692 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006693 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006694
6695 if (oldattrs == NULL)
6696 return;
6697 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6698 coordOrigin, &dwDummy);
6699 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6700 coordOrigin, &dwDummy);
6701
Bram Moolenaar0f873732019-12-05 20:28:46 +01006702 Sleep(15); // wait for 15 msec
Christopher Plewright38804d62022-11-09 23:55:52 +00006703 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006704 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006705 coordOrigin, &dwDummy);
6706 vim_free(oldattrs);
6707}
6708
6709
6710/*
6711 * Make the cursor visible or invisible
6712 */
6713 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006714cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006715{
6716 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006717
Christopher Plewright38804d62022-11-09 23:55:52 +00006718 if (vtp_working)
Bram Moolenaar2695de62020-04-17 21:13:01 +02006719 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6720
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006721# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006722 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006723# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006724}
6725
6726
6727/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006728 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006729 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006730 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006731 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006732write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006733 char_u *pchBuf,
6734 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006735{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006736 COORD coord = g_coord;
6737 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006738 DWORD n, cchwritten;
6739 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006740 static WCHAR *unicodebuf = NULL;
6741 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006742 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006743 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006744 static WCHAR *utf8spbuf = NULL;
6745 static int utf8splength;
6746 static DWORD utf8spcells;
6747 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006748
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006749 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006750 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006751 utf8usingbuf = &unicodebuf;
6752 do
6753 {
6754 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6755 unicodebuf, unibuflen);
6756 if (length && length <= unibuflen)
6757 break;
6758 vim_free(unicodebuf);
6759 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6760 unibuflen = unibuflen ? 0 : length;
6761 } while(1);
6762 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006763 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006764 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6765 {
6766 if (utf8usingbuf != &utf8spbuf)
6767 {
6768 if (utf8spbuf == NULL)
6769 {
6770 cells = mb_string2cells((char_u *)" ", 1);
6771 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6772 utf8spbuf = LALLOC_MULT(WCHAR, length);
6773 if (utf8spbuf != NULL)
6774 {
6775 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6776 utf8usingbuf = &utf8spbuf;
6777 utf8splength = length;
6778 utf8spcells = cells;
6779 }
6780 }
6781 else
6782 {
6783 utf8usingbuf = &utf8spbuf;
6784 length = utf8splength;
6785 cells = utf8spcells;
6786 }
6787 }
6788 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006789
Christopher Plewright38804d62022-11-09 23:55:52 +00006790 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006791# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006792 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006793# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006794 ))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006795 {
6796 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6797 coord, &written);
6798 // When writing fails or didn't write a single character, pretend one
6799 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006800 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006801 coord, &cchwritten) == 0
6802 || cchwritten == 0 || cchwritten == (DWORD)-1)
6803 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006804 }
6805 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006806 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006807 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006808 NULL) == 0 || cchwritten == 0)
6809 cchwritten = 1;
6810 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006811
K.Takata135e1522022-01-29 15:27:58 +00006812 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006813 {
6814 written = cbToWrite;
6815 g_coord.X += (SHORT)cells;
6816 }
6817 else
6818 {
6819 char_u *p = pchBuf;
6820 for (n = 0; n < cchwritten; n++)
6821 MB_CPTR_ADV(p);
6822 written = p - pchBuf;
6823 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006824 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006825
6826 while (g_coord.X > g_srScrollRegion.Right)
6827 {
6828 g_coord.X -= (SHORT) Columns;
6829 if (g_coord.Y < g_srScrollRegion.Bottom)
6830 g_coord.Y++;
6831 }
6832
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006833 // Cursor under VTP is always in the correct position, no need to reset.
Christopher Plewright38804d62022-11-09 23:55:52 +00006834 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006835# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006836 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006837# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006838 ))
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006839 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006840
6841 return written;
6842}
6843
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006844 static char_u *
6845get_seq(
6846 int *args,
6847 int *count,
6848 char_u *head)
6849{
6850 int argc;
6851 char_u *p;
6852
6853 if (head == NULL || *head != '\033')
6854 return NULL;
6855
6856 argc = 0;
6857 p = head;
6858 ++p;
6859 do
6860 {
6861 ++p;
6862 args[argc] = getdigits(&p);
6863 argc += (argc < 15) ? 1 : 0;
6864 } while (*p == ';');
6865 *count = argc;
6866
6867 return p;
6868}
6869
6870 static char_u *
6871get_sgr(
6872 int *args,
6873 int *count,
6874 char_u *head)
6875{
6876 char_u *p = get_seq(args, count, head);
6877
6878 return (p && *p == 'm') ? ++p : NULL;
6879}
6880
6881/*
6882 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6883 */
6884 static char_u *
6885sgrn2(
6886 char_u *head,
6887 int n)
6888{
6889 int argc;
6890 int args[16];
6891 char_u *p = get_sgr(args, &argc, head);
6892
6893 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6894}
6895
6896/*
6897 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6898 */
6899 static char_u *
6900sgrnc(
6901 char_u *head,
6902 int n)
6903{
6904 int argc;
6905 int args[16];
6906 char_u *p = get_sgr(args, &argc, head);
6907
6908 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6909 ? p : NULL;
6910}
6911
6912 static char_u *
6913skipblank(char_u *q)
6914{
6915 char_u *p = q;
6916
6917 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6918 ++p;
6919 return p;
6920}
6921
6922/*
6923 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6924 * NULL.
6925 */
6926 static char_u *
6927sgrn2c(
6928 char_u *head,
6929 int n)
6930{
6931 char_u *p = sgrn2(head, n);
6932
6933 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6934}
6935
6936/*
6937 * If there is only a newline between the sequence immediately following it,
6938 * a pointer to the character following the newline is returned.
6939 * Otherwise NULL.
6940 */
6941 static char_u *
6942sgrn2cn(
6943 char_u *head,
6944 int n)
6945{
6946 char_u *p = sgrn2(head, n);
6947
6948 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6949}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006950
6951/*
6952 * mch_write(): write the output buffer to the screen, translating ESC
6953 * sequences into calls to console output routines.
6954 */
6955 void
6956mch_write(
6957 char_u *s,
6958 int len)
6959{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006960 char_u *end = s + len;
6961
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006962# ifdef VIMDLL
6963 if (gui.in_use)
6964 return;
6965# endif
6966
Bram Moolenaar071d4272004-06-13 20:20:40 +00006967 if (!term_console)
6968 {
6969 write(1, s, (unsigned)len);
6970 return;
6971 }
6972
Bram Moolenaar0f873732019-12-05 20:28:46 +01006973 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00006974 while (len--)
6975 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006976 int prefix = -1;
6977 char_u ch;
6978
6979 // While processing a sequence, on rare occasions it seems that another
6980 // sequence may be inserted asynchronously.
6981 if (len < 0)
6982 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006983 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006984 return;
6985 }
6986
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006987 while (s + ++prefix < end)
6988 {
6989 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006990 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6991 && ch != '\a' && ch != '\033'))
6992 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006993 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006994
6995 if (p_wd)
6996 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006997 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006998 if (prefix != 0)
6999 prefix = 1;
7000 }
7001
7002 if (prefix != 0)
7003 {
7004 DWORD nWritten;
7005
7006 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007007# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007008 if (fdDump)
7009 {
7010 fputc('>', fdDump);
7011 fwrite(s, sizeof(char_u), nWritten, fdDump);
7012 fputs("<\n", fdDump);
7013 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007014# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007015 len -= (nWritten - 1);
7016 s += nWritten;
7017 }
7018 else if (s[0] == '\n')
7019 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007020 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00007021 if (g_coord.Y == g_srScrollRegion.Bottom)
7022 {
7023 scroll(1);
7024 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
7025 }
7026 else
7027 {
7028 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
7029 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007030# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007031 if (fdDump)
7032 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007033# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007034 s++;
7035 }
7036 else if (s[0] == '\r')
7037 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007038 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00007039 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007040# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007041 if (fdDump)
7042 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007043# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007044 s++;
7045 }
7046 else if (s[0] == '\b')
7047 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007048 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00007049 if (g_coord.X > g_srScrollRegion.Left)
7050 g_coord.X--;
7051 else if (g_coord.Y > g_srScrollRegion.Top)
7052 {
7053 g_coord.X = g_srScrollRegion.Right;
7054 g_coord.Y--;
7055 }
7056 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007057# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007058 if (fdDump)
7059 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007060# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007061 s++;
7062 }
7063 else if (s[0] == '\a')
7064 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007065 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00007066 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007067# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007068 if (fdDump)
7069 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007070# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007071 s++;
7072 }
7073 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
7074 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007075# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007076 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007077# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007078 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007079 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007080 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007081
7082 switch (s[2])
7083 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007084 case '0': case '1': case '2': case '3': case '4':
7085 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007086 if (*(p = get_seq(args, &argc, s)) != 'm')
7087 goto notsgr;
7088
7089 p = s;
7090
7091 // Handling frequent optional sequences. Output to the screen
7092 // takes too long, so do not output as much as possible.
7093
7094 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
7095 // resetFG,FG,BG are omitted.
7096 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007097 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007098 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
7099 len = len + 1 - (int)(p - s);
7100 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007101 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007102 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007103
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007104 // If FG,BG,BG,FG of SGR are connected, the first FG can be
7105 // omitted.
7106 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
7107 p = sp;
7108
7109 // If FG,BG,FG,BG of SGR are connected, the first FG can be
7110 // omitted.
7111 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
7112 p = sp;
7113
7114 // If BG,BG of SGR are connected, the first BG can be omitted.
7115 if (sgrn2((sp = sgrn2(p, 48)), 48))
7116 p = sp;
7117
7118 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007119 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007120 if (sgrn2((sp = sgrnc(p, 39)), 38))
7121 p = sp;
7122
7123 p = get_seq(args, &argc, p);
7124
7125notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007126 arg1 = args[0];
7127 arg2 = args[1];
7128 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007129 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007130 if (argc == 1 && args[0] == 0)
7131 normvideo();
7132 else if (argc == 1)
7133 {
Christopher Plewright38804d62022-11-09 23:55:52 +00007134 if (vtp_working
7135# ifdef FEAT_TERMGUICOLORS
7136 && (p_tgc || t_colors >= 256)
7137# endif
7138 )
7139 textcolor((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007140 else
Christopher Plewright38804d62022-11-09 23:55:52 +00007141 textattr((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007142 }
Christopher Plewright38804d62022-11-09 23:55:52 +00007143 else if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007144 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007145 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007146 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007147 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007148 gotoxy(arg2, arg1);
7149 }
7150 else if (argc == 2 && *p == 'r')
7151 {
7152 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
7153 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01007154 else if (argc == 2 && *p == 'R')
7155 {
7156 set_scroll_region_tb(arg1, arg2);
7157 }
7158 else if (argc == 2 && *p == 'V')
7159 {
7160 set_scroll_region_lr(arg1, arg2);
7161 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007162 else if (argc == 1 && *p == 'A')
7163 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007164 gotoxy(g_coord.X + 1,
7165 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
7166 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007167 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007168 {
7169 textbackground((WORD) arg1);
7170 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007171 else if (argc == 1 && *p == 'C')
7172 {
7173 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
7174 g_coord.Y + 1);
7175 }
7176 else if (argc == 1 && *p == 'f')
7177 {
7178 textcolor((WORD) arg1);
7179 }
7180 else if (argc == 1 && *p == 'H')
7181 {
7182 gotoxy(1, arg1);
7183 }
7184 else if (argc == 1 && *p == 'L')
7185 {
7186 insert_lines(arg1);
7187 }
7188 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007189 {
7190 delete_lines(arg1);
7191 }
7192
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007193 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007194 s = p + 1;
7195 break;
7196
Bram Moolenaar071d4272004-06-13 20:20:40 +00007197 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007198 gotoxy(g_coord.X + 1,
7199 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
7200 goto got3;
7201
7202 case 'B':
7203 visual_bell();
7204 goto got3;
7205
7206 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007207 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
7208 g_coord.Y + 1);
7209 goto got3;
7210
7211 case 'E':
7212 termcap_mode_end();
7213 goto got3;
7214
7215 case 'F':
7216 standout();
7217 goto got3;
7218
7219 case 'f':
7220 standend();
7221 goto got3;
7222
7223 case 'H':
7224 gotoxy(1, 1);
7225 goto got3;
7226
7227 case 'j':
7228 clear_to_end_of_display();
7229 goto got3;
7230
7231 case 'J':
7232 clear_screen();
7233 goto got3;
7234
7235 case 'K':
7236 clear_to_end_of_line();
7237 goto got3;
7238
7239 case 'L':
7240 insert_lines(1);
7241 goto got3;
7242
7243 case 'M':
7244 delete_lines(1);
7245 goto got3;
7246
7247 case 'S':
7248 termcap_mode_start();
7249 goto got3;
7250
7251 case 'V':
7252 cursor_visible(TRUE);
7253 goto got3;
7254
7255 case 'v':
7256 cursor_visible(FALSE);
7257 goto got3;
7258
7259 got3:
7260 s += 3;
7261 len -= 2;
7262 }
7263
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007264# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007265 if (fdDump)
7266 {
7267 fputs("ESC | ", fdDump);
7268 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
7269 fputc('\n', fdDump);
7270 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007271# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007272 }
K.Takatadf5320c2022-09-01 13:20:16 +01007273 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
7274 {
7275 int l = 2;
7276
7277 if (isdigit(s[l]))
7278 l++;
7279 if (s[l] == ' ' && s[l + 1] == 'q')
7280 {
7281 // DECSCUSR (cursor style) sequences
Christopher Plewright38804d62022-11-09 23:55:52 +00007282 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01007283 vtp_printf("%.*s", l + 2, s); // Pass through
7284 s += l + 2;
7285 len -= l + 1;
7286 }
7287 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007288 else
7289 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007290 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00007291 DWORD nWritten;
7292
7293 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007294# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007295 if (fdDump)
7296 {
7297 fputc('>', fdDump);
7298 fwrite(s, sizeof(char_u), nWritten, fdDump);
7299 fputs("<\n", fdDump);
7300 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007301# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007302
7303 len -= (nWritten - 1);
7304 s += nWritten;
7305 }
7306 }
7307
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007308# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007309 if (fdDump)
7310 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007311# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007312}
7313
Bram Moolenaar0f873732019-12-05 20:28:46 +01007314#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00007315
7316
7317/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01007318 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007319 */
7320 void
7321mch_delay(
7322 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02007323 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007324{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007325#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007326 Sleep((int)msec); // never wait for input
7327#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007328# ifdef VIMDLL
7329 if (gui.in_use)
7330 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007331 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007332 return;
7333 }
7334# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02007335 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007336# ifdef FEAT_MZSCHEME
7337 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
7338 {
7339 int towait = p_mzq;
7340
Bram Moolenaar0f873732019-12-05 20:28:46 +01007341 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007342 while (msec > 0)
7343 {
7344 mzvim_check_threads();
7345 if (msec < towait)
7346 towait = msec;
7347 Sleep(towait);
7348 msec -= towait;
7349 }
7350 }
7351 else
7352# endif
7353 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007354 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007355 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007356#endif
7357}
7358
7359
7360/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01007361 * This version of remove is not scared by a readonly (backup) file.
7362 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007363 * Return 0 for success, -1 for failure.
7364 */
7365 int
7366mch_remove(char_u *name)
7367{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007368 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007369 int n;
7370
Bram Moolenaar203258c2016-01-17 22:15:16 +01007371 /*
7372 * On Windows, deleting a directory's symbolic link is done by
7373 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
7374 */
7375 if (mch_isdir(name) && mch_is_symbolic_link(name))
7376 return mch_rmdir(name);
7377
Bram Moolenaar12b559e2013-06-12 22:41:37 +02007378 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
7379
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007380 wn = enc_to_utf16(name, NULL);
7381 if (wn == NULL)
7382 return -1;
7383
7384 n = DeleteFileW(wn) ? 0 : -1;
7385 vim_free(wn);
7386 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007387}
7388
7389
7390/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007391 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007392 */
7393 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007394mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007395{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007396#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7397# ifdef VIMDLL
7398 if (!gui.in_use)
7399# endif
7400 if (g_fCtrlCPressed || g_fCBrkPressed)
7401 {
7402 ctrl_break_was_pressed = g_fCBrkPressed;
7403 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7404 got_int = TRUE;
7405 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007406#endif
7407}
7408
Bram Moolenaar0f873732019-12-05 20:28:46 +01007409// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007410#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007411
7412/*
7413 * How much main memory in KiB that can be used by VIM.
7414 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007415 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007416mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007417{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007418 MEMORYSTATUSEX ms;
7419
Bram Moolenaar0f873732019-12-05 20:28:46 +01007420 // Need to use GlobalMemoryStatusEx() when there is more memory than
7421 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007422 ms.dwLength = sizeof(MEMORYSTATUSEX);
7423 GlobalMemoryStatusEx(&ms);
7424 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007425 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007426 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007427 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007428 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007429 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007430 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007431 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007432 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007433 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007434 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007435 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007436}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007437
Bram Moolenaar071d4272004-06-13 20:20:40 +00007438/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007439 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00007440 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
7441 * file whose short file name is "FOO.BAR" (its long file name will
7442 * be correct: "foo.bar~"). Because a file can be accessed by
7443 * either its SFN or its LFN, "foo.bar" has effectively been
7444 * renamed to "foo.bar", which is not at all what was wanted. This
7445 * seems to happen only when renaming files with three-character
7446 * extensions by appending a suffix that does not include ".".
7447 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
7448 *
7449 * There is another problem, which isn't really a bug but isn't right either:
7450 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
7451 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
7452 * service pack 6. Doesn't seem to happen on Windows 98.
7453 *
7454 * Like rename(), returns 0 upon success, non-zero upon failure.
7455 * Should probably set errno appropriately when errors occur.
7456 */
7457 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007458mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007459{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007460 WCHAR *p;
7461 int i;
7462 WCHAR szTempFile[_MAX_PATH + 1];
7463 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007464 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007465
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007466 // No need to play tricks unless the file name contains a "~" as the
7467 // seventh character.
7468 p = wold;
7469 for (i = 0; wold[i] != NUL; ++i)
7470 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
7471 && wold[i + 1] != 0)
7472 p = wold + i + 1;
7473 if ((int)(wold + i - p) < 8 || p[6] != '~')
7474 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007475
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007476 // Get base path of new file name. Undocumented feature: If pszNewFile is
7477 // a directory, no error is returned and pszFilePart will be NULL.
7478 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007479 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007480 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007481
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007482 // Get (and create) a unique temporary file name in directory of new file
7483 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007484 return -2;
7485
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007486 // blow the temp file away
7487 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007488 return -3;
7489
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007490 // rename old file to the temp file
7491 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007492 return -4;
7493
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007494 // now create an empty file called pszOldFile; this prevents the operating
7495 // system using pszOldFile as an alias (SFN) if we're renaming within the
7496 // same directory. For example, we're editing a file called
7497 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7498 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7499 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7500 // cause all sorts of problems later in buf_write(). So, we create an
7501 // empty file called filena~1.txt and the system will have to find some
7502 // other SFN for filena~1.txt~, such as filena~2.txt
7503 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007504 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7505 return -5;
7506 if (!CloseHandle(hf))
7507 return -6;
7508
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007509 // rename the temp file to the new file
7510 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007511 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007512 // Renaming failed. Rename the file back to its old name, so that it
7513 // looks like nothing happened.
7514 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007515 return -7;
7516 }
7517
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007518 // Seems to be left around on Novell filesystems
7519 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007520
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007521 // finally, remove the empty old file
7522 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007523 return -8;
7524
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007525 return 0;
7526}
7527
7528
7529/*
7530 * Converts the filenames to UTF-16, then call mch_wrename().
7531 * Like rename(), returns 0 upon success, non-zero upon failure.
7532 */
7533 int
7534mch_rename(
7535 const char *pszOldFile,
7536 const char *pszNewFile)
7537{
7538 WCHAR *wold = NULL;
7539 WCHAR *wnew = NULL;
7540 int retval = -1;
7541
7542 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7543 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7544 if (wold != NULL && wnew != NULL)
7545 retval = mch_wrename(wold, wnew);
7546 vim_free(wold);
7547 vim_free(wnew);
7548 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007549}
7550
7551/*
7552 * Get the default shell for the current hardware platform
7553 */
7554 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007555default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007556{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007557 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007558}
7559
7560/*
7561 * mch_access() extends access() to do more detailed check on network drives.
7562 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7563 */
7564 int
7565mch_access(char *n, int p)
7566{
7567 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007568 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007569 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007570
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007571 wn = enc_to_utf16((char_u *)n, NULL);
7572 if (wn == NULL)
7573 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007574
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007575 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007576 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007577 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007578
7579 if (p & R_OK)
7580 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007581 // Read check is performed by seeing if we can do a find file on
7582 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007583 int i;
7584 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007585
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007586 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7587 TempNameW[i] = wn[i];
7588 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7589 TempNameW[i++] = '\\';
7590 TempNameW[i++] = '*';
7591 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007592
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007593 hFile = FindFirstFileW(TempNameW, &d);
7594 if (hFile == INVALID_HANDLE_VALUE)
7595 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007596 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007597 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007598 }
7599
7600 if (p & W_OK)
7601 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007602 // Trying to create a temporary file in the directory should catch
7603 // directories on read-only network shares. However, in
7604 // directories whose ACL allows writes but denies deletes will end
7605 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007606 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7607 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007608 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007609 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007610 }
7611 }
7612 else
7613 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007614 // Don't consider a file read-only if another process has opened it.
7615 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7616
Bram Moolenaar0f873732019-12-05 20:28:46 +01007617 // Trying to open the file for the required access does ACL, read-only
7618 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007619 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7620 | ((p & R_OK) ? GENERIC_READ : 0);
7621
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007622 hFile = CreateFileW(wn, access_mode, share_mode,
7623 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007624 if (hFile == INVALID_HANDLE_VALUE)
7625 goto getout;
7626 CloseHandle(hFile);
7627 }
7628
Bram Moolenaar0f873732019-12-05 20:28:46 +01007629 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007630getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007631 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007632 return retval;
7633}
7634
Bram Moolenaar071d4272004-06-13 20:20:40 +00007635/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007636 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007637 */
7638 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007639mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007640{
7641 WCHAR *wn;
7642 int f;
7643
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007644 wn = enc_to_utf16((char_u *)name, NULL);
7645 if (wn == NULL)
7646 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007647
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007648 f = _wopen(wn, flags, mode);
7649 vim_free(wn);
7650 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007651}
7652
7653/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007654 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007655 */
7656 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007657mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007658{
7659 WCHAR *wn, *wm;
7660 FILE *f = NULL;
7661
Bram Moolenaara12a1612019-01-24 16:39:02 +01007662#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007663 // Work around an annoying assertion in the Microsoft debug CRT
7664 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007665 char newMode = mode[strlen(mode) - 1];
7666 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007667
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007668 _get_fmode(&oldMode);
7669 if (newMode == 't')
7670 _set_fmode(_O_TEXT);
7671 else if (newMode == 'b')
7672 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007673#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007674 wn = enc_to_utf16((char_u *)name, NULL);
7675 wm = enc_to_utf16((char_u *)mode, NULL);
7676 if (wn != NULL && wm != NULL)
7677 f = _wfopen(wn, wm);
7678 vim_free(wn);
7679 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007680
Bram Moolenaara12a1612019-01-24 16:39:02 +01007681#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007682 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007683#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007684 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007685}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007686
Bram Moolenaar071d4272004-06-13 20:20:40 +00007687/*
7688 * SUB STREAM (aka info stream) handling:
7689 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007690 * NTFS can have sub streams for each file. The normal contents of a file is
7691 * stored in the main stream, and extra contents (author information, title and
7692 * so on) can be stored in a sub stream. After Windows 2000, the user can
7693 * access and store this information in sub streams via an explorer's property
7694 * menu item in the right click menu. This information in sub streams was lost
7695 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007696 *
7697 * Incomplete explanation:
7698 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7699 * More useful info and an example:
7700 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7701 */
7702
7703/*
7704 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7705 * and write to stream "substream" of file "to".
7706 * Errors are ignored.
7707 */
7708 static void
7709copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7710{
7711 HANDLE hTo;
7712 WCHAR *to_name;
7713
7714 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7715 wcscpy(to_name, to);
7716 wcscat(to_name, substream);
7717
7718 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7719 FILE_ATTRIBUTE_NORMAL, NULL);
7720 if (hTo != INVALID_HANDLE_VALUE)
7721 {
7722 long done;
7723 DWORD todo;
7724 DWORD readcnt, written;
7725 char buf[4096];
7726
Bram Moolenaar0f873732019-12-05 20:28:46 +01007727 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007728 for (done = 0; done < len; done += written)
7729 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007730 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007731 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7732 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007733 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7734 FALSE, FALSE, context)
7735 || readcnt != todo
7736 || !WriteFile(hTo, buf, todo, &written, NULL)
7737 || written != todo)
7738 break;
7739 }
7740 CloseHandle(hTo);
7741 }
7742
7743 free(to_name);
7744}
7745
7746/*
7747 * Copy info streams from file "from" to file "to".
7748 */
7749 static void
7750copy_infostreams(char_u *from, char_u *to)
7751{
7752 WCHAR *fromw;
7753 WCHAR *tow;
7754 HANDLE sh;
7755 WIN32_STREAM_ID sid;
7756 int headersize;
7757 WCHAR streamname[_MAX_PATH];
7758 DWORD readcount;
7759 void *context = NULL;
7760 DWORD lo, hi;
7761 int len;
7762
Bram Moolenaar0f873732019-12-05 20:28:46 +01007763 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007764 fromw = enc_to_utf16(from, NULL);
7765 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007766 if (fromw != NULL && tow != NULL)
7767 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007768 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007769 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7770 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7771 if (sh != INVALID_HANDLE_VALUE)
7772 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007773 // Use BackupRead() to find the info streams. Repeat until we
7774 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007775 for (;;)
7776 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007777 // Get the header to find the length of the stream name. If
7778 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007779 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007780 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007781 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7782 &readcount, FALSE, FALSE, &context)
7783 || readcount == 0)
7784 break;
7785
Bram Moolenaar0f873732019-12-05 20:28:46 +01007786 // We only deal with streams that have a name. The normal
7787 // file data appears to be without a name, even though docs
7788 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007789 if (sid.dwStreamNameSize > 0)
7790 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007791 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007792 if (!BackupRead(sh, (LPBYTE)streamname,
7793 sid.dwStreamNameSize,
7794 &readcount, FALSE, FALSE, &context))
7795 break;
7796
Bram Moolenaar0f873732019-12-05 20:28:46 +01007797 // Copy an info stream with a name ":anything:$DATA".
7798 // Skip "::$DATA", it has no stream name (examples suggest
7799 // it might be used for the normal file contents).
7800 // Note that BackupRead() counts bytes, but the name is in
7801 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007802 len = readcount / sizeof(WCHAR);
7803 streamname[len] = 0;
7804 if (len > 7 && wcsicmp(streamname + len - 6,
7805 L":$DATA") == 0)
7806 {
7807 streamname[len - 6] = 0;
7808 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007809 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007810 }
7811 }
7812
Bram Moolenaar0f873732019-12-05 20:28:46 +01007813 // Advance to the next stream. We might try seeking too far,
7814 // but BackupSeek() doesn't skip over stream borders, thus
7815 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007816 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007817 &lo, &hi, &context);
7818 }
7819
Bram Moolenaar0f873732019-12-05 20:28:46 +01007820 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007821 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7822
7823 CloseHandle(sh);
7824 }
7825 }
7826 vim_free(fromw);
7827 vim_free(tow);
7828}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007829
7830/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007831 * ntdll.dll definitions
7832 */
7833#define FileEaInformation 7
7834#ifndef STATUS_SUCCESS
7835# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7836#endif
7837
7838typedef struct _FILE_FULL_EA_INFORMATION_ {
7839 ULONG NextEntryOffset;
7840 UCHAR Flags;
7841 UCHAR EaNameLength;
7842 USHORT EaValueLength;
7843 CHAR EaName[1];
7844} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7845
7846typedef struct _FILE_EA_INFORMATION_ {
7847 ULONG EaSize;
7848} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7849
Paul Ollis65745772022-06-05 16:55:54 +01007850#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007851typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7852 PHANDLE FileHandle,
7853 ACCESS_MASK DesiredAccess,
7854 POBJECT_ATTRIBUTES ObjectAttributes,
7855 PIO_STATUS_BLOCK IoStatusBlock,
7856 ULONG ShareAccess,
7857 ULONG OpenOptions);
7858typedef NTSTATUS (NTAPI *PfnNtClose)(
7859 HANDLE Handle);
7860typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007861 HANDLE FileHandle,
7862 PIO_STATUS_BLOCK IoStatusBlock,
7863 PVOID Buffer,
7864 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007865typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7866 HANDLE FileHandle,
7867 PIO_STATUS_BLOCK IoStatusBlock,
7868 PVOID Buffer,
7869 ULONG Length,
7870 BOOLEAN ReturnSingleEntry,
7871 PVOID EaList,
7872 ULONG EaListLength,
7873 PULONG EaIndex,
7874 BOOLEAN RestartScan);
7875typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007876 HANDLE FileHandle,
7877 PIO_STATUS_BLOCK IoStatusBlock,
7878 PVOID FileInformation,
7879 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007880 FILE_INFORMATION_CLASS FileInformationClass);
7881typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7882 PUNICODE_STRING DestinationString,
7883 PCWSTR SourceString);
7884
7885PfnNtOpenFile pNtOpenFile = NULL;
7886PfnNtClose pNtClose = NULL;
7887PfnNtSetEaFile pNtSetEaFile = NULL;
7888PfnNtQueryEaFile pNtQueryEaFile = NULL;
7889PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7890PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01007891#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007892
7893/*
7894 * Load ntdll.dll functions.
7895 */
7896 static BOOL
7897load_ntdll(void)
7898{
7899 static int loaded = -1;
7900
7901 if (loaded == -1)
7902 {
7903 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7904 if (hNtdll != NULL)
7905 {
7906 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7907 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7908 pNtSetEaFile = (PfnNtSetEaFile)
7909 GetProcAddress(hNtdll, "NtSetEaFile");
7910 pNtQueryEaFile = (PfnNtQueryEaFile)
7911 GetProcAddress(hNtdll, "NtQueryEaFile");
7912 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7913 GetProcAddress(hNtdll, "NtQueryInformationFile");
7914 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7915 GetProcAddress(hNtdll, "RtlInitUnicodeString");
7916 }
7917 if (pNtOpenFile == NULL
7918 || pNtClose == NULL
7919 || pNtSetEaFile == NULL
7920 || pNtQueryEaFile == NULL
7921 || pNtQueryInformationFile == NULL
7922 || pRtlInitUnicodeString == NULL)
7923 loaded = FALSE;
7924 else
7925 loaded = TRUE;
7926 }
7927 return (BOOL) loaded;
7928}
7929
7930/*
7931 * Copy extended attributes (EA) from file "from" to file "to".
7932 */
7933 static void
7934copy_extattr(char_u *from, char_u *to)
7935{
7936 char_u *fromf = NULL;
7937 char_u *tof = NULL;
7938 WCHAR *fromw = NULL;
7939 WCHAR *tow = NULL;
7940 UNICODE_STRING u;
7941 HANDLE h;
7942 OBJECT_ATTRIBUTES oa;
7943 IO_STATUS_BLOCK iosb;
7944 FILE_EA_INFORMATION_ eainfo = {0};
7945 void *ea = NULL;
7946
7947 if (!load_ntdll())
7948 return;
7949
7950 // Convert the file names to the fully qualified object names.
7951 fromf = alloc(STRLEN(from) + 5);
7952 tof = alloc(STRLEN(to) + 5);
7953 if (fromf == NULL || tof == NULL)
7954 goto theend;
7955 STRCPY(fromf, "\\??\\");
7956 STRCAT(fromf, from);
7957 STRCPY(tof, "\\??\\");
7958 STRCAT(tof, to);
7959
7960 // Convert the names to wide characters.
7961 fromw = enc_to_utf16(fromf, NULL);
7962 tow = enc_to_utf16(tof, NULL);
7963 if (fromw == NULL || tow == NULL)
7964 goto theend;
7965
7966 // Get the EA.
7967 pRtlInitUnicodeString(&u, fromw);
7968 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7969 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7970 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7971 goto theend;
7972 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7973 FileEaInformation);
7974 if (eainfo.EaSize != 0)
7975 {
7976 ea = alloc(eainfo.EaSize);
7977 if (ea != NULL)
7978 {
7979 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7980 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7981 {
7982 vim_free(ea);
7983 ea = NULL;
7984 }
7985 }
7986 }
7987 pNtClose(h);
7988
7989 // Set the EA.
7990 if (ea != NULL)
7991 {
7992 pRtlInitUnicodeString(&u, tow);
7993 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7994 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7995 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7996 goto theend;
7997
7998 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
7999 pNtClose(h);
8000 }
8001
8002theend:
8003 vim_free(fromf);
8004 vim_free(tof);
8005 vim_free(fromw);
8006 vim_free(tow);
8007 vim_free(ea);
8008}
8009
8010/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008011 * Copy file attributes from file "from" to file "to".
8012 * For Windows NT and later we copy info streams.
8013 * Always returns zero, errors are ignored.
8014 */
8015 int
8016mch_copy_file_attribute(char_u *from, char_u *to)
8017{
Bram Moolenaar0f873732019-12-05 20:28:46 +01008018 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02008019 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008020 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008021 return 0;
8022}
8023
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008024
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008025/*
K.Takatadc73b4b2021-06-08 18:32:36 +02008026 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008027 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008028static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008029static LPWSTR *ArglistW = NULL;
8030static int global_argc = 0;
8031static char **global_argv;
8032
Bram Moolenaar0f873732019-12-05 20:28:46 +01008033static int used_file_argc = 0; // last argument in global_argv[] used
8034 // for the argument list.
8035static int *used_file_indexes = NULL; // indexes in global_argv[] for
8036 // command line arguments added to
8037 // the argument list
8038static int used_file_count = 0; // nr of entries in used_file_indexes
8039static int used_file_literal = FALSE; // take file names literally
8040static int used_file_full_path = FALSE; // file name was full path
8041static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008042static int used_alist_count = 0;
8043
8044
8045/*
8046 * Get the command line arguments. Unicode version.
8047 * Returns argc. Zero when something fails.
8048 */
8049 int
8050get_cmd_argsW(char ***argvp)
8051{
8052 char **argv = NULL;
8053 int argc = 0;
8054 int i;
8055
Bram Moolenaar14993322014-09-09 12:25:33 +02008056 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008057 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
8058 if (ArglistW != NULL)
8059 {
8060 argv = malloc((nArgsW + 1) * sizeof(char *));
8061 if (argv != NULL)
8062 {
8063 argc = nArgsW;
8064 argv[argc] = NULL;
8065 for (i = 0; i < argc; ++i)
8066 {
8067 int len;
8068
K.Takatadc73b4b2021-06-08 18:32:36 +02008069 // Convert each Unicode argument to UTF-8.
8070 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008071 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008072 (LPSTR *)&argv[i], &len, 0, 0);
8073 if (argv[i] == NULL)
8074 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008075 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008076 while (i > 0)
8077 free(argv[--i]);
8078 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01008079 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008080 argc = 0;
8081 }
8082 }
8083 }
8084 }
8085
8086 global_argc = argc;
8087 global_argv = argv;
8088 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02008089 {
8090 if (used_file_indexes != NULL)
8091 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008092 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02008093 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008094
8095 if (argvp != NULL)
8096 *argvp = argv;
8097 return argc;
8098}
8099
8100 void
8101free_cmd_argsW(void)
8102{
8103 if (ArglistW != NULL)
8104 {
8105 GlobalFree(ArglistW);
8106 ArglistW = NULL;
8107 }
8108}
8109
8110/*
8111 * Remember "name" is an argument that was added to the argument list.
8112 * This avoids that we have to re-parse the argument list when fix_arg_enc()
8113 * is called.
8114 */
8115 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008116used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008117{
8118 int i;
8119
8120 if (used_file_indexes == NULL)
8121 return;
8122 for (i = used_file_argc + 1; i < global_argc; ++i)
8123 if (STRCMP(global_argv[i], name) == 0)
8124 {
8125 used_file_argc = i;
8126 used_file_indexes[used_file_count++] = i;
8127 break;
8128 }
8129 used_file_literal = literal;
8130 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008131 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008132}
8133
8134/*
8135 * Remember the length of the argument list as it was. If it changes then we
8136 * leave it alone when 'encoding' is set.
8137 */
8138 void
8139set_alist_count(void)
8140{
8141 used_alist_count = GARGCOUNT;
8142}
8143
8144/*
8145 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02008146 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008147 * and convert them to 'encoding'.
8148 */
8149 void
8150fix_arg_enc(void)
8151{
8152 int i;
8153 int idx;
8154 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00008155 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008156
Bram Moolenaar0f873732019-12-05 20:28:46 +01008157 // Safety checks:
8158 // - if argument count differs between the wide and non-wide argument
8159 // list, something must be wrong.
8160 // - the file name arguments must have been located.
8161 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008162 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008163 || ArglistW == NULL
8164 || used_file_indexes == NULL
8165 || used_file_count == 0
8166 || used_alist_count != GARGCOUNT)
8167 return;
8168
Bram Moolenaar0f873732019-12-05 20:28:46 +01008169 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02008170 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008171 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008172 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00008173 for (i = 0; i < GARGCOUNT; ++i)
8174 fnum_list[i] = GARGLIST[i].ae_fnum;
8175
Bram Moolenaar0f873732019-12-05 20:28:46 +01008176 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008177 alist_clear(&global_alist);
8178 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008179 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008180
8181 for (i = 0; i < used_file_count; ++i)
8182 {
8183 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008184 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008185 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00008186 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008187 int literal = used_file_literal;
8188
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008189#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01008190 // When using diff mode may need to concatenate file name to
8191 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008192 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
8193 && !mch_isdir(alist_name(&GARGLIST[0])))
8194 {
8195 char_u *r;
8196
8197 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
8198 if (r != NULL)
8199 {
8200 vim_free(str);
8201 str = r;
8202 }
8203 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008204#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01008205 // Re-use the old buffer by renaming it. When not using literal
8206 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00008207 if (used_file_literal)
8208 buf_set_name(fnum_list[i], str);
8209
Bram Moolenaar0f873732019-12-05 20:28:46 +01008210 // Check backtick literal. backtick literal is already expanded in
8211 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008212 if (literal == FALSE)
8213 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02008214 size_t len = STRLEN(str);
8215
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008216 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
8217 literal = TRUE;
8218 }
8219 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008220 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008221 }
8222
8223 if (!used_file_literal)
8224 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008225 // Now expand wildcards in the arguments.
8226 // Temporarily add '(' and ')' to 'isfname'. These are valid
8227 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00008228 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01008229 // Also, unset wildignore to not be influenced by this option.
8230 // The arguments specified in command-line should be kept even if
8231 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00008232 // Use :legacy so that it also works when in Vim9 script.
8233 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
8234 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00008235 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00008236 do_cmdline_cmd(
8237 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
8238 do_cmdline_cmd(
8239 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008240 }
8241
Bram Moolenaar0f873732019-12-05 20:28:46 +01008242 // If wildcard expansion failed, we are editing the first file of the
8243 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008244 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
8245 {
8246 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00008247 if (GARGCOUNT == 1 && used_file_full_path
8248 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
8249 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008250 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00008251
8252 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008253}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008254
8255 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02008256mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008257{
8258 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008259 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008260
Bram Moolenaar964b3742019-05-24 18:54:09 +02008261 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008262 if (envbuf == NULL)
8263 return -1;
8264
8265 sprintf((char *)envbuf, "%s=%s", var, value);
8266
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008267 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008268
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008269 vim_free(envbuf);
8270 if (p == NULL)
8271 return -1;
8272 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008273#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008274 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008275#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008276 // Unlike Un*x systems, we can free the string for _wputenv().
8277 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008278
8279 return 0;
8280}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008281
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008282/*
8283 * Support for 256 colors and 24-bit colors was added in Windows 10
8284 * version 1703 (Creators update).
8285 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008286#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
8287
8288/*
8289 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02008290 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008291 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008292#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008293
8294/*
8295 * ConPTY differences between versions, need different logic.
8296 * version 1903 (May 2019 update).
8297 */
8298#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
8299
8300/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008301 * version 1909 (November 2019 update).
8302 */
8303#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
8304
8305/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008306 * Stay ahead of the next update, and when it's done, fix this.
8307 * version ? (2020 update, temporarily use the build number of insider preview)
8308 */
8309#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
8310
8311/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02008312 * Confirm until this version. Also the logic changes.
8313 * insider preview.
8314 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02008315#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008316
8317/*
8318 * Not stable now.
8319 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008320#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Christopher Plewright1140b512022-11-12 18:46:05 +00008321// Notes:
8322// Win 10 22H2 Final is build 19045, it's conpty is widely used.
8323// Strangely, 19045 is newer but is a lower build number than the 2020 insider
8324// preview which had a build 19587. And, not sure how stable that was?
8325// Win Server 2022 (May 10, 2022) is build 20348, its conpty is widely used.
8326// Win 11 starts from build 22000, even though the major version says 10!
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008327
8328 static void
8329vtp_flag_init(void)
8330{
8331 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008332#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008333 DWORD mode;
8334 HANDLE out;
8335
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008336# ifdef VIMDLL
8337 if (!gui.in_use)
8338# endif
8339 {
8340 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008341
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008342 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
8343 GetConsoleMode(out, &mode);
8344 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
8345 if (SetConsoleMode(out, mode) == 0)
8346 vtp_working = 0;
8347 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008348#endif
8349
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008350 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008351 conpty_working = 1;
8352 if (ver >= CONPTY_STABLE_BUILD)
8353 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008354
Bram Moolenaar57da6982019-09-13 22:30:11 +02008355 if (ver <= CONPTY_INSIDER_BUILD)
8356 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008357 if (ver <= CONPTY_1909_BUILD)
8358 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02008359 if (ver <= CONPTY_1903_BUILD)
8360 conpty_type = 2;
8361 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
8362 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008363
8364 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
8365 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008366}
8367
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008368#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008369
8370 static void
8371vtp_init(void)
8372{
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008373# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00008374 if (!vtp_working)
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008375 {
Christopher Plewright38804d62022-11-09 23:55:52 +00008376 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8377 csbi.cbSize = sizeof(csbi);
8378 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8379 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
8380 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
8381 store_console_bg_rgb = save_console_bg_rgb;
8382 store_console_fg_rgb = save_console_fg_rgb;
8383
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008384 COLORREF bg;
8385 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
8386 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8387 default_console_color_bg = bg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008388
8389 COLORREF fg;
8390 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
8391 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8392 default_console_color_fg = fg;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008393 }
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008394# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008395
8396 set_console_color_rgb();
8397}
8398
8399 static void
8400vtp_exit(void)
8401{
Bram Moolenaardf543822020-01-30 11:53:59 +01008402 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008403}
8404
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008405 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008406vtp_printf(
8407 char *format,
8408 ...)
8409{
8410 char_u buf[100];
8411 va_list list;
8412 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008413 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008414
8415 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008416 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008417 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008418 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008419 return (int)result;
8420}
8421
8422 static void
8423vtp_sgr_bulk(
8424 int arg)
8425{
8426 int args[1];
8427
8428 args[0] = arg;
8429 vtp_sgr_bulks(1, args);
8430}
8431
K.Takata6e1d31e2022-02-03 13:05:32 +00008432# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008433 if ((*p-- = "0123456789"[(n = x % 10)]) \
8434 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8435 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8436
K.Takata6e1d31e2022-02-03 13:05:32 +00008437# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008438 case x: \
8439 FAST256(newargs[x - 1]);
8440
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008441 static void
8442vtp_sgr_bulks(
8443 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008444 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008445{
K.Takata6e1d31e2022-02-03 13:05:32 +00008446# define MAXSGR 16
8447# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008448 char_u buf[SGRBUFSIZE];
8449 char_u *p;
8450 int in, out;
8451 int newargs[16];
8452 static int sgrfgr = -1, sgrfgg, sgrfgb;
8453 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008454
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008455 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008456 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008457 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008458 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008459 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008460 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008461
8462 in = out = 0;
8463 while (in < argc)
8464 {
8465 int s = args[in];
8466 int copylen = 1;
8467
8468 if (s == 38)
8469 {
8470 if (argc - in >= 5 && args[in + 1] == 2)
8471 {
8472 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8473 && sgrfgb == args[in + 4])
8474 {
8475 in += 5;
8476 copylen = 0;
8477 }
8478 else
8479 {
8480 sgrfgr = args[in + 2];
8481 sgrfgg = args[in + 3];
8482 sgrfgb = args[in + 4];
8483 copylen = 5;
8484 }
8485 }
8486 else if (argc - in >= 3 && args[in + 1] == 5)
8487 {
8488 sgrfgr = -1;
8489 copylen = 3;
8490 }
8491 }
8492 else if (s == 48)
8493 {
8494 if (argc - in >= 5 && args[in + 1] == 2)
8495 {
8496 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8497 && sgrbgb == args[in + 4])
8498 {
8499 in += 5;
8500 copylen = 0;
8501 }
8502 else
8503 {
8504 sgrbgr = args[in + 2];
8505 sgrbgg = args[in + 3];
8506 sgrbgb = args[in + 4];
8507 copylen = 5;
8508 }
8509 }
8510 else if (argc - in >= 3 && args[in + 1] == 5)
8511 {
8512 sgrbgr = -1;
8513 copylen = 3;
8514 }
8515 }
8516 else if (30 <= s && s <= 39)
8517 sgrfgr = -1;
8518 else if (90 <= s && s <= 97)
8519 sgrfgr = -1;
8520 else if (40 <= s && s <= 49)
8521 sgrbgr = -1;
8522 else if (100 <= s && s <= 107)
8523 sgrbgr = -1;
8524 else if (s == 0)
8525 sgrfgr = sgrbgr = -1;
8526
8527 while (copylen--)
8528 newargs[out++] = args[in++];
8529 }
8530
8531 p = &buf[sizeof(buf) - 1];
8532 *p-- = 'm';
8533
8534 switch (out)
8535 {
8536 int n, m;
8537 DWORD r;
8538
8539 FAST256CASE(16);
8540 *p-- = ';';
8541 FAST256CASE(15);
8542 *p-- = ';';
8543 FAST256CASE(14);
8544 *p-- = ';';
8545 FAST256CASE(13);
8546 *p-- = ';';
8547 FAST256CASE(12);
8548 *p-- = ';';
8549 FAST256CASE(11);
8550 *p-- = ';';
8551 FAST256CASE(10);
8552 *p-- = ';';
8553 FAST256CASE(9);
8554 *p-- = ';';
8555 FAST256CASE(8);
8556 *p-- = ';';
8557 FAST256CASE(7);
8558 *p-- = ';';
8559 FAST256CASE(6);
8560 *p-- = ';';
8561 FAST256CASE(5);
8562 *p-- = ';';
8563 FAST256CASE(4);
8564 *p-- = ';';
8565 FAST256CASE(3);
8566 *p-- = ';';
8567 FAST256CASE(2);
8568 *p-- = ';';
8569 FAST256CASE(1);
8570 *p-- = '[';
8571 *p = '\033';
8572 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8573 default:
8574 break;
8575 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008576}
8577
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008578 static void
8579wt_init(void)
8580{
Christopher Plewright1140b512022-11-12 18:46:05 +00008581 wt_working = mch_getenv("WT_SESSION") != NULL;
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008582}
8583
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008584# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008585 static int
8586ctermtoxterm(
8587 int cterm)
8588{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008589 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008590
8591 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8592 return (((int)r << 16) | ((int)g << 8) | (int)b);
8593}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008594# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008595
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008596 static void
8597set_console_color_rgb(void)
8598{
8599# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008600 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008601 guicolor_T fg, bg;
8602 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008603
Christopher Plewright38804d62022-11-09 23:55:52 +00008604 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008605 return;
8606
Bram Moolenaara050b942019-12-02 21:35:31 +01008607 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8608
Christopher Plewright38804d62022-11-09 23:55:52 +00008609 if (p_tgc || t_colors >= 256)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008610 {
8611 term_fg_rgb_color(fg);
8612 term_bg_rgb_color(bg);
8613 return;
8614 }
8615
Christopher Plewright38804d62022-11-09 23:55:52 +00008616 if (!conpty_working)
8617 {
8618 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8619 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008620
Christopher Plewright38804d62022-11-09 23:55:52 +00008621 csbi.cbSize = sizeof(csbi);
8622 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008623
Christopher Plewright38804d62022-11-09 23:55:52 +00008624 csbi.cbSize = sizeof(csbi);
8625 csbi.srWindow.Right += 1;
8626 csbi.srWindow.Bottom += 1;
8627 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8628 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
8629 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8630 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
8631 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8632 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008633# endif
8634}
8635
Bram Moolenaara050b942019-12-02 21:35:31 +01008636# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8637 void
8638get_default_console_color(
8639 int *cterm_fg,
8640 int *cterm_bg,
8641 guicolor_T *gui_fg,
8642 guicolor_T *gui_bg)
8643{
8644 int id;
8645 guicolor_T guifg = INVALCOLOR;
8646 guicolor_T guibg = INVALCOLOR;
8647 int ctermfg = 0;
8648 int ctermbg = 0;
Christopher Plewright38804d62022-11-09 23:55:52 +00008649 int dummynull = 0;
Bram Moolenaara050b942019-12-02 21:35:31 +01008650
8651 id = syn_name2id((char_u *)"Normal");
8652 if (id > 0 && p_tgc)
8653 syn_id2colors(id, &guifg, &guibg);
8654 if (guifg == INVALCOLOR)
8655 {
8656 ctermfg = -1;
8657 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008658 syn_id2cterm_bg(id, &ctermfg, &dummynull);
8659 if (vtp_working)
8660 {
8661 cterm_normal_fg_gui_color = guifg =
8662 ctermfg != -1 ? ctermtoxterm(ctermfg) : INVALCOLOR;
8663 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8664 }
8665 else
8666 {
8667 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
Bram Moolenaara050b942019-12-02 21:35:31 +01008668 : default_console_color_fg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008669 cterm_normal_fg_gui_color = guifg;
8670 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8671 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008672 }
8673 if (guibg == INVALCOLOR)
8674 {
8675 ctermbg = -1;
8676 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008677 syn_id2cterm_bg(id, &dummynull, &ctermbg);
8678 if (vtp_working)
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008679 {
8680 cterm_normal_bg_gui_color = guibg =
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01008681 ctermbg != -1 ? ctermtoxterm(ctermbg) : INVALCOLOR;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008682 if (ctermbg < 0)
8683 ctermbg = 0;
8684 }
K.Takatae53a0d42022-09-05 21:45:11 +01008685 else
8686 {
8687 guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8688 : default_console_color_bg;
8689 cterm_normal_bg_gui_color = guibg;
8690 ctermbg = ctermbg < 0 ? 0 : ctermbg;
8691 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008692 }
8693
8694 *cterm_fg = ctermfg;
8695 *cterm_bg = ctermbg;
8696 *gui_fg = guifg;
8697 *gui_bg = guibg;
8698}
8699# endif
8700
Bram Moolenaardf543822020-01-30 11:53:59 +01008701/*
8702 * Set the console colors to the original colors or the last set colors.
8703 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008704 static void
8705reset_console_color_rgb(void)
8706{
8707# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008708
Christopher Plewright38804d62022-11-09 23:55:52 +00008709 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008710 return;
8711
Christopher Plewright38804d62022-11-09 23:55:52 +00008712 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8713
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008714 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008715 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008716
8717 csbi.cbSize = sizeof(csbi);
8718 csbi.srWindow.Right += 1;
8719 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008720 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8721 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008722 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008723# endif
8724}
8725
8726/*
8727 * Set the console colors to the original colors.
8728 */
8729 static void
8730restore_console_color_rgb(void)
8731{
8732# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00008733 if (vtp_working)
8734 return;
8735
K.Takata27b53be2022-09-18 12:25:49 +01008736 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008737
8738 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008739 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008740
8741 csbi.cbSize = sizeof(csbi);
8742 csbi.srWindow.Right += 1;
8743 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008744 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8745 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008746 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008747# endif
8748}
8749
8750 void
8751control_console_color_rgb(void)
8752{
Christopher Plewright38804d62022-11-09 23:55:52 +00008753 if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008754 set_console_color_rgb();
8755 else
8756 reset_console_color_rgb();
8757}
8758
8759 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008760use_vtp(void)
8761{
8762 return USE_VTP;
8763}
8764
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008765 int
8766is_term_win32(void)
8767{
8768 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8769}
8770
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008771 int
8772has_vtp_working(void)
8773{
8774 return vtp_working;
8775}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008776
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008777#endif
8778
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008779 int
8780has_conpty_working(void)
8781{
8782 return conpty_working;
8783}
8784
8785 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008786get_conpty_type(void)
8787{
8788 return conpty_type;
8789}
8790
8791 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008792is_conpty_stable(void)
8793{
8794 return conpty_stable;
8795}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008796
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008797 int
8798get_conpty_fix_type(void)
8799{
8800 return conpty_fix_type;
8801}
8802
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008803#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008804 void
8805resize_console_buf(void)
8806{
8807 CONSOLE_SCREEN_BUFFER_INFO csbi;
8808 COORD coord;
8809 SMALL_RECT newsize;
8810
8811 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8812 {
8813 coord.X = SRWIDTH(csbi.srWindow);
8814 coord.Y = SRHEIGHT(csbi.srWindow);
8815 SetConsoleScreenBufferSize(g_hConOut, coord);
8816
8817 newsize.Left = 0;
8818 newsize.Top = 0;
8819 newsize.Right = coord.X - 1;
8820 newsize.Bottom = coord.Y - 1;
8821 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8822
8823 SetConsoleScreenBufferSize(g_hConOut, coord);
8824 }
8825}
8826#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008827
8828 char *
8829GetWin32Error(void)
8830{
K.Takatad68b2fc2022-02-12 11:18:37 +00008831 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008832 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008833
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008834 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8835 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008836 if (oldmsg != NULL)
8837 LocalFree(oldmsg);
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008838 if (msg != NULL)
8839 {
8840 // remove trailing \r\n
8841 char *pcrlf = strstr(msg, "\r\n");
8842 if (pcrlf != NULL)
8843 *pcrlf = '\0';
K.Takatad68b2fc2022-02-12 11:18:37 +00008844 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008845 }
8846 return msg;
8847}
Paul Ollis65745772022-06-05 16:55:54 +01008848
8849#if defined(FEAT_RELTIME) || defined(PROTO)
8850static HANDLE timer_handle;
8851static int timer_active = FALSE;
8852
8853/*
8854 * Calls to start_timeout alternate the return value pointer between the two
8855 * entries in timeout_flags. If the previously active timeout is very close to
8856 * expiring when start_timeout() is called then a race condition means that the
8857 * set_flag() function may still be invoked after the previous timer is
8858 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8859 * timeouts.
8860 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008861static sig_atomic_t timeout_flags[2];
8862static int timeout_flag_idx = 0;
8863static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01008864
8865
8866 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01008867set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01008868{
8869 int *timeout_flag = (int *)param;
8870
8871 *timeout_flag = TRUE;
8872}
8873
8874/*
8875 * Stop any active timeout.
8876 */
8877 void
8878stop_timeout(void)
8879{
8880 if (timer_active)
8881 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01008882 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01008883 timer_active = FALSE;
8884 if (!ret && GetLastError() != ERROR_IO_PENDING)
8885 {
8886 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
8887 }
8888 }
8889 *timeout_flag = FALSE;
8890}
8891
8892/*
8893 * Start the timeout timer.
8894 *
8895 * The period is defined in milliseconds.
8896 *
8897 * The return value is a pointer to a flag that is initialised to 0. If the
8898 * timeout expires, the flag is set to 1. This will only return pointers to
8899 * static memory; i.e. any pointer returned by this function may always be
8900 * safely dereferenced.
8901 *
8902 * This function is not expected to fail, but if it does it still returns a
8903 * valid flag pointer; the flag will remain stuck at zero.
8904 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008905 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01008906start_timeout(long msec)
8907{
Paul Ollis65745772022-06-05 16:55:54 +01008908 BOOL ret;
8909
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008910 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01008911
8912 stop_timeout();
8913 ret = CreateTimerQueueTimer(
8914 &timer_handle, NULL, set_flag, timeout_flag,
8915 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
8916 if (!ret)
8917 {
8918 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
8919 }
8920 else
8921 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008922 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01008923 timer_active = TRUE;
8924 *timeout_flag = FALSE;
8925 }
8926 return timeout_flag;
8927}
8928#endif