blob: ff60e04aed9b51b321dbaf53e34c347c0e360ea6 [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
12 * Used for both the console version and the Win32 GUI. A lot of code is for
Bram Moolenaar4f974752019-02-17 17:44:42 +010013 * the console version only, so there is a lot of "#ifndef FEAT_GUI_MSWIN".
Bram Moolenaar071d4272004-06-13 20:20:40 +000014 *
15 * Win32 (Windows NT and Windows 95) system-dependent routines.
16 * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17 * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18 *
19 * George V. Reilly <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
Bram Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010032
Bram Moolenaar0f873732019-12-05 20:28:46 +010033// cproto fails on missing include files
Bram Moolenaar82881492012-11-20 16:53:39 +010034#ifndef PROTO
35# include <process.h>
Bram Moolenaare7bebc42021-02-01 20:50:37 +010036# include <winternl.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010037#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000038
39#undef chdir
40#ifdef __GNUC__
41# ifndef __MINGW32__
42# include <dirent.h>
43# endif
44#else
45# include <direct.h>
46#endif
47
Bram Moolenaar82881492012-11-20 16:53:39 +010048#ifndef PROTO
Bram Moolenaar651fca82021-11-29 20:39:38 +000049# if !defined(FEAT_GUI_MSWIN)
Bram Moolenaar82881492012-11-20 16:53:39 +010050# include <shellapi.h>
51# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000052#endif
53
Bram Moolenaarfb630902016-10-29 14:55:00 +020054#ifdef FEAT_JOB_CHANNEL
55# include <tlhelp32.h>
56#endif
57
Bram Moolenaar071d4272004-06-13 20:20:40 +000058#ifdef __MINGW32__
59# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
60# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
61# endif
62# ifndef RIGHTMOST_BUTTON_PRESSED
63# define RIGHTMOST_BUTTON_PRESSED 0x0002
64# endif
65# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
66# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
67# endif
68# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
69# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
70# endif
71# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
72# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
73# endif
74
75/*
76 * EventFlags
77 */
78# ifndef MOUSE_MOVED
79# define MOUSE_MOVED 0x0001
80# endif
81# ifndef DOUBLE_CLICK
82# define DOUBLE_CLICK 0x0002
83# endif
84#endif
85
Bram Moolenaar0f873732019-12-05 20:28:46 +010086// Record all output and all keyboard & mouse input
87// #define MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +000088
89#ifdef MCH_WRITE_DUMP
90FILE* fdDump = NULL;
91#endif
92
93/*
94 * When generating prototypes for Win32 on Unix, these lines make the syntax
95 * errors disappear. They do not need to be correct.
96 */
97#ifdef PROTO
Bram Moolenaar912bc4a2019-12-01 18:58:11 +010098# define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000099typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000100typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000101typedef int ACCESS_MASK;
102typedef int BOOL;
Paul Ollis65745772022-06-05 16:55:54 +0100103typedef int BOOLEAN;
104typedef int CALLBACK;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000105typedef int COLORREF;
106typedef int CONSOLE_CURSOR_INFO;
107typedef int COORD;
108typedef int DWORD;
109typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100110typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000111typedef int HDC;
112typedef int HFONT;
113typedef int HICON;
114typedef int HINSTANCE;
115typedef int HWND;
116typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200117typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000118typedef int KEY_EVENT_RECORD;
119typedef int LOGFONT;
120typedef int LPBOOL;
121typedef int LPCTSTR;
122typedef int LPDWORD;
123typedef int LPSTR;
124typedef int LPTSTR;
125typedef int LPVOID;
126typedef int MOUSE_EVENT_RECORD;
127typedef int PACL;
128typedef int PDWORD;
129typedef int PHANDLE;
130typedef int PRINTDLG;
131typedef int PSECURITY_DESCRIPTOR;
132typedef int PSID;
133typedef int SECURITY_INFORMATION;
134typedef int SHORT;
135typedef int SMALL_RECT;
136typedef int TEXTMETRIC;
137typedef int TOKEN_INFORMATION_CLASS;
138typedef int TRUSTEE;
139typedef int WORD;
140typedef int WCHAR;
141typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100142typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200143typedef int SE_OBJECT_TYPE;
144typedef int PSNSECINFO;
145typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100146typedef int STARTUPINFO;
147typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200148typedef int LPSECURITY_ATTRIBUTES;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100149# define __stdcall // empty
Bram Moolenaar071d4272004-06-13 20:20:40 +0000150#endif
151
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200152#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100153// Win32 Console handles for input and output
Bram Moolenaar071d4272004-06-13 20:20:40 +0000154static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
155static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
156
Bram Moolenaar0f873732019-12-05 20:28:46 +0100157// Win32 Screen buffer,coordinate,console I/O information
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158static SMALL_RECT g_srScrollRegion;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100159static COORD g_coord; // 0-based, but external coords are 1-based
Bram Moolenaar071d4272004-06-13 20:20:40 +0000160
Bram Moolenaar0f873732019-12-05 20:28:46 +0100161// The attribute of the screen when the editor was started
162static WORD g_attrDefault = 7; // lightgray text on black background
Bram Moolenaar071d4272004-06-13 20:20:40 +0000163static WORD g_attrCurrent;
164
Bram Moolenaar0f873732019-12-05 20:28:46 +0100165static int g_fCBrkPressed = FALSE; // set by ctrl-break interrupt
166static int g_fCtrlCPressed = FALSE; // set when ctrl-C or ctrl-break detected
167static int g_fForceExit = FALSE; // set when forcefully exiting
Bram Moolenaar071d4272004-06-13 20:20:40 +0000168
Bram Moolenaar071d4272004-06-13 20:20:40 +0000169static void scroll(unsigned cLines);
170static void set_scroll_region(unsigned left, unsigned top,
171 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100172static void set_scroll_region_tb(unsigned top, unsigned bottom);
173static void set_scroll_region_lr(unsigned left, unsigned right);
174static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000175static void delete_lines(unsigned cLines);
176static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000177static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000178static int s_cursor_visible = TRUE;
179static int did_create_conin = FALSE;
Christopher Plewright20b795e2022-12-20 20:01:58 +0000180// The 'input_record_buffer' is an internal dynamic fifo queue of MS-Windows
181// console INPUT_RECORD events that are normally read from the console input
182// buffer. This provides an injection point for testing the low-level handling
183// of INPUT_RECORDs.
184typedef struct input_record_buffer_node_S
185{
186 INPUT_RECORD ir;
187 struct input_record_buffer_node_S *next;
188} input_record_buffer_node_T;
189typedef struct input_record_buffer_S
190{
191 input_record_buffer_node_T *head;
192 input_record_buffer_node_T *tail;
193 int length;
194} input_record_buffer_T;
195static input_record_buffer_T input_record_buffer;
Christopher Plewright20b795e2022-12-20 20:01:58 +0000196static int read_input_record_buffer(INPUT_RECORD* irEvents, int nMaxLength);
197static int write_input_record_buffer(INPUT_RECORD* irEvents, int nLength);
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200198#endif
199#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000200static int s_dont_use_vimrun = TRUE;
201static int need_vimrun_warning = FALSE;
202static char *vimrun_path = "vimrun ";
203#endif
204
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200205static int win32_getattrs(char_u *name);
206static int win32_setattrs(char_u *name, int attrs);
207static int win32_set_archive(char_u *name);
208
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100209static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200210static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100211static int conpty_stable = 0;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +0200212static int conpty_fix_type = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100213static void vtp_flag_init();
214
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200215#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100216static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100217static void vtp_init();
218static void vtp_exit();
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100219static void vtp_sgr_bulk(int arg);
220static void vtp_sgr_bulks(int argc, int *argv);
221
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200222static int wt_working = 0;
Christopher Plewright1140b512022-11-12 18:46:05 +0000223static void wt_init(void);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200224
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200225static int g_color_index_bg = 0;
226static int g_color_index_fg = 7;
227
228# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +0000229static guicolor_T save_console_bg_rgb;
230static guicolor_T save_console_fg_rgb;
231static guicolor_T store_console_bg_rgb;
232static guicolor_T store_console_fg_rgb;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +0100233static int default_console_color_bg = 0x000000; // black
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200234static int default_console_color_fg = 0xc0c0c0; // white
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +0000235# define USE_VTP (vtp_working && is_term_win32() \
236 && (p_tgc || t_colors >= 256))
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200237# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100238# else
239# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200240# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100241# endif
242
243static void set_console_color_rgb(void);
244static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100245static void restore_console_color_rgb(void);
Christopher Plewright20b795e2022-12-20 20:01:58 +0000246#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100247
Bram Moolenaar0f873732019-12-05 20:28:46 +0100248// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100249#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
250# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
251#endif
252
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200253#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100254static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000255#endif
256
K.Takatace3189d2023-02-15 19:13:43 +0000257static WCHAR *exe_pathw = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200258
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100259static BOOL win8_or_later = FALSE;
Christopher Plewrightc8b126d2022-12-22 13:45:23 +0000260static BOOL win10_22H2_or_later = FALSE;
Bram Moolenaar9fca1332022-12-22 21:06:41 +0000261#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Christopher Plewrightc8b126d2022-12-22 13:45:23 +0000262static BOOL use_alternate_screen_buffer = FALSE;
Bram Moolenaar9fca1332022-12-22 21:06:41 +0000263#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100264
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100265/*
266 * Get version number including build number
267 */
268typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100269#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100270 (((major) << 24) | ((minor) << 16) | (build))
271
272 static DWORD
273get_build_number(void)
274{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100275 OSVERSIONINFOW osver;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100276 HMODULE hNtdll;
277 PfnRtlGetVersion pRtlGetVersion;
278 DWORD ver = MAKE_VER(0, 0, 0);
279
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100280 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100281 hNtdll = GetModuleHandle("ntdll.dll");
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000282 if (hNtdll == NULL)
283 return ver;
284
285 pRtlGetVersion =
286 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
287 pRtlGetVersion(&osver);
288 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
289 min(osver.dwMinorVersion, 255),
290 min(osver.dwBuildNumber, 32767));
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100291 return ver;
292}
293
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200294#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200295 static BOOL
296is_ambiwidth_event(
297 INPUT_RECORD *ir)
298{
299 return ir->EventType == KEY_EVENT
300 && ir->Event.KeyEvent.bKeyDown
301 && ir->Event.KeyEvent.wRepeatCount == 1
302 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
303 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000304 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200305 && ir->Event.KeyEvent.dwControlKeyState == 2;
306}
307
308 static void
309make_ambiwidth_event(
310 INPUT_RECORD *down,
311 INPUT_RECORD *up)
312{
313 down->Event.KeyEvent.wVirtualKeyCode = 0;
314 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000315 down->Event.KeyEvent.uChar.UnicodeChar
316 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200317 down->Event.KeyEvent.dwControlKeyState = 0;
318}
319
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100320/*
321 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100322 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100323 */
324 static BOOL
325read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100326 HANDLE hInput,
327 INPUT_RECORD *lpBuffer,
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100328 int nLength,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100329 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100330{
331 enum
332 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100333 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100334 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100335 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100336 static DWORD s_dwIndex = 0;
337 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100338 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100339 int head;
340 int tail;
341 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200342 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100343
Christopher Plewright20b795e2022-12-20 20:01:58 +0000344 if (s_dwMax == 0 && input_record_buffer.length > 0)
345 {
346 dwEvents = read_input_record_buffer(s_irCache, IRSIZE);
347 s_dwIndex = 0;
348 s_dwMax = dwEvents;
349 }
350
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200351 if (nLength == -2)
352 return (s_dwMax > 0) ? TRUE : FALSE;
353
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100354 if (!win8_or_later)
355 {
356 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200357 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
358 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100359 }
360
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100361 if (s_dwMax == 0)
362 {
Christopher Plewright38804d62022-11-09 23:55:52 +0000363 if (!vtp_working && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200364 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200365 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
366 if (dwEvents == 0 && nLength == -1)
367 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
368 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100369 s_dwIndex = 0;
370 s_dwMax = dwEvents;
371 if (dwEvents == 0)
372 {
373 *lpEvents = 0;
374 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100375 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100376
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200377 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
378 if (is_ambiwidth_event(&s_irCache[i]))
379 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
380
Bram Moolenaardd415a62014-02-05 14:02:27 +0100381 if (s_dwMax > 1)
382 {
383 head = 0;
384 tail = s_dwMax - 1;
385 while (head != tail)
386 {
387 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
388 && s_irCache[head + 1].EventType
389 == WINDOW_BUFFER_SIZE_EVENT)
390 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100391 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100392 for (i = head; i < tail; ++i)
393 s_irCache[i] = s_irCache[i + 1];
394 --tail;
395 continue;
396 }
397 head++;
398 }
399 s_dwMax = tail + 1;
400 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100401 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100402
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200403 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
404 {
405 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
406 {
407 s_irPseudo = s_irCache[s_dwIndex];
408 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
409 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
410 *lpBuffer = s_irPseudo;
411 *lpEvents = 1;
412 return TRUE;
413 }
414 }
415
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100416 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200417 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100418 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100419 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100420 return TRUE;
421}
422
423/*
424 * Version of PeekConsoleInput() that works with IME.
425 */
426 static BOOL
427peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100428 HANDLE hInput,
429 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200430 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100431 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100432{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100433 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100434}
435
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100436# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200437 static DWORD
438msg_wait_for_multiple_objects(
439 DWORD nCount,
440 LPHANDLE pHandles,
441 BOOL fWaitAll,
442 DWORD dwMilliseconds,
443 DWORD dwWakeMask)
444{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100445 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200446 return WAIT_OBJECT_0;
447 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
448 dwMilliseconds, dwWakeMask);
449}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100450# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200451
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100452# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200453 static DWORD
454wait_for_single_object(
455 HANDLE hHandle,
456 DWORD dwMilliseconds)
457{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100458 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200459 return WAIT_OBJECT_0;
460 return WaitForSingleObject(hHandle, dwMilliseconds);
461}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100462# endif
Christopher Plewright20b795e2022-12-20 20:01:58 +0000463#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200464
K.Takatace3189d2023-02-15 19:13:43 +0000465 void
466mch_get_exe_name(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000467{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100468 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
K.Takataf741e3e2023-05-15 16:41:40 +0100469 // as the maximum length that works. Add 1 for a NUL byte and 5 for
470 // "PATH=".
471#define MAX_ENV_PATH_LEN (8191 + 1 + 5)
472 WCHAR temp[MAX_ENV_PATH_LEN];
K.Takatace3189d2023-02-15 19:13:43 +0000473 WCHAR buf[MAX_PATH];
474 int updated = FALSE;
475 static int enc_prev = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000476
K.Takatace3189d2023-02-15 19:13:43 +0000477 if (exe_name == NULL || exe_pathw == NULL || enc_prev != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000478 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100479 // store the name of the executable, may be used for $VIM
K.Takatace3189d2023-02-15 19:13:43 +0000480 GetModuleFileNameW(NULL, buf, MAX_PATH);
481 if (*buf != NUL)
482 {
483 if (enc_codepage == -1)
484 enc_codepage = GetACP();
K.Takataf741e3e2023-05-15 16:41:40 +0100485 vim_free(exe_name);
K.Takatace3189d2023-02-15 19:13:43 +0000486 exe_name = utf16_to_enc(buf, NULL);
487 enc_prev = enc_codepage;
488
489 WCHAR *wp = wcsrchr(buf, '\\');
490 if (wp != NULL)
491 *wp = NUL;
K.Takataf741e3e2023-05-15 16:41:40 +0100492 vim_free(exe_pathw);
K.Takatace3189d2023-02-15 19:13:43 +0000493 exe_pathw = _wcsdup(buf);
494 updated = TRUE;
495 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000496 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000497
K.Takatace3189d2023-02-15 19:13:43 +0000498 if (exe_pathw == NULL || !updated)
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000499 return;
500
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000501 // Append our starting directory to $PATH, so that when doing
502 // "!xxd" it's found in our starting directory. Needed because
503 // SearchPath() also looks there.
K.Takataf741e3e2023-05-15 16:41:40 +0100504 WCHAR *p = _wgetenv(L"PATH");
505 if (p == NULL || wcslen(p) + wcslen(exe_pathw) + 2 + 5 < MAX_ENV_PATH_LEN)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000506 {
K.Takataf741e3e2023-05-15 16:41:40 +0100507 wcscpy(temp, L"PATH=");
508
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000509 if (p == NULL || *p == NUL)
K.Takataf741e3e2023-05-15 16:41:40 +0100510 wcscat(temp, exe_pathw);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000511 else
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000512 {
K.Takataf741e3e2023-05-15 16:41:40 +0100513 wcscat(temp, p);
514
515 // Check if exe_path is already included in $PATH.
516 if (wcsstr(temp, exe_pathw) == NULL)
517 {
518 // Append ';' if $PATH doesn't end with it.
519 size_t len = wcslen(temp);
520 if (temp[len - 1] != L';')
521 wcscat(temp, L";");
522
523 wcscat(temp, exe_pathw);
524 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000525 }
K.Takataf741e3e2023-05-15 16:41:40 +0100526 _wputenv(temp);
527#ifdef libintl_wputenv
528 libintl_wputenv(temp);
529#endif
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000530 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000531}
532
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200533/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100534 * Unescape characters in "p" that appear in "escaped".
535 */
536 static void
537unescape_shellxquote(char_u *p, char_u *escaped)
538{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100539 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100540 int n;
541
542 while (*p != NUL)
543 {
544 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
545 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100546 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100547 p += n;
548 l -= n;
549 }
550}
551
552/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200553 * Load library "name".
554 */
555 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000556vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200557{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200558 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200559
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200560 // No need to load any library when registering OLE.
561 if (found_register_arg)
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000562 return NULL;
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200563
Bram Moolenaar0f873732019-12-05 20:28:46 +0100564 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
565 // vimLoadLib() recursively, which causes a stack overflow.
K.Takatace3189d2023-02-15 19:13:43 +0000566 if (exe_pathw == NULL)
K.Takataf741e3e2023-05-15 16:41:40 +0100567 {
K.Takatace3189d2023-02-15 19:13:43 +0000568 mch_get_exe_name();
K.Takataf741e3e2023-05-15 16:41:40 +0100569 if (exe_pathw == NULL)
570 return NULL;
571 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000572
573 WCHAR old_dirw[MAXPATHL];
574
575 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) == 0)
576 return NULL;
577
578 // Change directory to where the executable is, both to make
579 // sure we find a .dll there and to avoid looking for a .dll
580 // in the current directory.
K.Takatace3189d2023-02-15 19:13:43 +0000581 SetCurrentDirectoryW(exe_pathw);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000582 dll = LoadLibrary(name);
583 SetCurrentDirectoryW(old_dirw);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200584 return dll;
585}
586
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200587#if defined(VIMDLL) || defined(PROTO)
588/*
589 * Check if the current executable file is for the GUI subsystem.
590 */
591 int
592mch_is_gui_executable(void)
593{
594 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
595 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
596 PIMAGE_NT_HEADERS pPE;
597
598 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
599 return FALSE;
600 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
601 if (pPE->Signature != IMAGE_NT_SIGNATURE)
602 return FALSE;
603 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
604 return TRUE;
605 return FALSE;
606}
607#endif
608
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000609#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
610 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100611/*
612 * Get related information about 'funcname' which is imported by 'hInst'.
613 * If 'info' is 0, return the function address.
614 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000615 * If 'info' is 2, hook the function with 'ptr', and return the original
616 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100617 */
618 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000619get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
620 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100621{
622 PBYTE pImage = (PBYTE)hInst;
623 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
624 PIMAGE_NT_HEADERS pPE;
625 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100626 PIMAGE_THUNK_DATA pIAT; // Import Address Table
627 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100628 PIMAGE_IMPORT_BY_NAME pImpName;
629
630 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
631 return NULL;
632 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
633 if (pPE->Signature != IMAGE_NT_SIGNATURE)
634 return NULL;
635 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
636 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
637 .VirtualAddress);
638 for (; pImpDesc->FirstThunk; ++pImpDesc)
639 {
640 if (!pImpDesc->OriginalFirstThunk)
641 continue;
642 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
643 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
644 for (; pIAT->u1.Function; ++pIAT, ++pINT)
645 {
646 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
647 continue;
648 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
649 + (UINT_PTR)(pINT->u1.AddressOfData));
650 if (strcmp((char *)pImpName->Name, funcname) == 0)
651 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000652 void *original;
653 DWORD old, new = PAGE_READWRITE;
654
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100655 switch (info)
656 {
657 case 0:
658 return (void *)pIAT->u1.Function;
659 case 1:
660 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000661 case 2:
662 original = (void *)pIAT->u1.Function;
663 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
664 new, &old);
665 pIAT->u1.Function = (UINT_PTR)ptr;
666 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
667 old, &new);
668 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100669 default:
670 return NULL;
671 }
672 }
673 }
674 }
675 return NULL;
676}
677
678/*
679 * Get the module handle which 'funcname' in 'hInst' is imported from.
680 */
681 HINSTANCE
682find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
683{
684 char *modulename;
685
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000686 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100687 if (modulename != NULL)
688 return GetModuleHandleA(modulename);
689 return NULL;
690}
691
692/*
693 * Get the address of 'funcname' which is imported by 'hInst' DLL.
694 */
695 void *
696get_dll_import_func(HINSTANCE hInst, const char *funcname)
697{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000698 return get_imported_func_info(hInst, funcname, 0, NULL);
699}
700
701/*
702 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
703 * and return the original function address.
704 */
705 void *
706hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
707{
708 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100709}
710#endif
711
Bram Moolenaar071d4272004-06-13 20:20:40 +0000712#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
713# ifndef GETTEXT_DLL
714# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200715# define GETTEXT_DLL_ALT1 "libintl-8.dll"
716# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000717# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100718// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000719static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200720static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000721static char *null_libintl_textdomain(const char *);
722static char *null_libintl_bindtextdomain(const char *, const char *);
723static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100724static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000725
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200726static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000727char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200728char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
729 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000730char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
731char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000732 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000733char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
734 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100735int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000736
737 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100738dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000739{
740 int i;
741 static struct
742 {
743 char *name;
744 FARPROC *ptr;
745 } libintl_entry[] =
746 {
747 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200748 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000749 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
750 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
751 {NULL, NULL}
752 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100753 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000754
Bram Moolenaar7554c542018-10-06 15:03:15 +0200755 // No need to initialize twice.
756 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000757 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200758 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100759 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100760# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100761 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200762 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100763# endif
764# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200765 if (!hLibintlDLL)
766 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100767# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100768 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000769 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200770 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000771 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200772 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000773 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200774 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000775 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200776 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000777 }
778 for (i = 0; libintl_entry[i].name != NULL
779 && libintl_entry[i].ptr != NULL; ++i)
780 {
K.Takata54119102022-02-03 13:33:03 +0000781 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000782 libintl_entry[i].name)) == NULL)
783 {
784 dyn_libintl_end();
785 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000786 {
787 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000788 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000789 verbose_leave();
790 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000791 return 0;
792 }
793 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000794
Bram Moolenaar0f873732019-12-05 20:28:46 +0100795 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100796 dyn_libintl_bind_textdomain_codeset = (char *(*)(const char *, const char *))
797 GetProcAddress(hLibintlDLL, "bind_textdomain_codeset");
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000798 if (dyn_libintl_bind_textdomain_codeset == NULL)
799 dyn_libintl_bind_textdomain_codeset =
800 null_libintl_bind_textdomain_codeset;
801
Bram Moolenaar0f873732019-12-05 20:28:46 +0100802 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100803 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
804 if (hmsvcrt != NULL)
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100805 dyn_libintl_wputenv = (int (*)(const wchar_t *))
806 GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100807 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
808 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100809
Bram Moolenaar071d4272004-06-13 20:20:40 +0000810 return 1;
811}
812
813 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100814dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000815{
816 if (hLibintlDLL)
817 FreeLibrary(hLibintlDLL);
818 hLibintlDLL = NULL;
819 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200820 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000821 dyn_libintl_textdomain = null_libintl_textdomain;
822 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000823 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100824 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000825}
826
827 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000828null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000829{
830 return (char*)msgid;
831}
832
833 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200834null_libintl_ngettext(
835 const char *msgid,
836 const char *msgid_plural,
837 unsigned long n)
838{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200839 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200840}
841
Bram Moolenaaree695f72016-08-03 22:08:45 +0200842 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100843null_libintl_bindtextdomain(
844 const char *domainname UNUSED,
845 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000846{
847 return NULL;
848}
849
850 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100851null_libintl_bind_textdomain_codeset(
852 const char *domainname UNUSED,
853 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000854{
855 return NULL;
856}
857
858 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100859null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000860{
861 return NULL;
862}
863
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200864 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100865null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100866{
867 return 0;
868}
869
Bram Moolenaar0f873732019-12-05 20:28:46 +0100870#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000871
Bram Moolenaar0f873732019-12-05 20:28:46 +0100872// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000873
874#ifndef VER_PLATFORM_WIN32_WINDOWS
875# define VER_PLATFORM_WIN32_WINDOWS 1
876#endif
877
Bram Moolenaar071d4272004-06-13 20:20:40 +0000878#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100879# ifndef PROTO
880# include <aclapi.h>
881# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200882# ifndef PROTECTED_DACL_SECURITY_INFORMATION
883# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
884# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000885#endif
886
Bram Moolenaar27515922013-06-29 15:36:26 +0200887#ifdef HAVE_ACL
888/*
889 * Enables or disables the specified privilege.
890 */
891 static BOOL
892win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
893{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100894 BOOL bResult;
895 LUID luid;
896 HANDLE hToken;
897 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200898
899 if (!OpenProcessToken(GetCurrentProcess(),
900 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
901 return FALSE;
902
903 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
904 {
905 CloseHandle(hToken);
906 return FALSE;
907 }
908
Bram Moolenaar45500912014-07-09 20:51:07 +0200909 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200910 tokenPrivileges.Privileges[0].Luid = luid;
911 tokenPrivileges.Privileges[0].Attributes = bEnable ?
912 SE_PRIVILEGE_ENABLED : 0;
913
914 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
915 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
916
917 CloseHandle(hToken);
918
919 return bResult && GetLastError() == ERROR_SUCCESS;
920}
921#endif
922
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100923#ifdef _MSC_VER
924// Suppress the deprecation warning for using GetVersionEx().
925// It is needed for implementing "windowsversion()".
926# pragma warning(push)
927# pragma warning(disable: 4996)
928#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000929/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200930 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000931 */
932 void
933PlatformId(void)
934{
935 static int done = FALSE;
936
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000937 if (done)
938 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000939
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000940 OSVERSIONINFO ovi;
941
942 ovi.dwOSVersionInfoSize = sizeof(ovi);
943 GetVersionEx(&ovi);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000944
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200945#ifdef FEAT_EVAL
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000946 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
947 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200948#endif
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000949 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
950 || ovi.dwMajorVersion > 6)
951 win8_or_later = TRUE;
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100952
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000953 if ((ovi.dwMajorVersion == 10 && ovi.dwBuildNumber >= 19045)
954 || ovi.dwMajorVersion > 10)
955 win10_22H2_or_later = TRUE;
Christopher Plewright1140b512022-11-12 18:46:05 +0000956
Bram Moolenaar071d4272004-06-13 20:20:40 +0000957#ifdef HAVE_ACL
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000958 // Enable privilege for getting or setting SACLs.
959 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000960#endif
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000961 done = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000962}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100963#ifdef _MSC_VER
964# pragma warning(pop)
965#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000966
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200967#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000968
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100969# define SHIFT (SHIFT_PRESSED)
970# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
971# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
972# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000973
974
Bram Moolenaar0f873732019-12-05 20:28:46 +0100975// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
976// We map function keys to their ANSI terminal equivalents, as produced
977// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
978// ANSI key with a value >= '\300' is nonstandard, but provided anyway
979// so that the user can have access to all SHIFT-, CTRL-, and ALT-
980// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000981
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000982static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000983{
984 WORD wVirtKey;
985 BOOL fAnsiKey;
986 int chAlone;
987 int chShift;
988 int chCtrl;
989 int chAlt;
990} VirtKeyMap[] =
991{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200992// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000993 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
994
995 { VK_F1, TRUE, ';', 'T', '^', 'h', },
996 { VK_F2, TRUE, '<', 'U', '_', 'i', },
997 { VK_F3, TRUE, '=', 'V', '`', 'j', },
998 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
999 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
1000 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
1001 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
1002 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
1003 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
1004 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001005 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
1006 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001007
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001008 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
1009 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
1010 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
1011 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
1012 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
1013 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
1014 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
1015 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
1016 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
1017 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001018 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +00001019
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001020 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +00001021
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001022# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001023 // Most people don't have F13-F20, but what the hell...
1024 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
1025 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
1026 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
1027 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
1028 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
1029 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
1030 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
1031 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001032# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001033 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
1034 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
1035 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
1036 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001037
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001038 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
1039 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
1040 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
1041 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
1042 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
1043 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
1044 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
1045 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
1046 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
1047 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001048 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001049};
1050
1051
Bram Moolenaar0f873732019-12-05 20:28:46 +01001052/*
1053 * The return code indicates key code size.
1054 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001055 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001056win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001057 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001058{
1059 UINT uMods = pker->dwControlKeyState;
1060 static int s_iIsDead = 0;
1061 static WORD awAnsiCode[2];
1062 static BYTE abKeystate[256];
1063
1064
1065 if (s_iIsDead == 2)
1066 {
K.Takata972db232022-02-04 10:45:38 +00001067 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001068 s_iIsDead = 0;
1069 return 1;
1070 }
1071
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001072 // check if it already has a valid unicode character.
Christopher Plewright566f76e2023-01-10 13:43:04 +00001073 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001074 return 1;
1075
Bram Moolenaara80faa82020-04-12 19:37:17 +02001076 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001077
Bram Moolenaar0f873732019-12-05 20:28:46 +01001078 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001079 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001080
1081 if (uMods & SHIFT_PRESSED)
1082 abKeystate[VK_SHIFT] = 0x80;
1083 if (uMods & CAPSLOCK_ON)
1084 abKeystate[VK_CAPITAL] = 1;
1085
1086 if ((uMods & ALT_GR) == ALT_GR)
1087 {
1088 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1089 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1090 }
1091
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001092 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1093 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001094
1095 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001096 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001097
1098 return s_iIsDead;
1099}
1100
Bram Moolenaar071d4272004-06-13 20:20:40 +00001101static BOOL g_fJustGotFocus = FALSE;
1102
1103/*
1104 * Decode a KEY_EVENT into one or two keystrokes
1105 */
1106 static BOOL
1107decode_key_event(
1108 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001109 WCHAR *pch,
1110 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001111 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001112 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001113{
1114 int i;
1115 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1116
1117 *pch = *pch2 = NUL;
1118 g_fJustGotFocus = FALSE;
1119
Bram Moolenaar0f873732019-12-05 20:28:46 +01001120 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001121 if (!pker->bKeyDown)
1122 return FALSE;
1123
Bram Moolenaar0f873732019-12-05 20:28:46 +01001124 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001125 switch (pker->wVirtualKeyCode)
1126 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001127 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001128 case VK_SHIFT:
1129 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001130 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001131 return FALSE;
1132
1133 default:
1134 break;
1135 }
1136
Bram Moolenaar0f873732019-12-05 20:28:46 +01001137 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001138 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1139 {
1140 *pch = K_NUL;
1141 *pch2 = '\017';
1142 return TRUE;
1143 }
1144
K.Takataeeec2542021-06-02 13:28:16 +02001145 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001146 {
1147 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1148 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001149 *pch = VirtKeyMap[i].chAlone;
1150 if ((nModifs & SHIFT) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001151 *pch = VirtKeyMap[i].chShift;
1152 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1153 *pch = VirtKeyMap[i].chCtrl;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001154 else if ((nModifs & ALT) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001155 *pch = VirtKeyMap[i].chAlt;
1156
1157 if (*pch != 0)
1158 {
1159 if (VirtKeyMap[i].fAnsiKey)
1160 {
1161 *pch2 = *pch;
1162 *pch = K_NUL;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001163 if (pmodifiers)
1164 {
1165 if (pker->wVirtualKeyCode >= VK_F1
1166 && pker->wVirtualKeyCode <= VK_F12)
1167 {
1168 if ((nModifs & ALT) != 0)
1169 {
1170 *pmodifiers |= MOD_MASK_ALT;
1171 if ((nModifs & SHIFT) == 0)
1172 *pch2 = VirtKeyMap[i].chAlone;
1173 }
1174 if ((nModifs & CTRL) != 0)
1175 {
1176 *pmodifiers |= MOD_MASK_CTRL;
1177 if ((nModifs & SHIFT) == 0)
1178 *pch2 = VirtKeyMap[i].chAlone;
1179 }
1180 }
1181 else if (pker->wVirtualKeyCode >= VK_END
1182 && pker->wVirtualKeyCode <= VK_DOWN)
1183 {
Christopher Plewright566f76e2023-01-10 13:43:04 +00001184 // (0x23 - 0x28): VK_END, VK_HOME,
1185 // VK_LEFT, VK_UP, VK_RIGHT, VK_DOWN
1186
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001187 *pmodifiers = 0;
1188 *pch2 = VirtKeyMap[i].chAlone;
1189 if ((nModifs & SHIFT) != 0
1190 && (nModifs & ~SHIFT) == 0)
1191 {
1192 *pch2 = VirtKeyMap[i].chShift;
1193 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001194 if ((nModifs & CTRL) != 0
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001195 && (nModifs & ~CTRL) == 0)
1196 {
1197 *pch2 = VirtKeyMap[i].chCtrl;
1198 if (pker->wVirtualKeyCode == VK_UP
1199 || pker->wVirtualKeyCode == VK_DOWN)
1200 {
1201 *pmodifiers |= MOD_MASK_CTRL;
1202 *pch2 = VirtKeyMap[i].chAlone;
1203 }
1204 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001205 if ((nModifs & SHIFT) != 0
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001206 && (nModifs & CTRL) != 0)
1207 {
1208 *pmodifiers |= MOD_MASK_CTRL;
1209 *pch2 = VirtKeyMap[i].chShift;
1210 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001211 if ((nModifs & ALT) != 0)
1212 {
1213 *pch2 = VirtKeyMap[i].chAlt;
1214 *pmodifiers |= MOD_MASK_ALT;
1215 if ((nModifs & ~ALT) == 0)
1216 {
1217 *pch2 = VirtKeyMap[i].chAlone;
1218 }
1219 else if ((nModifs & SHIFT) != 0)
1220 {
1221 *pch2 = VirtKeyMap[i].chShift;
1222 }
1223 else if ((nModifs & CTRL) != 0)
1224 {
1225 if (pker->wVirtualKeyCode == VK_UP
1226 || pker->wVirtualKeyCode == VK_DOWN)
1227 {
1228 *pmodifiers |= MOD_MASK_CTRL;
1229 *pch2 = VirtKeyMap[i].chAlone;
1230 }
1231 else
1232 {
1233 *pch2 = VirtKeyMap[i].chCtrl;
1234 }
1235 }
1236 }
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001237 }
1238 else
1239 {
1240 *pch2 = VirtKeyMap[i].chAlone;
1241 if ((nModifs & SHIFT) != 0)
1242 *pmodifiers |= MOD_MASK_SHIFT;
1243 if ((nModifs & CTRL) != 0)
1244 *pmodifiers |= MOD_MASK_CTRL;
1245 if ((nModifs & ALT) != 0)
1246 *pmodifiers |= MOD_MASK_ALT;
1247 }
1248 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001249 }
1250
1251 return TRUE;
1252 }
1253 }
1254 }
1255
1256 i = win32_kbd_patch_key(pker);
1257
1258 if (i < 0)
1259 *pch = NUL;
1260 else
1261 {
K.Takata972db232022-02-04 10:45:38 +00001262 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001263
1264 if (pmodifiers != NULL)
1265 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001266 // Pass on the ALT key as a modifier, but only when not combined
1267 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001268 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1269 *pmodifiers |= MOD_MASK_ALT;
1270
Bram Moolenaar0f873732019-12-05 20:28:46 +01001271 // Pass on SHIFT only for special keys, because we don't know when
1272 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001273 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1274 *pmodifiers |= MOD_MASK_SHIFT;
1275
Bram Moolenaar0f873732019-12-05 20:28:46 +01001276 // Pass on CTRL only for non-special keys, because we don't know
1277 // when it's already included with the character. And not when
1278 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001279 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1280 && *pch >= 0x20 && *pch < 0x80)
1281 *pmodifiers |= MOD_MASK_CTRL;
1282 }
1283 }
1284
1285 return (*pch != NUL);
1286}
1287
Christopher Plewright20b795e2022-12-20 20:01:58 +00001288# if defined(FEAT_EVAL)
1289 static int
1290encode_key_event(dict_T *args, INPUT_RECORD *ir)
1291{
1292 static int s_dwMods = 0;
1293
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001294 char_u *action = dict_get_string(args, "event", TRUE);
1295 if (action && (STRICMP(action, "keydown") == 0
1296 || STRICMP(action, "keyup") == 0))
Christopher Plewright20b795e2022-12-20 20:01:58 +00001297 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001298 BOOL isKeyDown = STRICMP(action, "keydown") == 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001299 WORD vkCode = dict_get_number_def(args, "keycode", 0);
1300 if (vkCode <= 0 || vkCode >= 0xFF)
1301 {
1302 semsg(_(e_invalid_argument_nr), (long)vkCode);
1303 return FALSE;
1304 }
1305
1306 ir->EventType = KEY_EVENT;
1307 KEY_EVENT_RECORD ker;
1308 ZeroMemory(&ker, sizeof(ker));
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001309 ker.bKeyDown = isKeyDown;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001310 ker.wRepeatCount = 1;
1311 ker.wVirtualScanCode = 0;
1312 ker.dwControlKeyState = 0;
1313 int mods = (int)dict_get_number(args, "modifiers");
1314 // Encode the win32 console key modifiers from Vim keyboard modifiers.
1315 if (mods)
1316 {
1317 // If "modifiers" is explicitly set in the args, then we reset any
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00001318 // remembered modifier key state that may have been set from
1319 // earlier mod-key-down events, even if they are not yet unset by
1320 // earlier mod-key-up events.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001321 s_dwMods = 0;
1322 if (mods & MOD_MASK_SHIFT)
1323 ker.dwControlKeyState |= SHIFT_PRESSED;
1324 if (mods & MOD_MASK_CTRL)
1325 ker.dwControlKeyState |= LEFT_CTRL_PRESSED;
1326 if (mods & MOD_MASK_ALT)
1327 ker.dwControlKeyState |= LEFT_ALT_PRESSED;
1328 }
1329
1330 if (vkCode == VK_LSHIFT || vkCode == VK_RSHIFT || vkCode == VK_SHIFT)
1331 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001332 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001333 s_dwMods |= SHIFT_PRESSED;
1334 else
1335 s_dwMods &= ~SHIFT_PRESSED;
1336 }
1337 else if (vkCode == VK_LCONTROL || vkCode == VK_CONTROL)
1338 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001339 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001340 s_dwMods |= LEFT_CTRL_PRESSED;
1341 else
1342 s_dwMods &= ~LEFT_CTRL_PRESSED;
1343 }
1344 else if (vkCode == VK_RCONTROL)
1345 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001346 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001347 s_dwMods |= RIGHT_CTRL_PRESSED;
1348 else
1349 s_dwMods &= ~RIGHT_CTRL_PRESSED;
1350 }
1351 else if (vkCode == VK_LMENU || vkCode == VK_MENU)
1352 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001353 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001354 s_dwMods |= LEFT_ALT_PRESSED;
1355 else
1356 s_dwMods &= ~LEFT_ALT_PRESSED;
1357 }
1358 else if (vkCode == VK_RMENU)
1359 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001360 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001361 s_dwMods |= RIGHT_ALT_PRESSED;
1362 else
1363 s_dwMods &= ~RIGHT_ALT_PRESSED;
1364 }
1365 ker.dwControlKeyState |= s_dwMods;
1366 ker.wVirtualKeyCode = vkCode;
Christopher Plewright566f76e2023-01-10 13:43:04 +00001367 ker.uChar.UnicodeChar = 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001368 ir->Event.KeyEvent = ker;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001369 vim_free(action);
Christopher Plewright20b795e2022-12-20 20:01:58 +00001370 }
1371 else
1372 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001373 if (action == NULL)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001374 {
1375 semsg(_(e_missing_argument_str), "event");
1376 }
1377 else
1378 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001379 semsg(_(e_invalid_value_for_argument_str_str), "event", action);
1380 vim_free(action);
Christopher Plewright20b795e2022-12-20 20:01:58 +00001381 }
1382 return FALSE;
1383 }
1384 return TRUE;
1385}
1386# endif // FEAT_EVAL
1387#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00001388
1389
Bram Moolenaar071d4272004-06-13 20:20:40 +00001390/*
1391 * For the GUI the mouse handling is in gui_w32.c.
1392 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001393#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001394 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001395mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001396{
1397}
Christopher Plewright20b795e2022-12-20 20:01:58 +00001398#else // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar0f873732019-12-05 20:28:46 +01001399static int g_fMouseAvail = FALSE; // mouse present
1400static int g_fMouseActive = FALSE; // mouse enabled
1401static int g_nMouseClick = -1; // mouse status
1402static int g_xMouse; // mouse x coordinate
1403static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001404static DWORD g_cmodein = 0; // Original console input mode
1405static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001406
1407/*
1408 * Enable or disable mouse input
1409 */
1410 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001411mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001412{
1413 DWORD cmodein;
1414
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001415# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001416 if (gui.in_use)
1417 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001418# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001419 if (!g_fMouseAvail)
1420 return;
1421
1422 g_fMouseActive = on;
1423 GetConsoleMode(g_hConIn, &cmodein);
1424
1425 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001426 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001427 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001428 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1429 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001430 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001431 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001432 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001433 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1434 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001435
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001436 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001437}
1438
Bram Moolenaar157d8132018-03-06 17:09:20 +01001439
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001440# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001441/*
1442 * Called when 'balloonevalterm' changed.
1443 */
1444 void
1445mch_bevalterm_changed(void)
1446{
1447 mch_setmouse(g_fMouseActive);
1448}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001449# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001450
Christopher Plewright2a46f812022-10-16 19:47:45 +01001451/*
1452 * Win32 console mouse scroll event handler.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001453 * Console version of the _OnMouseWheel() function in gui_w32.c
Christopher Plewright2a46f812022-10-16 19:47:45 +01001454 *
1455 * This encodes the mouse scroll direction and keyboard modifiers into
1456 * g_nMouseClick, and the mouse position into g_xMouse and g_yMouse
1457 *
1458 * The direction of the scroll is decoded from two fields of the win32 console
1459 * mouse event record;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001460 * 1. The orientation - vertical or horizontal flag - from dwEventFlags
Christopher Plewright2a46f812022-10-16 19:47:45 +01001461 * 2. The sign - positive or negative (aka delta flag) - from dwButtonState
1462 *
Christopher Plewright20b795e2022-12-20 20:01:58 +00001463 * When scroll orientation is HORIZONTAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001464 * - If the high word of the dwButtonState member contains a positive
1465 * value, the wheel was rotated to the right.
1466 * - Otherwise, the wheel was rotated to the left.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001467 * When scroll orientation is VERTICAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001468 * - If the high word of the dwButtonState member contains a positive value,
1469 * the wheel was rotated forward, away from the user.
1470 * - Otherwise, the wheel was rotated backward, toward the user.
1471 */
1472 static void
1473decode_mouse_wheel(MOUSE_EVENT_RECORD *pmer)
1474{
Christopher Plewright2a46f812022-10-16 19:47:45 +01001475 int horizontal = (pmer->dwEventFlags == MOUSE_HWHEELED);
1476 int zDelta = pmer->dwButtonState;
1477
1478 g_xMouse = pmer->dwMousePosition.X;
1479 g_yMouse = pmer->dwMousePosition.Y;
1480
K.Takata161b6ac2022-11-14 15:31:07 +00001481# ifdef FEAT_PROP_POPUP
Christopher Plewright605d02a2022-10-19 11:54:46 +01001482 int lcol = g_xMouse;
1483 int lrow = g_yMouse;
Christopher Plewright38804d62022-11-09 23:55:52 +00001484 win_T *wp = mouse_find_win(&lrow, &lcol, FIND_POPUP);
Christopher Plewright2a46f812022-10-16 19:47:45 +01001485 if (wp != NULL && popup_is_popup(wp))
1486 {
1487 g_nMouseClick = -1;
1488 cmdarg_T cap;
1489 oparg_T oa;
1490 CLEAR_FIELD(cap);
1491 clear_oparg(&oa);
1492 cap.oap = &oa;
1493 if (horizontal)
1494 {
1495 cap.arg = zDelta < 0 ? MSCR_LEFT : MSCR_RIGHT;
1496 cap.cmdchar = zDelta < 0 ? K_MOUSELEFT : K_MOUSERIGHT;
1497 }
1498 else
1499 {
1500 cap.cmdchar = zDelta < 0 ? K_MOUSEUP : K_MOUSEDOWN;
1501 cap.arg = zDelta < 0 ? MSCR_UP : MSCR_DOWN;
1502 }
1503
1504 // Mouse hovers over popup window, scroll it if possible.
1505 mouse_row = wp->w_winrow;
1506 mouse_col = wp->w_wincol;
1507 nv_mousescroll(&cap);
1508 update_screen(0);
1509 setcursor();
1510 out_flush();
1511 return;
1512 }
K.Takata161b6ac2022-11-14 15:31:07 +00001513# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01001514 mouse_col = g_xMouse;
1515 mouse_row = g_yMouse;
1516
1517 char_u modifiers = 0;
1518 char_u direction = 0;
1519
1520 // Decode the direction into an event that Vim can process
1521 if (horizontal)
1522 direction = zDelta >= 0 ? KE_MOUSELEFT : KE_MOUSERIGHT;
1523 else
1524 direction = zDelta >= 0 ? KE_MOUSEDOWN : KE_MOUSEUP;
1525
dundargocc57b5bc2022-11-02 13:30:51 +00001526 // Decode the win32 console key modifiers into Vim mouse modifiers.
Christopher Plewright2a46f812022-10-16 19:47:45 +01001527 if (pmer->dwControlKeyState & SHIFT_PRESSED)
Christopher Plewright605d02a2022-10-19 11:54:46 +01001528 modifiers |= MOD_MASK_SHIFT; // MOUSE_SHIFT;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001529 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
Christopher Plewright605d02a2022-10-19 11:54:46 +01001530 modifiers |= MOD_MASK_CTRL; // MOUSE_CTRL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001531 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1532 modifiers |= MOD_MASK_ALT; // MOUSE_ALT;
1533
1534 // add (bitwise or) the scroll direction and the key modifier chars
1535 // together.
1536 g_nMouseClick = ((direction << 8) | modifiers);
1537
1538 return;
1539}
1540
Bram Moolenaar071d4272004-06-13 20:20:40 +00001541/*
1542 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1543 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1544 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1545 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1546 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1547 * and we return the mouse position in g_xMouse and g_yMouse.
1548 *
1549 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1550 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1551 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1552 *
1553 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1554 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1555 *
1556 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1557 * moves, even if it stays within the same character cell. We ignore
1558 * all MOUSE_MOVED messages if the position hasn't really changed, and
1559 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1560 * we're only interested in MOUSE_DRAG).
1561 *
1562 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1563 * 2-button mouses by pressing the left & right buttons simultaneously.
1564 * In practice, it's almost impossible to click both at the same time,
1565 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1566 * in such cases, if the user is clicking quickly.
1567 */
1568 static BOOL
1569decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001570 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001571{
1572 static int s_nOldButton = -1;
1573 static int s_nOldMouseClick = -1;
1574 static int s_xOldMouse = -1;
1575 static int s_yOldMouse = -1;
1576 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001577# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001578 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001579# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001580 static int s_cClicks = 1;
1581 static BOOL s_fReleased = TRUE;
1582 static DWORD s_dwLastClickTime = 0;
1583 static BOOL s_fNextIsMiddle = FALSE;
1584
Bram Moolenaar0f873732019-12-05 20:28:46 +01001585 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001586
1587 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1588 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1589 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1590 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1591
1592 int nButton;
1593
1594 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1595 cButtons = 2;
1596
1597 if (!g_fMouseAvail || !g_fMouseActive)
1598 {
1599 g_nMouseClick = -1;
1600 return FALSE;
1601 }
1602
Bram Moolenaar0f873732019-12-05 20:28:46 +01001603 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001604 if (g_fJustGotFocus)
1605 {
1606 g_fJustGotFocus = FALSE;
1607 return FALSE;
1608 }
1609
Christopher Plewright605d02a2022-10-19 11:54:46 +01001610 // If there is an unprocessed mouse click drop this one.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001611 if (g_nMouseClick != -1)
1612 return TRUE;
Christopher Plewright605d02a2022-10-19 11:54:46 +01001613
Christopher Plewright2a46f812022-10-16 19:47:45 +01001614 if (pmer->dwEventFlags == MOUSE_WHEELED
1615 || pmer->dwEventFlags == MOUSE_HWHEELED)
1616 {
1617 decode_mouse_wheel(pmer);
1618 return TRUE; // we now should have a mouse scroll in g_nMouseClick
1619 }
Christopher Plewright605d02a2022-10-19 11:54:46 +01001620
Bram Moolenaar071d4272004-06-13 20:20:40 +00001621 nButton = -1;
1622 g_xMouse = pmer->dwMousePosition.X;
1623 g_yMouse = pmer->dwMousePosition.Y;
1624
1625 if (pmer->dwEventFlags == MOUSE_MOVED)
1626 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001627 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1628 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001629 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1630 return FALSE;
1631 }
1632
Bram Moolenaar0f873732019-12-05 20:28:46 +01001633 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001634 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1635 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001636 nButton = MOUSE_RELEASE;
1637
Bram Moolenaar0f873732019-12-05 20:28:46 +01001638 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001639 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001640 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001641# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001642 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001643 if (p_bevalterm)
1644 nButton = MOUSE_DRAG;
1645 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001646# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001647 return FALSE;
1648 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001649
Bram Moolenaar071d4272004-06-13 20:20:40 +00001650 s_fReleased = TRUE;
1651 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001652 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001653 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001654 // on a 2-button mouse, hold down left and right buttons
1655 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001656
1657 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1658 {
1659 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1660
Bram Moolenaar0f873732019-12-05 20:28:46 +01001661 // if either left or right button only is pressed, see if the
1662 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001663 if (dwLR == LEFT || dwLR == RIGHT)
1664 {
1665 for (;;)
1666 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001667 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001668 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1669 != WAIT_OBJECT_0)
1670 break;
1671 else
1672 {
1673 DWORD cRecords = 0;
1674 INPUT_RECORD ir;
1675 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1676
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001677 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001678
1679 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1680 || !(pmer2->dwButtonState & LEFT_RIGHT))
1681 break;
1682 else
1683 {
1684 if (pmer2->dwEventFlags != MOUSE_MOVED)
1685 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001686 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001687
1688 return decode_mouse_event(pmer2);
1689 }
1690 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1691 s_yOldMouse == pmer2->dwMousePosition.Y)
1692 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001693 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001694 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001695
Bram Moolenaar0f873732019-12-05 20:28:46 +01001696 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001697 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001698
1699 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1700 break;
1701 }
1702 else
1703 break;
1704 }
1705 }
1706 }
1707 }
1708 }
1709
1710 if (s_fNextIsMiddle)
1711 {
1712 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1713 ? MOUSE_DRAG : MOUSE_MIDDLE;
1714 s_fNextIsMiddle = FALSE;
1715 }
1716 else if (cButtons == 2 &&
1717 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1718 {
1719 nButton = MOUSE_MIDDLE;
1720
1721 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1722 {
1723 s_fNextIsMiddle = TRUE;
1724 nButton = MOUSE_RELEASE;
1725 }
1726 }
1727 else if ((pmer->dwButtonState & LEFT) == LEFT)
1728 nButton = MOUSE_LEFT;
1729 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1730 nButton = MOUSE_MIDDLE;
1731 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1732 nButton = MOUSE_RIGHT;
1733
1734 if (! s_fReleased && ! s_fNextIsMiddle
1735 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1736 return FALSE;
1737
1738 s_fReleased = s_fNextIsMiddle;
1739 }
1740
1741 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1742 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001743 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001744 if (nButton != -1 && nButton != MOUSE_RELEASE)
1745 {
1746 DWORD dwCurrentTime = GetTickCount();
1747
1748 if (s_xOldMouse != g_xMouse
1749 || s_yOldMouse != g_yMouse
1750 || s_nOldButton != nButton
1751 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001752# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001753 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001754# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001755 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1756 {
1757 s_cClicks = 1;
1758 }
1759 else if (++s_cClicks > 4)
1760 {
1761 s_cClicks = 1;
1762 }
1763
1764 s_dwLastClickTime = dwCurrentTime;
1765 }
1766 }
1767 else if (pmer->dwEventFlags == MOUSE_MOVED)
1768 {
1769 if (nButton != -1 && nButton != MOUSE_RELEASE)
1770 nButton = MOUSE_DRAG;
1771
1772 s_cClicks = 1;
1773 }
1774
1775 if (nButton == -1)
1776 return FALSE;
1777
1778 if (nButton != MOUSE_RELEASE)
1779 s_nOldButton = nButton;
1780
1781 g_nMouseClick = nButton;
1782
1783 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1784 g_nMouseClick |= MOUSE_SHIFT;
1785 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1786 g_nMouseClick |= MOUSE_CTRL;
1787 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1788 g_nMouseClick |= MOUSE_ALT;
1789
1790 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1791 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1792
Bram Moolenaar0f873732019-12-05 20:28:46 +01001793 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001794 if (s_xOldMouse == g_xMouse
1795 && s_yOldMouse == g_yMouse
1796 && s_nOldMouseClick == g_nMouseClick)
1797 {
1798 g_nMouseClick = -1;
1799 return FALSE;
1800 }
1801
1802 s_xOldMouse = g_xMouse;
1803 s_yOldMouse = g_yMouse;
1804 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001805# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001806 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001807# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001808 s_nOldMouseClick = g_nMouseClick;
1809
1810 return TRUE;
1811}
1812
Christopher Plewright20b795e2022-12-20 20:01:58 +00001813# ifdef FEAT_EVAL
1814 static int
1815encode_mouse_event(dict_T *args, INPUT_RECORD *ir)
1816{
1817 int button;
1818 int row;
1819 int col;
1820 int repeated_click;
Bram Moolenaar9b8a3652022-12-20 20:47:28 +00001821 int_u mods = 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001822 int move;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001823
Christopher Plewright20b795e2022-12-20 20:01:58 +00001824 if (!dict_has_key(args, "row") || !dict_has_key(args, "col"))
1825 return FALSE;
1826
1827 // Note: "move" is optional, requires fewer arguments
1828 move = (int)dict_get_bool(args, "move", FALSE);
1829 if (!move && (!dict_has_key(args, "button")
1830 || !dict_has_key(args, "multiclick")
1831 || !dict_has_key(args, "modifiers")))
1832 return FALSE;
1833
1834 row = (int)dict_get_number(args, "row") - 1;
1835 col = (int)dict_get_number(args, "col") - 1;
1836
1837 ir->EventType = MOUSE_EVENT;
1838 MOUSE_EVENT_RECORD mer;
1839 ZeroMemory(&mer, sizeof(mer));
1840 mer.dwMousePosition.X = col;
1841 mer.dwMousePosition.Y = row;
1842
1843 if (move)
1844 {
1845 mer.dwButtonState = 0;
1846 mer.dwEventFlags = MOUSE_MOVED;
1847 }
1848 else
1849 {
1850 button = (int)dict_get_number(args, "button");
1851 repeated_click = (int)dict_get_number(args, "multiclick");
1852 mods = (int)dict_get_number(args, "modifiers");
1853 // Reset the scroll values to known values.
1854 // XXX: Remove this when/if the scroll step is made configurable.
1855 mouse_set_hor_scroll_step(6);
1856 mouse_set_vert_scroll_step(3);
1857
1858 switch (button)
1859 {
1860 case MOUSE_LEFT:
1861 mer.dwButtonState = FROM_LEFT_1ST_BUTTON_PRESSED;
1862 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1863 break;
1864 case MOUSE_MIDDLE:
1865 mer.dwButtonState = FROM_LEFT_2ND_BUTTON_PRESSED;
1866 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1867 break;
1868 case MOUSE_RIGHT:
1869 mer.dwButtonState = RIGHTMOST_BUTTON_PRESSED;
1870 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1871 break;
1872 case MOUSE_RELEASE:
1873 // umm? Assume Left Release?
1874 mer.dwEventFlags = 0;
1875
1876 case MOUSE_MOVE:
1877 mer.dwButtonState = 0;
1878 mer.dwEventFlags = MOUSE_MOVED;
1879 break;
1880 case MOUSE_X1:
1881 mer.dwButtonState = FROM_LEFT_3RD_BUTTON_PRESSED;
1882 break;
1883 case MOUSE_X2:
1884 mer.dwButtonState = FROM_LEFT_4TH_BUTTON_PRESSED;
1885 break;
1886 case MOUSE_4: // KE_MOUSEDOWN;
1887 mer.dwButtonState = -1;
1888 mer.dwEventFlags = MOUSE_WHEELED;
1889 break;
1890 case MOUSE_5: // KE_MOUSEUP;
1891 mer.dwButtonState = +1;
1892 mer.dwEventFlags = MOUSE_WHEELED;
1893 break;
1894 case MOUSE_6: // KE_MOUSELEFT;
1895 mer.dwButtonState = -1;
1896 mer.dwEventFlags = MOUSE_HWHEELED;
1897 break;
1898 case MOUSE_7: // KE_MOUSERIGHT;
1899 mer.dwButtonState = +1;
1900 mer.dwEventFlags = MOUSE_HWHEELED;
1901 break;
1902 default:
1903 semsg(_(e_invalid_argument_str), "button");
1904 return FALSE;
1905 }
1906 }
1907
1908 mer.dwControlKeyState = 0;
1909 if (mods != 0)
1910 {
1911 // Encode the win32 console key modifiers from Vim MOUSE modifiers.
1912 if (mods & MOUSE_SHIFT)
1913 mer.dwControlKeyState |= SHIFT_PRESSED;
1914 if (mods & MOUSE_CTRL)
1915 mer.dwControlKeyState |= LEFT_CTRL_PRESSED;
1916 if (mods & MOUSE_ALT)
1917 mer.dwControlKeyState |= LEFT_ALT_PRESSED;
1918 }
1919 ir->Event.MouseEvent = mer;
1920 return TRUE;
1921}
1922# endif // FEAT_EVAL
1923
1924 static int
1925write_input_record_buffer(INPUT_RECORD* irEvents, int nLength)
1926{
1927 int nCount = 0;
1928 while (nCount < nLength)
1929 {
1930 input_record_buffer.length++;
1931 input_record_buffer_node_T *event_node =
1932 malloc(sizeof(input_record_buffer_node_T));
1933 event_node->ir = irEvents[nCount++];
1934 event_node->next = NULL;
1935 if (input_record_buffer.tail == NULL)
1936 {
1937 input_record_buffer.head = event_node;
1938 input_record_buffer.tail = event_node;
1939 }
1940 else
1941 {
1942 input_record_buffer.tail->next = event_node;
1943 input_record_buffer.tail = input_record_buffer.tail->next;
1944 }
1945 }
1946 return nCount;
1947}
1948
1949 static int
1950read_input_record_buffer(INPUT_RECORD* irEvents, int nMaxLength)
1951{
1952 int nCount = 0;
1953 while (nCount < nMaxLength && input_record_buffer.head != NULL)
1954 {
1955 input_record_buffer.length--;
1956 input_record_buffer_node_T *pop_head = input_record_buffer.head;
1957 irEvents[nCount++] = pop_head->ir;
1958 input_record_buffer.head = pop_head->next;
1959 vim_free(pop_head);
1960 if (input_record_buffer.length == 0)
1961 input_record_buffer.tail = NULL;
1962 }
1963 return nCount;
1964}
Christopher Plewright20b795e2022-12-20 20:01:58 +00001965#endif // !FEAT_GUI_MSWIN || VIMDLL
1966
1967#ifdef FEAT_EVAL
1968/*
1969 * The 'test_mswin_event' function is for testing Vim's low-level handling of
1970 * user input events. ie, this manages the encoding of INPUT_RECORD events
1971 * so that we have a way to test how Vim decodes INPUT_RECORD events in Windows
1972 * consoles.
1973 *
1974 * The 'test_mswin_event' function is based on 'test_gui_event'. In fact, when
1975 * the Windows GUI is running, the arguments; 'event' and 'args', are the same.
1976 * So, it acts as an alias for 'test_gui_event' for the Windows GUI.
1977 *
1978 * When the Windows console is running, the arguments; 'event' and 'args', are
1979 * a subset of what 'test_gui_event' handles, ie, only "key" and "mouse"
1980 * events are encoded as INPUT_RECORD events.
1981 *
1982 * Note: INPUT_RECORDs are only used by the Windows console, not the GUI. The
1983 * GUI sends MSG structs instead.
1984 */
1985 int
1986test_mswin_event(char_u *event, dict_T *args)
1987{
1988 int lpEventsWritten = 0;
1989
1990# if defined(VIMDLL) || defined(FEAT_GUI_MSWIN)
1991 if (gui.in_use)
1992 return test_gui_w32_sendevent(event, args);
1993# endif
1994
1995# if defined(VIMDLL) || !defined(FEAT_GUI_MSWIN)
1996
1997// Currently implemented event record types are; KEY_EVENT and MOUSE_EVENT
1998// Potentially could also implement: FOCUS_EVENT and WINDOW_BUFFER_SIZE_EVENT
1999// Maybe also: MENU_EVENT
2000
2001 INPUT_RECORD ir;
2002 BOOL input_encoded = FALSE;
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002003 BOOL execute = FALSE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00002004 if (STRCMP(event, "key") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002005 {
2006 execute = dict_get_bool(args, "execute", FALSE);
2007 if (dict_has_key(args, "event"))
2008 input_encoded = encode_key_event(args, &ir);
2009 else if (!execute)
2010 {
2011 semsg(_(e_missing_argument_str), "event");
2012 return FALSE;
2013 }
2014 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002015 else if (STRCMP(event, "mouse") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002016 {
2017 execute = TRUE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00002018 input_encoded = encode_mouse_event(args, &ir);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002019 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002020 else
2021 {
2022 semsg(_(e_invalid_value_for_argument_str_str), "event", event);
2023 return FALSE;
2024 }
2025
2026 // Ideally, WriteConsoleInput would be used to inject these low-level
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00002027 // events. But, this doesn't work well in the CI test environment. So
Christopher Plewright20b795e2022-12-20 20:01:58 +00002028 // implementing an input_record_buffer instead.
2029 if (input_encoded)
2030 lpEventsWritten = write_input_record_buffer(&ir, 1);
2031
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002032 // Set flags to execute the event, ie. like feedkeys mode X.
2033 if (execute)
2034 {
2035 int save_msg_scroll = msg_scroll;
2036 // Avoid a 1 second delay when the keys start Insert mode.
2037 msg_scroll = FALSE;
2038 ch_log(NULL, "test_mswin_event() executing");
Christopher Plewright20b795e2022-12-20 20:01:58 +00002039 exec_normal(TRUE, TRUE, TRUE);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002040 msg_scroll |= save_msg_scroll;
2041 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002042
2043# endif
2044 return lpEventsWritten;
2045}
2046#endif // FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002047
2048#ifdef MCH_CURSOR_SHAPE
2049/*
2050 * Set the shape of the cursor.
2051 * 'thickness' can be from 1 (thin) to 99 (block)
2052 */
2053 static void
2054mch_set_cursor_shape(int thickness)
2055{
Christopher Plewright38804d62022-11-09 23:55:52 +00002056 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01002057 {
2058 if (*T_CSI == NUL)
2059 {
2060 // If 't_SI' is not set, use the default cursor styles.
2061 if (thickness < 50)
2062 vtp_printf("\033[3 q"); // underline
2063 else
2064 vtp_printf("\033[0 q"); // default
2065 }
2066 }
2067 else
2068 {
2069 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
2070 ConsoleCursorInfo.dwSize = thickness;
2071 ConsoleCursorInfo.bVisible = s_cursor_visible;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002072
K.Takatadf5320c2022-09-01 13:20:16 +01002073 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
2074 if (s_cursor_visible)
2075 SetConsoleCursorPosition(g_hConOut, g_coord);
2076 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002077}
2078
2079 void
2080mch_update_cursor(void)
2081{
2082 int idx;
2083 int thickness;
2084
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002085# ifdef VIMDLL
2086 if (gui.in_use)
2087 return;
2088# endif
2089
Bram Moolenaar071d4272004-06-13 20:20:40 +00002090 /*
2091 * How the cursor is drawn depends on the current mode.
2092 */
2093 idx = get_shape_idx(FALSE);
2094
2095 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002096 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00002097 else
2098 thickness = shape_table[idx].percentage;
2099 mch_set_cursor_shape(thickness);
2100}
2101#endif
2102
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002103#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002104/*
2105 * Handle FOCUS_EVENT.
2106 */
2107 static void
2108handle_focus_event(INPUT_RECORD ir)
2109{
2110 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
2111 ui_focus_change((int)g_fJustGotFocus);
2112}
2113
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002114static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
2115
Bram Moolenaar071d4272004-06-13 20:20:40 +00002116/*
2117 * Wait until console input from keyboard or mouse is available,
2118 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002119 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002120 * Return TRUE if something is available FALSE if not.
2121 */
2122 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002123WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002124{
2125 DWORD dwNow = 0, dwEndTime = 0;
2126 INPUT_RECORD ir;
2127 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002128 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002129# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02002130 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002131# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002132
2133 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002134 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002135 dwEndTime = GetTickCount() + msec;
2136 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002137 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002138 dwEndTime = INFINITE;
2139
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002140 // We need to loop until the end of the time period, because
2141 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002142 for (;;)
2143 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002144 // Only process messages when waiting.
2145 if (msec != 0)
2146 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002147# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002148 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002149# endif
2150# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002151 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002152# endif
2153# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002154 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002155# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002156 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002157
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02002158 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002159# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002160 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002161# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002162 )
2163 return TRUE;
2164
2165 if (msec > 0)
2166 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002167 // If the specified wait time has passed, return. Beware that
2168 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002169 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02002170 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002171 break;
2172 }
2173 if (msec != 0)
2174 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00002175 DWORD dwWaitTime = dwEndTime - dwNow;
2176
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002177 // Don't wait for more than 11 msec to avoid dropping characters,
2178 // check channel while waiting for input and handle a callback from
2179 // 'balloonexpr'.
2180 if (dwWaitTime > 11)
2181 dwWaitTime = 11;
2182
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002183# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002184 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002185 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002186# endif
2187# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002188 // When waiting very briefly don't trigger timers.
2189 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002190 {
2191 long due_time;
2192
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002193 // Trigger timers and then get the time in msec until the next
2194 // one is due. Wait up to that time.
2195 due_time = check_due_timer();
2196 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002197 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002198 // timer may have used feedkeys().
2199 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002200 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002201 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
2202 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002203 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002204# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002205 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002206# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002207 // Wait for either an event on the console input or a
2208 // message in the client-server window.
2209 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
2210 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002211# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002212 wait_for_single_object(g_hConIn, dwWaitTime)
2213 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002214# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002215 )
2216 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002217 }
2218
2219 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002220 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002221
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002222# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02002223 // May have to redraw if the cursor ends up in the wrong place.
2224 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01002225 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002226 {
2227 CONSOLE_SCREEN_BUFFER_INFO csbi;
2228
2229 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2230 {
2231 if (csbi.dwCursorPosition.Y != msg_row)
2232 {
matveyte08795e2021-05-07 15:00:17 +02002233 // The screen is now messed up, must redraw the command
2234 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002235 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02002236 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002237 redrawcmd();
2238 }
2239 }
2240 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002241# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002242
2243 if (cRecords > 0)
2244 {
2245 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
2246 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002247# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01002248 // Windows IME sends two '\n's with only one 'ENTER'. First:
2249 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00002250 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002251 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
2252 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002253 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002254 continue;
2255 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002256# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002257 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
2258 NULL, FALSE))
2259 return TRUE;
2260 }
2261
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002262 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002263
2264 if (ir.EventType == FOCUS_EVENT)
2265 handle_focus_event(ir);
2266 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002267 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002268 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
2269
Bram Moolenaar36698e32019-12-11 22:57:40 +01002270 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002271 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002272 if (dwSize.X != Columns || dwSize.Y != Rows)
2273 {
2274 CONSOLE_SCREEN_BUFFER_INFO csbi;
2275 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01002276 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002277 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01002278 if (dwSize.X != Columns || dwSize.Y != Rows)
2279 {
2280 ResizeConBuf(g_hConOut, dwSize);
2281 shell_resized();
2282 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002283 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002284 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002285 else if (ir.EventType == MOUSE_EVENT
2286 && decode_mouse_event(&ir.Event.MouseEvent))
2287 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002288 }
2289 else if (msec == 0)
2290 break;
2291 }
2292
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002293# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01002294 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002295 if (input_available())
2296 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002297# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002298
Bram Moolenaar071d4272004-06-13 20:20:40 +00002299 return FALSE;
2300}
2301
Bram Moolenaar071d4272004-06-13 20:20:40 +00002302/*
2303 * return non-zero if a character is available
2304 */
2305 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002306mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002307{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002308# ifdef VIMDLL
2309 if (gui.in_use)
2310 return TRUE;
2311# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002312 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002313}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002314
2315# if defined(FEAT_TERMINAL) || defined(PROTO)
2316/*
2317 * Check for any pending input or messages.
2318 */
2319 int
2320mch_check_messages(void)
2321{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002322# ifdef VIMDLL
2323 if (gui.in_use)
2324 return TRUE;
2325# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002326 return WaitForChar(0L, TRUE);
2327}
2328# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002329
2330/*
2331 * Create the console input. Used when reading stdin doesn't work.
2332 */
2333 static void
2334create_conin(void)
2335{
2336 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
2337 FILE_SHARE_READ|FILE_SHARE_WRITE,
2338 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002339 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002340 did_create_conin = TRUE;
2341}
2342
2343/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002344 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002345 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002346 static WCHAR
2347tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002348{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002349 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002350
2351 for (;;)
2352 {
2353 INPUT_RECORD ir;
2354 DWORD cRecords = 0;
2355
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002356# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002357 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002358 if (input_available())
2359 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002360 if (g_nMouseClick != -1)
2361 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002362# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002363 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002364 {
2365 if (did_create_conin)
2366 read_error_exit();
2367 create_conin();
2368 continue;
2369 }
2370
2371 if (ir.EventType == KEY_EVENT)
2372 {
2373 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
2374 pmodifiers, TRUE))
2375 return ch;
2376 }
2377 else if (ir.EventType == FOCUS_EVENT)
2378 handle_focus_event(ir);
2379 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
2380 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002381 else if (ir.EventType == MOUSE_EVENT)
2382 {
2383 if (decode_mouse_event(&ir.Event.MouseEvent))
2384 return 0;
2385 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002386 }
2387}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002388#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002389
2390
2391/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02002392 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002393 * Get one or more characters from the keyboard or the mouse.
2394 * If time == 0, do not wait for characters.
2395 * If time == n, wait a short time for characters.
2396 * If time == -1, wait forever for characters.
2397 * Returns the number of characters read into buf.
2398 */
2399 int
2400mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002401 char_u *buf UNUSED,
2402 int maxlen UNUSED,
2403 long time UNUSED,
2404 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002405{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002406#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002407
2408 int len;
2409 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002410# ifdef VIMDLL
2411// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
2412# define TYPEAHEADSPACE 6
2413# else
2414# define TYPEAHEADSPACE 0
2415# endif
2416# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002417 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002418 static int typeaheadlen = 0;
2419
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002420# ifdef VIMDLL
2421 if (gui.in_use)
2422 return 0;
2423# endif
2424
Bram Moolenaar0f873732019-12-05 20:28:46 +01002425 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002426 if (typeaheadlen > 0)
2427 goto theend;
2428
Bram Moolenaar071d4272004-06-13 20:20:40 +00002429 if (time >= 0)
2430 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002431 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00002432 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002433 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01002434 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00002435 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002436 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00002437
Bram Moolenaar3918c952005-03-15 22:34:55 +00002438 /*
2439 * If there is no character available within 2 seconds (default)
2440 * write the autoscript file to disk. Or cause the CursorHold event
2441 * to be triggered.
2442 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002443 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002444 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00002445 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002446 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00002447 buf[0] = K_SPECIAL;
2448 buf[1] = KS_EXTRA;
2449 buf[2] = (int)KE_CURSORHOLD;
2450 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002451 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00002452 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002453 }
2454 }
2455
2456 /*
2457 * Try to read as many characters as there are, until the buffer is full.
2458 */
2459
Bram Moolenaar0f873732019-12-05 20:28:46 +01002460 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002461 g_fCBrkPressed = FALSE;
2462
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002463# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002464 if (fdDump)
2465 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002466# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002467
Bram Moolenaar0f873732019-12-05 20:28:46 +01002468 // Keep looping until there is something in the typeahead buffer and more
2469 // to get and still room in the buffer (up to two bytes for a char and
2470 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002471 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01002472 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002473 {
2474 if (typebuf_changed(tb_change_cnt))
2475 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002476 // "buf" may be invalid now if a client put something in the
2477 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002478 typeaheadlen = 0;
2479 break;
2480 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002481 if (g_nMouseClick != -1)
2482 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002483# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002484 if (fdDump)
2485 fprintf(fdDump, "{%02x @ %d, %d}",
2486 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002487# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01002488 char_u modifiers = ((char_u *)(&g_nMouseClick))[0];
2489 char_u scroll_dir = ((char_u *)(&g_nMouseClick))[1];
2490
2491 if (scroll_dir == KE_MOUSEDOWN
2492 || scroll_dir == KE_MOUSEUP
2493 || scroll_dir == KE_MOUSELEFT
2494 || scroll_dir == KE_MOUSERIGHT)
2495 {
2496 if (modifiers > 0)
2497 {
Christopher Plewright03193062022-11-22 12:58:27 +00002498 // use K_SPECIAL instead of CSI to make mappings work
2499 typeahead[typeaheadlen++] = K_SPECIAL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002500 typeahead[typeaheadlen++] = KS_MODIFIER;
2501 typeahead[typeaheadlen++] = modifiers;
2502 }
2503 typeahead[typeaheadlen++] = CSI;
2504 typeahead[typeaheadlen++] = KS_EXTRA;
2505 typeahead[typeaheadlen++] = scroll_dir;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002506 }
2507 else
2508 {
2509 typeahead[typeaheadlen++] = ESC + 128;
2510 typeahead[typeaheadlen++] = 'M';
2511 typeahead[typeaheadlen++] = g_nMouseClick;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002512 }
Christopher Plewright36446bb2022-11-23 22:28:08 +00002513
2514 // Pass the pointer coordinates of the mouse event in 2 bytes,
2515 // allowing for > 223 columns. Both for click and scroll events.
2516 // This is the same as what is used for the GUI.
2517 typeahead[typeaheadlen++] = (char_u)(g_xMouse / 128 + ' ' + 1);
2518 typeahead[typeaheadlen++] = (char_u)(g_xMouse % 128 + ' ' + 1);
2519 typeahead[typeaheadlen++] = (char_u)(g_yMouse / 128 + ' ' + 1);
2520 typeahead[typeaheadlen++] = (char_u)(g_yMouse % 128 + ' ' + 1);
2521
2522 g_nMouseClick = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002523 }
2524 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002525 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002526 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002527 int modifiers = 0;
2528
2529 c = tgetch(&modifiers, &ch2);
2530
Christopher Plewrightc8b20492023-01-04 18:06:00 +00002531 c = simplify_key(c, &modifiers);
2532
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002533 // Some chars need adjustment when the Ctrl modifier is used.
2534 ++no_reduce_keys;
2535 c = may_adjust_key_for_ctrl(modifiers, c);
2536 --no_reduce_keys;
2537
2538 // remove the SHIFT modifier for keys where it's already included,
2539 // e.g., '(' and '*'
2540 modifiers = may_remove_shift_modifier(modifiers, c);
2541
Bram Moolenaar071d4272004-06-13 20:20:40 +00002542 if (typebuf_changed(tb_change_cnt))
2543 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002544 // "buf" may be invalid now if a client put something in the
2545 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002546 typeaheadlen = 0;
2547 break;
2548 }
2549
2550 if (c == Ctrl_C && ctrl_c_interrupts)
2551 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002552# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002553 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002554# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002555 got_int = TRUE;
2556 }
2557
Bram Moolenaar071d4272004-06-13 20:20:40 +00002558 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002559 {
2560 int n = 1;
2561
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002562 if (ch2 == NUL)
2563 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002564 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002565 char_u *p;
2566 WCHAR ch[2];
2567
2568 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002569 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002570 {
2571 ch[1] = tgetch(&modifiers, &ch2);
2572 n++;
2573 }
2574 p = utf16_to_enc(ch, &n);
2575 if (p != NULL)
2576 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002577 for (i = 0, j = 0; i < n; i++)
2578 {
2579 typeahead[typeaheadlen + j++] = p[i];
2580# ifdef VIMDLL
2581 if (p[i] == CSI)
2582 {
2583 typeahead[typeaheadlen + j++] = KS_EXTRA;
2584 typeahead[typeaheadlen + j++] = KE_CSI;
2585 }
2586# endif
2587 }
2588 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002589 vim_free(p);
2590 }
2591 }
2592 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002593 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002594 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002595# ifdef VIMDLL
2596 if (c == CSI)
2597 {
2598 typeahead[typeaheadlen + 1] = KS_EXTRA;
2599 typeahead[typeaheadlen + 2] = KE_CSI;
2600 n = 3;
2601 }
2602# endif
2603 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002604 if (ch2 != NUL)
2605 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002606 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002607 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002608 switch (ch2)
2609 {
2610 case (WCHAR)'\324': // SHIFT+Insert
2611 case (WCHAR)'\325': // CTRL+Insert
2612 case (WCHAR)'\327': // SHIFT+Delete
2613 case (WCHAR)'\330': // CTRL+Delete
2614 typeahead[typeaheadlen + n] = (char_u)ch2;
2615 n++;
2616 break;
2617
2618 default:
2619 typeahead[typeaheadlen + n] = 3;
2620 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2621 n += 2;
2622 break;
2623 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002624 }
2625 else
2626 {
2627 typeahead[typeaheadlen + n] = 3;
2628 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2629 n += 2;
2630 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002631 }
2632
Bram Moolenaar0f873732019-12-05 20:28:46 +01002633 // Use the ALT key to set the 8th bit of the character
2634 // when it's one byte, the 8th bit isn't set yet and not
2635 // using a double-byte encoding (would become a lead
2636 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002637 if ((modifiers & MOD_MASK_ALT)
2638 && n == 1
2639 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002640 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002641 )
2642 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002643 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2644 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002645 modifiers &= ~MOD_MASK_ALT;
2646 }
2647
2648 if (modifiers != 0)
2649 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002650 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002651 mch_memmove(typeahead + typeaheadlen + 3,
2652 typeahead + typeaheadlen, n);
2653 typeahead[typeaheadlen++] = K_SPECIAL;
2654 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2655 typeahead[typeaheadlen++] = modifiers;
2656 }
2657
2658 typeaheadlen += n;
2659
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002660# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002661 if (fdDump)
2662 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002663# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002664 }
2665 }
2666 }
2667
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002668# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002669 if (fdDump)
2670 {
2671 fputs("]\n", fdDump);
2672 fflush(fdDump);
2673 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002674# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002675
Bram Moolenaar071d4272004-06-13 20:20:40 +00002676theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002677 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002678 len = 0;
2679 while (len < maxlen && typeaheadlen > 0)
2680 {
2681 buf[len++] = typeahead[0];
2682 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2683 }
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00002684# ifdef FEAT_EVAL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002685 if (len > 0)
2686 {
2687 buf[len] = NUL;
2688 ch_log(NULL, "raw key input: \"%s\"", buf);
2689 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002690# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002691 return len;
2692
Bram Moolenaar0f873732019-12-05 20:28:46 +01002693#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002694 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002695#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002696}
2697
Bram Moolenaar82881492012-11-20 16:53:39 +01002698#ifndef PROTO
2699# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002700# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002701# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002702#endif
2703
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002704/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002705 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002706 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2707 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002708 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002709 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002710 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002711executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002712{
LemonBoy40fd7e62022-05-05 20:18:16 +01002713 int attrs = win32_getattrs((char_u *)name);
2714
2715 // The file doesn't exist or is a folder.
2716 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2717 return FALSE;
2718 // Check if the file is an AppExecLink, a special alias used by Windows
2719 // Store for its apps.
2720 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002721 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002722 char_u *res = resolve_appexeclink((char_u *)name);
2723 if (res == NULL)
AmberArrf5d0f542023-08-20 20:03:45 +02002724 res = resolve_reparse_point((char_u *)name);
2725 if (res == NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002726 return FALSE;
2727 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002728 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002729 *path = res;
2730 else
2731 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002732 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002733 else if (path != NULL)
2734 *path = FullName_save((char_u *)name, FALSE);
2735 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002736}
2737
2738/*
2739 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2740 * If "use_path" is FALSE: Return TRUE if "name" exists.
2741 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2742 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2743 * the allocated memory.
2744 */
2745 static int
2746executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2747{
2748 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2749 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2750 // UTF-8.
2751 char_u buf[_MAX_PATH * 3];
2752 size_t len = STRLEN(name);
2753 size_t tmplen;
2754 char_u *p, *e, *e2;
2755 char_u *pathbuf = NULL;
2756 char_u *pathext = NULL;
2757 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002758 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002759 int noext = FALSE;
2760 int retval = FALSE;
2761
2762 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002763 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002764
2765 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002766 shname = gettail(p_sh);
2767 if (strstr((char *)shname, "sh") != NULL &&
2768 !(strstr((char *)shname, "powershell") != NULL
2769 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002770 noext = TRUE;
2771
2772 if (use_pathext)
2773 {
2774 pathext = mch_getenv("PATHEXT");
2775 if (pathext == NULL)
2776 pathext = (char_u *)".com;.exe;.bat;.cmd";
2777
2778 if (noext == FALSE)
2779 {
2780 /*
2781 * Loop over all extensions in $PATHEXT.
2782 * Check "name" ends with extension.
2783 */
2784 p = pathext;
2785 while (*p)
2786 {
2787 if (p[0] == ';'
2788 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2789 {
2790 // Skip empty or single ".".
2791 ++p;
2792 continue;
2793 }
2794 e = vim_strchr(p, ';');
2795 if (e == NULL)
2796 e = p + STRLEN(p);
2797 tmplen = e - p;
2798
2799 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2800 {
2801 noext = TRUE;
2802 break;
2803 }
2804
2805 p = e;
2806 }
2807 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002808 }
2809
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002810 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002811 if (pathext == NULL)
2812 pathext = (char_u *)".";
2813 else if (noext == TRUE)
2814 {
2815 if (pathextbuf == NULL)
2816 pathextbuf = alloc(STRLEN(pathext) + 3);
2817 if (pathextbuf == NULL)
2818 {
2819 retval = FALSE;
2820 goto theend;
2821 }
2822 STRCPY(pathextbuf, ".;");
2823 STRCAT(pathextbuf, pathext);
2824 pathext = pathextbuf;
2825 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002826
Bram Moolenaar95da1362020-05-30 18:37:55 +02002827 // Use $PATH when "use_path" is TRUE and "name" is basename.
2828 if (use_path && gettail((char_u *)name) == (char_u *)name)
2829 {
2830 p = mch_getenv("PATH");
2831 if (p != NULL)
2832 {
2833 pathbuf = alloc(STRLEN(p) + 3);
2834 if (pathbuf == NULL)
2835 {
2836 retval = FALSE;
2837 goto theend;
2838 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002839
2840 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2841 STRCPY(pathbuf, ".;");
2842 else
2843 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002844 STRCAT(pathbuf, p);
2845 }
2846 }
2847
2848 /*
2849 * Walk through all entries in $PATH to check if "name" exists there and
2850 * is an executable file.
2851 */
2852 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2853 while (*p)
2854 {
2855 if (*p == ';') // Skip empty entry
2856 {
2857 ++p;
2858 continue;
2859 }
2860 e = vim_strchr(p, ';');
2861 if (e == NULL)
2862 e = p + STRLEN(p);
2863
2864 if (e - p + len + 2 > sizeof(buf))
2865 {
2866 retval = FALSE;
2867 goto theend;
2868 }
2869 // A single "." that means current dir.
2870 if (e - p == 1 && *p == '.')
2871 STRCPY(buf, name);
2872 else
2873 {
2874 vim_strncpy(buf, p, e - p);
2875 add_pathsep(buf);
2876 STRCAT(buf, name);
2877 }
2878 tmplen = STRLEN(buf);
2879
2880 /*
2881 * Loop over all extensions in $PATHEXT.
2882 * Check "name" with extension added.
2883 */
2884 p = pathext;
2885 while (*p)
2886 {
2887 if (*p == ';')
2888 {
2889 // Skip empty entry
2890 ++p;
2891 continue;
2892 }
2893 e2 = vim_strchr(p, (int)';');
2894 if (e2 == NULL)
2895 e2 = p + STRLEN(p);
2896
2897 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2898 {
2899 // Not a single "." that means no extension is added.
2900 if (e2 - p + tmplen + 1 > sizeof(buf))
2901 {
2902 retval = FALSE;
2903 goto theend;
2904 }
2905 vim_strncpy(buf + tmplen, p, e2 - p);
2906 }
2907 if (executable_file((char *)buf, path))
2908 {
2909 retval = TRUE;
2910 goto theend;
2911 }
2912
2913 p = e2;
2914 }
2915
2916 p = e;
2917 }
2918
2919theend:
2920 free(pathextbuf);
2921 free(pathbuf);
2922 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002923}
2924
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002925#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2926 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002927/*
2928 * Bad parameter handler.
2929 *
2930 * Certain MS CRT functions will intentionally crash when passed invalid
2931 * parameters to highlight possible security holes. Setting this function as
2932 * the bad parameter handler will prevent the crash.
2933 *
2934 * In debug builds the parameters contain CRT information that might help track
2935 * down the source of a problem, but in non-debug builds the arguments are all
2936 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2937 * worth allowing these to make debugging of issues easier.
2938 */
2939 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002940bad_param_handler(const wchar_t *expression UNUSED,
2941 const wchar_t *function UNUSED,
2942 const wchar_t *file UNUSED,
2943 unsigned int line UNUSED,
2944 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002945{
2946}
2947
2948# define SET_INVALID_PARAM_HANDLER \
2949 ((void)_set_invalid_parameter_handler(bad_param_handler))
2950#else
2951# define SET_INVALID_PARAM_HANDLER
2952#endif
2953
Bram Moolenaar4f974752019-02-17 17:44:42 +01002954#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002955
2956/*
2957 * GUI version of mch_init().
2958 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002959 static void
2960mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002961{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002962# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002963 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002964# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002965
Bram Moolenaar0f873732019-12-05 20:28:46 +01002966 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002967 SET_INVALID_PARAM_HANDLER;
2968
Bram Moolenaar0f873732019-12-05 20:28:46 +01002969 // Let critical errors result in a failure, not in a dialog box. Required
2970 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002971 SetErrorMode(SEM_FAILCRITICALERRORS);
2972
Bram Moolenaar0f873732019-12-05 20:28:46 +01002973 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002974
Bram Moolenaar0f873732019-12-05 20:28:46 +01002975 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002976 Rows = 25;
2977 Columns = 80;
2978
Bram Moolenaar0f873732019-12-05 20:28:46 +01002979 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002980 {
2981 char_u vimrun_location[_MAX_PATH + 4];
2982
Bram Moolenaar0f873732019-12-05 20:28:46 +01002983 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002984 STRCPY(vimrun_location, exe_name);
2985 STRCPY(gettail(vimrun_location), "vimrun.exe");
2986 if (mch_getperm(vimrun_location) >= 0)
2987 {
2988 if (*skiptowhite(vimrun_location) != NUL)
2989 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002990 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002991 mch_memmove(vimrun_location + 1, vimrun_location,
2992 STRLEN(vimrun_location) + 1);
2993 *vimrun_location = '"';
2994 STRCPY(gettail(vimrun_location), "vimrun\" ");
2995 }
2996 else
2997 STRCPY(gettail(vimrun_location), "vimrun ");
2998
2999 vimrun_path = (char *)vim_strsave(vimrun_location);
3000 s_dont_use_vimrun = FALSE;
3001 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02003002 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003003 s_dont_use_vimrun = FALSE;
3004
Bram Moolenaar0f873732019-12-05 20:28:46 +01003005 // Don't give the warning for a missing vimrun.exe right now, but only
3006 // when vimrun was supposed to be used. Don't bother people that do
3007 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003008 if (s_dont_use_vimrun)
3009 need_vimrun_warning = TRUE;
3010 }
3011
3012 /*
3013 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
3014 * Otherwise the default "findstr /n" is used.
3015 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02003016 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01003017 set_option_value_give_err((char_u *)"grepprg",
3018 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003019
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003020# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003021 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003022# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003023
3024 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025}
3026
3027
Bram Moolenaar0f873732019-12-05 20:28:46 +01003028#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003029
3030#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003031
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003032# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
3033# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003034
3035/*
3036 * ClearConsoleBuffer()
3037 * Description:
3038 * Clears the entire contents of the console screen buffer, using the
3039 * specified attribute.
3040 * Returns:
3041 * TRUE on success
3042 */
3043 static BOOL
3044ClearConsoleBuffer(WORD wAttribute)
3045{
3046 CONSOLE_SCREEN_BUFFER_INFO csbi;
3047 COORD coord;
3048 DWORD NumCells, dummy;
3049
3050 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3051 return FALSE;
3052
3053 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
3054 coord.X = 0;
3055 coord.Y = 0;
3056 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
3057 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003058 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003059 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
3060 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003061 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003062
3063 return TRUE;
3064}
3065
3066/*
3067 * FitConsoleWindow()
3068 * Description:
3069 * Checks if the console window will fit within given buffer dimensions.
3070 * Also, if requested, will shrink the window to fit.
3071 * Returns:
3072 * TRUE on success
3073 */
3074 static BOOL
3075FitConsoleWindow(
3076 COORD dwBufferSize,
3077 BOOL WantAdjust)
3078{
3079 CONSOLE_SCREEN_BUFFER_INFO csbi;
3080 COORD dwWindowSize;
3081 BOOL NeedAdjust = FALSE;
3082
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003083 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3084 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003085
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003086 /*
3087 * A buffer resize will fail if the current console window does
3088 * not lie completely within that buffer. To avoid this, we might
3089 * have to move and possibly shrink the window.
3090 */
3091 if (csbi.srWindow.Right >= dwBufferSize.X)
3092 {
3093 dwWindowSize.X = SRWIDTH(csbi.srWindow);
3094 if (dwWindowSize.X > dwBufferSize.X)
3095 dwWindowSize.X = dwBufferSize.X;
3096 csbi.srWindow.Right = dwBufferSize.X - 1;
3097 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
3098 NeedAdjust = TRUE;
3099 }
3100 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
3101 {
3102 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
3103 if (dwWindowSize.Y > dwBufferSize.Y)
3104 dwWindowSize.Y = dwBufferSize.Y;
3105 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
3106 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
3107 NeedAdjust = TRUE;
3108 }
3109 if (NeedAdjust && WantAdjust)
3110 {
3111 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
3112 return FALSE;
3113 }
3114 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003115}
3116
3117typedef struct ConsoleBufferStruct
3118{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003119 BOOL IsValid;
3120 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003121 PCHAR_INFO Buffer;
3122 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003123 PSMALL_RECT Regions;
3124 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003125} ConsoleBuffer;
3126
3127/*
3128 * SaveConsoleBuffer()
3129 * Description:
3130 * Saves important information about the console buffer, including the
3131 * actual buffer contents. The saved information is suitable for later
3132 * restoration by RestoreConsoleBuffer().
3133 * Returns:
3134 * TRUE if all information was saved; FALSE otherwise
3135 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
3136 */
3137 static BOOL
3138SaveConsoleBuffer(
3139 ConsoleBuffer *cb)
3140{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003141 DWORD NumCells;
3142 COORD BufferCoord;
3143 SMALL_RECT ReadRegion;
3144 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003145 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003146
Bram Moolenaar071d4272004-06-13 20:20:40 +00003147 if (cb == NULL)
3148 return FALSE;
3149
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003150 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003151 {
3152 cb->IsValid = FALSE;
3153 return FALSE;
3154 }
3155 cb->IsValid = TRUE;
3156
Christopher Plewright1140b512022-11-12 18:46:05 +00003157 // VTP uses alternate screen buffer.
3158 // No need to save buffer contents for restoration.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003159 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003160 return TRUE;
3161
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003162 /*
3163 * Allocate a buffer large enough to hold the entire console screen
3164 * buffer. If this ConsoleBuffer structure has already been initialized
3165 * with a buffer of the correct size, then just use that one.
3166 */
3167 if (!cb->IsValid || cb->Buffer == NULL ||
3168 cb->BufferSize.X != cb->Info.dwSize.X ||
3169 cb->BufferSize.Y != cb->Info.dwSize.Y)
3170 {
3171 cb->BufferSize.X = cb->Info.dwSize.X;
3172 cb->BufferSize.Y = cb->Info.dwSize.Y;
3173 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
3174 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003175 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003176 if (cb->Buffer == NULL)
3177 return FALSE;
3178 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003179
3180 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003181 * We will now copy the console screen buffer into our buffer.
3182 * ReadConsoleOutput() seems to be limited as far as how much you
3183 * can read at a time. Empirically, this number seems to be about
3184 * 12000 cells (rows * columns). Start at position (0, 0) and copy
3185 * in chunks until it is all copied. The chunks will all have the
3186 * same horizontal characteristics, so initialize them now. The
3187 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003188 */
Bram Moolenaar61594242015-09-01 20:23:37 +02003189 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003190 ReadRegion.Left = 0;
3191 ReadRegion.Right = cb->Info.dwSize.X - 1;
3192 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003193
3194 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
3195 if (cb->Regions == NULL || numregions != cb->NumRegions)
3196 {
3197 cb->NumRegions = numregions;
3198 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003199 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003200 if (cb->Regions == NULL)
3201 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003202 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003203 return FALSE;
3204 }
3205 }
3206
3207 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003208 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003209 /*
3210 * Read into position (0, Y) in our buffer.
3211 */
3212 BufferCoord.Y = Y;
3213 /*
3214 * Read the region whose top left corner is (0, Y) and whose bottom
3215 * right corner is (width - 1, Y + Y_incr - 1). This should define
3216 * a region of size width by Y_incr. Don't worry if this region is
3217 * too large for the remaining buffer; it will be cropped.
3218 */
3219 ReadRegion.Top = Y;
3220 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003221 if (!ReadConsoleOutputW(g_hConOut, // output handle
3222 cb->Buffer, // our buffer
3223 cb->BufferSize, // dimensions of our buffer
3224 BufferCoord, // offset in our buffer
3225 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003226 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003227 VIM_CLEAR(cb->Buffer);
3228 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003229 return FALSE;
3230 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02003231 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003232 }
3233
3234 return TRUE;
3235}
3236
3237/*
3238 * RestoreConsoleBuffer()
3239 * Description:
3240 * Restores important information about the console buffer, including the
3241 * actual buffer contents, if desired. The information to restore is in
3242 * the same format used by SaveConsoleBuffer().
3243 * Returns:
3244 * TRUE on success
3245 */
3246 static BOOL
3247RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003248 ConsoleBuffer *cb,
3249 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003250{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003251 COORD BufferCoord;
3252 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003253 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003254
Christopher Plewright1140b512022-11-12 18:46:05 +00003255 // VTP uses alternate screen buffer.
3256 // No need to restore buffer contents.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003257 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003258 return TRUE;
3259
Bram Moolenaar071d4272004-06-13 20:20:40 +00003260 if (cb == NULL || !cb->IsValid)
3261 return FALSE;
3262
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003263 /*
3264 * Before restoring the buffer contents, clear the current buffer, and
3265 * restore the cursor position and window information. Doing this now
3266 * prevents old buffer contents from "flashing" onto the screen.
3267 */
3268 if (RestoreScreen)
3269 ClearConsoleBuffer(cb->Info.wAttributes);
3270
3271 FitConsoleWindow(cb->Info.dwSize, TRUE);
3272 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
3273 return FALSE;
3274 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
3275 return FALSE;
3276
3277 if (!RestoreScreen)
3278 {
3279 /*
3280 * No need to restore the screen buffer contents, so we're done.
3281 */
3282 return TRUE;
3283 }
3284
3285 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
3286 return FALSE;
3287 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
3288 return FALSE;
3289
3290 /*
3291 * Restore the screen buffer contents.
3292 */
3293 if (cb->Buffer != NULL)
3294 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003295 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003296 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003297 BufferCoord.X = cb->Regions[i].Left;
3298 BufferCoord.Y = cb->Regions[i].Top;
3299 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01003300 if (!WriteConsoleOutputW(g_hConOut, // output handle
3301 cb->Buffer, // our buffer
3302 cb->BufferSize, // dimensions of our buffer
3303 BufferCoord, // offset in our buffer
3304 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02003305 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003306 }
3307 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003308
3309 return TRUE;
3310}
3311
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003312# define FEAT_RESTORE_ORIG_SCREEN
3313# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003314static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003315# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003316static ConsoleBuffer g_cbNonTermcap = { 0 };
3317static ConsoleBuffer g_cbTermcap = { 0 };
3318
Bram Moolenaar071d4272004-06-13 20:20:40 +00003319char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01003320HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00003321static HICON g_hOrigIconSmall = NULL;
3322static HICON g_hOrigIcon = NULL;
3323static HICON g_hVimIcon = NULL;
3324static BOOL g_fCanChangeIcon = FALSE;
3325
Bram Moolenaar071d4272004-06-13 20:20:40 +00003326/*
3327 * GetConsoleIcon()
3328 * Description:
3329 * Attempts to retrieve the small icon and/or the big icon currently in
3330 * use by a given window.
3331 * Returns:
3332 * TRUE on success
3333 */
3334 static BOOL
3335GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003336 HWND hWnd,
3337 HICON *phIconSmall,
3338 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003339{
3340 if (hWnd == NULL)
3341 return FALSE;
3342
3343 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003344 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
3345 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003346 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003347 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
3348 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003349 return TRUE;
3350}
3351
3352/*
3353 * SetConsoleIcon()
3354 * Description:
3355 * Attempts to change the small icon and/or the big icon currently in
3356 * use by a given window.
3357 * Returns:
3358 * TRUE on success
3359 */
3360 static BOOL
3361SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003362 HWND hWnd,
3363 HICON hIconSmall,
3364 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003365{
Bram Moolenaar071d4272004-06-13 20:20:40 +00003366 if (hWnd == NULL)
3367 return FALSE;
3368
3369 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003370 SendMessage(hWnd, WM_SETICON,
3371 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003372 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003373 SendMessage(hWnd, WM_SETICON,
3374 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003375 return TRUE;
3376}
3377
3378/*
3379 * SaveConsoleTitleAndIcon()
3380 * Description:
3381 * Saves the current console window title in g_szOrigTitle, for later
3382 * restoration. Also, attempts to obtain a handle to the console window,
3383 * and use it to save the small and big icons currently in use by the
3384 * console window. This is not always possible on some versions of Windows;
3385 * nor is it possible when running Vim remotely using Telnet (since the
3386 * console window the user sees is owned by a remote process).
3387 */
3388 static void
3389SaveConsoleTitleAndIcon(void)
3390{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003391 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003392 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
3393 return;
3394
3395 /*
3396 * Obtain a handle to the console window using GetConsoleWindow() from
3397 * KERNEL32.DLL; we need to handle in order to change the window icon.
3398 * This function only exists on NT-based Windows, starting with Windows
3399 * 2000. On older operating systems, we can't change the window icon
3400 * anyway.
3401 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003402 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003403 if (g_hWnd == NULL)
3404 return;
3405
Bram Moolenaar0f873732019-12-05 20:28:46 +01003406 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003407 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
3408 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
3409 return;
3410
Bram Moolenaar0f873732019-12-05 20:28:46 +01003411 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01003412 if (
3413# ifdef FEAT_LIBCALL
3414 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
3415# endif
3416 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003417 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003418 if (g_hVimIcon != NULL)
3419 g_fCanChangeIcon = TRUE;
3420}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003421
3422static int g_fWindInitCalled = FALSE;
3423static int g_fTermcapMode = FALSE;
3424static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003425
3426/*
3427 * non-GUI version of mch_init().
3428 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003429 static void
3430mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003431{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003432# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003433 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003434# endif
3435# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00003436 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003437# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003438
Bram Moolenaar0f873732019-12-05 20:28:46 +01003439 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02003440 SET_INVALID_PARAM_HANDLER;
3441
Bram Moolenaar0f873732019-12-05 20:28:46 +01003442 // Let critical errors result in a failure, not in a dialog box. Required
3443 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003444 SetErrorMode(SEM_FAILCRITICALERRORS);
3445
Bram Moolenaar0f873732019-12-05 20:28:46 +01003446 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00003447 out_flush();
3448
Bram Moolenaar0f873732019-12-05 20:28:46 +01003449 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00003450 if (read_cmd_fd == 0)
3451 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
3452 else
3453 create_conin();
3454 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
3455
Christopher Plewright38804d62022-11-09 23:55:52 +00003456 wt_init();
3457 vtp_flag_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003458# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01003459 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003460 SaveConsoleBuffer(&g_cbOrig);
3461 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003462# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01003463 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003464 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
3465 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003466# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003467 if (cterm_normal_fg_color == 0)
3468 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
3469 if (cterm_normal_bg_color == 0)
3470 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
3471
Bram Moolenaarbdace832019-03-02 10:13:42 +01003472 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02003473 g_color_index_fg = g_attrDefault & 0xf;
3474 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
3475
Bram Moolenaar0f873732019-12-05 20:28:46 +01003476 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00003477 update_tcap(g_attrCurrent);
3478
3479 GetConsoleCursorInfo(g_hConOut, &g_cci);
3480 GetConsoleMode(g_hConIn, &g_cmodein);
3481 GetConsoleMode(g_hConOut, &g_cmodeout);
3482
Bram Moolenaar071d4272004-06-13 20:20:40 +00003483 SaveConsoleTitleAndIcon();
3484 /*
3485 * Set both the small and big icons of the console window to Vim's icon.
3486 * Note that Vim presently only has one size of icon (32x32), but it
3487 * automatically gets scaled down to 16x16 when setting the small icon.
3488 */
3489 if (g_fCanChangeIcon)
3490 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003491
3492 ui_get_shellsize();
3493
Christopher Plewrightd343c602023-01-22 18:58:30 +00003494 vtp_init();
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00003495 // Switch to a new alternate screen buffer.
3496 if (use_alternate_screen_buffer)
3497 vtp_printf("\033[?1049h");
Christopher Plewrightd343c602023-01-22 18:58:30 +00003498
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003499# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003500 fdDump = fopen("dump", "wt");
3501
3502 if (fdDump)
3503 {
3504 time_t t;
3505
3506 time(&t);
3507 fputs(ctime(&t), fdDump);
3508 fflush(fdDump);
3509 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003510# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003511
3512 g_fWindInitCalled = TRUE;
3513
Bram Moolenaar071d4272004-06-13 20:20:40 +00003514 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003515
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003516# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003517 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003518# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003519}
3520
3521/*
3522 * non-GUI version of mch_exit().
3523 * Shut down and exit with status `r'
3524 * Careful: mch_exit() may be called before mch_init()!
3525 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003526 static void
3527mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003528{
Bram Moolenaar955f1982017-02-05 15:10:51 +01003529 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003530
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003531 vtp_exit();
3532
Bram Moolenaar955f1982017-02-05 15:10:51 +01003533 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003534 if (g_fWindInitCalled)
3535 settmode(TMODE_COOK);
3536
Bram Moolenaar0f873732019-12-05 20:28:46 +01003537 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00003538
3539 if (g_fWindInitCalled)
3540 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02003541 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003542 /*
3543 * Restore both the small and big icons of the console window to
3544 * what they were at startup. Don't do this when the window is
3545 * closed, Vim would hang here.
3546 */
3547 if (g_fCanChangeIcon && !g_fForceExit)
3548 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003549
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003550# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003551 if (fdDump)
3552 {
3553 time_t t;
3554
3555 time(&t);
3556 fputs(ctime(&t), fdDump);
3557 fclose(fdDump);
3558 }
3559 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003560# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003561 }
3562
3563 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003564 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003565 SetConsoleMode(g_hConOut, g_cmodeout);
3566
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003567# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003568 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003569# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003570
3571 exit(r);
3572}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003573#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003574
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003575 void
3576mch_init(void)
3577{
3578#ifdef VIMDLL
3579 if (gui.starting)
3580 mch_init_g();
3581 else
3582 mch_init_c();
3583#elif defined(FEAT_GUI_MSWIN)
3584 mch_init_g();
3585#else
3586 mch_init_c();
3587#endif
3588}
3589
3590 void
3591mch_exit(int r)
3592{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003593#ifdef FEAT_NETBEANS_INTG
3594 netbeans_send_disconnect();
3595#endif
3596
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003597#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003598 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003599 mch_exit_g(r);
3600 else
3601 mch_exit_c(r);
3602#elif defined(FEAT_GUI_MSWIN)
3603 mch_exit_g(r);
3604#else
3605 mch_exit_c(r);
3606#endif
3607}
3608
Bram Moolenaar071d4272004-06-13 20:20:40 +00003609/*
3610 * Do we have an interactive window?
3611 */
3612 int
3613mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003614 int argc UNUSED,
3615 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003616{
K.Takatace3189d2023-02-15 19:13:43 +00003617 mch_get_exe_name();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003618
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003619#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003620 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003621#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003622# ifdef VIMDLL
3623 if (gui.in_use)
3624 return OK;
3625# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003626 if (isatty(1))
3627 return OK;
3628 return FAIL;
3629#endif
3630}
3631
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003632/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003633 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003634 * When "len" is > 0, also expand short to long filenames.
3635 */
3636 void
3637fname_case(
3638 char_u *name,
3639 int len)
3640{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003641 int flen;
3642 WCHAR *p;
3643 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003644
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003645 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003646 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003647 return;
3648
3649 slash_adjust(name);
3650
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003651 p = enc_to_utf16(name, NULL);
3652 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003653 return;
3654
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003655 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003656 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003657 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003658
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003659 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003660 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003661 if (len > 0 || flen >= (int)STRLEN(q))
3662 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3663 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003664 }
3665 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003666 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003667}
3668
3669
3670/*
3671 * Insert user name in s[len].
3672 */
3673 int
3674mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003675 char_u *s,
3676 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003677{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003678 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003679 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003680
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003681 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003682 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003683 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003684
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003685 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003686 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003687 vim_strncpy(s, p, len - 1);
3688 vim_free(p);
3689 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003690 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003691 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003692 s[0] = NUL;
3693 return FAIL;
3694}
3695
3696
3697/*
3698 * Insert host name in s[len].
3699 */
3700 void
3701mch_get_host_name(
3702 char_u *s,
3703 int len)
3704{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003705 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003706 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003707
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003708 if (!GetComputerNameW(wszHostName, &wcch))
3709 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003710
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003711 char_u *p = utf16_to_enc(wszHostName, NULL);
3712 if (p == NULL)
3713 return;
3714
3715 vim_strncpy(s, p, len - 1);
3716 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003717}
3718
3719
3720/*
3721 * return process ID
3722 */
3723 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003724mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003725{
3726 return (long)GetCurrentProcessId();
3727}
3728
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003729/*
3730 * return TRUE if process "pid" is still running
3731 */
3732 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003733mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003734{
3735 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3736 DWORD status = 0;
3737 int ret = FALSE;
3738
3739 if (hProcess == NULL)
3740 return FALSE; // might not have access
3741 if (GetExitCodeProcess(hProcess, &status) )
3742 ret = status == STILL_ACTIVE;
3743 CloseHandle(hProcess);
3744 return ret;
3745}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003746
3747/*
3748 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3749 * Return OK for success, FAIL for failure.
3750 */
3751 int
3752mch_dirname(
3753 char_u *buf,
3754 int len)
3755{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003756 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003757
Bram Moolenaar071d4272004-06-13 20:20:40 +00003758 /*
3759 * Originally this was:
3760 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3761 * But the Win32s known bug list says that getcwd() doesn't work
3762 * so use the Win32 system call instead. <Negri>
3763 */
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003764 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) == 0)
3765 return FAIL;
3766
3767 WCHAR wcbuf[_MAX_PATH + 1];
3768 char_u *p = NULL;
3769
3770 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003771 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003772 p = utf16_to_enc(wcbuf, NULL);
3773 if (STRLEN(p) >= (size_t)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003774 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003775 // long path name is too long, fall back to short one
Yegappan Lakshmanan960dcbd2023-03-07 17:45:11 +00003776 VIM_CLEAR(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003777 }
3778 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003779 if (p == NULL)
3780 p = utf16_to_enc(wbuf, NULL);
3781
3782 if (p == NULL)
3783 return FAIL;
3784
3785 vim_strncpy(buf, p, len - 1);
3786 vim_free(p);
3787 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003788}
3789
3790/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003791 * Get file permissions for "name".
3792 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003793 */
3794 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003795mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003796{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003797 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003798 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003799
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003800 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003801 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003802}
3803
3804
3805/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003806 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003807 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003808 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003809 */
3810 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003811mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003812{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003813 long n;
3814 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003815
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003816 p = enc_to_utf16(name, NULL);
3817 if (p == NULL)
3818 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003819
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003820 n = _wchmod(p, perm);
3821 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003822 if (n == -1)
3823 return FAIL;
3824
3825 win32_set_archive(name);
3826
3827 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003828}
3829
3830/*
3831 * Set hidden flag for "name".
3832 */
3833 void
3834mch_hide(char_u *name)
3835{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003836 int attrs = win32_getattrs(name);
3837 if (attrs == -1)
3838 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003839
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003840 attrs |= FILE_ATTRIBUTE_HIDDEN;
3841 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003842}
3843
3844/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003845 * Return TRUE if file "name" exists and is hidden.
3846 */
3847 int
3848mch_ishidden(char_u *name)
3849{
3850 int f = win32_getattrs(name);
3851
3852 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003853 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003854
3855 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3856}
3857
3858/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003859 * return TRUE if "name" is a directory
3860 * return FALSE if "name" is not a directory or upon error
3861 */
3862 int
3863mch_isdir(char_u *name)
3864{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003865 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003866
3867 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003868 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003869
3870 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3871}
3872
3873/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003874 * return TRUE if "name" is a directory, NOT a symlink to a directory
3875 * return FALSE if "name" is not a directory
3876 * return FALSE for error
3877 */
3878 int
3879mch_isrealdir(char_u *name)
3880{
3881 return mch_isdir(name) && !mch_is_symbolic_link(name);
3882}
3883
3884/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003885 * Create directory "name".
3886 * Return 0 on success, -1 on error.
3887 */
3888 int
3889mch_mkdir(char_u *name)
3890{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003891 WCHAR *p;
3892 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003893
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003894 p = enc_to_utf16(name, NULL);
3895 if (p == NULL)
3896 return -1;
3897 retval = _wmkdir(p);
3898 vim_free(p);
3899 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003900}
3901
3902/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003903 * Delete directory "name".
3904 * Return 0 on success, -1 on error.
3905 */
3906 int
3907mch_rmdir(char_u *name)
3908{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003909 WCHAR *p;
3910 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003911
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003912 p = enc_to_utf16(name, NULL);
3913 if (p == NULL)
3914 return -1;
3915 retval = _wrmdir(p);
3916 vim_free(p);
3917 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003918}
3919
3920/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003921 * Return TRUE if file "fname" has more than one link.
3922 */
3923 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003924mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003925{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003926 BY_HANDLE_FILE_INFORMATION info;
3927
3928 return win32_fileinfo(fname, &info) == FILEINFO_OK
3929 && info.nNumberOfLinks > 1;
3930}
3931
3932/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003933 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003934 */
3935 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003936mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003937{
3938 HANDLE hFind;
3939 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003940 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003941 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003942 WIN32_FIND_DATAW findDataW;
3943
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003944 wn = enc_to_utf16(name, NULL);
3945 if (wn == NULL)
3946 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003947
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003948 hFind = FindFirstFileW(wn, &findDataW);
3949 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003950 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003951 {
3952 fileFlags = findDataW.dwFileAttributes;
3953 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003954 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003955 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003956
3957 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003958 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3959 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003960 res = TRUE;
3961
3962 return res;
3963}
3964
3965/*
3966 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3967 * link.
3968 */
3969 int
3970mch_is_linked(char_u *fname)
3971{
3972 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3973 return TRUE;
3974 return FALSE;
3975}
3976
3977/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003978 * Get the by-handle-file-information for "fname".
3979 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003980 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003981 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3982 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3983 */
3984 int
3985win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3986{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003987 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003988 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003989 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003990
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003991 wn = enc_to_utf16(fname, NULL);
3992 if (wn == NULL)
3993 return FILEINFO_ENC_FAIL;
3994
3995 hFile = CreateFileW(wn, // file name
3996 GENERIC_READ, // access mode
3997 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3998 NULL, // security descriptor
3999 OPEN_EXISTING, // creation disposition
4000 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
4001 NULL); // handle to template file
4002 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00004003
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00004004 if (hFile == INVALID_HANDLE_VALUE)
4005 return FILEINFO_READ_FAIL;
4006
4007 if (GetFileInformationByHandle(hFile, info) != 0)
4008 res = FILEINFO_OK;
4009 else
4010 res = FILEINFO_INFO_FAIL;
4011 CloseHandle(hFile);
Bram Moolenaar03f48552006-02-28 23:52:23 +00004012
Bram Moolenaar03f48552006-02-28 23:52:23 +00004013 return res;
4014}
4015
4016/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004017 * get file attributes for `name'
4018 * -1 : error
4019 * else FILE_ATTRIBUTE_* defined in winnt.h
4020 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01004021 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004022win32_getattrs(char_u *name)
4023{
4024 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004025 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004026
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004027 p = enc_to_utf16(name, NULL);
4028 if (p == NULL)
4029 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004030
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004031 attr = GetFileAttributesW(p);
4032 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004033
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004034 return attr;
4035}
4036
4037/*
4038 * set file attributes for `name' to `attrs'
4039 *
4040 * return -1 for failure, 0 otherwise
4041 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004042 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004043win32_setattrs(char_u *name, int attrs)
4044{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004045 int res;
4046 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004047
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004048 p = enc_to_utf16(name, NULL);
4049 if (p == NULL)
4050 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004051
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004052 res = SetFileAttributesW(p, attrs);
4053 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004054
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004055 return res ? 0 : -1;
4056}
4057
4058/*
4059 * Set archive flag for "name".
4060 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004061 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004062win32_set_archive(char_u *name)
4063{
4064 int attrs = win32_getattrs(name);
4065 if (attrs == -1)
4066 return -1;
4067
4068 attrs |= FILE_ATTRIBUTE_ARCHIVE;
4069 return win32_setattrs(name, attrs);
4070}
4071
4072/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004073 * Return TRUE if file or directory "name" is writable (not readonly).
4074 * Strange semantics of Win32: a readonly directory is writable, but you can't
4075 * delete a file. Let's say this means it is writable.
4076 */
4077 int
4078mch_writable(char_u *name)
4079{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004080 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004081
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004082 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
4083 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004084}
4085
Bram Moolenaar071d4272004-06-13 20:20:40 +00004086/*
Bram Moolenaar43663192017-03-05 14:29:12 +01004087 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01004088 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01004089 * When returning TRUE and "path" is not NULL save the path and set "*path" to
4090 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004091 */
4092 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01004093mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004094{
Bram Moolenaar95da1362020-05-30 18:37:55 +02004095 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004096}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004097
4098/*
4099 * Check what "name" is:
4100 * NODE_NORMAL: file or directory (or doesn't exist)
4101 * NODE_WRITABLE: writable device, socket, fifo, etc.
4102 * NODE_OTHER: non-writable things
4103 */
4104 int
4105mch_nodetype(char_u *name)
4106{
4107 HANDLE hFile;
4108 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004109 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004110
Bram Moolenaar0f873732019-12-05 20:28:46 +01004111 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
4112 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
4113 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00004114 if (STRNCMP(name, "\\\\.\\", 4) == 0)
4115 return NODE_WRITABLE;
4116
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004117 wn = enc_to_utf16(name, NULL);
4118 if (wn == NULL)
4119 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004120
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004121 hFile = CreateFileW(wn, // file name
4122 GENERIC_WRITE, // access mode
4123 0, // share mode
4124 NULL, // security descriptor
4125 OPEN_EXISTING, // creation disposition
4126 0, // file attributes
4127 NULL); // handle to template file
4128 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004129 if (hFile == INVALID_HANDLE_VALUE)
4130 return NODE_NORMAL;
4131
4132 type = GetFileType(hFile);
4133 CloseHandle(hFile);
4134 if (type == FILE_TYPE_CHAR)
4135 return NODE_WRITABLE;
4136 if (type == FILE_TYPE_DISK)
4137 return NODE_NORMAL;
4138 return NODE_OTHER;
4139}
4140
4141#ifdef HAVE_ACL
4142struct my_acl
4143{
4144 PSECURITY_DESCRIPTOR pSecurityDescriptor;
4145 PSID pSidOwner;
4146 PSID pSidGroup;
4147 PACL pDacl;
4148 PACL pSacl;
4149};
4150#endif
4151
4152/*
4153 * Return a pointer to the ACL of file "fname" in allocated memory.
4154 * Return NULL if the ACL is not available for whatever reason.
4155 */
4156 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004157mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004158{
4159#ifndef HAVE_ACL
4160 return (vim_acl_T)NULL;
4161#else
4162 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02004163 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004164
Bram Moolenaarc799fe22019-05-28 23:08:19 +02004165 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004166 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004167 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004168 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02004169
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004170 wn = enc_to_utf16(fname, NULL);
4171 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004172 {
4173 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004174 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004175 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004176
4177 // Try to retrieve the entire security descriptor.
4178 err = GetNamedSecurityInfoW(
4179 wn, // Abstract filename
4180 SE_FILE_OBJECT, // File Object
4181 OWNER_SECURITY_INFORMATION |
4182 GROUP_SECURITY_INFORMATION |
4183 DACL_SECURITY_INFORMATION |
4184 SACL_SECURITY_INFORMATION,
4185 &p->pSidOwner, // Ownership information.
4186 &p->pSidGroup, // Group membership.
4187 &p->pDacl, // Discretionary information.
4188 &p->pSacl, // For auditing purposes.
4189 &p->pSecurityDescriptor);
4190 if (err == ERROR_ACCESS_DENIED ||
4191 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004192 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004193 // Retrieve only DACL.
4194 (void)GetNamedSecurityInfoW(
4195 wn,
4196 SE_FILE_OBJECT,
4197 DACL_SECURITY_INFORMATION,
4198 NULL,
4199 NULL,
4200 &p->pDacl,
4201 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004202 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004203 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004204 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004205 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004206 mch_free_acl((vim_acl_T)p);
4207 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004208 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004209 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004210 }
4211
4212 return (vim_acl_T)p;
4213#endif
4214}
4215
Bram Moolenaar27515922013-06-29 15:36:26 +02004216#ifdef HAVE_ACL
4217/*
4218 * Check if "acl" contains inherited ACE.
4219 */
4220 static BOOL
4221is_acl_inherited(PACL acl)
4222{
4223 DWORD i;
4224 ACL_SIZE_INFORMATION acl_info;
4225 PACCESS_ALLOWED_ACE ace;
4226
4227 acl_info.AceCount = 0;
4228 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
4229 for (i = 0; i < acl_info.AceCount; i++)
4230 {
4231 GetAce(acl, i, (LPVOID *)&ace);
4232 if (ace->Header.AceFlags & INHERITED_ACE)
4233 return TRUE;
4234 }
4235 return FALSE;
4236}
4237#endif
4238
Bram Moolenaar071d4272004-06-13 20:20:40 +00004239/*
4240 * Set the ACL of file "fname" to "acl" (unless it's NULL).
4241 * Errors are ignored.
4242 * This must only be called with "acl" equal to what mch_get_acl() returned.
4243 */
4244 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004245mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004246{
4247#ifdef HAVE_ACL
4248 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02004249 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004250 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004251
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004252 if (p == NULL)
4253 return;
4254
4255 wn = enc_to_utf16(fname, NULL);
4256 if (wn == NULL)
4257 return;
4258
4259 // Set security flags
4260 if (p->pSidOwner)
4261 sec_info |= OWNER_SECURITY_INFORMATION;
4262 if (p->pSidGroup)
4263 sec_info |= GROUP_SECURITY_INFORMATION;
4264 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02004265 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004266 sec_info |= DACL_SECURITY_INFORMATION;
4267 // Do not inherit its parent's DACL.
4268 // If the DACL is inherited, Cygwin permissions would be changed.
4269 if (!is_acl_inherited(p->pDacl))
4270 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02004271 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004272 if (p->pSacl)
4273 sec_info |= SACL_SECURITY_INFORMATION;
4274
4275 (void)SetNamedSecurityInfoW(
4276 wn, // Abstract filename
4277 SE_FILE_OBJECT, // File Object
4278 sec_info,
4279 p->pSidOwner, // Ownership information.
4280 p->pSidGroup, // Group membership.
4281 p->pDacl, // Discretionary information.
4282 p->pSacl // For auditing purposes.
4283 );
4284 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004285#endif
4286}
4287
4288 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004289mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004290{
4291#ifdef HAVE_ACL
4292 struct my_acl *p = (struct my_acl *)acl;
4293
4294 if (p != NULL)
4295 {
4296 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
4297 vim_free(p);
4298 }
4299#endif
4300}
4301
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004302#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004303
4304/*
4305 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
4306 */
4307 static BOOL WINAPI
4308handler_routine(
4309 DWORD dwCtrlType)
4310{
Bram Moolenaar589b1102017-08-12 16:39:05 +02004311 INPUT_RECORD ir;
4312 DWORD out;
4313
Bram Moolenaar071d4272004-06-13 20:20:40 +00004314 switch (dwCtrlType)
4315 {
4316 case CTRL_C_EVENT:
4317 if (ctrl_c_interrupts)
4318 g_fCtrlCPressed = TRUE;
4319 return TRUE;
4320
4321 case CTRL_BREAK_EVENT:
4322 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02004323 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004324 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02004325 ir.EventType = KEY_EVENT;
4326 ir.Event.KeyEvent.bKeyDown = TRUE;
4327 ir.Event.KeyEvent.wRepeatCount = 1;
4328 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
4329 ir.Event.KeyEvent.wVirtualScanCode = 0;
4330 ir.Event.KeyEvent.dwControlKeyState = 0;
4331 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
4332 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004333 return TRUE;
4334
Bram Moolenaar0f873732019-12-05 20:28:46 +01004335 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00004336 case CTRL_CLOSE_EVENT:
4337 case CTRL_LOGOFF_EVENT:
4338 case CTRL_SHUTDOWN_EVENT:
4339 windgoto((int)Rows - 1, 0);
4340 g_fForceExit = TRUE;
4341
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004342 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004343 (dwCtrlType == CTRL_CLOSE_EVENT
4344 ? _("close")
4345 : dwCtrlType == CTRL_LOGOFF_EVENT
4346 ? _("logoff")
4347 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004348# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00004349 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004350# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004351
Bram Moolenaar0f873732019-12-05 20:28:46 +01004352 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00004353
Bram Moolenaar0f873732019-12-05 20:28:46 +01004354 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00004355
4356 default:
4357 return FALSE;
4358 }
4359}
4360
4361
4362/*
4363 * set the tty in (raw) ? "raw" : "cooked" mode
4364 */
4365 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02004366mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004367{
4368 DWORD cmodein;
4369 DWORD cmodeout;
4370 BOOL bEnableHandler;
4371
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004372# ifdef VIMDLL
4373 if (gui.in_use)
4374 return;
4375# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004376 GetConsoleMode(g_hConIn, &cmodein);
4377 GetConsoleMode(g_hConOut, &cmodeout);
4378 if (tmode == TMODE_RAW)
4379 {
4380 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4381 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004382 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004383 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004384 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004385 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
4386 }
4387 else
4388 {
4389 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
4390 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004391 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004392# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01004393 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
4394 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004395 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004396# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004397 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004398# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004399 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004400 bEnableHandler = TRUE;
4401 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004402 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00004403 {
4404 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4405 ENABLE_ECHO_INPUT);
4406 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
4407 bEnableHandler = FALSE;
4408 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004409 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004410 SetConsoleMode(g_hConOut, cmodeout);
4411 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
4412
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004413# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004414 if (fdDump)
4415 {
4416 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
4417 tmode == TMODE_RAW ? "raw" :
4418 tmode == TMODE_COOK ? "cooked" : "normal",
4419 cmodein, cmodeout);
4420 fflush(fdDump);
4421 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004422# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004423}
4424
4425
4426/*
4427 * Get the size of the current window in `Rows' and `Columns'
4428 * Return OK when size could be determined, FAIL otherwise.
4429 */
4430 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004431mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004432{
4433 CONSOLE_SCREEN_BUFFER_INFO csbi;
4434
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004435# ifdef VIMDLL
4436 if (gui.in_use)
4437 return OK;
4438# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004439 if (!g_fTermcapMode && g_cbTermcap.IsValid)
4440 {
4441 /*
4442 * For some reason, we are trying to get the screen dimensions
4443 * even though we are not in termcap mode. The 'Rows' and 'Columns'
4444 * variables are really intended to mean the size of Vim screen
4445 * while in termcap mode.
4446 */
4447 Rows = g_cbTermcap.Info.dwSize.Y;
4448 Columns = g_cbTermcap.Info.dwSize.X;
4449 }
4450 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4451 {
4452 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4453 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4454 }
4455 else
4456 {
4457 Rows = 25;
4458 Columns = 80;
4459 }
4460 return OK;
4461}
4462
4463/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004464 * Resize console buffer to 'COORD'
4465 */
4466 static void
4467ResizeConBuf(
4468 HANDLE hConsole,
4469 COORD coordScreen)
4470{
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00004471 if (use_alternate_screen_buffer)
4472 return;
4473
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004474 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4475 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004476# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004477 if (fdDump)
4478 {
4479 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4480 GetLastError());
4481 fflush(fdDump);
4482 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004483# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004484 }
4485}
4486
4487/*
4488 * Resize console window size to 'srWindowRect'
4489 */
4490 static void
4491ResizeWindow(
4492 HANDLE hConsole,
4493 SMALL_RECT srWindowRect)
4494{
4495 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4496 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004497# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004498 if (fdDump)
4499 {
4500 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4501 GetLastError());
4502 fflush(fdDump);
4503 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004504# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004505 }
4506}
4507
4508/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004509 * Set a console window to `xSize' * `ySize'
4510 */
4511 static void
4512ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004513 HANDLE hConsole,
4514 int xSize,
4515 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004516{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004517 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
4518 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004519 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004520 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004521 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004522
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004523# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004524 if (fdDump)
4525 {
4526 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4527 fflush(fdDump);
4528 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004529# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004530
Bram Moolenaar0f873732019-12-05 20:28:46 +01004531 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00004532 coordScreen = GetLargestConsoleWindowSize(hConsole);
4533
Bram Moolenaar0f873732019-12-05 20:28:46 +01004534 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00004535 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4536 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4537 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4538
4539 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4540 {
4541 int sx, sy;
4542
4543 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4544 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4545 if (sy < ySize || sx < xSize)
4546 {
4547 /*
4548 * Increasing number of lines/columns, do buffer first.
4549 * Use the maximal size in x and y direction.
4550 */
4551 if (sy < ySize)
4552 coordScreen.Y = ySize;
4553 else
4554 coordScreen.Y = sy;
4555 if (sx < xSize)
4556 coordScreen.X = xSize;
4557 else
4558 coordScreen.X = sx;
4559 SetConsoleScreenBufferSize(hConsole, coordScreen);
4560 }
4561 }
4562
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004563 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004564 coordScreen.X = xSize;
4565 coordScreen.Y = ySize;
4566
Bram Moolenaar2551c032018-08-23 22:38:31 +02004567 // In the new console call API, only the first time in reverse order
4568 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004569 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004570 ResizeWindow(hConsole, srWindowRect);
4571 ResizeConBuf(hConsole, coordScreen);
4572 }
4573 else
4574 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004575 // Workaround for a Windows 10 bug
4576 cursor.X = srWindowRect.Left;
4577 cursor.Y = srWindowRect.Top;
4578 SetConsoleCursorPosition(hConsole, cursor);
4579
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004580 ResizeConBuf(hConsole, coordScreen);
4581 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004582 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004583 }
4584}
4585
4586
4587/*
4588 * Set the console window to `Rows' * `Columns'
4589 */
4590 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004591mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004592{
4593 COORD coordScreen;
4594
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004595# ifdef VIMDLL
4596 if (gui.in_use)
4597 return;
4598# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004599 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004600 if (suppress_winsize != 0)
4601 {
4602 suppress_winsize = 2;
4603 return;
4604 }
4605
4606 if (term_console)
4607 {
4608 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4609
Bram Moolenaar0f873732019-12-05 20:28:46 +01004610 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004611 if (Rows > coordScreen.Y)
4612 Rows = coordScreen.Y;
4613 if (Columns > coordScreen.X)
4614 Columns = coordScreen.X;
4615
4616 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4617 }
4618}
4619
4620/*
4621 * Rows and/or Columns has changed.
4622 */
4623 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004624mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004625{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004626# ifdef VIMDLL
4627 if (gui.in_use)
4628 return;
4629# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004630 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4631}
4632
4633
4634/*
4635 * Called when started up, to set the winsize that was delayed.
4636 */
4637 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004638mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004639{
4640 if (suppress_winsize == 2)
4641 {
4642 suppress_winsize = 0;
4643 mch_set_shellsize();
4644 shell_resized();
4645 }
4646 suppress_winsize = 0;
4647}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004648#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004649
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004650 static BOOL
4651vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004652 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004653 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004654 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004655 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004656 PROCESS_INFORMATION *pi,
4657 LPVOID *env,
4658 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004659{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004660 BOOL ret = FALSE;
4661 WCHAR *wcmd, *wcwd = NULL;
4662
4663 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4664 if (wcmd == NULL)
4665 return FALSE;
4666 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004667 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004668 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4669 if (wcwd == NULL)
4670 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004671 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004672
4673 ret = CreateProcessW(
4674 NULL, // Executable name
4675 wcmd, // Command to execute
4676 NULL, // Process security attributes
4677 NULL, // Thread security attributes
4678 inherit_handles, // Inherit handles
4679 flags, // Creation flags
4680 env, // Environment
4681 wcwd, // Current directory
4682 (LPSTARTUPINFOW)si, // Startup information
4683 pi); // Process information
4684theend:
4685 vim_free(wcmd);
4686 vim_free(wcwd);
4687 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004688}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004689
4690
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004691 static HINSTANCE
4692vim_shell_execute(
4693 char *cmd,
4694 INT n_show_cmd)
4695{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004696 HINSTANCE ret;
4697 WCHAR *wcmd;
4698
4699 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4700 if (wcmd == NULL)
4701 return (HINSTANCE) 0;
4702
4703 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4704 vim_free(wcmd);
4705 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004706}
4707
4708
Bram Moolenaar4f974752019-02-17 17:44:42 +01004709#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004710
4711/*
4712 * Specialised version of system() for Win32 GUI mode.
4713 * This version proceeds as follows:
4714 * 1. Create a console window for use by the subprocess
4715 * 2. Run the subprocess (it gets the allocated console by default)
4716 * 3. Wait for the subprocess to terminate and get its exit code
4717 * 4. Prompt the user to press a key to close the console window
4718 */
4719 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004720mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004721{
4722 STARTUPINFO si;
4723 PROCESS_INFORMATION pi;
4724 DWORD ret = 0;
4725 HWND hwnd = GetFocus();
4726
4727 si.cb = sizeof(si);
4728 si.lpReserved = NULL;
4729 si.lpDesktop = NULL;
4730 si.lpTitle = NULL;
4731 si.dwFlags = STARTF_USESHOWWINDOW;
4732 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004733 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004734 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004735 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004736 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004737 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004738 else
4739 si.wShowWindow = SW_SHOWNORMAL;
4740 si.cbReserved2 = 0;
4741 si.lpReserved2 = NULL;
4742
Bram Moolenaar0f873732019-12-05 20:28:46 +01004743 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004744 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004745 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4746 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004747
Bram Moolenaar0f873732019-12-05 20:28:46 +01004748 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004749 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004750# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004751 int delay = 1;
4752
Bram Moolenaar0f873732019-12-05 20:28:46 +01004753 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004754 for (;;)
4755 {
4756 MSG msg;
4757
K.Takatab7057bd2022-01-21 11:37:07 +00004758 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004759 {
4760 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004761 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004762 delay = 1;
4763 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004764 }
4765 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4766 break;
4767
Bram Moolenaar0f873732019-12-05 20:28:46 +01004768 // We start waiting for a very short time and then increase it, so
4769 // that we respond quickly when the process is quick, and don't
4770 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004771 if (delay < 50)
4772 delay += 10;
4773 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004774# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004775 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004776# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004777
Bram Moolenaar0f873732019-12-05 20:28:46 +01004778 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004779 GetExitCodeProcess(pi.hProcess, &ret);
4780 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004781
Bram Moolenaar0f873732019-12-05 20:28:46 +01004782 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004783 CloseHandle(pi.hThread);
4784 CloseHandle(pi.hProcess);
4785
Bram Moolenaar0f873732019-12-05 20:28:46 +01004786 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004787 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4788
4789 return ret;
4790}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004791
4792/*
4793 * Thread launched by the gui to send the current buffer data to the
4794 * process. This way avoid to hang up vim totally if the children
4795 * process take a long time to process the lines.
4796 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004797 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004798sub_process_writer(LPVOID param)
4799{
4800 HANDLE g_hChildStd_IN_Wr = param;
4801 linenr_T lnum = curbuf->b_op_start.lnum;
4802 DWORD len = 0;
4803 DWORD l;
4804 char_u *lp = ml_get(lnum);
4805 char_u *s;
4806 int written = 0;
4807
4808 for (;;)
4809 {
4810 l = (DWORD)STRLEN(lp + written);
4811 if (l == 0)
4812 len = 0;
4813 else if (lp[written] == NL)
4814 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004815 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004816 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4817 }
4818 else
4819 {
4820 s = vim_strchr(lp + written, NL);
4821 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4822 s == NULL ? l : (DWORD)(s - (lp + written)),
4823 &len, NULL);
4824 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004825 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004826 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004827 // Finished a line, add a NL, unless this line should not have
4828 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004829 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004830 || (!curbuf->b_p_bin
4831 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004832 || (lnum != curbuf->b_no_eol_lnum
4833 && (lnum != curbuf->b_ml.ml_line_count
4834 || curbuf->b_p_eol)))
4835 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004836 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4837 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004838 }
4839
4840 ++lnum;
4841 if (lnum > curbuf->b_op_end.lnum)
4842 break;
4843
4844 lp = ml_get(lnum);
4845 written = 0;
4846 }
4847 else if (len > 0)
4848 written += len;
4849 }
4850
Bram Moolenaar0f873732019-12-05 20:28:46 +01004851 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004852 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004853 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004854}
4855
4856
Bram Moolenaar0f873732019-12-05 20:28:46 +01004857# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004858
4859/*
4860 * This function read from the children's stdout and write the
4861 * data on screen or in the buffer accordingly.
4862 */
4863 static void
4864dump_pipe(int options,
4865 HANDLE g_hChildStd_OUT_Rd,
4866 garray_T *ga,
4867 char_u buffer[],
4868 DWORD *buffer_off)
4869{
4870 DWORD availableBytes = 0;
4871 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004872 int ret;
4873 DWORD len;
4874 DWORD toRead;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004875
Bram Moolenaar0f873732019-12-05 20:28:46 +01004876 // we query the pipe to see if there is any data to read
4877 // to avoid to perform a blocking read
4878 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4879 NULL, // optional buffer
4880 0, // buffer size
4881 NULL, // number of read bytes
4882 &availableBytes, // available bytes total
4883 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004884
Bram Moolenaar0f873732019-12-05 20:28:46 +01004885 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004886 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004887 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01004888 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004889 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004890 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004891
Bram Moolenaar0f873732019-12-05 20:28:46 +01004892 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004893 if (len == 0)
4894 break;
4895
4896 availableBytes -= len;
4897
4898 if (options & SHELL_READ)
4899 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004900 // Do NUL -> NL translation, append NL separated
4901 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004902 for (i = 0; i < len; ++i)
4903 {
4904 if (buffer[i] == NL)
4905 append_ga_line(ga);
4906 else if (buffer[i] == NUL)
4907 ga_append(ga, NL);
4908 else
4909 ga_append(ga, buffer[i]);
4910 }
4911 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004912 else if (has_mbyte)
4913 {
4914 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004915 int c;
4916 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004917
4918 len += *buffer_off;
4919 buffer[len] = NUL;
4920
Bram Moolenaar0f873732019-12-05 20:28:46 +01004921 // Check if the last character in buffer[] is
4922 // incomplete, keep these bytes for the next
4923 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004924 for (p = buffer; p < buffer + len; p += l)
4925 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004926 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004927 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004928 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004929 else if (MB_BYTE2LEN(*p) != l)
4930 break;
4931 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004932 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004933 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004934 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004935 if (len >= 12)
4936 ++p;
4937 else
4938 {
4939 *buffer_off = len;
4940 return;
4941 }
4942 }
4943 c = *p;
4944 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004945 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004946 if (p < buffer + len)
4947 {
4948 *p = c;
4949 *buffer_off = (DWORD)((buffer + len) - p);
4950 mch_memmove(buffer, p, *buffer_off);
4951 return;
4952 }
4953 *buffer_off = 0;
4954 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004955 else
4956 {
4957 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004958 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004959 }
4960
4961 windgoto(msg_row, msg_col);
4962 cursor_on();
4963 out_flush();
4964 }
4965}
4966
4967/*
4968 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4969 * for communication and doesn't open any new window.
4970 */
4971 static int
4972mch_system_piped(char *cmd, int options)
4973{
4974 STARTUPINFO si;
4975 PROCESS_INFORMATION pi;
4976 DWORD ret = 0;
4977
4978 HANDLE g_hChildStd_IN_Rd = NULL;
4979 HANDLE g_hChildStd_IN_Wr = NULL;
4980 HANDLE g_hChildStd_OUT_Rd = NULL;
4981 HANDLE g_hChildStd_OUT_Wr = NULL;
4982
Bram Moolenaar0f873732019-12-05 20:28:46 +01004983 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004984 DWORD len;
4985
Bram Moolenaar0f873732019-12-05 20:28:46 +01004986 // buffer used to receive keys
4987 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4988 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004989
4990 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004991 int noread_cnt = 0;
4992 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004993 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004994 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004995 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004996
4997 SECURITY_ATTRIBUTES saAttr;
4998
Bram Moolenaar0f873732019-12-05 20:28:46 +01004999 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005000 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5001 saAttr.bInheritHandle = TRUE;
5002 saAttr.lpSecurityDescriptor = NULL;
5003
5004 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005005 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005006 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005007 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005008 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005009 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005010 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005011 {
5012 CloseHandle(g_hChildStd_IN_Rd);
5013 CloseHandle(g_hChildStd_IN_Wr);
5014 CloseHandle(g_hChildStd_OUT_Rd);
5015 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01005016 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005017 }
5018
5019 si.cb = sizeof(si);
5020 si.lpReserved = NULL;
5021 si.lpDesktop = NULL;
5022 si.lpTitle = NULL;
5023 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
5024
Bram Moolenaar0f873732019-12-05 20:28:46 +01005025 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005026 si.hStdError = g_hChildStd_OUT_Wr;
5027 si.hStdOutput = g_hChildStd_OUT_Wr;
5028 si.hStdInput = g_hChildStd_IN_Rd;
5029 si.wShowWindow = SW_HIDE;
5030 si.cbReserved2 = 0;
5031 si.lpReserved2 = NULL;
5032
5033 if (options & SHELL_READ)
5034 ga_init2(&ga, 1, BUFLEN);
5035
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005036 if (cmd != NULL)
5037 {
5038 p = (char *)vim_strsave((char_u *)cmd);
5039 if (p != NULL)
5040 unescape_shellxquote((char_u *)p, p_sxe);
5041 else
5042 p = cmd;
5043 }
5044
Bram Moolenaar0f873732019-12-05 20:28:46 +01005045 // Now, run the command.
5046 // About "Inherit handles" being TRUE: this command can be litigious,
5047 // handle inheritance was deactivated for pending temp file, but, if we
5048 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005049 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
5050 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005051
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005052 if (p != cmd)
5053 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005054
Bram Moolenaar0f873732019-12-05 20:28:46 +01005055 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005056 CloseHandle(g_hChildStd_IN_Rd);
5057 CloseHandle(g_hChildStd_OUT_Wr);
5058
5059 if (options & SHELL_WRITE)
5060 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02005061 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005062 _beginthreadex(NULL, // security attributes
5063 0, // default stack size
5064 sub_process_writer, // function to be executed
5065 g_hChildStd_IN_Wr, // parameter
5066 0, // creation flag, start immediately
5067 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005068 CloseHandle(thread);
5069 g_hChildStd_IN_Wr = NULL;
5070 }
5071
Bram Moolenaar0f873732019-12-05 20:28:46 +01005072 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005073 for (;;)
5074 {
5075 MSG msg;
5076
K.Takatab7057bd2022-01-21 11:37:07 +00005077 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005078 {
5079 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00005080 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005081 }
5082
Bram Moolenaar0f873732019-12-05 20:28:46 +01005083 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005084 if ((options & (SHELL_READ|SHELL_WRITE))
5085# ifdef FEAT_GUI
5086 || gui.in_use
5087# endif
5088 )
5089 {
5090 len = 0;
5091 if (!(options & SHELL_EXPAND)
5092 && ((options &
5093 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
5094 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
5095# ifdef FEAT_GUI
5096 || gui.in_use
5097# endif
5098 )
5099 && (ta_len > 0 || noread_cnt > 4))
5100 {
5101 if (ta_len == 0)
5102 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005103 // Get extra characters when we don't have any. Reset the
5104 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005105 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005106 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
5107 }
5108 if (ta_len > 0 || len > 0)
5109 {
5110 /*
5111 * For pipes: Check for CTRL-C: send interrupt signal to
5112 * child. Check for CTRL-D: EOF, close pipe to child.
5113 */
5114 if (len == 1 && cmd != NULL)
5115 {
5116 if (ta_buf[ta_len] == Ctrl_C)
5117 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005118 // Learn what exit code is expected, for
5119 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005120 TerminateProcess(pi.hProcess, 9);
5121 }
5122 if (ta_buf[ta_len] == Ctrl_D)
5123 {
5124 CloseHandle(g_hChildStd_IN_Wr);
5125 g_hChildStd_IN_Wr = NULL;
5126 }
5127 }
5128
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01005129 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005130
5131 /*
5132 * For pipes: echo the typed characters. For a pty this
5133 * does not seem to work.
5134 */
5135 for (i = ta_len; i < ta_len + len; ++i)
5136 {
5137 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
5138 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005139 else if (has_mbyte)
5140 {
5141 int l = (*mb_ptr2len)(ta_buf + i);
5142
5143 msg_outtrans_len(ta_buf + i, l);
5144 i += l - 1;
5145 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005146 else
5147 msg_outtrans_len(ta_buf + i, 1);
5148 }
5149 windgoto(msg_row, msg_col);
5150 out_flush();
5151
5152 ta_len += len;
5153
5154 /*
5155 * Write the characters to the child, unless EOF has been
5156 * typed for pipes. Write one character at a time, to
5157 * avoid losing too much typeahead. When writing buffer
5158 * lines, drop the typed characters (only check for
5159 * CTRL-C).
5160 */
5161 if (options & SHELL_WRITE)
5162 ta_len = 0;
5163 else if (g_hChildStd_IN_Wr != NULL)
5164 {
5165 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
5166 1, &len, NULL);
5167 // if we are typing in, we want to keep things reactive
5168 delay = 1;
5169 if (len > 0)
5170 {
5171 ta_len -= len;
5172 mch_memmove(ta_buf, ta_buf + len, ta_len);
5173 }
5174 }
5175 }
5176 }
5177 }
5178
5179 if (ta_len)
5180 ui_inchar_undo(ta_buf, ta_len);
5181
5182 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
5183 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005184 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005185 break;
5186 }
5187
5188 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005189 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005190
Bram Moolenaar0f873732019-12-05 20:28:46 +01005191 // We start waiting for a very short time and then increase it, so
5192 // that we respond quickly when the process is quick, and don't
5193 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005194 if (delay < 50)
5195 delay += 10;
5196 }
5197
Bram Moolenaar0f873732019-12-05 20:28:46 +01005198 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005199 CloseHandle(g_hChildStd_OUT_Rd);
5200 if (g_hChildStd_IN_Wr != NULL)
5201 CloseHandle(g_hChildStd_IN_Wr);
5202
5203 WaitForSingleObject(pi.hProcess, INFINITE);
5204
Bram Moolenaar0f873732019-12-05 20:28:46 +01005205 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005206 GetExitCodeProcess(pi.hProcess, &ret);
5207
5208 if (options & SHELL_READ)
5209 {
5210 if (ga.ga_len > 0)
5211 {
5212 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01005213 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005214 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
5215 }
5216 else
5217 curbuf->b_no_eol_lnum = 0;
5218 ga_clear(&ga);
5219 }
5220
Bram Moolenaar0f873732019-12-05 20:28:46 +01005221 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005222 CloseHandle(pi.hThread);
5223 CloseHandle(pi.hProcess);
5224
5225 return ret;
5226}
5227
5228 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005229mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005230{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005231 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005232 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005233 return mch_system_piped(cmd, options);
5234 else
5235 return mch_system_classic(cmd, options);
5236}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005237#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005238
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005239#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005240 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02005241mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005242{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005243 int ret;
5244 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005245 char_u *buf;
5246 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005247
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005248 // If the command starts and ends with double quotes, enclose the command
5249 // in parentheses.
5250 len = STRLEN(cmd);
5251 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
5252 {
5253 len += 3;
5254 buf = alloc(len);
5255 if (buf == NULL)
5256 return -1;
5257 vim_snprintf((char *)buf, len, "(%s)", cmd);
5258 wcmd = enc_to_utf16(buf, NULL);
5259 free(buf);
5260 }
5261 else
5262 wcmd = enc_to_utf16((char_u *)cmd, NULL);
5263
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005264 if (wcmd == NULL)
5265 return -1;
5266
5267 ret = _wsystem(wcmd);
5268 vim_free(wcmd);
5269 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005270}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005271
5272#endif
5273
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005274 static int
5275mch_system(char *cmd, int options)
5276{
5277#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005278 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005279 return mch_system_g(cmd, options);
5280 else
5281 return mch_system_c(cmd, options);
5282#elif defined(FEAT_GUI_MSWIN)
5283 return mch_system_g(cmd, options);
5284#else
5285 return mch_system_c(cmd, options);
5286#endif
5287}
5288
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005289#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
5290/*
5291 * Use a terminal window to run a shell command in.
5292 */
5293 static int
5294mch_call_shell_terminal(
5295 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005296 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005297{
5298 jobopt_T opt;
5299 char_u *newcmd = NULL;
5300 typval_T argvar[2];
5301 long_u cmdlen;
5302 int retval = -1;
5303 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005304 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005305 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005306 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005307
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005308 if (cmd == NULL)
5309 cmdlen = STRLEN(p_sh) + 1;
5310 else
5311 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005312 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005313 if (newcmd == NULL)
5314 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005315 if (cmd == NULL)
5316 {
5317 STRCPY(newcmd, p_sh);
5318 ch_log(NULL, "starting terminal to run a shell");
5319 }
5320 else
5321 {
5322 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
5323 ch_log(NULL, "starting terminal for system command '%s'", cmd);
5324 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005325
5326 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005327
5328 argvar[0].v_type = VAR_STRING;
5329 argvar[0].vval.v_string = newcmd;
5330 argvar[1].v_type = VAR_UNKNOWN;
5331 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005332 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01005333 {
5334 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005335 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01005336 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005337
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005338 job = term_getjob(buf->b_term);
5339 ++job->jv_refcount;
5340
Bram Moolenaar0f873732019-12-05 20:28:46 +01005341 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005342 aucmd_prepbuf(&aco, buf);
Bram Moolenaare76062c2022-11-28 18:51:43 +00005343 if (curbuf == buf)
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005344 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005345 // Only do this when a window was found for "buf".
5346 clear_oparg(&oa);
5347 while (term_use_loop())
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005348 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005349 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
5350 {
5351 // If terminal_loop() returns OK we got a key that is handled
5352 // in Normal model. We don't do redrawing anyway.
5353 if (terminal_loop(TRUE) == OK)
5354 normal_cmd(&oa, TRUE);
5355 }
5356 else
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005357 normal_cmd(&oa, TRUE);
5358 }
Bram Moolenaare76062c2022-11-28 18:51:43 +00005359 retval = job->jv_exitval;
5360 ch_log(NULL, "system command finished");
5361
5362 job_unref(job);
5363
5364 // restore curwin/curbuf and a few other things
5365 aucmd_restbuf(&aco);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005366 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005367
5368 wait_return(TRUE);
5369 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
5370
5371 vim_free(newcmd);
5372 return retval;
5373}
5374#endif
5375
Bram Moolenaar071d4272004-06-13 20:20:40 +00005376/*
5377 * Either execute a command by calling the shell or start a new shell
5378 */
5379 int
5380mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005381 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005382 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00005383{
5384 int x = 0;
5385 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005386 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02005387
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00005388#ifdef FEAT_EVAL
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01005389 ch_log(NULL, "executing shell command: %s", cmd);
5390#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01005391 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02005392 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005393 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005394 if (cmd == NULL)
5395 wcscat(szShellTitle, L" :sh");
5396 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005397 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005398 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005399
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005400 if (wn != NULL)
5401 {
5402 wcscat(szShellTitle, L" - !");
5403 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02005404 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005405 wcscat(szShellTitle, wn);
5406 SetConsoleTitleW(szShellTitle);
5407 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005408 }
5409 }
5410 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005411
5412 out_flush();
5413
5414#ifdef MCH_WRITE_DUMP
5415 if (fdDump)
5416 {
5417 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
5418 fflush(fdDump);
5419 }
5420#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005421#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005422 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005423 if (
5424# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005425 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005426# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005427 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005428 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
5429 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005430 char_u *cmdbase = cmd;
5431
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02005432 if (cmdbase != NULL)
5433 // Skip a leading quote and (.
5434 while (*cmdbase == '"' || *cmdbase == '(')
5435 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005436
5437 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01005438 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
5439 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005440 {
5441 // Use a terminal window to run the command in.
5442 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005443 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005444 return x;
5445 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005446 }
5447#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005448
5449 /*
5450 * Catch all deadly signals while running the external command, because a
5451 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5452 */
ichizok378447f2023-05-11 22:25:42 +01005453 mch_signal(SIGINT, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005454#if defined(__GNUC__) && !defined(__MINGW32__)
ichizok378447f2023-05-11 22:25:42 +01005455 mch_signal(SIGKILL, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005456#else
ichizok378447f2023-05-11 22:25:42 +01005457 mch_signal(SIGBREAK, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005458#endif
ichizok378447f2023-05-11 22:25:42 +01005459 mch_signal(SIGILL, SIG_IGN);
5460 mch_signal(SIGFPE, SIG_IGN);
5461 mch_signal(SIGSEGV, SIG_IGN);
5462 mch_signal(SIGTERM, SIG_IGN);
5463 mch_signal(SIGABRT, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005464
5465 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005466 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00005467
5468 if (cmd == NULL)
5469 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005470 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005471 }
5472 else
5473 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005474 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005475 char_u *newcmd = NULL;
5476 char_u *cmdbase = cmd;
5477 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005478
Bram Moolenaar0f873732019-12-05 20:28:46 +01005479 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005480 if (*cmdbase == '"' )
5481 ++cmdbase;
5482 if (*cmdbase == '(')
5483 ++cmdbase;
5484
Bram Moolenaar1c465442017-03-12 20:10:05 +01005485 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005486 {
5487 STARTUPINFO si;
5488 PROCESS_INFORMATION pi;
5489 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005490 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005491 char_u *p;
5492
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005493 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005494 si.cb = sizeof(si);
5495 si.lpReserved = NULL;
5496 si.lpDesktop = NULL;
5497 si.lpTitle = NULL;
5498 si.dwFlags = 0;
5499 si.cbReserved2 = 0;
5500 si.lpReserved2 = NULL;
5501
5502 cmdbase = skipwhite(cmdbase + 5);
5503 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005504 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005505 {
5506 cmdbase = skipwhite(cmdbase + 4);
5507 si.dwFlags = STARTF_USESHOWWINDOW;
5508 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005509 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005510 }
5511 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005512 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005513 {
5514 cmdbase = skipwhite(cmdbase + 2);
5515 flags = CREATE_NO_WINDOW;
5516 si.dwFlags = STARTF_USESTDHANDLES;
5517 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005518 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005519 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005520 NULL, // Security att.
5521 OPEN_EXISTING, // Open flags
5522 FILE_ATTRIBUTE_NORMAL, // File att.
5523 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005524 si.hStdOutput = si.hStdInput;
5525 si.hStdError = si.hStdInput;
5526 }
5527
Bram Moolenaar0f873732019-12-05 20:28:46 +01005528 // Remove a trailing ", ) and )" if they have a match
5529 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005530 if (cmdbase > cmd)
5531 {
5532 p = cmdbase + STRLEN(cmdbase);
5533 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5534 *--p = NUL;
5535 if (p > cmdbase && p[-1] == ')'
5536 && (*cmd =='(' || cmd[1] == '('))
5537 *--p = NUL;
5538 }
5539
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005540 newcmd = cmdbase;
5541 unescape_shellxquote(cmdbase, p_sxe);
5542
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005543 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005544 * If creating new console, arguments are passed to the
5545 * 'cmd.exe' as-is. If it's not, arguments are not treated
5546 * correctly for current 'cmd.exe'. So unescape characters in
5547 * shellxescape except '|' for avoiding to be treated as
5548 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005549 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005550 if (flags != CREATE_NEW_CONSOLE)
5551 {
5552 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005553 char_u *cmd_shell = mch_getenv("COMSPEC");
5554
5555 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005556 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005557
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005558 subcmd = vim_strsave_escaped_ext(cmdbase,
5559 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005560 if (subcmd != NULL)
5561 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005562 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005563 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005564 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005565 if (newcmd != NULL)
5566 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005567 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005568 else
5569 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005570 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005571 }
5572 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005573
5574 /*
5575 * Now, start the command as a process, so that it doesn't
5576 * inherit our handles which causes unpleasant dangling swap
5577 * files if we exit before the spawned process
5578 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005579 if (vim_create_process((char *)newcmd, FALSE, flags,
5580 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005581 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005582 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5583 > (HINSTANCE)32)
5584 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005585 else
5586 {
5587 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005588#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005589# ifdef VIMDLL
5590 if (gui.in_use)
5591# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005592 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005593#endif
5594 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005595
5596 if (newcmd != cmdbase)
5597 vim_free(newcmd);
5598
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005599 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005600 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005601 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005602 CloseHandle(si.hStdInput);
5603 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005604 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005605 CloseHandle(pi.hThread);
5606 CloseHandle(pi.hProcess);
5607 }
5608 else
5609 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005610 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005611#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005612 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005613 (!s_dont_use_vimrun && p_stmp ?
5614 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5615 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005616#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005617 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005618
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005619 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005620 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005621 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005622#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005623 if (
5624# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005625 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005626# endif
5627 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005628 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005629 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5630 "External commands will not pause after completion.\n"
5631 "See :help win32-vimrun for more information.");
5632 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005633 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5634 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005635
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005636 if (wmsg != NULL && wtitle != NULL)
5637 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5638 vim_free(wmsg);
5639 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005640 need_vimrun_warning = FALSE;
5641 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005642 if (
5643# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005644 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005645# endif
5646 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005647 // Use vimrun to execute the command. It opens a console
5648 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005649 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005650 vimrun_path,
5651 (msg_silent != 0 || (options & SHELL_DOOUT))
5652 ? "-s " : "",
5653 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005654 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005655# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005656 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005657# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005658 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005659 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005660 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5661 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005662 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005663#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005664 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005665 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005666 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005667 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005668 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005669 }
5670 }
5671
5672 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005673 {
5674 // The shell may have messed with the mode, always set it.
5675 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005676 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005677 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005678
Bram Moolenaar0f873732019-12-05 20:28:46 +01005679 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005680 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005681#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005682 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005683 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005684#endif
5685 )
5686 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005687 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005688 msg_putchar('\n');
5689 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005690 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005691
ichizok378447f2023-05-11 22:25:42 +01005692 mch_signal(SIGINT, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005693#if defined(__GNUC__) && !defined(__MINGW32__)
ichizok378447f2023-05-11 22:25:42 +01005694 mch_signal(SIGKILL, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005695#else
ichizok378447f2023-05-11 22:25:42 +01005696 mch_signal(SIGBREAK, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005697#endif
ichizok378447f2023-05-11 22:25:42 +01005698 mch_signal(SIGILL, SIG_DFL);
5699 mch_signal(SIGFPE, SIG_DFL);
5700 mch_signal(SIGSEGV, SIG_DFL);
5701 mch_signal(SIGTERM, SIG_DFL);
5702 mch_signal(SIGABRT, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005703
5704 return x;
5705}
5706
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005707#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005708 static HANDLE
5709job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005710 char_u *fname,
5711 DWORD dwDesiredAccess,
5712 DWORD dwShareMode,
5713 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5714 DWORD dwCreationDisposition,
5715 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005716{
5717 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005718 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005719
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005720 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005721 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005722 return INVALID_HANDLE_VALUE;
5723
5724 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5725 lpSecurityAttributes, dwCreationDisposition,
5726 dwFlagsAndAttributes, NULL);
5727 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005728 return h;
5729}
5730
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005731/*
5732 * Turn the dictionary "env" into a NUL separated list that can be used as the
5733 * environment argument of vim_create_process().
5734 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005735 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005736win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005737{
5738 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005739 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005740 LPVOID base = GetEnvironmentStringsW();
5741
Bram Moolenaar0f873732019-12-05 20:28:46 +01005742 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005743 if (ga_grow(gap, 1) == FAIL)
5744 return;
5745
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005746 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005747 {
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00005748 FOR_ALL_HASHTAB_ITEMS(&env->dv_hashtab, hi, todo)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005749 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005750 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005751 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005752 typval_T *item = &dict_lookup(hi)->di_tv;
5753 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005754 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005755 --todo;
5756 if (wkey != NULL && wval != NULL)
5757 {
5758 size_t n;
5759 size_t lkey = wcslen(wkey);
5760 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005761
Yegappan Lakshmananfadc02a2023-01-27 21:03:12 +00005762 if (ga_grow(gap, (int)(lkey + lval + 2)) == FAIL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005763 continue;
5764 for (n = 0; n < lkey; n++)
5765 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5766 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5767 for (n = 0; n < lval; n++)
5768 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5769 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5770 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005771 vim_free(wkey);
5772 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005773 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005774 }
5775 }
5776
Bram Moolenaar355757a2020-02-10 22:06:32 +01005777 if (base)
5778 {
5779 WCHAR *p = (WCHAR*) base;
5780
5781 // for last \0
5782 if (ga_grow(gap, 1) == FAIL)
5783 return;
5784
5785 while (*p != 0 || *(p + 1) != 0)
5786 {
5787 if (ga_grow(gap, 1) == OK)
5788 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5789 p++;
5790 }
5791 FreeEnvironmentStrings(base);
5792 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5793 }
5794
Bram Moolenaar493359e2018-06-12 20:25:52 +02005795# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005796 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005797# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005798 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005799 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005800# endif
5801# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005802 char_u *version = get_vim_var_str(VV_VERSION);
5803 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005804# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005805 // size of "VIM_SERVERNAME=" and value,
5806 // plus "VIM_TERMINAL=" and value,
5807 // plus two terminating NULs
5808 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005809# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005810 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005811# endif
5812# ifdef FEAT_TERMINAL
5813 + 13 + version_len + 2
5814# endif
5815 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005816
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005817 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005818 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005819# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005820 for (n = 0; n < 15; n++)
5821 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5822 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005823 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005824 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5825 (WCHAR)servername[n];
5826 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005827# endif
5828# ifdef FEAT_TERMINAL
5829 if (is_terminal)
5830 {
5831 for (n = 0; n < 13; n++)
5832 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5833 (WCHAR)"VIM_TERMINAL="[n];
5834 for (n = 0; n < version_len; n++)
5835 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5836 (WCHAR)version[n];
5837 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5838 }
5839# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005840 }
5841 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005842# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005843}
5844
Bram Moolenaarb091f302019-01-19 14:37:00 +01005845/*
5846 * Create a pair of pipes.
5847 * Return TRUE for success, FALSE for failure.
5848 */
5849 static BOOL
5850create_pipe_pair(HANDLE handles[2])
5851{
5852 static LONG s;
5853 char name[64];
5854 SECURITY_ATTRIBUTES sa;
5855
5856 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5857 GetCurrentProcessId(),
5858 InterlockedIncrement(&s));
5859
5860 // Create named pipe. Max size of named pipe is 65535.
5861 handles[1] = CreateNamedPipe(
5862 name,
5863 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5864 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005865 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005866
5867 if (handles[1] == INVALID_HANDLE_VALUE)
5868 return FALSE;
5869
5870 sa.nLength = sizeof(sa);
5871 sa.bInheritHandle = TRUE;
5872 sa.lpSecurityDescriptor = NULL;
5873
5874 handles[0] = CreateFile(name,
5875 FILE_GENERIC_READ,
5876 FILE_SHARE_READ, &sa,
5877 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5878
5879 if (handles[0] == INVALID_HANDLE_VALUE)
5880 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005881 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005882 return FALSE;
5883 }
5884
5885 return TRUE;
5886}
5887
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005888 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005889mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005890{
5891 STARTUPINFO si;
5892 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005893 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005894 SECURITY_ATTRIBUTES saAttr;
5895 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005896 HANDLE ifd[2];
5897 HANDLE ofd[2];
5898 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005899 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005900
5901 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5902 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5903 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5904 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5905 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5906 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5907 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5908
5909 if (use_out_for_err && use_null_for_out)
5910 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005911
5912 ifd[0] = INVALID_HANDLE_VALUE;
5913 ifd[1] = INVALID_HANDLE_VALUE;
5914 ofd[0] = INVALID_HANDLE_VALUE;
5915 ofd[1] = INVALID_HANDLE_VALUE;
5916 efd[0] = INVALID_HANDLE_VALUE;
5917 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005918 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005919
Bram Moolenaar14207f42016-10-27 21:13:10 +02005920 jo = CreateJobObject(NULL, NULL);
5921 if (jo == NULL)
5922 {
5923 job->jv_status = JOB_FAILED;
5924 goto failed;
5925 }
5926
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005927 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005928 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005929
Bram Moolenaar76467df2016-02-12 19:30:26 +01005930 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005931 ZeroMemory(&si, sizeof(si));
5932 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005933 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005934 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005935
Bram Moolenaard8070362016-02-15 21:56:54 +01005936 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5937 saAttr.bInheritHandle = TRUE;
5938 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005939
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005940 if (use_file_for_in)
5941 {
5942 char_u *fname = options->jo_io_name[PART_IN];
5943
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005944 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5945 FILE_SHARE_READ | FILE_SHARE_WRITE,
5946 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5947 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005948 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005949 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005950 goto failed;
5951 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005952 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005953 else if (!use_null_for_in
5954 && (!create_pipe_pair(ifd)
5955 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005956 goto failed;
5957
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005958 if (use_file_for_out)
5959 {
5960 char_u *fname = options->jo_io_name[PART_OUT];
5961
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005962 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5963 FILE_SHARE_READ | FILE_SHARE_WRITE,
5964 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5965 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005966 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005967 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005968 goto failed;
5969 }
5970 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005971 else if (!use_null_for_out &&
5972 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005973 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005974 goto failed;
5975
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005976 if (use_file_for_err)
5977 {
5978 char_u *fname = options->jo_io_name[PART_ERR];
5979
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005980 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5981 FILE_SHARE_READ | FILE_SHARE_WRITE,
5982 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5983 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005984 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005985 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005986 goto failed;
5987 }
5988 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005989 else if (!use_out_for_err && !use_null_for_err &&
5990 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005991 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005992 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005993
Bram Moolenaard8070362016-02-15 21:56:54 +01005994 si.dwFlags |= STARTF_USESTDHANDLES;
5995 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005996 si.hStdOutput = ofd[1];
5997 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5998
5999 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
6000 {
Bram Moolenaarde279892016-03-11 22:19:44 +01006001 if (options->jo_set & JO_CHANNEL)
6002 {
6003 channel = options->jo_channel;
6004 if (channel != NULL)
6005 ++channel->ch_refcount;
6006 }
6007 else
6008 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006009 if (channel == NULL)
6010 goto failed;
6011 }
Bram Moolenaard8070362016-02-15 21:56:54 +01006012
6013 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02006014 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006015 CREATE_DEFAULT_ERROR_MODE |
6016 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006017 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01006018 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006019 &si, &pi,
6020 ga.ga_data,
6021 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01006022 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02006023 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006024 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006025 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006026 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006027
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006028 ga_clear(&ga);
6029
Bram Moolenaar14207f42016-10-27 21:13:10 +02006030 if (!AssignProcessToJobObject(jo, pi.hProcess))
6031 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006032 // if failing, switch the way to terminate
6033 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02006034 CloseHandle(jo);
6035 jo = NULL;
6036 }
6037 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01006038 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006039 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02006040 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006041 job->jv_status = JOB_STARTED;
6042
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02006043 CloseHandle(ifd[0]);
6044 CloseHandle(ofd[1]);
6045 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01006046 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01006047
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006048 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006049 if (channel != NULL)
6050 {
6051 channel_set_pipes(channel,
6052 use_file_for_in || use_null_for_in
6053 ? INVALID_FD : (sock_T)ifd[1],
6054 use_file_for_out || use_null_for_out
6055 ? INVALID_FD : (sock_T)ofd[0],
6056 use_out_for_err || use_file_for_err || use_null_for_err
6057 ? INVALID_FD : (sock_T)efd[0]);
6058 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006059 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006060 return;
6061
6062failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01006063 CloseHandle(ifd[0]);
6064 CloseHandle(ofd[0]);
6065 CloseHandle(efd[0]);
6066 CloseHandle(ifd[1]);
6067 CloseHandle(ofd[1]);
6068 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01006069 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006070 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006071}
6072
6073 char *
6074mch_job_status(job_T *job)
6075{
6076 DWORD dwExitCode = 0;
6077
Bram Moolenaar76467df2016-02-12 19:30:26 +01006078 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
6079 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006080 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01006081 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01006082 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02006083 {
6084 ch_log(job->jv_channel, "Job ended");
6085 job->jv_status = JOB_ENDED;
6086 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006087 return "dead";
6088 }
6089 return "run";
6090}
6091
Bram Moolenaar97792de2016-10-15 18:36:49 +02006092 job_T *
6093mch_detect_ended_job(job_T *job_list)
6094{
6095 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
6096 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
6097 job_T *job = job_list;
6098
6099 while (job != NULL)
6100 {
6101 DWORD n;
6102 DWORD result;
6103
6104 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
6105 && job != NULL; job = job->jv_next)
6106 {
6107 if (job->jv_status == JOB_STARTED)
6108 {
6109 jobHandles[n] = job->jv_proc_info.hProcess;
6110 jobArray[n] = job;
6111 ++n;
6112 }
6113 }
6114 if (n == 0)
6115 continue;
6116 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
6117 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
6118 {
6119 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
6120
6121 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
6122 return wait_job;
6123 }
6124 }
6125 return NULL;
6126}
6127
Bram Moolenaarfb630902016-10-29 14:55:00 +02006128 static BOOL
6129terminate_all(HANDLE process, int code)
6130{
6131 PROCESSENTRY32 pe;
6132 HANDLE h = INVALID_HANDLE_VALUE;
6133 DWORD pid = GetProcessId(process);
6134
6135 if (pid != 0)
6136 {
6137 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
6138 if (h != INVALID_HANDLE_VALUE)
6139 {
6140 pe.dwSize = sizeof(PROCESSENTRY32);
6141 if (!Process32First(h, &pe))
6142 goto theend;
6143
6144 do
6145 {
6146 if (pe.th32ParentProcessID == pid)
6147 {
6148 HANDLE ph = OpenProcess(
6149 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
6150 if (ph != NULL)
6151 {
6152 terminate_all(ph, code);
6153 CloseHandle(ph);
6154 }
6155 }
6156 } while (Process32Next(h, &pe));
6157
6158 CloseHandle(h);
6159 }
6160 }
6161
6162theend:
6163 return TerminateProcess(process, code);
6164}
6165
6166/*
6167 * Send a (deadly) signal to "job".
6168 * Return FAIL if it didn't work.
6169 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006170 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02006171mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006172{
Bram Moolenaar923d9262016-02-25 20:56:01 +01006173 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006174
Bram Moolenaar923d9262016-02-25 20:56:01 +01006175 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01006176 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006177 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02006178 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006179 {
6180 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
6181 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00006182 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006183 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01006184 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006185 }
6186
6187 if (!AttachConsole(job->jv_proc_info.dwProcessId))
6188 return FAIL;
6189 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01006190 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
6191 job->jv_proc_info.dwProcessId)
6192 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006193 FreeConsole();
6194 return ret;
6195}
6196
6197/*
6198 * Clear the data related to "job".
6199 */
6200 void
6201mch_clear_job(job_T *job)
6202{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00006203 if (job->jv_status == JOB_FAILED)
6204 return;
6205
6206 if (job->jv_job_object != NULL)
6207 CloseHandle(job->jv_job_object);
6208 CloseHandle(job->jv_proc_info.hProcess);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006209}
6210#endif
6211
Bram Moolenaar071d4272004-06-13 20:20:40 +00006212
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006213#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006214
6215/*
6216 * Start termcap mode
6217 */
6218 static void
6219termcap_mode_start(void)
6220{
6221 DWORD cmodein;
6222
6223 if (g_fTermcapMode)
6224 return;
6225
6226 SaveConsoleBuffer(&g_cbNonTermcap);
6227
6228 if (g_cbTermcap.IsValid)
6229 {
6230 /*
6231 * We've been in termcap mode before. Restore certain screen
6232 * characteristics, including the buffer size and the window
6233 * size. Since we will be redrawing the screen, we don't need
6234 * to restore the actual contents of the buffer.
6235 */
6236 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006237 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006238 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
6239 Rows = g_cbTermcap.Info.dwSize.Y;
6240 Columns = g_cbTermcap.Info.dwSize.X;
6241 }
6242 else
6243 {
6244 /*
6245 * This is our first time entering termcap mode. Clear the console
6246 * screen buffer, and resize the buffer to match the current window
6247 * size. We will use this as the size of our editing environment.
6248 */
6249 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006250 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006251 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
6252 }
6253
Bram Moolenaar071d4272004-06-13 20:20:40 +00006254 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006255
6256 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006257 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006258 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006259 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006260 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
6261 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006262 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006263 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006264 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006265 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6266 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006267 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006268 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006269
6270 redraw_later_clear();
6271 g_fTermcapMode = TRUE;
6272}
6273
6274
6275/*
6276 * End termcap mode
6277 */
6278 static void
6279termcap_mode_end(void)
6280{
6281 DWORD cmodein;
6282 ConsoleBuffer *cb;
6283 COORD coord;
6284 DWORD dwDummy;
6285
6286 if (!g_fTermcapMode)
6287 return;
6288
6289 SaveConsoleBuffer(&g_cbTermcap);
6290
6291 GetConsoleMode(g_hConIn, &cmodein);
6292 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006293 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6294 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006295
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006296# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01006297 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006298# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006299 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006300# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006301 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01006302 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006303
Christopher Plewright1140b512022-11-12 18:46:05 +00006304 // Switch back to main screen buffer.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00006305 if (exiting && use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00006306 vtp_printf("\033[?1049l");
6307
6308 if (!USE_WT && (p_rs || exiting))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006309 {
6310 /*
6311 * Clear anything that happens to be on the current line.
6312 */
6313 coord.X = 0;
6314 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006315 FillConsoleOutputCharacter(g_hConOut, ' ',
6316 cb->Info.dwSize.X, coord, &dwDummy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006317 /*
6318 * The following is just for aesthetics. If we are exiting without
6319 * restoring the screen, then we want to have a prompt string
6320 * appear at the bottom line. However, the command interpreter
6321 * seems to always advance the cursor one line before displaying
6322 * the prompt string, which causes the screen to scroll. To
6323 * counter this, move the cursor up one line before exiting.
6324 */
6325 if (exiting && !p_rs)
6326 coord.Y--;
6327 /*
6328 * Position the cursor at the leftmost column of the desired row.
6329 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006330 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006331 }
Christopher Plewright1140b512022-11-12 18:46:05 +00006332 SetConsoleCursorInfo(g_hConOut, &g_cci);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006333 g_fTermcapMode = FALSE;
6334}
Christopher Plewright38804d62022-11-09 23:55:52 +00006335#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006336
6337
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006338#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006339 void
6340mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01006341 char_u *s UNUSED,
6342 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006343{
Bram Moolenaar0f873732019-12-05 20:28:46 +01006344 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00006345}
6346
6347#else
6348
6349/*
6350 * clear `n' chars, starting from `coord'
6351 */
6352 static void
6353clear_chars(
6354 COORD coord,
6355 DWORD n)
6356{
Christopher Plewright38804d62022-11-09 23:55:52 +00006357 if (!vtp_working)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006358 {
6359 DWORD dwDummy;
6360
6361 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
6362 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
6363 &dwDummy);
6364 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006365 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02006366 {
6367 set_console_color_rgb();
6368 gotoxy(coord.X + 1, coord.Y + 1);
6369 vtp_printf("\033[%dX", n);
6370 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006371}
6372
6373
6374/*
6375 * Clear the screen
6376 */
6377 static void
6378clear_screen(void)
6379{
6380 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006381
Christopher Plewright38804d62022-11-09 23:55:52 +00006382 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006383 clear_chars(g_coord, Rows * Columns);
6384 else
6385 {
6386 set_console_color_rgb();
6387 gotoxy(1, 1);
6388 vtp_printf("\033[2J");
6389 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006390}
6391
6392
6393/*
6394 * Clear to end of display
6395 */
6396 static void
6397clear_to_end_of_display(void)
6398{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006399 COORD save = g_coord;
6400
Christopher Plewright38804d62022-11-09 23:55:52 +00006401 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006402 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006403 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006404 else
6405 {
6406 set_console_color_rgb();
6407 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6408 vtp_printf("\033[0J");
6409
6410 gotoxy(save.X + 1, save.Y + 1);
6411 g_coord = save;
6412 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006413}
6414
6415
6416/*
6417 * Clear to end of line
6418 */
6419 static void
6420clear_to_end_of_line(void)
6421{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006422 COORD save = g_coord;
6423
Christopher Plewright38804d62022-11-09 23:55:52 +00006424 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006425 clear_chars(g_coord, Columns - g_coord.X);
6426 else
6427 {
6428 set_console_color_rgb();
6429 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6430 vtp_printf("\033[0K");
6431
6432 gotoxy(save.X + 1, save.Y + 1);
6433 g_coord = save;
6434 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006435}
6436
6437
6438/*
6439 * Scroll the scroll region up by `cLines' lines
6440 */
6441 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006442scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006443{
6444 COORD oldcoord = g_coord;
6445
6446 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6447 delete_lines(cLines);
6448
6449 g_coord = oldcoord;
6450}
6451
6452
6453/*
6454 * Set the scroll region
6455 */
6456 static void
6457set_scroll_region(
6458 unsigned left,
6459 unsigned top,
6460 unsigned right,
6461 unsigned bottom)
6462{
6463 if (left >= right
6464 || top >= bottom
6465 || right > (unsigned) Columns - 1
6466 || bottom > (unsigned) Rows - 1)
6467 return;
6468
6469 g_srScrollRegion.Left = left;
6470 g_srScrollRegion.Top = top;
6471 g_srScrollRegion.Right = right;
6472 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006473}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006474
Bram Moolenaar6982f422019-02-16 16:48:01 +01006475 static void
6476set_scroll_region_tb(
6477 unsigned top,
6478 unsigned bottom)
6479{
6480 if (top >= bottom || bottom > (unsigned)Rows - 1)
6481 return;
6482
6483 g_srScrollRegion.Top = top;
6484 g_srScrollRegion.Bottom = bottom;
6485}
6486
6487 static void
6488set_scroll_region_lr(
6489 unsigned left,
6490 unsigned right)
6491{
6492 if (left >= right || right > (unsigned)Columns - 1)
6493 return;
6494
6495 g_srScrollRegion.Left = left;
6496 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006497}
6498
6499
6500/*
6501 * Insert `cLines' lines at the current cursor position
6502 */
6503 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006504insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006505{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006506 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006507 COORD dest;
6508 CHAR_INFO fill;
6509
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006510 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6511
Bram Moolenaar6982f422019-02-16 16:48:01 +01006512 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006513 dest.Y = g_coord.Y + cLines;
6514
Bram Moolenaar6982f422019-02-16 16:48:01 +01006515 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006516 source.Top = g_coord.Y;
6517 source.Right = g_srScrollRegion.Right;
6518 source.Bottom = g_srScrollRegion.Bottom - cLines;
6519
Bram Moolenaar6982f422019-02-16 16:48:01 +01006520 clip.Left = g_srScrollRegion.Left;
6521 clip.Top = g_coord.Y;
6522 clip.Right = g_srScrollRegion.Right;
6523 clip.Bottom = g_srScrollRegion.Bottom;
6524
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006525 fill.Char.AsciiChar = ' ';
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006526 if (!USE_VTP)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006527 fill.Attributes = g_attrCurrent;
6528 else
6529 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006530
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006531 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006532
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006533 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6534
Bram Moolenaar6982f422019-02-16 16:48:01 +01006535 // Here we have to deal with a win32 console flake: If the scroll
6536 // region looks like abc and we scroll c to a and fill with d we get
6537 // cbd... if we scroll block c one line at a time to a, we get cdd...
6538 // vim expects cdd consistently... So we have to deal with that
6539 // here... (this also occurs scrolling the same way in the other
6540 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006541
6542 if (source.Bottom < dest.Y)
6543 {
6544 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006545 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006546
Bram Moolenaar6982f422019-02-16 16:48:01 +01006547 coord.X = source.Left;
6548 for (i = clip.Top; i < dest.Y; ++i)
6549 {
6550 coord.Y = i;
6551 clear_chars(coord, source.Right - source.Left + 1);
6552 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006553 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006554
Christopher Plewright38804d62022-11-09 23:55:52 +00006555 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006556 {
6557 COORD coord;
6558 int i;
6559
6560 coord.X = source.Left;
6561 for (i = source.Top; i < dest.Y; ++i)
6562 {
6563 coord.Y = i;
6564 clear_chars(coord, source.Right - source.Left + 1);
6565 }
6566 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006567}
6568
6569
6570/*
6571 * Delete `cLines' lines at the current cursor position
6572 */
6573 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006574delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006575{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006576 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006577 COORD dest;
6578 CHAR_INFO fill;
6579 int nb;
6580
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006581 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6582
Bram Moolenaar6982f422019-02-16 16:48:01 +01006583 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006584 dest.Y = g_coord.Y;
6585
Bram Moolenaar6982f422019-02-16 16:48:01 +01006586 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006587 source.Top = g_coord.Y + cLines;
6588 source.Right = g_srScrollRegion.Right;
6589 source.Bottom = g_srScrollRegion.Bottom;
6590
Bram Moolenaar6982f422019-02-16 16:48:01 +01006591 clip.Left = g_srScrollRegion.Left;
6592 clip.Top = g_coord.Y;
6593 clip.Right = g_srScrollRegion.Right;
6594 clip.Bottom = g_srScrollRegion.Bottom;
6595
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006596 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006597 if (!vtp_working)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006598 fill.Attributes = g_attrCurrent;
6599 else
6600 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006601
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006602 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006603
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006604 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6605
Bram Moolenaar6982f422019-02-16 16:48:01 +01006606 // Here we have to deal with a win32 console flake; See insert_lines()
6607 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006608
6609 nb = dest.Y + (source.Bottom - source.Top) + 1;
6610
6611 if (nb < source.Top)
6612 {
6613 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006614 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006615
Bram Moolenaar6982f422019-02-16 16:48:01 +01006616 coord.X = source.Left;
6617 for (i = nb; i < clip.Bottom; ++i)
6618 {
6619 coord.Y = i;
6620 clear_chars(coord, source.Right - source.Left + 1);
6621 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006622 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006623
Christopher Plewright38804d62022-11-09 23:55:52 +00006624 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006625 {
6626 COORD coord;
6627 int i;
6628
6629 coord.X = source.Left;
6630 for (i = nb; i <= source.Bottom; ++i)
6631 {
6632 coord.Y = i;
6633 clear_chars(coord, source.Right - source.Left + 1);
6634 }
6635 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006636}
6637
6638
6639/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006640 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006641 */
6642 static void
6643gotoxy(
6644 unsigned x,
6645 unsigned y)
6646{
6647 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6648 return;
6649
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006650 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006651 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006652 // There are reports of double-width characters not displayed
6653 // correctly. This workaround should fix it, similar to how it's done
6654 // for VTP.
6655 g_coord.X = 0;
6656 SetConsoleCursorPosition(g_hConOut, g_coord);
6657
Bram Moolenaar2313b612019-09-27 14:14:32 +02006658 // external cursor coords are 1-based; internal are 0-based
6659 g_coord.X = x - 1;
6660 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006661 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006662 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006663 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006664 {
6665 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006666 // destruction. Insider build bug. Always enabled because it's cheap
6667 // and avoids mistakes with recognizing the build.
6668 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006669
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006670 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006671
6672 g_coord.X = x - 1;
6673 g_coord.Y = y - 1;
6674 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006675}
6676
6677
6678/*
6679 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006680 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006681 */
6682 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006683textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006684{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006685 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006686
6687 SetConsoleTextAttribute(g_hConOut, wAttr);
6688}
6689
6690
6691 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006692textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006693{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006694 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006695
Christopher Plewright38804d62022-11-09 23:55:52 +00006696 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006697 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6698 else
6699 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006700}
6701
6702
6703 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006704textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006705{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006706 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006707
Christopher Plewright38804d62022-11-09 23:55:52 +00006708 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006709 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6710 else
6711 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006712}
6713
6714
6715/*
6716 * restore the default text attribute (whatever we started with)
6717 */
6718 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006719normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006720{
Christopher Plewright38804d62022-11-09 23:55:52 +00006721 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006722 textattr(g_attrDefault);
6723 else
6724 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006725}
6726
6727
6728static WORD g_attrPreStandout = 0;
6729
6730/*
6731 * Make the text standout, by brightening it
6732 */
6733 static void
6734standout(void)
6735{
6736 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006737
Bram Moolenaar071d4272004-06-13 20:20:40 +00006738 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6739}
6740
6741
6742/*
6743 * Turn off standout mode
6744 */
6745 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006746standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006747{
6748 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006749 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006750
6751 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006752}
6753
6754
6755/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006756 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006757 */
6758 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006759mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006760{
6761 char_u *p;
6762 int n;
6763
6764 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6765 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006766 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006767# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006768 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006769# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006770 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006771 {
6772 p = T_ME + 2;
6773 n = getdigits(&p);
6774 if (*p == 'm' && n > 0)
6775 {
6776 cterm_normal_fg_color = (n & 0xf) + 1;
6777 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6778 }
6779 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006780# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006781 cterm_normal_fg_gui_color = INVALCOLOR;
6782 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006783# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006784}
6785
6786
6787/*
6788 * visual bell: flash the screen
6789 */
6790 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006791visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006792{
6793 COORD coordOrigin = {0, 0};
6794 WORD attrFlash = ~g_attrCurrent & 0xff;
6795
6796 DWORD dwDummy;
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006797 LPWORD oldattrs = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006798
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006799# ifdef FEAT_TERMGUICOLORS
6800 if (!(p_tgc || t_colors >= 256))
6801# endif
6802 {
6803 oldattrs = ALLOC_MULT(WORD, Rows * Columns);
6804 if (oldattrs == NULL)
6805 return;
6806 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006807 coordOrigin, &dwDummy);
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006808 }
6809
Bram Moolenaar071d4272004-06-13 20:20:40 +00006810 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6811 coordOrigin, &dwDummy);
6812
Bram Moolenaar0f873732019-12-05 20:28:46 +01006813 Sleep(15); // wait for 15 msec
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006814
6815 if (oldattrs != NULL)
6816 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006817 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006818 coordOrigin, &dwDummy);
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006819 vim_free(oldattrs);
6820 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006821}
6822
6823
6824/*
6825 * Make the cursor visible or invisible
6826 */
6827 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006828cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006829{
6830 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006831
Christopher Plewright38804d62022-11-09 23:55:52 +00006832 if (vtp_working)
Bram Moolenaar2695de62020-04-17 21:13:01 +02006833 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6834
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006835# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006836 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006837# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006838}
6839
6840
6841/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006842 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006843 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006844 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006845 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006846write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006847 char_u *pchBuf,
6848 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006849{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006850 COORD coord = g_coord;
6851 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006852 DWORD n, cchwritten;
6853 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006854 static WCHAR *unicodebuf = NULL;
6855 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006856 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006857 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006858 static WCHAR *utf8spbuf = NULL;
6859 static int utf8splength;
6860 static DWORD utf8spcells;
6861 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006862
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006863 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006864 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006865 utf8usingbuf = &unicodebuf;
6866 do
6867 {
6868 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6869 unicodebuf, unibuflen);
6870 if (length && length <= unibuflen)
6871 break;
6872 vim_free(unicodebuf);
6873 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6874 unibuflen = unibuflen ? 0 : length;
Bram Moolenaarc9471b12023-05-09 15:00:00 +01006875 } while (TRUE);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006876 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006877 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006878 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6879 {
6880 if (utf8usingbuf != &utf8spbuf)
6881 {
6882 if (utf8spbuf == NULL)
6883 {
6884 cells = mb_string2cells((char_u *)" ", 1);
6885 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6886 utf8spbuf = LALLOC_MULT(WCHAR, length);
6887 if (utf8spbuf != NULL)
6888 {
6889 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6890 utf8usingbuf = &utf8spbuf;
6891 utf8splength = length;
6892 utf8spcells = cells;
6893 }
6894 }
6895 else
6896 {
6897 utf8usingbuf = &utf8spbuf;
6898 length = utf8splength;
6899 cells = utf8spcells;
6900 }
6901 }
6902 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006903
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006904 if (!USE_VTP)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006905 {
6906 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6907 coord, &written);
6908 // When writing fails or didn't write a single character, pretend one
6909 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006910 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006911 coord, &cchwritten) == 0
6912 || cchwritten == 0 || cchwritten == (DWORD)-1)
6913 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006914 }
6915 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006916 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006917 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006918 NULL) == 0 || cchwritten == 0)
6919 cchwritten = 1;
6920 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006921
K.Takata135e1522022-01-29 15:27:58 +00006922 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006923 {
6924 written = cbToWrite;
6925 g_coord.X += (SHORT)cells;
6926 }
6927 else
6928 {
6929 char_u *p = pchBuf;
6930 for (n = 0; n < cchwritten; n++)
6931 MB_CPTR_ADV(p);
6932 written = p - pchBuf;
6933 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006934 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006935
6936 while (g_coord.X > g_srScrollRegion.Right)
6937 {
6938 g_coord.X -= (SHORT) Columns;
6939 if (g_coord.Y < g_srScrollRegion.Bottom)
6940 g_coord.Y++;
6941 }
6942
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006943 // Cursor under VTP is always in the correct position, no need to reset.
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006944 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006945 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006946
6947 return written;
6948}
6949
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006950 static char_u *
6951get_seq(
6952 int *args,
6953 int *count,
6954 char_u *head)
6955{
6956 int argc;
6957 char_u *p;
6958
6959 if (head == NULL || *head != '\033')
6960 return NULL;
6961
6962 argc = 0;
6963 p = head;
6964 ++p;
6965 do
6966 {
6967 ++p;
6968 args[argc] = getdigits(&p);
6969 argc += (argc < 15) ? 1 : 0;
6970 } while (*p == ';');
6971 *count = argc;
6972
6973 return p;
6974}
6975
6976 static char_u *
6977get_sgr(
6978 int *args,
6979 int *count,
6980 char_u *head)
6981{
6982 char_u *p = get_seq(args, count, head);
6983
6984 return (p && *p == 'm') ? ++p : NULL;
6985}
6986
6987/*
6988 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6989 */
6990 static char_u *
6991sgrn2(
6992 char_u *head,
6993 int n)
6994{
6995 int argc;
6996 int args[16];
6997 char_u *p = get_sgr(args, &argc, head);
6998
6999 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
7000}
7001
7002/*
7003 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
7004 */
7005 static char_u *
7006sgrnc(
7007 char_u *head,
7008 int n)
7009{
7010 int argc;
7011 int args[16];
7012 char_u *p = get_sgr(args, &argc, head);
7013
7014 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
7015 ? p : NULL;
7016}
7017
7018 static char_u *
7019skipblank(char_u *q)
7020{
7021 char_u *p = q;
7022
7023 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
7024 ++p;
7025 return p;
7026}
7027
7028/*
7029 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
7030 * NULL.
7031 */
7032 static char_u *
7033sgrn2c(
7034 char_u *head,
7035 int n)
7036{
7037 char_u *p = sgrn2(head, n);
7038
7039 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
7040}
7041
7042/*
7043 * If there is only a newline between the sequence immediately following it,
7044 * a pointer to the character following the newline is returned.
7045 * Otherwise NULL.
7046 */
7047 static char_u *
7048sgrn2cn(
7049 char_u *head,
7050 int n)
7051{
7052 char_u *p = sgrn2(head, n);
7053
7054 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
7055}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007056
7057/*
7058 * mch_write(): write the output buffer to the screen, translating ESC
7059 * sequences into calls to console output routines.
7060 */
7061 void
7062mch_write(
7063 char_u *s,
7064 int len)
7065{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007066 char_u *end = s + len;
7067
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007068# ifdef VIMDLL
7069 if (gui.in_use)
7070 return;
7071# endif
7072
Bram Moolenaar071d4272004-06-13 20:20:40 +00007073 if (!term_console)
7074 {
7075 write(1, s, (unsigned)len);
7076 return;
7077 }
7078
Bram Moolenaar0f873732019-12-05 20:28:46 +01007079 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00007080 while (len--)
7081 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007082 int prefix = -1;
7083 char_u ch;
7084
7085 // While processing a sequence, on rare occasions it seems that another
7086 // sequence may be inserted asynchronously.
7087 if (len < 0)
7088 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01007089 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007090 return;
7091 }
7092
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007093 while (s + ++prefix < end)
7094 {
7095 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007096 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
7097 && ch != '\a' && ch != '\033'))
7098 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007099 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007100
7101 if (p_wd)
7102 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007103 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007104 if (prefix != 0)
7105 prefix = 1;
7106 }
7107
7108 if (prefix != 0)
7109 {
7110 DWORD nWritten;
7111
7112 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007113# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007114 if (fdDump)
7115 {
7116 fputc('>', fdDump);
7117 fwrite(s, sizeof(char_u), nWritten, fdDump);
7118 fputs("<\n", fdDump);
7119 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007120# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007121 len -= (nWritten - 1);
7122 s += nWritten;
7123 }
7124 else if (s[0] == '\n')
7125 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007126 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00007127 if (g_coord.Y == g_srScrollRegion.Bottom)
7128 {
7129 scroll(1);
7130 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
7131 }
7132 else
7133 {
7134 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
7135 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007136# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007137 if (fdDump)
7138 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007139# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007140 s++;
7141 }
7142 else if (s[0] == '\r')
7143 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007144 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00007145 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007146# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007147 if (fdDump)
7148 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007149# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007150 s++;
7151 }
7152 else if (s[0] == '\b')
7153 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007154 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00007155 if (g_coord.X > g_srScrollRegion.Left)
7156 g_coord.X--;
7157 else if (g_coord.Y > g_srScrollRegion.Top)
7158 {
7159 g_coord.X = g_srScrollRegion.Right;
7160 g_coord.Y--;
7161 }
7162 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007163# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007164 if (fdDump)
7165 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007166# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007167 s++;
7168 }
7169 else if (s[0] == '\a')
7170 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007171 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00007172 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007173# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007174 if (fdDump)
7175 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007176# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007177 s++;
7178 }
7179 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
7180 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007181# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007182 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007183# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007184 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007185 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007186 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007187
7188 switch (s[2])
7189 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007190 case '0': case '1': case '2': case '3': case '4':
7191 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007192 if (*(p = get_seq(args, &argc, s)) != 'm')
7193 goto notsgr;
7194
7195 p = s;
7196
7197 // Handling frequent optional sequences. Output to the screen
7198 // takes too long, so do not output as much as possible.
7199
7200 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
7201 // resetFG,FG,BG are omitted.
7202 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007203 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007204 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
7205 len = len + 1 - (int)(p - s);
7206 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007207 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007208 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007209
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007210 // If FG,BG,BG,FG of SGR are connected, the first FG can be
7211 // omitted.
7212 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
7213 p = sp;
7214
7215 // If FG,BG,FG,BG of SGR are connected, the first FG can be
7216 // omitted.
7217 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
7218 p = sp;
7219
7220 // If BG,BG of SGR are connected, the first BG can be omitted.
7221 if (sgrn2((sp = sgrn2(p, 48)), 48))
7222 p = sp;
7223
7224 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007225 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007226 if (sgrn2((sp = sgrnc(p, 39)), 38))
7227 p = sp;
7228
7229 p = get_seq(args, &argc, p);
7230
7231notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007232 arg1 = args[0];
7233 arg2 = args[1];
7234 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007235 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007236 if (argc == 1 && args[0] == 0)
7237 normvideo();
7238 else if (argc == 1)
7239 {
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00007240 if (USE_VTP)
Christopher Plewright38804d62022-11-09 23:55:52 +00007241 textcolor((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007242 else
Christopher Plewright38804d62022-11-09 23:55:52 +00007243 textattr((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007244 }
Christopher Plewright38804d62022-11-09 23:55:52 +00007245 else if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007246 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007247 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007248 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007249 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007250 gotoxy(arg2, arg1);
7251 }
7252 else if (argc == 2 && *p == 'r')
7253 {
7254 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
7255 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01007256 else if (argc == 2 && *p == 'R')
7257 {
7258 set_scroll_region_tb(arg1, arg2);
7259 }
7260 else if (argc == 2 && *p == 'V')
7261 {
7262 set_scroll_region_lr(arg1, arg2);
7263 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007264 else if (argc == 1 && *p == 'A')
7265 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007266 gotoxy(g_coord.X + 1,
7267 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
7268 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007269 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007270 {
7271 textbackground((WORD) arg1);
7272 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007273 else if (argc == 1 && *p == 'C')
7274 {
7275 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
7276 g_coord.Y + 1);
7277 }
7278 else if (argc == 1 && *p == 'f')
7279 {
7280 textcolor((WORD) arg1);
7281 }
7282 else if (argc == 1 && *p == 'H')
7283 {
7284 gotoxy(1, arg1);
7285 }
7286 else if (argc == 1 && *p == 'L')
7287 {
7288 insert_lines(arg1);
7289 }
7290 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007291 {
7292 delete_lines(arg1);
7293 }
7294
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007295 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007296 s = p + 1;
7297 break;
7298
Bram Moolenaar071d4272004-06-13 20:20:40 +00007299 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007300 gotoxy(g_coord.X + 1,
7301 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
7302 goto got3;
7303
7304 case 'B':
7305 visual_bell();
7306 goto got3;
7307
7308 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007309 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
7310 g_coord.Y + 1);
7311 goto got3;
7312
7313 case 'E':
7314 termcap_mode_end();
7315 goto got3;
7316
7317 case 'F':
7318 standout();
7319 goto got3;
7320
7321 case 'f':
7322 standend();
7323 goto got3;
7324
7325 case 'H':
7326 gotoxy(1, 1);
7327 goto got3;
7328
7329 case 'j':
7330 clear_to_end_of_display();
7331 goto got3;
7332
7333 case 'J':
7334 clear_screen();
7335 goto got3;
7336
7337 case 'K':
7338 clear_to_end_of_line();
7339 goto got3;
7340
7341 case 'L':
7342 insert_lines(1);
7343 goto got3;
7344
7345 case 'M':
7346 delete_lines(1);
7347 goto got3;
7348
7349 case 'S':
7350 termcap_mode_start();
7351 goto got3;
7352
7353 case 'V':
7354 cursor_visible(TRUE);
7355 goto got3;
7356
7357 case 'v':
7358 cursor_visible(FALSE);
7359 goto got3;
7360
7361 got3:
7362 s += 3;
7363 len -= 2;
7364 }
7365
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007366# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007367 if (fdDump)
7368 {
7369 fputs("ESC | ", fdDump);
7370 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
7371 fputc('\n', fdDump);
7372 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007373# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007374 }
K.Takatadf5320c2022-09-01 13:20:16 +01007375 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
7376 {
7377 int l = 2;
7378
7379 if (isdigit(s[l]))
7380 l++;
7381 if (s[l] == ' ' && s[l + 1] == 'q')
7382 {
7383 // DECSCUSR (cursor style) sequences
Christopher Plewright38804d62022-11-09 23:55:52 +00007384 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01007385 vtp_printf("%.*s", l + 2, s); // Pass through
7386 s += l + 2;
7387 len -= l + 1;
7388 }
7389 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007390 else
7391 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007392 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00007393 DWORD nWritten;
7394
7395 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007396# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007397 if (fdDump)
7398 {
7399 fputc('>', fdDump);
7400 fwrite(s, sizeof(char_u), nWritten, fdDump);
7401 fputs("<\n", fdDump);
7402 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007403# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007404
7405 len -= (nWritten - 1);
7406 s += nWritten;
7407 }
7408 }
7409
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007410# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007411 if (fdDump)
7412 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007413# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007414}
7415
Bram Moolenaar0f873732019-12-05 20:28:46 +01007416#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00007417
7418
7419/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01007420 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007421 */
7422 void
7423mch_delay(
7424 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02007425 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007426{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007427#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007428 Sleep((int)msec); // never wait for input
7429#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007430# ifdef VIMDLL
7431 if (gui.in_use)
7432 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007433 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007434 return;
7435 }
7436# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02007437 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007438# ifdef FEAT_MZSCHEME
7439 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
7440 {
7441 int towait = p_mzq;
7442
Bram Moolenaar0f873732019-12-05 20:28:46 +01007443 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007444 while (msec > 0)
7445 {
7446 mzvim_check_threads();
7447 if (msec < towait)
7448 towait = msec;
7449 Sleep(towait);
7450 msec -= towait;
7451 }
7452 }
7453 else
7454# endif
7455 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007456 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007457 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007458#endif
7459}
7460
7461
7462/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01007463 * This version of remove is not scared by a readonly (backup) file.
7464 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007465 * Return 0 for success, -1 for failure.
7466 */
7467 int
7468mch_remove(char_u *name)
7469{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007470 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007471 int n;
7472
Bram Moolenaar203258c2016-01-17 22:15:16 +01007473 /*
7474 * On Windows, deleting a directory's symbolic link is done by
7475 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
7476 */
7477 if (mch_isdir(name) && mch_is_symbolic_link(name))
7478 return mch_rmdir(name);
7479
Bram Moolenaar12b559e2013-06-12 22:41:37 +02007480 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
7481
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007482 wn = enc_to_utf16(name, NULL);
7483 if (wn == NULL)
7484 return -1;
7485
7486 n = DeleteFileW(wn) ? 0 : -1;
7487 vim_free(wn);
7488 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007489}
7490
7491
7492/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007493 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007494 */
7495 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007496mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007497{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007498#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7499# ifdef VIMDLL
7500 if (!gui.in_use)
7501# endif
7502 if (g_fCtrlCPressed || g_fCBrkPressed)
7503 {
7504 ctrl_break_was_pressed = g_fCBrkPressed;
7505 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7506 got_int = TRUE;
7507 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007508#endif
7509}
7510
Bram Moolenaar0f873732019-12-05 20:28:46 +01007511// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007512#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007513
7514/*
7515 * How much main memory in KiB that can be used by VIM.
7516 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007517 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007518mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007519{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007520 MEMORYSTATUSEX ms;
7521
Bram Moolenaar0f873732019-12-05 20:28:46 +01007522 // Need to use GlobalMemoryStatusEx() when there is more memory than
7523 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007524 ms.dwLength = sizeof(MEMORYSTATUSEX);
7525 GlobalMemoryStatusEx(&ms);
7526 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007527 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007528 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007529 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007530 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007531 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007532 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007533 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007534 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007535 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007536 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007537 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007538}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007539
Bram Moolenaar071d4272004-06-13 20:20:40 +00007540/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007541 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00007542 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
7543 * file whose short file name is "FOO.BAR" (its long file name will
7544 * be correct: "foo.bar~"). Because a file can be accessed by
7545 * either its SFN or its LFN, "foo.bar" has effectively been
7546 * renamed to "foo.bar", which is not at all what was wanted. This
7547 * seems to happen only when renaming files with three-character
7548 * extensions by appending a suffix that does not include ".".
7549 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
7550 *
7551 * There is another problem, which isn't really a bug but isn't right either:
7552 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
7553 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
7554 * service pack 6. Doesn't seem to happen on Windows 98.
7555 *
7556 * Like rename(), returns 0 upon success, non-zero upon failure.
7557 * Should probably set errno appropriately when errors occur.
7558 */
7559 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007560mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007561{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007562 WCHAR *p;
7563 int i;
7564 WCHAR szTempFile[_MAX_PATH + 1];
7565 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007566 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007567
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007568 // No need to play tricks unless the file name contains a "~" as the
7569 // seventh character.
7570 p = wold;
7571 for (i = 0; wold[i] != NUL; ++i)
7572 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
7573 && wold[i + 1] != 0)
7574 p = wold + i + 1;
7575 if ((int)(wold + i - p) < 8 || p[6] != '~')
7576 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007577
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007578 // Get base path of new file name. Undocumented feature: If pszNewFile is
7579 // a directory, no error is returned and pszFilePart will be NULL.
7580 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007581 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007582 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007583
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007584 // Get (and create) a unique temporary file name in directory of new file
7585 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007586 return -2;
7587
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007588 // blow the temp file away
7589 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007590 return -3;
7591
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007592 // rename old file to the temp file
7593 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007594 return -4;
7595
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007596 // now create an empty file called pszOldFile; this prevents the operating
7597 // system using pszOldFile as an alias (SFN) if we're renaming within the
7598 // same directory. For example, we're editing a file called
7599 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7600 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7601 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7602 // cause all sorts of problems later in buf_write(). So, we create an
7603 // empty file called filena~1.txt and the system will have to find some
7604 // other SFN for filena~1.txt~, such as filena~2.txt
7605 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007606 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7607 return -5;
7608 if (!CloseHandle(hf))
7609 return -6;
7610
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007611 // rename the temp file to the new file
7612 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007613 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007614 // Renaming failed. Rename the file back to its old name, so that it
7615 // looks like nothing happened.
7616 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007617 return -7;
7618 }
7619
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007620 // Seems to be left around on Novell filesystems
7621 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007622
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007623 // finally, remove the empty old file
7624 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007625 return -8;
7626
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007627 return 0;
7628}
7629
7630
7631/*
7632 * Converts the filenames to UTF-16, then call mch_wrename().
7633 * Like rename(), returns 0 upon success, non-zero upon failure.
7634 */
7635 int
7636mch_rename(
7637 const char *pszOldFile,
7638 const char *pszNewFile)
7639{
7640 WCHAR *wold = NULL;
7641 WCHAR *wnew = NULL;
7642 int retval = -1;
7643
7644 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7645 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7646 if (wold != NULL && wnew != NULL)
7647 retval = mch_wrename(wold, wnew);
7648 vim_free(wold);
7649 vim_free(wnew);
7650 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007651}
7652
7653/*
7654 * Get the default shell for the current hardware platform
7655 */
7656 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007657default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007658{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007659 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007660}
7661
7662/*
7663 * mch_access() extends access() to do more detailed check on network drives.
7664 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7665 */
7666 int
7667mch_access(char *n, int p)
7668{
7669 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007670 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007671 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007672
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007673 wn = enc_to_utf16((char_u *)n, NULL);
7674 if (wn == NULL)
7675 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007676
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007677 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007678 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007679 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007680
7681 if (p & R_OK)
7682 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007683 // Read check is performed by seeing if we can do a find file on
7684 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007685 int i;
7686 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007687
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007688 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7689 TempNameW[i] = wn[i];
7690 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7691 TempNameW[i++] = '\\';
7692 TempNameW[i++] = '*';
7693 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007694
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007695 hFile = FindFirstFileW(TempNameW, &d);
7696 if (hFile == INVALID_HANDLE_VALUE)
7697 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007698 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007699 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007700 }
7701
7702 if (p & W_OK)
7703 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007704 // Trying to create a temporary file in the directory should catch
7705 // directories on read-only network shares. However, in
7706 // directories whose ACL allows writes but denies deletes will end
7707 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007708 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7709 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007710 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007711 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007712 }
7713 }
7714 else
7715 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007716 // Don't consider a file read-only if another process has opened it.
7717 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7718
Bram Moolenaar0f873732019-12-05 20:28:46 +01007719 // Trying to open the file for the required access does ACL, read-only
7720 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007721 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7722 | ((p & R_OK) ? GENERIC_READ : 0);
7723
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007724 hFile = CreateFileW(wn, access_mode, share_mode,
7725 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007726 if (hFile == INVALID_HANDLE_VALUE)
7727 goto getout;
7728 CloseHandle(hFile);
7729 }
7730
Bram Moolenaar0f873732019-12-05 20:28:46 +01007731 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007732getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007733 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007734 return retval;
7735}
7736
Bram Moolenaar071d4272004-06-13 20:20:40 +00007737/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007738 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007739 */
7740 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007741mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007742{
7743 WCHAR *wn;
7744 int f;
7745
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007746 wn = enc_to_utf16((char_u *)name, NULL);
7747 if (wn == NULL)
7748 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007749
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007750 f = _wopen(wn, flags, mode);
7751 vim_free(wn);
7752 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007753}
7754
7755/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007756 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007757 */
7758 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007759mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007760{
7761 WCHAR *wn, *wm;
7762 FILE *f = NULL;
7763
Bram Moolenaara12a1612019-01-24 16:39:02 +01007764#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007765 // Work around an annoying assertion in the Microsoft debug CRT
7766 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007767 char newMode = mode[strlen(mode) - 1];
7768 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007769
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007770 _get_fmode(&oldMode);
7771 if (newMode == 't')
7772 _set_fmode(_O_TEXT);
7773 else if (newMode == 'b')
7774 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007775#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007776 wn = enc_to_utf16((char_u *)name, NULL);
7777 wm = enc_to_utf16((char_u *)mode, NULL);
7778 if (wn != NULL && wm != NULL)
7779 f = _wfopen(wn, wm);
7780 vim_free(wn);
7781 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007782
Bram Moolenaara12a1612019-01-24 16:39:02 +01007783#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007784 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007785#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007786 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007787}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007788
Bram Moolenaar071d4272004-06-13 20:20:40 +00007789/*
7790 * SUB STREAM (aka info stream) handling:
7791 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007792 * NTFS can have sub streams for each file. The normal contents of a file is
7793 * stored in the main stream, and extra contents (author information, title and
7794 * so on) can be stored in a sub stream. After Windows 2000, the user can
7795 * access and store this information in sub streams via an explorer's property
7796 * menu item in the right click menu. This information in sub streams was lost
7797 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007798 *
7799 * Incomplete explanation:
7800 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7801 * More useful info and an example:
7802 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7803 */
7804
7805/*
7806 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7807 * and write to stream "substream" of file "to".
7808 * Errors are ignored.
7809 */
7810 static void
7811copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7812{
7813 HANDLE hTo;
7814 WCHAR *to_name;
7815
7816 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7817 wcscpy(to_name, to);
7818 wcscat(to_name, substream);
7819
7820 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7821 FILE_ATTRIBUTE_NORMAL, NULL);
7822 if (hTo != INVALID_HANDLE_VALUE)
7823 {
7824 long done;
7825 DWORD todo;
7826 DWORD readcnt, written;
7827 char buf[4096];
7828
Bram Moolenaar0f873732019-12-05 20:28:46 +01007829 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007830 for (done = 0; done < len; done += written)
7831 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007832 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007833 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7834 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007835 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7836 FALSE, FALSE, context)
7837 || readcnt != todo
7838 || !WriteFile(hTo, buf, todo, &written, NULL)
7839 || written != todo)
7840 break;
7841 }
7842 CloseHandle(hTo);
7843 }
7844
7845 free(to_name);
7846}
7847
7848/*
7849 * Copy info streams from file "from" to file "to".
7850 */
7851 static void
7852copy_infostreams(char_u *from, char_u *to)
7853{
7854 WCHAR *fromw;
7855 WCHAR *tow;
7856 HANDLE sh;
7857 WIN32_STREAM_ID sid;
7858 int headersize;
7859 WCHAR streamname[_MAX_PATH];
7860 DWORD readcount;
7861 void *context = NULL;
7862 DWORD lo, hi;
7863 int len;
7864
Bram Moolenaar0f873732019-12-05 20:28:46 +01007865 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007866 fromw = enc_to_utf16(from, NULL);
7867 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007868 if (fromw != NULL && tow != NULL)
7869 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007870 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007871 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7872 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7873 if (sh != INVALID_HANDLE_VALUE)
7874 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007875 // Use BackupRead() to find the info streams. Repeat until we
7876 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007877 for (;;)
7878 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007879 // Get the header to find the length of the stream name. If
7880 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007881 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007882 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007883 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7884 &readcount, FALSE, FALSE, &context)
7885 || readcount == 0)
7886 break;
7887
Bram Moolenaar0f873732019-12-05 20:28:46 +01007888 // We only deal with streams that have a name. The normal
7889 // file data appears to be without a name, even though docs
7890 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007891 if (sid.dwStreamNameSize > 0)
7892 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007893 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007894 if (!BackupRead(sh, (LPBYTE)streamname,
7895 sid.dwStreamNameSize,
7896 &readcount, FALSE, FALSE, &context))
7897 break;
7898
Bram Moolenaar0f873732019-12-05 20:28:46 +01007899 // Copy an info stream with a name ":anything:$DATA".
7900 // Skip "::$DATA", it has no stream name (examples suggest
7901 // it might be used for the normal file contents).
7902 // Note that BackupRead() counts bytes, but the name is in
7903 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007904 len = readcount / sizeof(WCHAR);
7905 streamname[len] = 0;
7906 if (len > 7 && wcsicmp(streamname + len - 6,
7907 L":$DATA") == 0)
7908 {
7909 streamname[len - 6] = 0;
7910 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007911 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007912 }
7913 }
7914
Bram Moolenaar0f873732019-12-05 20:28:46 +01007915 // Advance to the next stream. We might try seeking too far,
7916 // but BackupSeek() doesn't skip over stream borders, thus
7917 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007918 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007919 &lo, &hi, &context);
7920 }
7921
Bram Moolenaar0f873732019-12-05 20:28:46 +01007922 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007923 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7924
7925 CloseHandle(sh);
7926 }
7927 }
7928 vim_free(fromw);
7929 vim_free(tow);
7930}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007931
7932/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007933 * ntdll.dll definitions
7934 */
7935#define FileEaInformation 7
7936#ifndef STATUS_SUCCESS
7937# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7938#endif
7939
7940typedef struct _FILE_FULL_EA_INFORMATION_ {
7941 ULONG NextEntryOffset;
7942 UCHAR Flags;
7943 UCHAR EaNameLength;
7944 USHORT EaValueLength;
7945 CHAR EaName[1];
7946} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7947
7948typedef struct _FILE_EA_INFORMATION_ {
7949 ULONG EaSize;
7950} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7951
Paul Ollis65745772022-06-05 16:55:54 +01007952#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007953typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7954 PHANDLE FileHandle,
7955 ACCESS_MASK DesiredAccess,
7956 POBJECT_ATTRIBUTES ObjectAttributes,
7957 PIO_STATUS_BLOCK IoStatusBlock,
7958 ULONG ShareAccess,
7959 ULONG OpenOptions);
7960typedef NTSTATUS (NTAPI *PfnNtClose)(
7961 HANDLE Handle);
7962typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007963 HANDLE FileHandle,
7964 PIO_STATUS_BLOCK IoStatusBlock,
7965 PVOID Buffer,
7966 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007967typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7968 HANDLE FileHandle,
7969 PIO_STATUS_BLOCK IoStatusBlock,
7970 PVOID Buffer,
7971 ULONG Length,
7972 BOOLEAN ReturnSingleEntry,
7973 PVOID EaList,
7974 ULONG EaListLength,
7975 PULONG EaIndex,
7976 BOOLEAN RestartScan);
7977typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007978 HANDLE FileHandle,
7979 PIO_STATUS_BLOCK IoStatusBlock,
7980 PVOID FileInformation,
7981 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007982 FILE_INFORMATION_CLASS FileInformationClass);
7983typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7984 PUNICODE_STRING DestinationString,
7985 PCWSTR SourceString);
7986
7987PfnNtOpenFile pNtOpenFile = NULL;
7988PfnNtClose pNtClose = NULL;
7989PfnNtSetEaFile pNtSetEaFile = NULL;
7990PfnNtQueryEaFile pNtQueryEaFile = NULL;
7991PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7992PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01007993#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007994
7995/*
7996 * Load ntdll.dll functions.
7997 */
7998 static BOOL
7999load_ntdll(void)
8000{
8001 static int loaded = -1;
8002
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008003 if (loaded != -1)
8004 return (BOOL) loaded;
8005
8006 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
8007 if (hNtdll != NULL)
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008008 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008009 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
8010 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
8011 pNtSetEaFile = (PfnNtSetEaFile)
8012 GetProcAddress(hNtdll, "NtSetEaFile");
8013 pNtQueryEaFile = (PfnNtQueryEaFile)
8014 GetProcAddress(hNtdll, "NtQueryEaFile");
8015 pNtQueryInformationFile = (PfnNtQueryInformationFile)
8016 GetProcAddress(hNtdll, "NtQueryInformationFile");
8017 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
8018 GetProcAddress(hNtdll, "RtlInitUnicodeString");
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008019 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008020 if (pNtOpenFile == NULL
8021 || pNtClose == NULL
8022 || pNtSetEaFile == NULL
8023 || pNtQueryEaFile == NULL
8024 || pNtQueryInformationFile == NULL
8025 || pRtlInitUnicodeString == NULL)
8026 loaded = FALSE;
8027 else
8028 loaded = TRUE;
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008029 return (BOOL) loaded;
8030}
8031
8032/*
8033 * Copy extended attributes (EA) from file "from" to file "to".
8034 */
8035 static void
8036copy_extattr(char_u *from, char_u *to)
8037{
8038 char_u *fromf = NULL;
8039 char_u *tof = NULL;
8040 WCHAR *fromw = NULL;
8041 WCHAR *tow = NULL;
8042 UNICODE_STRING u;
8043 HANDLE h;
8044 OBJECT_ATTRIBUTES oa;
8045 IO_STATUS_BLOCK iosb;
8046 FILE_EA_INFORMATION_ eainfo = {0};
8047 void *ea = NULL;
8048
8049 if (!load_ntdll())
8050 return;
8051
8052 // Convert the file names to the fully qualified object names.
8053 fromf = alloc(STRLEN(from) + 5);
8054 tof = alloc(STRLEN(to) + 5);
8055 if (fromf == NULL || tof == NULL)
8056 goto theend;
8057 STRCPY(fromf, "\\??\\");
8058 STRCAT(fromf, from);
8059 STRCPY(tof, "\\??\\");
8060 STRCAT(tof, to);
8061
8062 // Convert the names to wide characters.
8063 fromw = enc_to_utf16(fromf, NULL);
8064 tow = enc_to_utf16(tof, NULL);
8065 if (fromw == NULL || tow == NULL)
8066 goto theend;
8067
8068 // Get the EA.
8069 pRtlInitUnicodeString(&u, fromw);
8070 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8071 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
8072 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8073 goto theend;
8074 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
8075 FileEaInformation);
8076 if (eainfo.EaSize != 0)
8077 {
8078 ea = alloc(eainfo.EaSize);
8079 if (ea != NULL)
8080 {
8081 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
8082 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
8083 {
Yegappan Lakshmanan960dcbd2023-03-07 17:45:11 +00008084 VIM_CLEAR(ea);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008085 }
8086 }
8087 }
8088 pNtClose(h);
8089
8090 // Set the EA.
8091 if (ea != NULL)
8092 {
8093 pRtlInitUnicodeString(&u, tow);
8094 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8095 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
8096 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8097 goto theend;
8098
8099 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
8100 pNtClose(h);
8101 }
8102
8103theend:
8104 vim_free(fromf);
8105 vim_free(tof);
8106 vim_free(fromw);
8107 vim_free(tow);
8108 vim_free(ea);
8109}
8110
8111/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008112 * Copy file attributes from file "from" to file "to".
8113 * For Windows NT and later we copy info streams.
8114 * Always returns zero, errors are ignored.
8115 */
8116 int
8117mch_copy_file_attribute(char_u *from, char_u *to)
8118{
Bram Moolenaar0f873732019-12-05 20:28:46 +01008119 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02008120 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008121 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008122 return 0;
8123}
8124
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008125
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008126/*
K.Takatadc73b4b2021-06-08 18:32:36 +02008127 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008128 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008129static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008130static LPWSTR *ArglistW = NULL;
8131static int global_argc = 0;
8132static char **global_argv;
8133
Bram Moolenaar0f873732019-12-05 20:28:46 +01008134static int used_file_argc = 0; // last argument in global_argv[] used
8135 // for the argument list.
8136static int *used_file_indexes = NULL; // indexes in global_argv[] for
8137 // command line arguments added to
8138 // the argument list
8139static int used_file_count = 0; // nr of entries in used_file_indexes
8140static int used_file_literal = FALSE; // take file names literally
8141static int used_file_full_path = FALSE; // file name was full path
8142static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008143static int used_alist_count = 0;
8144
8145
8146/*
8147 * Get the command line arguments. Unicode version.
8148 * Returns argc. Zero when something fails.
8149 */
8150 int
8151get_cmd_argsW(char ***argvp)
8152{
8153 char **argv = NULL;
8154 int argc = 0;
8155 int i;
8156
Bram Moolenaar14993322014-09-09 12:25:33 +02008157 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008158 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
8159 if (ArglistW != NULL)
8160 {
8161 argv = malloc((nArgsW + 1) * sizeof(char *));
8162 if (argv != NULL)
8163 {
8164 argc = nArgsW;
8165 argv[argc] = NULL;
8166 for (i = 0; i < argc; ++i)
8167 {
8168 int len;
8169
K.Takatadc73b4b2021-06-08 18:32:36 +02008170 // Convert each Unicode argument to UTF-8.
8171 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008172 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008173 (LPSTR *)&argv[i], &len, 0, 0);
8174 if (argv[i] == NULL)
8175 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008176 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008177 while (i > 0)
8178 free(argv[--i]);
8179 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01008180 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008181 argc = 0;
8182 }
8183 }
8184 }
8185 }
8186
8187 global_argc = argc;
8188 global_argv = argv;
8189 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02008190 {
8191 if (used_file_indexes != NULL)
8192 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008193 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02008194 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008195
8196 if (argvp != NULL)
8197 *argvp = argv;
8198 return argc;
8199}
8200
8201 void
8202free_cmd_argsW(void)
8203{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008204 if (ArglistW == NULL)
8205 return;
8206
8207 GlobalFree(ArglistW);
8208 ArglistW = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008209}
8210
8211/*
8212 * Remember "name" is an argument that was added to the argument list.
8213 * This avoids that we have to re-parse the argument list when fix_arg_enc()
8214 * is called.
8215 */
8216 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008217used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008218{
8219 int i;
8220
8221 if (used_file_indexes == NULL)
8222 return;
8223 for (i = used_file_argc + 1; i < global_argc; ++i)
8224 if (STRCMP(global_argv[i], name) == 0)
8225 {
8226 used_file_argc = i;
8227 used_file_indexes[used_file_count++] = i;
8228 break;
8229 }
8230 used_file_literal = literal;
8231 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008232 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008233}
8234
8235/*
8236 * Remember the length of the argument list as it was. If it changes then we
8237 * leave it alone when 'encoding' is set.
8238 */
8239 void
8240set_alist_count(void)
8241{
8242 used_alist_count = GARGCOUNT;
8243}
8244
8245/*
8246 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02008247 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008248 * and convert them to 'encoding'.
8249 */
8250 void
8251fix_arg_enc(void)
8252{
8253 int i;
8254 int idx;
8255 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00008256 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008257
Bram Moolenaar0f873732019-12-05 20:28:46 +01008258 // Safety checks:
8259 // - if argument count differs between the wide and non-wide argument
8260 // list, something must be wrong.
8261 // - the file name arguments must have been located.
8262 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008263 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008264 || ArglistW == NULL
8265 || used_file_indexes == NULL
8266 || used_file_count == 0
8267 || used_alist_count != GARGCOUNT)
8268 return;
8269
Bram Moolenaar0f873732019-12-05 20:28:46 +01008270 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02008271 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008272 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008273 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00008274 for (i = 0; i < GARGCOUNT; ++i)
8275 fnum_list[i] = GARGLIST[i].ae_fnum;
8276
Bram Moolenaar0f873732019-12-05 20:28:46 +01008277 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008278 alist_clear(&global_alist);
8279 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008280 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008281
8282 for (i = 0; i < used_file_count; ++i)
8283 {
8284 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008285 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008286 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00008287 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008288 int literal = used_file_literal;
8289
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008290#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01008291 // When using diff mode may need to concatenate file name to
8292 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008293 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
8294 && !mch_isdir(alist_name(&GARGLIST[0])))
8295 {
8296 char_u *r;
8297
8298 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
8299 if (r != NULL)
8300 {
8301 vim_free(str);
8302 str = r;
8303 }
8304 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008305#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01008306 // Re-use the old buffer by renaming it. When not using literal
8307 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00008308 if (used_file_literal)
8309 buf_set_name(fnum_list[i], str);
8310
Bram Moolenaar0f873732019-12-05 20:28:46 +01008311 // Check backtick literal. backtick literal is already expanded in
8312 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008313 if (literal == FALSE)
8314 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02008315 size_t len = STRLEN(str);
8316
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008317 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
8318 literal = TRUE;
8319 }
8320 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008321 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008322 }
8323
8324 if (!used_file_literal)
8325 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008326 // Now expand wildcards in the arguments.
8327 // Temporarily add '(' and ')' to 'isfname'. These are valid
8328 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00008329 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01008330 // Also, unset wildignore to not be influenced by this option.
8331 // The arguments specified in command-line should be kept even if
8332 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00008333 // Use :legacy so that it also works when in Vim9 script.
8334 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
8335 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00008336 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00008337 do_cmdline_cmd(
8338 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
8339 do_cmdline_cmd(
8340 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008341 }
8342
Bram Moolenaar0f873732019-12-05 20:28:46 +01008343 // If wildcard expansion failed, we are editing the first file of the
8344 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008345 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
8346 {
8347 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00008348 if (GARGCOUNT == 1 && used_file_full_path
8349 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
8350 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008351 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00008352
8353 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008354}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008355
8356 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02008357mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008358{
8359 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008360 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008361
Bram Moolenaar964b3742019-05-24 18:54:09 +02008362 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008363 if (envbuf == NULL)
8364 return -1;
8365
8366 sprintf((char *)envbuf, "%s=%s", var, value);
8367
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008368 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008369
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008370 vim_free(envbuf);
8371 if (p == NULL)
8372 return -1;
8373 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008374#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008375 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008376#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008377 // Unlike Un*x systems, we can free the string for _wputenv().
8378 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008379
8380 return 0;
8381}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008382
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008383/*
8384 * Support for 256 colors and 24-bit colors was added in Windows 10
8385 * version 1703 (Creators update).
8386 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008387#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
8388
8389/*
8390 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02008391 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008392 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008393#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008394
8395/*
8396 * ConPTY differences between versions, need different logic.
8397 * version 1903 (May 2019 update).
8398 */
8399#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
8400
8401/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008402 * version 1909 (November 2019 update).
8403 */
8404#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
8405
8406/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008407 * Stay ahead of the next update, and when it's done, fix this.
8408 * version ? (2020 update, temporarily use the build number of insider preview)
8409 */
8410#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
8411
8412/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02008413 * Confirm until this version. Also the logic changes.
8414 * insider preview.
8415 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02008416#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008417
8418/*
8419 * Not stable now.
8420 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008421#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Christopher Plewright1140b512022-11-12 18:46:05 +00008422// Notes:
8423// Win 10 22H2 Final is build 19045, it's conpty is widely used.
8424// Strangely, 19045 is newer but is a lower build number than the 2020 insider
8425// preview which had a build 19587. And, not sure how stable that was?
8426// Win Server 2022 (May 10, 2022) is build 20348, its conpty is widely used.
8427// Win 11 starts from build 22000, even though the major version says 10!
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008428
8429 static void
8430vtp_flag_init(void)
8431{
8432 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008433#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008434 DWORD mode;
8435 HANDLE out;
8436
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008437# ifdef VIMDLL
8438 if (!gui.in_use)
8439# endif
8440 {
8441 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008442
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008443 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
8444 GetConsoleMode(out, &mode);
8445 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
8446 if (SetConsoleMode(out, mode) == 0)
8447 vtp_working = 0;
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008448
8449 // VTP uses alternate screen buffer.
8450 // But, not if running in a nested terminal
8451 use_alternate_screen_buffer = win10_22H2_or_later && p_rs && vtp_working
8452 && !mch_getenv("VIM_TERMINAL");
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008453 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008454#endif
8455
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008456 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008457 conpty_working = 1;
8458 if (ver >= CONPTY_STABLE_BUILD)
8459 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008460
Bram Moolenaar57da6982019-09-13 22:30:11 +02008461 if (ver <= CONPTY_INSIDER_BUILD)
8462 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008463 if (ver <= CONPTY_1909_BUILD)
8464 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02008465 if (ver <= CONPTY_1903_BUILD)
8466 conpty_type = 2;
8467 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
8468 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008469
8470 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
8471 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008472}
8473
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008474#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008475
8476 static void
8477vtp_init(void)
8478{
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008479# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightd343c602023-01-22 18:58:30 +00008480 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8481 csbi.cbSize = sizeof(csbi);
8482 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8483 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
8484 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
8485 store_console_bg_rgb = save_console_bg_rgb;
8486 store_console_fg_rgb = save_console_fg_rgb;
Christopher Plewright38804d62022-11-09 23:55:52 +00008487
Christopher Plewrightd343c602023-01-22 18:58:30 +00008488 COLORREF bg;
8489 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
8490 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8491 default_console_color_bg = bg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008492
Christopher Plewrightd343c602023-01-22 18:58:30 +00008493 COLORREF fg;
8494 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
8495 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8496 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008497# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008498 set_console_color_rgb();
8499}
8500
8501 static void
8502vtp_exit(void)
8503{
Bram Moolenaardf543822020-01-30 11:53:59 +01008504 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008505}
8506
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008507 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008508vtp_printf(
8509 char *format,
8510 ...)
8511{
8512 char_u buf[100];
8513 va_list list;
8514 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008515 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008516
8517 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008518 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008519 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008520 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008521 return (int)result;
8522}
8523
8524 static void
8525vtp_sgr_bulk(
8526 int arg)
8527{
8528 int args[1];
8529
8530 args[0] = arg;
8531 vtp_sgr_bulks(1, args);
8532}
8533
K.Takata6e1d31e2022-02-03 13:05:32 +00008534# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008535 if ((*p-- = "0123456789"[(n = x % 10)]) \
8536 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8537 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8538
K.Takata6e1d31e2022-02-03 13:05:32 +00008539# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008540 case x: \
8541 FAST256(newargs[x - 1]);
8542
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008543 static void
8544vtp_sgr_bulks(
8545 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008546 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008547{
K.Takata6e1d31e2022-02-03 13:05:32 +00008548# define MAXSGR 16
8549# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008550 char_u buf[SGRBUFSIZE];
8551 char_u *p;
8552 int in, out;
8553 int newargs[16];
8554 static int sgrfgr = -1, sgrfgg, sgrfgb;
8555 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008556
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008557 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008558 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008559 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008560 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008561 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008562 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008563
8564 in = out = 0;
8565 while (in < argc)
8566 {
8567 int s = args[in];
8568 int copylen = 1;
8569
8570 if (s == 38)
8571 {
8572 if (argc - in >= 5 && args[in + 1] == 2)
8573 {
8574 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8575 && sgrfgb == args[in + 4])
8576 {
8577 in += 5;
8578 copylen = 0;
8579 }
8580 else
8581 {
8582 sgrfgr = args[in + 2];
8583 sgrfgg = args[in + 3];
8584 sgrfgb = args[in + 4];
8585 copylen = 5;
8586 }
8587 }
8588 else if (argc - in >= 3 && args[in + 1] == 5)
8589 {
8590 sgrfgr = -1;
8591 copylen = 3;
8592 }
8593 }
8594 else if (s == 48)
8595 {
8596 if (argc - in >= 5 && args[in + 1] == 2)
8597 {
8598 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8599 && sgrbgb == args[in + 4])
8600 {
8601 in += 5;
8602 copylen = 0;
8603 }
8604 else
8605 {
8606 sgrbgr = args[in + 2];
8607 sgrbgg = args[in + 3];
8608 sgrbgb = args[in + 4];
8609 copylen = 5;
8610 }
8611 }
8612 else if (argc - in >= 3 && args[in + 1] == 5)
8613 {
8614 sgrbgr = -1;
8615 copylen = 3;
8616 }
8617 }
8618 else if (30 <= s && s <= 39)
8619 sgrfgr = -1;
8620 else if (90 <= s && s <= 97)
8621 sgrfgr = -1;
8622 else if (40 <= s && s <= 49)
8623 sgrbgr = -1;
8624 else if (100 <= s && s <= 107)
8625 sgrbgr = -1;
8626 else if (s == 0)
8627 sgrfgr = sgrbgr = -1;
8628
8629 while (copylen--)
8630 newargs[out++] = args[in++];
8631 }
8632
8633 p = &buf[sizeof(buf) - 1];
8634 *p-- = 'm';
8635
8636 switch (out)
8637 {
8638 int n, m;
8639 DWORD r;
8640
8641 FAST256CASE(16);
8642 *p-- = ';';
8643 FAST256CASE(15);
8644 *p-- = ';';
8645 FAST256CASE(14);
8646 *p-- = ';';
8647 FAST256CASE(13);
8648 *p-- = ';';
8649 FAST256CASE(12);
8650 *p-- = ';';
8651 FAST256CASE(11);
8652 *p-- = ';';
8653 FAST256CASE(10);
8654 *p-- = ';';
8655 FAST256CASE(9);
8656 *p-- = ';';
8657 FAST256CASE(8);
8658 *p-- = ';';
8659 FAST256CASE(7);
8660 *p-- = ';';
8661 FAST256CASE(6);
8662 *p-- = ';';
8663 FAST256CASE(5);
8664 *p-- = ';';
8665 FAST256CASE(4);
8666 *p-- = ';';
8667 FAST256CASE(3);
8668 *p-- = ';';
8669 FAST256CASE(2);
8670 *p-- = ';';
8671 FAST256CASE(1);
8672 *p-- = '[';
8673 *p = '\033';
8674 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8675 default:
8676 break;
8677 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008678}
8679
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008680 static void
8681wt_init(void)
8682{
Christopher Plewright1140b512022-11-12 18:46:05 +00008683 wt_working = mch_getenv("WT_SESSION") != NULL;
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008684}
8685
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008686# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008687 static int
8688ctermtoxterm(
8689 int cterm)
8690{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008691 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008692
8693 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8694 return (((int)r << 16) | ((int)g << 8) | (int)b);
8695}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008696# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008697
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008698 static void
8699set_console_color_rgb(void)
8700{
8701# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008702 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008703 guicolor_T fg, bg;
8704 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008705
Christopher Plewright38804d62022-11-09 23:55:52 +00008706 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008707 return;
8708
Bram Moolenaara050b942019-12-02 21:35:31 +01008709 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8710
Christopher Plewright38804d62022-11-09 23:55:52 +00008711 if (p_tgc || t_colors >= 256)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008712 {
8713 term_fg_rgb_color(fg);
8714 term_bg_rgb_color(bg);
8715 return;
8716 }
8717
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008718 if (use_alternate_screen_buffer)
8719 return;
8720
Christopher Plewrightd343c602023-01-22 18:58:30 +00008721 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8722 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008723
Christopher Plewrightd343c602023-01-22 18:58:30 +00008724 csbi.cbSize = sizeof(csbi);
8725 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008726
Christopher Plewrightd343c602023-01-22 18:58:30 +00008727 csbi.cbSize = sizeof(csbi);
8728 csbi.srWindow.Right += 1;
8729 csbi.srWindow.Bottom += 1;
8730 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8731 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
8732 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8733 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
8734 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008735# endif
8736}
8737
Bram Moolenaara050b942019-12-02 21:35:31 +01008738# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8739 void
8740get_default_console_color(
8741 int *cterm_fg,
8742 int *cterm_bg,
8743 guicolor_T *gui_fg,
8744 guicolor_T *gui_bg)
8745{
8746 int id;
8747 guicolor_T guifg = INVALCOLOR;
8748 guicolor_T guibg = INVALCOLOR;
8749 int ctermfg = 0;
8750 int ctermbg = 0;
Christopher Plewright38804d62022-11-09 23:55:52 +00008751 int dummynull = 0;
Bram Moolenaara050b942019-12-02 21:35:31 +01008752
8753 id = syn_name2id((char_u *)"Normal");
8754 if (id > 0 && p_tgc)
8755 syn_id2colors(id, &guifg, &guibg);
8756 if (guifg == INVALCOLOR)
8757 {
8758 ctermfg = -1;
8759 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008760 syn_id2cterm_bg(id, &ctermfg, &dummynull);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008761 if (ctermfg != -1)
8762 guifg = ctermtoxterm(ctermfg);
Christopher Plewright38804d62022-11-09 23:55:52 +00008763 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008764 guifg = USE_WT ? INVALCOLOR : default_console_color_fg;
8765 cterm_normal_fg_gui_color = guifg;
8766 ctermfg = ctermfg < 0 ? 0 : ctermfg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008767 }
8768 if (guibg == INVALCOLOR)
8769 {
8770 ctermbg = -1;
8771 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008772 syn_id2cterm_bg(id, &dummynull, &ctermbg);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008773 if (ctermbg != -1)
8774 guibg = ctermtoxterm(ctermbg);
K.Takatae53a0d42022-09-05 21:45:11 +01008775 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008776 guibg = USE_WT ? INVALCOLOR : default_console_color_bg;
8777 cterm_normal_bg_gui_color = guibg;
8778 ctermbg = ctermbg < 0 ? 0 : ctermbg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008779 }
8780
8781 *cterm_fg = ctermfg;
8782 *cterm_bg = ctermbg;
8783 *gui_fg = guifg;
8784 *gui_bg = guibg;
8785}
8786# endif
8787
Bram Moolenaardf543822020-01-30 11:53:59 +01008788/*
8789 * Set the console colors to the original colors or the last set colors.
8790 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008791 static void
8792reset_console_color_rgb(void)
8793{
8794# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008795 if (use_alternate_screen_buffer)
8796 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008797
Christopher Plewright38804d62022-11-09 23:55:52 +00008798 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8799
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008800 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008801 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008802
8803 csbi.cbSize = sizeof(csbi);
8804 csbi.srWindow.Right += 1;
8805 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008806 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8807 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008808 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008809# endif
8810}
8811
8812/*
8813 * Set the console colors to the original colors.
8814 */
8815 static void
8816restore_console_color_rgb(void)
8817{
8818# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008819 if (use_alternate_screen_buffer)
8820 return;
Christopher Plewright38804d62022-11-09 23:55:52 +00008821
K.Takata27b53be2022-09-18 12:25:49 +01008822 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008823
8824 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008825 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008826
8827 csbi.cbSize = sizeof(csbi);
8828 csbi.srWindow.Right += 1;
8829 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008830 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8831 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008832 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008833# endif
8834}
8835
8836 void
8837control_console_color_rgb(void)
8838{
Christopher Plewright38804d62022-11-09 23:55:52 +00008839 if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008840 set_console_color_rgb();
8841 else
8842 reset_console_color_rgb();
8843}
8844
8845 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008846use_vtp(void)
8847{
8848 return USE_VTP;
8849}
8850
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008851 int
8852is_term_win32(void)
8853{
8854 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8855}
8856
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008857 int
8858has_vtp_working(void)
8859{
8860 return vtp_working;
8861}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008862
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008863#endif
8864
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008865 int
8866has_conpty_working(void)
8867{
8868 return conpty_working;
8869}
8870
8871 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008872get_conpty_type(void)
8873{
8874 return conpty_type;
8875}
8876
8877 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008878is_conpty_stable(void)
8879{
8880 return conpty_stable;
8881}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008882
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008883 int
8884get_conpty_fix_type(void)
8885{
8886 return conpty_fix_type;
8887}
8888
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008889#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008890 void
8891resize_console_buf(void)
8892{
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008893 if (use_alternate_screen_buffer)
8894 return;
8895
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008896 CONSOLE_SCREEN_BUFFER_INFO csbi;
8897 COORD coord;
8898 SMALL_RECT newsize;
8899
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008900 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8901 return;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008902
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008903 coord.X = SRWIDTH(csbi.srWindow);
8904 coord.Y = SRHEIGHT(csbi.srWindow);
8905 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008906
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008907 newsize.Left = 0;
8908 newsize.Top = 0;
8909 newsize.Right = coord.X - 1;
8910 newsize.Bottom = coord.Y - 1;
8911 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8912
8913 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008914}
8915#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008916
8917 char *
8918GetWin32Error(void)
8919{
K.Takatad68b2fc2022-02-12 11:18:37 +00008920 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008921 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008922
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008923 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8924 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008925 if (oldmsg != NULL)
8926 LocalFree(oldmsg);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008927 if (msg == NULL)
8928 return NULL;
8929
8930 // remove trailing \r\n
8931 char *pcrlf = strstr(msg, "\r\n");
8932 if (pcrlf != NULL)
8933 *pcrlf = '\0';
8934 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008935 return msg;
8936}
Paul Ollis65745772022-06-05 16:55:54 +01008937
8938#if defined(FEAT_RELTIME) || defined(PROTO)
8939static HANDLE timer_handle;
8940static int timer_active = FALSE;
8941
8942/*
8943 * Calls to start_timeout alternate the return value pointer between the two
8944 * entries in timeout_flags. If the previously active timeout is very close to
8945 * expiring when start_timeout() is called then a race condition means that the
8946 * set_flag() function may still be invoked after the previous timer is
8947 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8948 * timeouts.
8949 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008950static sig_atomic_t timeout_flags[2];
8951static int timeout_flag_idx = 0;
8952static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01008953
8954
8955 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01008956set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01008957{
8958 int *timeout_flag = (int *)param;
8959
8960 *timeout_flag = TRUE;
8961}
8962
8963/*
8964 * Stop any active timeout.
8965 */
8966 void
8967stop_timeout(void)
8968{
8969 if (timer_active)
8970 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01008971 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01008972 timer_active = FALSE;
8973 if (!ret && GetLastError() != ERROR_IO_PENDING)
8974 {
8975 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
8976 }
8977 }
8978 *timeout_flag = FALSE;
8979}
8980
8981/*
8982 * Start the timeout timer.
8983 *
8984 * The period is defined in milliseconds.
8985 *
8986 * The return value is a pointer to a flag that is initialised to 0. If the
8987 * timeout expires, the flag is set to 1. This will only return pointers to
8988 * static memory; i.e. any pointer returned by this function may always be
8989 * safely dereferenced.
8990 *
8991 * This function is not expected to fail, but if it does it still returns a
8992 * valid flag pointer; the flag will remain stuck at zero.
8993 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008994 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01008995start_timeout(long msec)
8996{
Paul Ollis65745772022-06-05 16:55:54 +01008997 BOOL ret;
8998
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008999 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01009000
9001 stop_timeout();
9002 ret = CreateTimerQueueTimer(
9003 &timer_handle, NULL, set_flag, timeout_flag,
9004 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
9005 if (!ret)
9006 {
9007 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
9008 }
9009 else
9010 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01009011 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01009012 timer_active = TRUE;
9013 *timeout_flag = FALSE;
9014 }
9015 return timeout_flag;
9016}
9017#endif