blob: 52e0583fc65190836e36a0cc5bc69ced20bd908d [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)
2724 return FALSE;
2725 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002726 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002727 *path = res;
2728 else
2729 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002730 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002731 else if (path != NULL)
2732 *path = FullName_save((char_u *)name, FALSE);
2733 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002734}
2735
2736/*
2737 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2738 * If "use_path" is FALSE: Return TRUE if "name" exists.
2739 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2740 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2741 * the allocated memory.
2742 */
2743 static int
2744executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2745{
2746 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2747 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2748 // UTF-8.
2749 char_u buf[_MAX_PATH * 3];
2750 size_t len = STRLEN(name);
2751 size_t tmplen;
2752 char_u *p, *e, *e2;
2753 char_u *pathbuf = NULL;
2754 char_u *pathext = NULL;
2755 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002756 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002757 int noext = FALSE;
2758 int retval = FALSE;
2759
2760 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002761 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002762
2763 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002764 shname = gettail(p_sh);
2765 if (strstr((char *)shname, "sh") != NULL &&
2766 !(strstr((char *)shname, "powershell") != NULL
2767 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002768 noext = TRUE;
2769
2770 if (use_pathext)
2771 {
2772 pathext = mch_getenv("PATHEXT");
2773 if (pathext == NULL)
2774 pathext = (char_u *)".com;.exe;.bat;.cmd";
2775
2776 if (noext == FALSE)
2777 {
2778 /*
2779 * Loop over all extensions in $PATHEXT.
2780 * Check "name" ends with extension.
2781 */
2782 p = pathext;
2783 while (*p)
2784 {
2785 if (p[0] == ';'
2786 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2787 {
2788 // Skip empty or single ".".
2789 ++p;
2790 continue;
2791 }
2792 e = vim_strchr(p, ';');
2793 if (e == NULL)
2794 e = p + STRLEN(p);
2795 tmplen = e - p;
2796
2797 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2798 {
2799 noext = TRUE;
2800 break;
2801 }
2802
2803 p = e;
2804 }
2805 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002806 }
2807
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002808 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002809 if (pathext == NULL)
2810 pathext = (char_u *)".";
2811 else if (noext == TRUE)
2812 {
2813 if (pathextbuf == NULL)
2814 pathextbuf = alloc(STRLEN(pathext) + 3);
2815 if (pathextbuf == NULL)
2816 {
2817 retval = FALSE;
2818 goto theend;
2819 }
2820 STRCPY(pathextbuf, ".;");
2821 STRCAT(pathextbuf, pathext);
2822 pathext = pathextbuf;
2823 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002824
Bram Moolenaar95da1362020-05-30 18:37:55 +02002825 // Use $PATH when "use_path" is TRUE and "name" is basename.
2826 if (use_path && gettail((char_u *)name) == (char_u *)name)
2827 {
2828 p = mch_getenv("PATH");
2829 if (p != NULL)
2830 {
2831 pathbuf = alloc(STRLEN(p) + 3);
2832 if (pathbuf == NULL)
2833 {
2834 retval = FALSE;
2835 goto theend;
2836 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002837
2838 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2839 STRCPY(pathbuf, ".;");
2840 else
2841 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002842 STRCAT(pathbuf, p);
2843 }
2844 }
2845
2846 /*
2847 * Walk through all entries in $PATH to check if "name" exists there and
2848 * is an executable file.
2849 */
2850 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2851 while (*p)
2852 {
2853 if (*p == ';') // Skip empty entry
2854 {
2855 ++p;
2856 continue;
2857 }
2858 e = vim_strchr(p, ';');
2859 if (e == NULL)
2860 e = p + STRLEN(p);
2861
2862 if (e - p + len + 2 > sizeof(buf))
2863 {
2864 retval = FALSE;
2865 goto theend;
2866 }
2867 // A single "." that means current dir.
2868 if (e - p == 1 && *p == '.')
2869 STRCPY(buf, name);
2870 else
2871 {
2872 vim_strncpy(buf, p, e - p);
2873 add_pathsep(buf);
2874 STRCAT(buf, name);
2875 }
2876 tmplen = STRLEN(buf);
2877
2878 /*
2879 * Loop over all extensions in $PATHEXT.
2880 * Check "name" with extension added.
2881 */
2882 p = pathext;
2883 while (*p)
2884 {
2885 if (*p == ';')
2886 {
2887 // Skip empty entry
2888 ++p;
2889 continue;
2890 }
2891 e2 = vim_strchr(p, (int)';');
2892 if (e2 == NULL)
2893 e2 = p + STRLEN(p);
2894
2895 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2896 {
2897 // Not a single "." that means no extension is added.
2898 if (e2 - p + tmplen + 1 > sizeof(buf))
2899 {
2900 retval = FALSE;
2901 goto theend;
2902 }
2903 vim_strncpy(buf + tmplen, p, e2 - p);
2904 }
2905 if (executable_file((char *)buf, path))
2906 {
2907 retval = TRUE;
2908 goto theend;
2909 }
2910
2911 p = e2;
2912 }
2913
2914 p = e;
2915 }
2916
2917theend:
2918 free(pathextbuf);
2919 free(pathbuf);
2920 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002921}
2922
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002923#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2924 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002925/*
2926 * Bad parameter handler.
2927 *
2928 * Certain MS CRT functions will intentionally crash when passed invalid
2929 * parameters to highlight possible security holes. Setting this function as
2930 * the bad parameter handler will prevent the crash.
2931 *
2932 * In debug builds the parameters contain CRT information that might help track
2933 * down the source of a problem, but in non-debug builds the arguments are all
2934 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2935 * worth allowing these to make debugging of issues easier.
2936 */
2937 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002938bad_param_handler(const wchar_t *expression UNUSED,
2939 const wchar_t *function UNUSED,
2940 const wchar_t *file UNUSED,
2941 unsigned int line UNUSED,
2942 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002943{
2944}
2945
2946# define SET_INVALID_PARAM_HANDLER \
2947 ((void)_set_invalid_parameter_handler(bad_param_handler))
2948#else
2949# define SET_INVALID_PARAM_HANDLER
2950#endif
2951
Bram Moolenaar4f974752019-02-17 17:44:42 +01002952#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002953
2954/*
2955 * GUI version of mch_init().
2956 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002957 static void
2958mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002959{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002960# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002961 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002962# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002963
Bram Moolenaar0f873732019-12-05 20:28:46 +01002964 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002965 SET_INVALID_PARAM_HANDLER;
2966
Bram Moolenaar0f873732019-12-05 20:28:46 +01002967 // Let critical errors result in a failure, not in a dialog box. Required
2968 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002969 SetErrorMode(SEM_FAILCRITICALERRORS);
2970
Bram Moolenaar0f873732019-12-05 20:28:46 +01002971 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002972
Bram Moolenaar0f873732019-12-05 20:28:46 +01002973 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002974 Rows = 25;
2975 Columns = 80;
2976
Bram Moolenaar0f873732019-12-05 20:28:46 +01002977 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002978 {
2979 char_u vimrun_location[_MAX_PATH + 4];
2980
Bram Moolenaar0f873732019-12-05 20:28:46 +01002981 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002982 STRCPY(vimrun_location, exe_name);
2983 STRCPY(gettail(vimrun_location), "vimrun.exe");
2984 if (mch_getperm(vimrun_location) >= 0)
2985 {
2986 if (*skiptowhite(vimrun_location) != NUL)
2987 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002988 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002989 mch_memmove(vimrun_location + 1, vimrun_location,
2990 STRLEN(vimrun_location) + 1);
2991 *vimrun_location = '"';
2992 STRCPY(gettail(vimrun_location), "vimrun\" ");
2993 }
2994 else
2995 STRCPY(gettail(vimrun_location), "vimrun ");
2996
2997 vimrun_path = (char *)vim_strsave(vimrun_location);
2998 s_dont_use_vimrun = FALSE;
2999 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02003000 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003001 s_dont_use_vimrun = FALSE;
3002
Bram Moolenaar0f873732019-12-05 20:28:46 +01003003 // Don't give the warning for a missing vimrun.exe right now, but only
3004 // when vimrun was supposed to be used. Don't bother people that do
3005 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003006 if (s_dont_use_vimrun)
3007 need_vimrun_warning = TRUE;
3008 }
3009
3010 /*
3011 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
3012 * Otherwise the default "findstr /n" is used.
3013 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02003014 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01003015 set_option_value_give_err((char_u *)"grepprg",
3016 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003017
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003018# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003019 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003020# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003021
3022 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003023}
3024
3025
Bram Moolenaar0f873732019-12-05 20:28:46 +01003026#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003027
3028#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003029
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003030# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
3031# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003032
3033/*
3034 * ClearConsoleBuffer()
3035 * Description:
3036 * Clears the entire contents of the console screen buffer, using the
3037 * specified attribute.
3038 * Returns:
3039 * TRUE on success
3040 */
3041 static BOOL
3042ClearConsoleBuffer(WORD wAttribute)
3043{
3044 CONSOLE_SCREEN_BUFFER_INFO csbi;
3045 COORD coord;
3046 DWORD NumCells, dummy;
3047
3048 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3049 return FALSE;
3050
3051 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
3052 coord.X = 0;
3053 coord.Y = 0;
3054 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
3055 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003056 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003057 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
3058 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003059 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003060
3061 return TRUE;
3062}
3063
3064/*
3065 * FitConsoleWindow()
3066 * Description:
3067 * Checks if the console window will fit within given buffer dimensions.
3068 * Also, if requested, will shrink the window to fit.
3069 * Returns:
3070 * TRUE on success
3071 */
3072 static BOOL
3073FitConsoleWindow(
3074 COORD dwBufferSize,
3075 BOOL WantAdjust)
3076{
3077 CONSOLE_SCREEN_BUFFER_INFO csbi;
3078 COORD dwWindowSize;
3079 BOOL NeedAdjust = FALSE;
3080
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003081 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3082 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003083
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003084 /*
3085 * A buffer resize will fail if the current console window does
3086 * not lie completely within that buffer. To avoid this, we might
3087 * have to move and possibly shrink the window.
3088 */
3089 if (csbi.srWindow.Right >= dwBufferSize.X)
3090 {
3091 dwWindowSize.X = SRWIDTH(csbi.srWindow);
3092 if (dwWindowSize.X > dwBufferSize.X)
3093 dwWindowSize.X = dwBufferSize.X;
3094 csbi.srWindow.Right = dwBufferSize.X - 1;
3095 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
3096 NeedAdjust = TRUE;
3097 }
3098 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
3099 {
3100 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
3101 if (dwWindowSize.Y > dwBufferSize.Y)
3102 dwWindowSize.Y = dwBufferSize.Y;
3103 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
3104 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
3105 NeedAdjust = TRUE;
3106 }
3107 if (NeedAdjust && WantAdjust)
3108 {
3109 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
3110 return FALSE;
3111 }
3112 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003113}
3114
3115typedef struct ConsoleBufferStruct
3116{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003117 BOOL IsValid;
3118 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003119 PCHAR_INFO Buffer;
3120 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003121 PSMALL_RECT Regions;
3122 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003123} ConsoleBuffer;
3124
3125/*
3126 * SaveConsoleBuffer()
3127 * Description:
3128 * Saves important information about the console buffer, including the
3129 * actual buffer contents. The saved information is suitable for later
3130 * restoration by RestoreConsoleBuffer().
3131 * Returns:
3132 * TRUE if all information was saved; FALSE otherwise
3133 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
3134 */
3135 static BOOL
3136SaveConsoleBuffer(
3137 ConsoleBuffer *cb)
3138{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003139 DWORD NumCells;
3140 COORD BufferCoord;
3141 SMALL_RECT ReadRegion;
3142 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003143 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003144
Bram Moolenaar071d4272004-06-13 20:20:40 +00003145 if (cb == NULL)
3146 return FALSE;
3147
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003148 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003149 {
3150 cb->IsValid = FALSE;
3151 return FALSE;
3152 }
3153 cb->IsValid = TRUE;
3154
Christopher Plewright1140b512022-11-12 18:46:05 +00003155 // VTP uses alternate screen buffer.
3156 // No need to save buffer contents for restoration.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003157 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003158 return TRUE;
3159
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003160 /*
3161 * Allocate a buffer large enough to hold the entire console screen
3162 * buffer. If this ConsoleBuffer structure has already been initialized
3163 * with a buffer of the correct size, then just use that one.
3164 */
3165 if (!cb->IsValid || cb->Buffer == NULL ||
3166 cb->BufferSize.X != cb->Info.dwSize.X ||
3167 cb->BufferSize.Y != cb->Info.dwSize.Y)
3168 {
3169 cb->BufferSize.X = cb->Info.dwSize.X;
3170 cb->BufferSize.Y = cb->Info.dwSize.Y;
3171 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
3172 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003173 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003174 if (cb->Buffer == NULL)
3175 return FALSE;
3176 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003177
3178 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003179 * We will now copy the console screen buffer into our buffer.
3180 * ReadConsoleOutput() seems to be limited as far as how much you
3181 * can read at a time. Empirically, this number seems to be about
3182 * 12000 cells (rows * columns). Start at position (0, 0) and copy
3183 * in chunks until it is all copied. The chunks will all have the
3184 * same horizontal characteristics, so initialize them now. The
3185 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003186 */
Bram Moolenaar61594242015-09-01 20:23:37 +02003187 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003188 ReadRegion.Left = 0;
3189 ReadRegion.Right = cb->Info.dwSize.X - 1;
3190 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003191
3192 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
3193 if (cb->Regions == NULL || numregions != cb->NumRegions)
3194 {
3195 cb->NumRegions = numregions;
3196 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003197 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003198 if (cb->Regions == NULL)
3199 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003200 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003201 return FALSE;
3202 }
3203 }
3204
3205 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003206 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003207 /*
3208 * Read into position (0, Y) in our buffer.
3209 */
3210 BufferCoord.Y = Y;
3211 /*
3212 * Read the region whose top left corner is (0, Y) and whose bottom
3213 * right corner is (width - 1, Y + Y_incr - 1). This should define
3214 * a region of size width by Y_incr. Don't worry if this region is
3215 * too large for the remaining buffer; it will be cropped.
3216 */
3217 ReadRegion.Top = Y;
3218 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003219 if (!ReadConsoleOutputW(g_hConOut, // output handle
3220 cb->Buffer, // our buffer
3221 cb->BufferSize, // dimensions of our buffer
3222 BufferCoord, // offset in our buffer
3223 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003224 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003225 VIM_CLEAR(cb->Buffer);
3226 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003227 return FALSE;
3228 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02003229 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003230 }
3231
3232 return TRUE;
3233}
3234
3235/*
3236 * RestoreConsoleBuffer()
3237 * Description:
3238 * Restores important information about the console buffer, including the
3239 * actual buffer contents, if desired. The information to restore is in
3240 * the same format used by SaveConsoleBuffer().
3241 * Returns:
3242 * TRUE on success
3243 */
3244 static BOOL
3245RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003246 ConsoleBuffer *cb,
3247 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003248{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003249 COORD BufferCoord;
3250 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003251 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003252
Christopher Plewright1140b512022-11-12 18:46:05 +00003253 // VTP uses alternate screen buffer.
3254 // No need to restore buffer contents.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003255 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003256 return TRUE;
3257
Bram Moolenaar071d4272004-06-13 20:20:40 +00003258 if (cb == NULL || !cb->IsValid)
3259 return FALSE;
3260
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003261 /*
3262 * Before restoring the buffer contents, clear the current buffer, and
3263 * restore the cursor position and window information. Doing this now
3264 * prevents old buffer contents from "flashing" onto the screen.
3265 */
3266 if (RestoreScreen)
3267 ClearConsoleBuffer(cb->Info.wAttributes);
3268
3269 FitConsoleWindow(cb->Info.dwSize, TRUE);
3270 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
3271 return FALSE;
3272 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
3273 return FALSE;
3274
3275 if (!RestoreScreen)
3276 {
3277 /*
3278 * No need to restore the screen buffer contents, so we're done.
3279 */
3280 return TRUE;
3281 }
3282
3283 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
3284 return FALSE;
3285 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
3286 return FALSE;
3287
3288 /*
3289 * Restore the screen buffer contents.
3290 */
3291 if (cb->Buffer != NULL)
3292 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003293 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003294 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003295 BufferCoord.X = cb->Regions[i].Left;
3296 BufferCoord.Y = cb->Regions[i].Top;
3297 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01003298 if (!WriteConsoleOutputW(g_hConOut, // output handle
3299 cb->Buffer, // our buffer
3300 cb->BufferSize, // dimensions of our buffer
3301 BufferCoord, // offset in our buffer
3302 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02003303 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003304 }
3305 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003306
3307 return TRUE;
3308}
3309
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003310# define FEAT_RESTORE_ORIG_SCREEN
3311# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003312static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003313# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003314static ConsoleBuffer g_cbNonTermcap = { 0 };
3315static ConsoleBuffer g_cbTermcap = { 0 };
3316
Bram Moolenaar071d4272004-06-13 20:20:40 +00003317char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01003318HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00003319static HICON g_hOrigIconSmall = NULL;
3320static HICON g_hOrigIcon = NULL;
3321static HICON g_hVimIcon = NULL;
3322static BOOL g_fCanChangeIcon = FALSE;
3323
Bram Moolenaar071d4272004-06-13 20:20:40 +00003324/*
3325 * GetConsoleIcon()
3326 * Description:
3327 * Attempts to retrieve the small icon and/or the big icon currently in
3328 * use by a given window.
3329 * Returns:
3330 * TRUE on success
3331 */
3332 static BOOL
3333GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003334 HWND hWnd,
3335 HICON *phIconSmall,
3336 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003337{
3338 if (hWnd == NULL)
3339 return FALSE;
3340
3341 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003342 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
3343 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003344 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003345 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
3346 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003347 return TRUE;
3348}
3349
3350/*
3351 * SetConsoleIcon()
3352 * Description:
3353 * Attempts to change the small icon and/or the big icon currently in
3354 * use by a given window.
3355 * Returns:
3356 * TRUE on success
3357 */
3358 static BOOL
3359SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003360 HWND hWnd,
3361 HICON hIconSmall,
3362 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003363{
Bram Moolenaar071d4272004-06-13 20:20:40 +00003364 if (hWnd == NULL)
3365 return FALSE;
3366
3367 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003368 SendMessage(hWnd, WM_SETICON,
3369 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003370 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003371 SendMessage(hWnd, WM_SETICON,
3372 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003373 return TRUE;
3374}
3375
3376/*
3377 * SaveConsoleTitleAndIcon()
3378 * Description:
3379 * Saves the current console window title in g_szOrigTitle, for later
3380 * restoration. Also, attempts to obtain a handle to the console window,
3381 * and use it to save the small and big icons currently in use by the
3382 * console window. This is not always possible on some versions of Windows;
3383 * nor is it possible when running Vim remotely using Telnet (since the
3384 * console window the user sees is owned by a remote process).
3385 */
3386 static void
3387SaveConsoleTitleAndIcon(void)
3388{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003389 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003390 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
3391 return;
3392
3393 /*
3394 * Obtain a handle to the console window using GetConsoleWindow() from
3395 * KERNEL32.DLL; we need to handle in order to change the window icon.
3396 * This function only exists on NT-based Windows, starting with Windows
3397 * 2000. On older operating systems, we can't change the window icon
3398 * anyway.
3399 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003400 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003401 if (g_hWnd == NULL)
3402 return;
3403
Bram Moolenaar0f873732019-12-05 20:28:46 +01003404 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003405 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
3406 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
3407 return;
3408
Bram Moolenaar0f873732019-12-05 20:28:46 +01003409 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01003410 if (
3411# ifdef FEAT_LIBCALL
3412 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
3413# endif
3414 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003415 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003416 if (g_hVimIcon != NULL)
3417 g_fCanChangeIcon = TRUE;
3418}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003419
3420static int g_fWindInitCalled = FALSE;
3421static int g_fTermcapMode = FALSE;
3422static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003423
3424/*
3425 * non-GUI version of mch_init().
3426 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003427 static void
3428mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003429{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003430# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003431 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003432# endif
3433# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00003434 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003435# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003436
Bram Moolenaar0f873732019-12-05 20:28:46 +01003437 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02003438 SET_INVALID_PARAM_HANDLER;
3439
Bram Moolenaar0f873732019-12-05 20:28:46 +01003440 // Let critical errors result in a failure, not in a dialog box. Required
3441 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003442 SetErrorMode(SEM_FAILCRITICALERRORS);
3443
Bram Moolenaar0f873732019-12-05 20:28:46 +01003444 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00003445 out_flush();
3446
Bram Moolenaar0f873732019-12-05 20:28:46 +01003447 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00003448 if (read_cmd_fd == 0)
3449 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
3450 else
3451 create_conin();
3452 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
3453
Christopher Plewright38804d62022-11-09 23:55:52 +00003454 wt_init();
3455 vtp_flag_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003456# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01003457 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003458 SaveConsoleBuffer(&g_cbOrig);
3459 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003460# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01003461 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003462 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
3463 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003464# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003465 if (cterm_normal_fg_color == 0)
3466 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
3467 if (cterm_normal_bg_color == 0)
3468 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
3469
Bram Moolenaarbdace832019-03-02 10:13:42 +01003470 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02003471 g_color_index_fg = g_attrDefault & 0xf;
3472 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
3473
Bram Moolenaar0f873732019-12-05 20:28:46 +01003474 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00003475 update_tcap(g_attrCurrent);
3476
3477 GetConsoleCursorInfo(g_hConOut, &g_cci);
3478 GetConsoleMode(g_hConIn, &g_cmodein);
3479 GetConsoleMode(g_hConOut, &g_cmodeout);
3480
Bram Moolenaar071d4272004-06-13 20:20:40 +00003481 SaveConsoleTitleAndIcon();
3482 /*
3483 * Set both the small and big icons of the console window to Vim's icon.
3484 * Note that Vim presently only has one size of icon (32x32), but it
3485 * automatically gets scaled down to 16x16 when setting the small icon.
3486 */
3487 if (g_fCanChangeIcon)
3488 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003489
3490 ui_get_shellsize();
3491
Christopher Plewrightd343c602023-01-22 18:58:30 +00003492 vtp_init();
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00003493 // Switch to a new alternate screen buffer.
3494 if (use_alternate_screen_buffer)
3495 vtp_printf("\033[?1049h");
Christopher Plewrightd343c602023-01-22 18:58:30 +00003496
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003497# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003498 fdDump = fopen("dump", "wt");
3499
3500 if (fdDump)
3501 {
3502 time_t t;
3503
3504 time(&t);
3505 fputs(ctime(&t), fdDump);
3506 fflush(fdDump);
3507 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003508# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003509
3510 g_fWindInitCalled = TRUE;
3511
Bram Moolenaar071d4272004-06-13 20:20:40 +00003512 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003513
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003514# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003515 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003516# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003517}
3518
3519/*
3520 * non-GUI version of mch_exit().
3521 * Shut down and exit with status `r'
3522 * Careful: mch_exit() may be called before mch_init()!
3523 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003524 static void
3525mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003526{
Bram Moolenaar955f1982017-02-05 15:10:51 +01003527 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003528
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003529 vtp_exit();
3530
Bram Moolenaar955f1982017-02-05 15:10:51 +01003531 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003532 if (g_fWindInitCalled)
3533 settmode(TMODE_COOK);
3534
Bram Moolenaar0f873732019-12-05 20:28:46 +01003535 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00003536
3537 if (g_fWindInitCalled)
3538 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02003539 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003540 /*
3541 * Restore both the small and big icons of the console window to
3542 * what they were at startup. Don't do this when the window is
3543 * closed, Vim would hang here.
3544 */
3545 if (g_fCanChangeIcon && !g_fForceExit)
3546 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003547
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003548# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003549 if (fdDump)
3550 {
3551 time_t t;
3552
3553 time(&t);
3554 fputs(ctime(&t), fdDump);
3555 fclose(fdDump);
3556 }
3557 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003558# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003559 }
3560
3561 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003562 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003563 SetConsoleMode(g_hConOut, g_cmodeout);
3564
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003565# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003566 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003567# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003568
3569 exit(r);
3570}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003571#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003572
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003573 void
3574mch_init(void)
3575{
3576#ifdef VIMDLL
3577 if (gui.starting)
3578 mch_init_g();
3579 else
3580 mch_init_c();
3581#elif defined(FEAT_GUI_MSWIN)
3582 mch_init_g();
3583#else
3584 mch_init_c();
3585#endif
3586}
3587
3588 void
3589mch_exit(int r)
3590{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003591#ifdef FEAT_NETBEANS_INTG
3592 netbeans_send_disconnect();
3593#endif
3594
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003595#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003596 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003597 mch_exit_g(r);
3598 else
3599 mch_exit_c(r);
3600#elif defined(FEAT_GUI_MSWIN)
3601 mch_exit_g(r);
3602#else
3603 mch_exit_c(r);
3604#endif
3605}
3606
Bram Moolenaar071d4272004-06-13 20:20:40 +00003607/*
3608 * Do we have an interactive window?
3609 */
3610 int
3611mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003612 int argc UNUSED,
3613 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003614{
K.Takatace3189d2023-02-15 19:13:43 +00003615 mch_get_exe_name();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003616
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003617#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003618 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003619#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003620# ifdef VIMDLL
3621 if (gui.in_use)
3622 return OK;
3623# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003624 if (isatty(1))
3625 return OK;
3626 return FAIL;
3627#endif
3628}
3629
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003630/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003631 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003632 * When "len" is > 0, also expand short to long filenames.
3633 */
3634 void
3635fname_case(
3636 char_u *name,
3637 int len)
3638{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003639 int flen;
3640 WCHAR *p;
3641 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003642
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003643 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003644 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003645 return;
3646
3647 slash_adjust(name);
3648
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003649 p = enc_to_utf16(name, NULL);
3650 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003651 return;
3652
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003653 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003654 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003655 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003656
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003657 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003658 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003659 if (len > 0 || flen >= (int)STRLEN(q))
3660 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3661 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003662 }
3663 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003664 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003665}
3666
3667
3668/*
3669 * Insert user name in s[len].
3670 */
3671 int
3672mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003673 char_u *s,
3674 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003675{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003676 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003677 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003678
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003679 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003680 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003681 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003682
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003683 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003684 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003685 vim_strncpy(s, p, len - 1);
3686 vim_free(p);
3687 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003688 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003689 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003690 s[0] = NUL;
3691 return FAIL;
3692}
3693
3694
3695/*
3696 * Insert host name in s[len].
3697 */
3698 void
3699mch_get_host_name(
3700 char_u *s,
3701 int len)
3702{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003703 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003704 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003705
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003706 if (!GetComputerNameW(wszHostName, &wcch))
3707 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003708
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003709 char_u *p = utf16_to_enc(wszHostName, NULL);
3710 if (p == NULL)
3711 return;
3712
3713 vim_strncpy(s, p, len - 1);
3714 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003715}
3716
3717
3718/*
3719 * return process ID
3720 */
3721 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003722mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003723{
3724 return (long)GetCurrentProcessId();
3725}
3726
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003727/*
3728 * return TRUE if process "pid" is still running
3729 */
3730 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003731mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003732{
3733 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3734 DWORD status = 0;
3735 int ret = FALSE;
3736
3737 if (hProcess == NULL)
3738 return FALSE; // might not have access
3739 if (GetExitCodeProcess(hProcess, &status) )
3740 ret = status == STILL_ACTIVE;
3741 CloseHandle(hProcess);
3742 return ret;
3743}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003744
3745/*
3746 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3747 * Return OK for success, FAIL for failure.
3748 */
3749 int
3750mch_dirname(
3751 char_u *buf,
3752 int len)
3753{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003754 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003755
Bram Moolenaar071d4272004-06-13 20:20:40 +00003756 /*
3757 * Originally this was:
3758 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3759 * But the Win32s known bug list says that getcwd() doesn't work
3760 * so use the Win32 system call instead. <Negri>
3761 */
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003762 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) == 0)
3763 return FAIL;
3764
3765 WCHAR wcbuf[_MAX_PATH + 1];
3766 char_u *p = NULL;
3767
3768 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003769 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003770 p = utf16_to_enc(wcbuf, NULL);
3771 if (STRLEN(p) >= (size_t)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003772 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003773 // long path name is too long, fall back to short one
Yegappan Lakshmanan960dcbd2023-03-07 17:45:11 +00003774 VIM_CLEAR(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003775 }
3776 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003777 if (p == NULL)
3778 p = utf16_to_enc(wbuf, NULL);
3779
3780 if (p == NULL)
3781 return FAIL;
3782
3783 vim_strncpy(buf, p, len - 1);
3784 vim_free(p);
3785 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003786}
3787
3788/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003789 * Get file permissions for "name".
3790 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003791 */
3792 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003793mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003794{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003795 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003796 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003797
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003798 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003799 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003800}
3801
3802
3803/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003804 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003805 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003806 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003807 */
3808 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003809mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003810{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003811 long n;
3812 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003813
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003814 p = enc_to_utf16(name, NULL);
3815 if (p == NULL)
3816 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003817
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003818 n = _wchmod(p, perm);
3819 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003820 if (n == -1)
3821 return FAIL;
3822
3823 win32_set_archive(name);
3824
3825 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003826}
3827
3828/*
3829 * Set hidden flag for "name".
3830 */
3831 void
3832mch_hide(char_u *name)
3833{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003834 int attrs = win32_getattrs(name);
3835 if (attrs == -1)
3836 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003837
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003838 attrs |= FILE_ATTRIBUTE_HIDDEN;
3839 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003840}
3841
3842/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003843 * Return TRUE if file "name" exists and is hidden.
3844 */
3845 int
3846mch_ishidden(char_u *name)
3847{
3848 int f = win32_getattrs(name);
3849
3850 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003851 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003852
3853 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3854}
3855
3856/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003857 * return TRUE if "name" is a directory
3858 * return FALSE if "name" is not a directory or upon error
3859 */
3860 int
3861mch_isdir(char_u *name)
3862{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003863 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003864
3865 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003866 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003867
3868 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3869}
3870
3871/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003872 * return TRUE if "name" is a directory, NOT a symlink to a directory
3873 * return FALSE if "name" is not a directory
3874 * return FALSE for error
3875 */
3876 int
3877mch_isrealdir(char_u *name)
3878{
3879 return mch_isdir(name) && !mch_is_symbolic_link(name);
3880}
3881
3882/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003883 * Create directory "name".
3884 * Return 0 on success, -1 on error.
3885 */
3886 int
3887mch_mkdir(char_u *name)
3888{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003889 WCHAR *p;
3890 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003891
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003892 p = enc_to_utf16(name, NULL);
3893 if (p == NULL)
3894 return -1;
3895 retval = _wmkdir(p);
3896 vim_free(p);
3897 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003898}
3899
3900/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003901 * Delete directory "name".
3902 * Return 0 on success, -1 on error.
3903 */
3904 int
3905mch_rmdir(char_u *name)
3906{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003907 WCHAR *p;
3908 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003909
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003910 p = enc_to_utf16(name, NULL);
3911 if (p == NULL)
3912 return -1;
3913 retval = _wrmdir(p);
3914 vim_free(p);
3915 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003916}
3917
3918/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003919 * Return TRUE if file "fname" has more than one link.
3920 */
3921 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003922mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003923{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003924 BY_HANDLE_FILE_INFORMATION info;
3925
3926 return win32_fileinfo(fname, &info) == FILEINFO_OK
3927 && info.nNumberOfLinks > 1;
3928}
3929
3930/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003931 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003932 */
3933 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003934mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003935{
3936 HANDLE hFind;
3937 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003938 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003939 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003940 WIN32_FIND_DATAW findDataW;
3941
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003942 wn = enc_to_utf16(name, NULL);
3943 if (wn == NULL)
3944 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003945
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003946 hFind = FindFirstFileW(wn, &findDataW);
3947 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003948 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003949 {
3950 fileFlags = findDataW.dwFileAttributes;
3951 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003952 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003953 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003954
3955 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003956 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3957 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003958 res = TRUE;
3959
3960 return res;
3961}
3962
3963/*
3964 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3965 * link.
3966 */
3967 int
3968mch_is_linked(char_u *fname)
3969{
3970 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3971 return TRUE;
3972 return FALSE;
3973}
3974
3975/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003976 * Get the by-handle-file-information for "fname".
3977 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003978 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003979 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3980 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3981 */
3982 int
3983win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3984{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003985 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003986 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003987 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003988
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003989 wn = enc_to_utf16(fname, NULL);
3990 if (wn == NULL)
3991 return FILEINFO_ENC_FAIL;
3992
3993 hFile = CreateFileW(wn, // file name
3994 GENERIC_READ, // access mode
3995 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3996 NULL, // security descriptor
3997 OPEN_EXISTING, // creation disposition
3998 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3999 NULL); // handle to template file
4000 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00004001
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00004002 if (hFile == INVALID_HANDLE_VALUE)
4003 return FILEINFO_READ_FAIL;
4004
4005 if (GetFileInformationByHandle(hFile, info) != 0)
4006 res = FILEINFO_OK;
4007 else
4008 res = FILEINFO_INFO_FAIL;
4009 CloseHandle(hFile);
Bram Moolenaar03f48552006-02-28 23:52:23 +00004010
Bram Moolenaar03f48552006-02-28 23:52:23 +00004011 return res;
4012}
4013
4014/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004015 * get file attributes for `name'
4016 * -1 : error
4017 * else FILE_ATTRIBUTE_* defined in winnt.h
4018 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01004019 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004020win32_getattrs(char_u *name)
4021{
4022 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004023 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004024
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004025 p = enc_to_utf16(name, NULL);
4026 if (p == NULL)
4027 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004028
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004029 attr = GetFileAttributesW(p);
4030 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004031
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004032 return attr;
4033}
4034
4035/*
4036 * set file attributes for `name' to `attrs'
4037 *
4038 * return -1 for failure, 0 otherwise
4039 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004040 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004041win32_setattrs(char_u *name, int attrs)
4042{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004043 int res;
4044 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004045
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004046 p = enc_to_utf16(name, NULL);
4047 if (p == NULL)
4048 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004049
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004050 res = SetFileAttributesW(p, attrs);
4051 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004052
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004053 return res ? 0 : -1;
4054}
4055
4056/*
4057 * Set archive flag for "name".
4058 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004059 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004060win32_set_archive(char_u *name)
4061{
4062 int attrs = win32_getattrs(name);
4063 if (attrs == -1)
4064 return -1;
4065
4066 attrs |= FILE_ATTRIBUTE_ARCHIVE;
4067 return win32_setattrs(name, attrs);
4068}
4069
4070/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004071 * Return TRUE if file or directory "name" is writable (not readonly).
4072 * Strange semantics of Win32: a readonly directory is writable, but you can't
4073 * delete a file. Let's say this means it is writable.
4074 */
4075 int
4076mch_writable(char_u *name)
4077{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004078 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004079
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004080 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
4081 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004082}
4083
Bram Moolenaar071d4272004-06-13 20:20:40 +00004084/*
Bram Moolenaar43663192017-03-05 14:29:12 +01004085 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01004086 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01004087 * When returning TRUE and "path" is not NULL save the path and set "*path" to
4088 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004089 */
4090 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01004091mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004092{
Bram Moolenaar95da1362020-05-30 18:37:55 +02004093 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004094}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004095
4096/*
4097 * Check what "name" is:
4098 * NODE_NORMAL: file or directory (or doesn't exist)
4099 * NODE_WRITABLE: writable device, socket, fifo, etc.
4100 * NODE_OTHER: non-writable things
4101 */
4102 int
4103mch_nodetype(char_u *name)
4104{
4105 HANDLE hFile;
4106 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004107 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004108
Bram Moolenaar0f873732019-12-05 20:28:46 +01004109 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
4110 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
4111 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00004112 if (STRNCMP(name, "\\\\.\\", 4) == 0)
4113 return NODE_WRITABLE;
4114
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004115 wn = enc_to_utf16(name, NULL);
4116 if (wn == NULL)
4117 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004118
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004119 hFile = CreateFileW(wn, // file name
4120 GENERIC_WRITE, // access mode
4121 0, // share mode
4122 NULL, // security descriptor
4123 OPEN_EXISTING, // creation disposition
4124 0, // file attributes
4125 NULL); // handle to template file
4126 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004127 if (hFile == INVALID_HANDLE_VALUE)
4128 return NODE_NORMAL;
4129
4130 type = GetFileType(hFile);
4131 CloseHandle(hFile);
4132 if (type == FILE_TYPE_CHAR)
4133 return NODE_WRITABLE;
4134 if (type == FILE_TYPE_DISK)
4135 return NODE_NORMAL;
4136 return NODE_OTHER;
4137}
4138
4139#ifdef HAVE_ACL
4140struct my_acl
4141{
4142 PSECURITY_DESCRIPTOR pSecurityDescriptor;
4143 PSID pSidOwner;
4144 PSID pSidGroup;
4145 PACL pDacl;
4146 PACL pSacl;
4147};
4148#endif
4149
4150/*
4151 * Return a pointer to the ACL of file "fname" in allocated memory.
4152 * Return NULL if the ACL is not available for whatever reason.
4153 */
4154 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004155mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004156{
4157#ifndef HAVE_ACL
4158 return (vim_acl_T)NULL;
4159#else
4160 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02004161 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004162
Bram Moolenaarc799fe22019-05-28 23:08:19 +02004163 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004164 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004165 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004166 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02004167
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004168 wn = enc_to_utf16(fname, NULL);
4169 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004170 {
4171 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004172 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004173 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004174
4175 // Try to retrieve the entire security descriptor.
4176 err = GetNamedSecurityInfoW(
4177 wn, // Abstract filename
4178 SE_FILE_OBJECT, // File Object
4179 OWNER_SECURITY_INFORMATION |
4180 GROUP_SECURITY_INFORMATION |
4181 DACL_SECURITY_INFORMATION |
4182 SACL_SECURITY_INFORMATION,
4183 &p->pSidOwner, // Ownership information.
4184 &p->pSidGroup, // Group membership.
4185 &p->pDacl, // Discretionary information.
4186 &p->pSacl, // For auditing purposes.
4187 &p->pSecurityDescriptor);
4188 if (err == ERROR_ACCESS_DENIED ||
4189 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004190 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004191 // Retrieve only DACL.
4192 (void)GetNamedSecurityInfoW(
4193 wn,
4194 SE_FILE_OBJECT,
4195 DACL_SECURITY_INFORMATION,
4196 NULL,
4197 NULL,
4198 &p->pDacl,
4199 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004200 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004201 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004202 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004203 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004204 mch_free_acl((vim_acl_T)p);
4205 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004206 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004207 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004208 }
4209
4210 return (vim_acl_T)p;
4211#endif
4212}
4213
Bram Moolenaar27515922013-06-29 15:36:26 +02004214#ifdef HAVE_ACL
4215/*
4216 * Check if "acl" contains inherited ACE.
4217 */
4218 static BOOL
4219is_acl_inherited(PACL acl)
4220{
4221 DWORD i;
4222 ACL_SIZE_INFORMATION acl_info;
4223 PACCESS_ALLOWED_ACE ace;
4224
4225 acl_info.AceCount = 0;
4226 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
4227 for (i = 0; i < acl_info.AceCount; i++)
4228 {
4229 GetAce(acl, i, (LPVOID *)&ace);
4230 if (ace->Header.AceFlags & INHERITED_ACE)
4231 return TRUE;
4232 }
4233 return FALSE;
4234}
4235#endif
4236
Bram Moolenaar071d4272004-06-13 20:20:40 +00004237/*
4238 * Set the ACL of file "fname" to "acl" (unless it's NULL).
4239 * Errors are ignored.
4240 * This must only be called with "acl" equal to what mch_get_acl() returned.
4241 */
4242 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004243mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004244{
4245#ifdef HAVE_ACL
4246 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02004247 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004248 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004249
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004250 if (p == NULL)
4251 return;
4252
4253 wn = enc_to_utf16(fname, NULL);
4254 if (wn == NULL)
4255 return;
4256
4257 // Set security flags
4258 if (p->pSidOwner)
4259 sec_info |= OWNER_SECURITY_INFORMATION;
4260 if (p->pSidGroup)
4261 sec_info |= GROUP_SECURITY_INFORMATION;
4262 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02004263 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004264 sec_info |= DACL_SECURITY_INFORMATION;
4265 // Do not inherit its parent's DACL.
4266 // If the DACL is inherited, Cygwin permissions would be changed.
4267 if (!is_acl_inherited(p->pDacl))
4268 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02004269 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004270 if (p->pSacl)
4271 sec_info |= SACL_SECURITY_INFORMATION;
4272
4273 (void)SetNamedSecurityInfoW(
4274 wn, // Abstract filename
4275 SE_FILE_OBJECT, // File Object
4276 sec_info,
4277 p->pSidOwner, // Ownership information.
4278 p->pSidGroup, // Group membership.
4279 p->pDacl, // Discretionary information.
4280 p->pSacl // For auditing purposes.
4281 );
4282 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004283#endif
4284}
4285
4286 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004287mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004288{
4289#ifdef HAVE_ACL
4290 struct my_acl *p = (struct my_acl *)acl;
4291
4292 if (p != NULL)
4293 {
4294 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
4295 vim_free(p);
4296 }
4297#endif
4298}
4299
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004300#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004301
4302/*
4303 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
4304 */
4305 static BOOL WINAPI
4306handler_routine(
4307 DWORD dwCtrlType)
4308{
Bram Moolenaar589b1102017-08-12 16:39:05 +02004309 INPUT_RECORD ir;
4310 DWORD out;
4311
Bram Moolenaar071d4272004-06-13 20:20:40 +00004312 switch (dwCtrlType)
4313 {
4314 case CTRL_C_EVENT:
4315 if (ctrl_c_interrupts)
4316 g_fCtrlCPressed = TRUE;
4317 return TRUE;
4318
4319 case CTRL_BREAK_EVENT:
4320 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02004321 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004322 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02004323 ir.EventType = KEY_EVENT;
4324 ir.Event.KeyEvent.bKeyDown = TRUE;
4325 ir.Event.KeyEvent.wRepeatCount = 1;
4326 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
4327 ir.Event.KeyEvent.wVirtualScanCode = 0;
4328 ir.Event.KeyEvent.dwControlKeyState = 0;
4329 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
4330 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004331 return TRUE;
4332
Bram Moolenaar0f873732019-12-05 20:28:46 +01004333 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00004334 case CTRL_CLOSE_EVENT:
4335 case CTRL_LOGOFF_EVENT:
4336 case CTRL_SHUTDOWN_EVENT:
4337 windgoto((int)Rows - 1, 0);
4338 g_fForceExit = TRUE;
4339
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004340 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004341 (dwCtrlType == CTRL_CLOSE_EVENT
4342 ? _("close")
4343 : dwCtrlType == CTRL_LOGOFF_EVENT
4344 ? _("logoff")
4345 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004346# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00004347 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004348# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004349
Bram Moolenaar0f873732019-12-05 20:28:46 +01004350 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00004351
Bram Moolenaar0f873732019-12-05 20:28:46 +01004352 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00004353
4354 default:
4355 return FALSE;
4356 }
4357}
4358
4359
4360/*
4361 * set the tty in (raw) ? "raw" : "cooked" mode
4362 */
4363 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02004364mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004365{
4366 DWORD cmodein;
4367 DWORD cmodeout;
4368 BOOL bEnableHandler;
4369
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004370# ifdef VIMDLL
4371 if (gui.in_use)
4372 return;
4373# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004374 GetConsoleMode(g_hConIn, &cmodein);
4375 GetConsoleMode(g_hConOut, &cmodeout);
4376 if (tmode == TMODE_RAW)
4377 {
4378 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4379 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004380 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004381 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004382 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004383 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
4384 }
4385 else
4386 {
4387 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
4388 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004389 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004390# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01004391 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
4392 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004393 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004394# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004395 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004396# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004397 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004398 bEnableHandler = TRUE;
4399 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004400 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00004401 {
4402 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4403 ENABLE_ECHO_INPUT);
4404 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
4405 bEnableHandler = FALSE;
4406 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004407 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004408 SetConsoleMode(g_hConOut, cmodeout);
4409 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
4410
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004411# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004412 if (fdDump)
4413 {
4414 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
4415 tmode == TMODE_RAW ? "raw" :
4416 tmode == TMODE_COOK ? "cooked" : "normal",
4417 cmodein, cmodeout);
4418 fflush(fdDump);
4419 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004420# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004421}
4422
4423
4424/*
4425 * Get the size of the current window in `Rows' and `Columns'
4426 * Return OK when size could be determined, FAIL otherwise.
4427 */
4428 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004429mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004430{
4431 CONSOLE_SCREEN_BUFFER_INFO csbi;
4432
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004433# ifdef VIMDLL
4434 if (gui.in_use)
4435 return OK;
4436# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004437 if (!g_fTermcapMode && g_cbTermcap.IsValid)
4438 {
4439 /*
4440 * For some reason, we are trying to get the screen dimensions
4441 * even though we are not in termcap mode. The 'Rows' and 'Columns'
4442 * variables are really intended to mean the size of Vim screen
4443 * while in termcap mode.
4444 */
4445 Rows = g_cbTermcap.Info.dwSize.Y;
4446 Columns = g_cbTermcap.Info.dwSize.X;
4447 }
4448 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4449 {
4450 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4451 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4452 }
4453 else
4454 {
4455 Rows = 25;
4456 Columns = 80;
4457 }
4458 return OK;
4459}
4460
4461/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004462 * Resize console buffer to 'COORD'
4463 */
4464 static void
4465ResizeConBuf(
4466 HANDLE hConsole,
4467 COORD coordScreen)
4468{
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00004469 if (use_alternate_screen_buffer)
4470 return;
4471
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004472 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4473 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004474# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004475 if (fdDump)
4476 {
4477 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4478 GetLastError());
4479 fflush(fdDump);
4480 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004481# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004482 }
4483}
4484
4485/*
4486 * Resize console window size to 'srWindowRect'
4487 */
4488 static void
4489ResizeWindow(
4490 HANDLE hConsole,
4491 SMALL_RECT srWindowRect)
4492{
4493 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4494 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004495# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004496 if (fdDump)
4497 {
4498 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4499 GetLastError());
4500 fflush(fdDump);
4501 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004502# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004503 }
4504}
4505
4506/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004507 * Set a console window to `xSize' * `ySize'
4508 */
4509 static void
4510ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004511 HANDLE hConsole,
4512 int xSize,
4513 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004514{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004515 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
4516 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004517 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004518 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004519 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004520
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004521# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004522 if (fdDump)
4523 {
4524 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4525 fflush(fdDump);
4526 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004527# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004528
Bram Moolenaar0f873732019-12-05 20:28:46 +01004529 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00004530 coordScreen = GetLargestConsoleWindowSize(hConsole);
4531
Bram Moolenaar0f873732019-12-05 20:28:46 +01004532 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00004533 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4534 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4535 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4536
4537 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4538 {
4539 int sx, sy;
4540
4541 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4542 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4543 if (sy < ySize || sx < xSize)
4544 {
4545 /*
4546 * Increasing number of lines/columns, do buffer first.
4547 * Use the maximal size in x and y direction.
4548 */
4549 if (sy < ySize)
4550 coordScreen.Y = ySize;
4551 else
4552 coordScreen.Y = sy;
4553 if (sx < xSize)
4554 coordScreen.X = xSize;
4555 else
4556 coordScreen.X = sx;
4557 SetConsoleScreenBufferSize(hConsole, coordScreen);
4558 }
4559 }
4560
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004561 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004562 coordScreen.X = xSize;
4563 coordScreen.Y = ySize;
4564
Bram Moolenaar2551c032018-08-23 22:38:31 +02004565 // In the new console call API, only the first time in reverse order
4566 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004567 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004568 ResizeWindow(hConsole, srWindowRect);
4569 ResizeConBuf(hConsole, coordScreen);
4570 }
4571 else
4572 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004573 // Workaround for a Windows 10 bug
4574 cursor.X = srWindowRect.Left;
4575 cursor.Y = srWindowRect.Top;
4576 SetConsoleCursorPosition(hConsole, cursor);
4577
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004578 ResizeConBuf(hConsole, coordScreen);
4579 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004580 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004581 }
4582}
4583
4584
4585/*
4586 * Set the console window to `Rows' * `Columns'
4587 */
4588 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004589mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004590{
4591 COORD coordScreen;
4592
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004593# ifdef VIMDLL
4594 if (gui.in_use)
4595 return;
4596# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004597 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004598 if (suppress_winsize != 0)
4599 {
4600 suppress_winsize = 2;
4601 return;
4602 }
4603
4604 if (term_console)
4605 {
4606 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4607
Bram Moolenaar0f873732019-12-05 20:28:46 +01004608 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004609 if (Rows > coordScreen.Y)
4610 Rows = coordScreen.Y;
4611 if (Columns > coordScreen.X)
4612 Columns = coordScreen.X;
4613
4614 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4615 }
4616}
4617
4618/*
4619 * Rows and/or Columns has changed.
4620 */
4621 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004622mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004623{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004624# ifdef VIMDLL
4625 if (gui.in_use)
4626 return;
4627# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004628 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4629}
4630
4631
4632/*
4633 * Called when started up, to set the winsize that was delayed.
4634 */
4635 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004636mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004637{
4638 if (suppress_winsize == 2)
4639 {
4640 suppress_winsize = 0;
4641 mch_set_shellsize();
4642 shell_resized();
4643 }
4644 suppress_winsize = 0;
4645}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004646#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004647
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004648 static BOOL
4649vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004650 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004651 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004652 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004653 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004654 PROCESS_INFORMATION *pi,
4655 LPVOID *env,
4656 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004657{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004658 BOOL ret = FALSE;
4659 WCHAR *wcmd, *wcwd = NULL;
4660
4661 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4662 if (wcmd == NULL)
4663 return FALSE;
4664 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004665 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004666 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4667 if (wcwd == NULL)
4668 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004669 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004670
4671 ret = CreateProcessW(
4672 NULL, // Executable name
4673 wcmd, // Command to execute
4674 NULL, // Process security attributes
4675 NULL, // Thread security attributes
4676 inherit_handles, // Inherit handles
4677 flags, // Creation flags
4678 env, // Environment
4679 wcwd, // Current directory
4680 (LPSTARTUPINFOW)si, // Startup information
4681 pi); // Process information
4682theend:
4683 vim_free(wcmd);
4684 vim_free(wcwd);
4685 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004686}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004687
4688
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004689 static HINSTANCE
4690vim_shell_execute(
4691 char *cmd,
4692 INT n_show_cmd)
4693{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004694 HINSTANCE ret;
4695 WCHAR *wcmd;
4696
4697 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4698 if (wcmd == NULL)
4699 return (HINSTANCE) 0;
4700
4701 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4702 vim_free(wcmd);
4703 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004704}
4705
4706
Bram Moolenaar4f974752019-02-17 17:44:42 +01004707#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004708
4709/*
4710 * Specialised version of system() for Win32 GUI mode.
4711 * This version proceeds as follows:
4712 * 1. Create a console window for use by the subprocess
4713 * 2. Run the subprocess (it gets the allocated console by default)
4714 * 3. Wait for the subprocess to terminate and get its exit code
4715 * 4. Prompt the user to press a key to close the console window
4716 */
4717 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004718mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004719{
4720 STARTUPINFO si;
4721 PROCESS_INFORMATION pi;
4722 DWORD ret = 0;
4723 HWND hwnd = GetFocus();
4724
4725 si.cb = sizeof(si);
4726 si.lpReserved = NULL;
4727 si.lpDesktop = NULL;
4728 si.lpTitle = NULL;
4729 si.dwFlags = STARTF_USESHOWWINDOW;
4730 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004731 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004732 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004733 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004734 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004735 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004736 else
4737 si.wShowWindow = SW_SHOWNORMAL;
4738 si.cbReserved2 = 0;
4739 si.lpReserved2 = NULL;
4740
Bram Moolenaar0f873732019-12-05 20:28:46 +01004741 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004742 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004743 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4744 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004745
Bram Moolenaar0f873732019-12-05 20:28:46 +01004746 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004747 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004748# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004749 int delay = 1;
4750
Bram Moolenaar0f873732019-12-05 20:28:46 +01004751 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004752 for (;;)
4753 {
4754 MSG msg;
4755
K.Takatab7057bd2022-01-21 11:37:07 +00004756 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004757 {
4758 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004759 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004760 delay = 1;
4761 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004762 }
4763 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4764 break;
4765
Bram Moolenaar0f873732019-12-05 20:28:46 +01004766 // We start waiting for a very short time and then increase it, so
4767 // that we respond quickly when the process is quick, and don't
4768 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004769 if (delay < 50)
4770 delay += 10;
4771 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004772# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004773 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004774# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004775
Bram Moolenaar0f873732019-12-05 20:28:46 +01004776 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004777 GetExitCodeProcess(pi.hProcess, &ret);
4778 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004779
Bram Moolenaar0f873732019-12-05 20:28:46 +01004780 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004781 CloseHandle(pi.hThread);
4782 CloseHandle(pi.hProcess);
4783
Bram Moolenaar0f873732019-12-05 20:28:46 +01004784 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004785 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4786
4787 return ret;
4788}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004789
4790/*
4791 * Thread launched by the gui to send the current buffer data to the
4792 * process. This way avoid to hang up vim totally if the children
4793 * process take a long time to process the lines.
4794 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004795 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004796sub_process_writer(LPVOID param)
4797{
4798 HANDLE g_hChildStd_IN_Wr = param;
4799 linenr_T lnum = curbuf->b_op_start.lnum;
4800 DWORD len = 0;
4801 DWORD l;
4802 char_u *lp = ml_get(lnum);
4803 char_u *s;
4804 int written = 0;
4805
4806 for (;;)
4807 {
4808 l = (DWORD)STRLEN(lp + written);
4809 if (l == 0)
4810 len = 0;
4811 else if (lp[written] == NL)
4812 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004813 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004814 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4815 }
4816 else
4817 {
4818 s = vim_strchr(lp + written, NL);
4819 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4820 s == NULL ? l : (DWORD)(s - (lp + written)),
4821 &len, NULL);
4822 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004823 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004824 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004825 // Finished a line, add a NL, unless this line should not have
4826 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004827 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004828 || (!curbuf->b_p_bin
4829 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004830 || (lnum != curbuf->b_no_eol_lnum
4831 && (lnum != curbuf->b_ml.ml_line_count
4832 || curbuf->b_p_eol)))
4833 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004834 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4835 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004836 }
4837
4838 ++lnum;
4839 if (lnum > curbuf->b_op_end.lnum)
4840 break;
4841
4842 lp = ml_get(lnum);
4843 written = 0;
4844 }
4845 else if (len > 0)
4846 written += len;
4847 }
4848
Bram Moolenaar0f873732019-12-05 20:28:46 +01004849 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004850 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004851 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004852}
4853
4854
Bram Moolenaar0f873732019-12-05 20:28:46 +01004855# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004856
4857/*
4858 * This function read from the children's stdout and write the
4859 * data on screen or in the buffer accordingly.
4860 */
4861 static void
4862dump_pipe(int options,
4863 HANDLE g_hChildStd_OUT_Rd,
4864 garray_T *ga,
4865 char_u buffer[],
4866 DWORD *buffer_off)
4867{
4868 DWORD availableBytes = 0;
4869 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004870 int ret;
4871 DWORD len;
4872 DWORD toRead;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004873
Bram Moolenaar0f873732019-12-05 20:28:46 +01004874 // we query the pipe to see if there is any data to read
4875 // to avoid to perform a blocking read
4876 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4877 NULL, // optional buffer
4878 0, // buffer size
4879 NULL, // number of read bytes
4880 &availableBytes, // available bytes total
4881 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004882
Bram Moolenaar0f873732019-12-05 20:28:46 +01004883 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004884 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004885 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01004886 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004887 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004888 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004889
Bram Moolenaar0f873732019-12-05 20:28:46 +01004890 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004891 if (len == 0)
4892 break;
4893
4894 availableBytes -= len;
4895
4896 if (options & SHELL_READ)
4897 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004898 // Do NUL -> NL translation, append NL separated
4899 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004900 for (i = 0; i < len; ++i)
4901 {
4902 if (buffer[i] == NL)
4903 append_ga_line(ga);
4904 else if (buffer[i] == NUL)
4905 ga_append(ga, NL);
4906 else
4907 ga_append(ga, buffer[i]);
4908 }
4909 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004910 else if (has_mbyte)
4911 {
4912 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004913 int c;
4914 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004915
4916 len += *buffer_off;
4917 buffer[len] = NUL;
4918
Bram Moolenaar0f873732019-12-05 20:28:46 +01004919 // Check if the last character in buffer[] is
4920 // incomplete, keep these bytes for the next
4921 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004922 for (p = buffer; p < buffer + len; p += l)
4923 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004924 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004925 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004926 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004927 else if (MB_BYTE2LEN(*p) != l)
4928 break;
4929 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004930 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004931 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004932 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004933 if (len >= 12)
4934 ++p;
4935 else
4936 {
4937 *buffer_off = len;
4938 return;
4939 }
4940 }
4941 c = *p;
4942 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004943 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004944 if (p < buffer + len)
4945 {
4946 *p = c;
4947 *buffer_off = (DWORD)((buffer + len) - p);
4948 mch_memmove(buffer, p, *buffer_off);
4949 return;
4950 }
4951 *buffer_off = 0;
4952 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004953 else
4954 {
4955 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004956 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004957 }
4958
4959 windgoto(msg_row, msg_col);
4960 cursor_on();
4961 out_flush();
4962 }
4963}
4964
4965/*
4966 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4967 * for communication and doesn't open any new window.
4968 */
4969 static int
4970mch_system_piped(char *cmd, int options)
4971{
4972 STARTUPINFO si;
4973 PROCESS_INFORMATION pi;
4974 DWORD ret = 0;
4975
4976 HANDLE g_hChildStd_IN_Rd = NULL;
4977 HANDLE g_hChildStd_IN_Wr = NULL;
4978 HANDLE g_hChildStd_OUT_Rd = NULL;
4979 HANDLE g_hChildStd_OUT_Wr = NULL;
4980
Bram Moolenaar0f873732019-12-05 20:28:46 +01004981 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004982 DWORD len;
4983
Bram Moolenaar0f873732019-12-05 20:28:46 +01004984 // buffer used to receive keys
4985 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4986 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004987
4988 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004989 int noread_cnt = 0;
4990 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004991 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004992 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004993 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004994
4995 SECURITY_ATTRIBUTES saAttr;
4996
Bram Moolenaar0f873732019-12-05 20:28:46 +01004997 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004998 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4999 saAttr.bInheritHandle = TRUE;
5000 saAttr.lpSecurityDescriptor = NULL;
5001
5002 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005003 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005004 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005005 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005006 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005007 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005008 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005009 {
5010 CloseHandle(g_hChildStd_IN_Rd);
5011 CloseHandle(g_hChildStd_IN_Wr);
5012 CloseHandle(g_hChildStd_OUT_Rd);
5013 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01005014 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005015 }
5016
5017 si.cb = sizeof(si);
5018 si.lpReserved = NULL;
5019 si.lpDesktop = NULL;
5020 si.lpTitle = NULL;
5021 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
5022
Bram Moolenaar0f873732019-12-05 20:28:46 +01005023 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005024 si.hStdError = g_hChildStd_OUT_Wr;
5025 si.hStdOutput = g_hChildStd_OUT_Wr;
5026 si.hStdInput = g_hChildStd_IN_Rd;
5027 si.wShowWindow = SW_HIDE;
5028 si.cbReserved2 = 0;
5029 si.lpReserved2 = NULL;
5030
5031 if (options & SHELL_READ)
5032 ga_init2(&ga, 1, BUFLEN);
5033
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005034 if (cmd != NULL)
5035 {
5036 p = (char *)vim_strsave((char_u *)cmd);
5037 if (p != NULL)
5038 unescape_shellxquote((char_u *)p, p_sxe);
5039 else
5040 p = cmd;
5041 }
5042
Bram Moolenaar0f873732019-12-05 20:28:46 +01005043 // Now, run the command.
5044 // About "Inherit handles" being TRUE: this command can be litigious,
5045 // handle inheritance was deactivated for pending temp file, but, if we
5046 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005047 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
5048 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005049
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005050 if (p != cmd)
5051 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005052
Bram Moolenaar0f873732019-12-05 20:28:46 +01005053 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005054 CloseHandle(g_hChildStd_IN_Rd);
5055 CloseHandle(g_hChildStd_OUT_Wr);
5056
5057 if (options & SHELL_WRITE)
5058 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02005059 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005060 _beginthreadex(NULL, // security attributes
5061 0, // default stack size
5062 sub_process_writer, // function to be executed
5063 g_hChildStd_IN_Wr, // parameter
5064 0, // creation flag, start immediately
5065 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005066 CloseHandle(thread);
5067 g_hChildStd_IN_Wr = NULL;
5068 }
5069
Bram Moolenaar0f873732019-12-05 20:28:46 +01005070 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005071 for (;;)
5072 {
5073 MSG msg;
5074
K.Takatab7057bd2022-01-21 11:37:07 +00005075 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005076 {
5077 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00005078 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005079 }
5080
Bram Moolenaar0f873732019-12-05 20:28:46 +01005081 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005082 if ((options & (SHELL_READ|SHELL_WRITE))
5083# ifdef FEAT_GUI
5084 || gui.in_use
5085# endif
5086 )
5087 {
5088 len = 0;
5089 if (!(options & SHELL_EXPAND)
5090 && ((options &
5091 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
5092 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
5093# ifdef FEAT_GUI
5094 || gui.in_use
5095# endif
5096 )
5097 && (ta_len > 0 || noread_cnt > 4))
5098 {
5099 if (ta_len == 0)
5100 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005101 // Get extra characters when we don't have any. Reset the
5102 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005103 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005104 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
5105 }
5106 if (ta_len > 0 || len > 0)
5107 {
5108 /*
5109 * For pipes: Check for CTRL-C: send interrupt signal to
5110 * child. Check for CTRL-D: EOF, close pipe to child.
5111 */
5112 if (len == 1 && cmd != NULL)
5113 {
5114 if (ta_buf[ta_len] == Ctrl_C)
5115 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005116 // Learn what exit code is expected, for
5117 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005118 TerminateProcess(pi.hProcess, 9);
5119 }
5120 if (ta_buf[ta_len] == Ctrl_D)
5121 {
5122 CloseHandle(g_hChildStd_IN_Wr);
5123 g_hChildStd_IN_Wr = NULL;
5124 }
5125 }
5126
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01005127 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005128
5129 /*
5130 * For pipes: echo the typed characters. For a pty this
5131 * does not seem to work.
5132 */
5133 for (i = ta_len; i < ta_len + len; ++i)
5134 {
5135 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
5136 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005137 else if (has_mbyte)
5138 {
5139 int l = (*mb_ptr2len)(ta_buf + i);
5140
5141 msg_outtrans_len(ta_buf + i, l);
5142 i += l - 1;
5143 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005144 else
5145 msg_outtrans_len(ta_buf + i, 1);
5146 }
5147 windgoto(msg_row, msg_col);
5148 out_flush();
5149
5150 ta_len += len;
5151
5152 /*
5153 * Write the characters to the child, unless EOF has been
5154 * typed for pipes. Write one character at a time, to
5155 * avoid losing too much typeahead. When writing buffer
5156 * lines, drop the typed characters (only check for
5157 * CTRL-C).
5158 */
5159 if (options & SHELL_WRITE)
5160 ta_len = 0;
5161 else if (g_hChildStd_IN_Wr != NULL)
5162 {
5163 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
5164 1, &len, NULL);
5165 // if we are typing in, we want to keep things reactive
5166 delay = 1;
5167 if (len > 0)
5168 {
5169 ta_len -= len;
5170 mch_memmove(ta_buf, ta_buf + len, ta_len);
5171 }
5172 }
5173 }
5174 }
5175 }
5176
5177 if (ta_len)
5178 ui_inchar_undo(ta_buf, ta_len);
5179
5180 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
5181 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005182 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005183 break;
5184 }
5185
5186 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005187 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005188
Bram Moolenaar0f873732019-12-05 20:28:46 +01005189 // We start waiting for a very short time and then increase it, so
5190 // that we respond quickly when the process is quick, and don't
5191 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005192 if (delay < 50)
5193 delay += 10;
5194 }
5195
Bram Moolenaar0f873732019-12-05 20:28:46 +01005196 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005197 CloseHandle(g_hChildStd_OUT_Rd);
5198 if (g_hChildStd_IN_Wr != NULL)
5199 CloseHandle(g_hChildStd_IN_Wr);
5200
5201 WaitForSingleObject(pi.hProcess, INFINITE);
5202
Bram Moolenaar0f873732019-12-05 20:28:46 +01005203 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005204 GetExitCodeProcess(pi.hProcess, &ret);
5205
5206 if (options & SHELL_READ)
5207 {
5208 if (ga.ga_len > 0)
5209 {
5210 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01005211 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005212 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
5213 }
5214 else
5215 curbuf->b_no_eol_lnum = 0;
5216 ga_clear(&ga);
5217 }
5218
Bram Moolenaar0f873732019-12-05 20:28:46 +01005219 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005220 CloseHandle(pi.hThread);
5221 CloseHandle(pi.hProcess);
5222
5223 return ret;
5224}
5225
5226 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005227mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005228{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005229 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005230 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005231 return mch_system_piped(cmd, options);
5232 else
5233 return mch_system_classic(cmd, options);
5234}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005235#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005236
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005237#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005238 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02005239mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005240{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005241 int ret;
5242 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005243 char_u *buf;
5244 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005245
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005246 // If the command starts and ends with double quotes, enclose the command
5247 // in parentheses.
5248 len = STRLEN(cmd);
5249 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
5250 {
5251 len += 3;
5252 buf = alloc(len);
5253 if (buf == NULL)
5254 return -1;
5255 vim_snprintf((char *)buf, len, "(%s)", cmd);
5256 wcmd = enc_to_utf16(buf, NULL);
5257 free(buf);
5258 }
5259 else
5260 wcmd = enc_to_utf16((char_u *)cmd, NULL);
5261
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005262 if (wcmd == NULL)
5263 return -1;
5264
5265 ret = _wsystem(wcmd);
5266 vim_free(wcmd);
5267 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005268}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005269
5270#endif
5271
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005272 static int
5273mch_system(char *cmd, int options)
5274{
5275#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005276 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005277 return mch_system_g(cmd, options);
5278 else
5279 return mch_system_c(cmd, options);
5280#elif defined(FEAT_GUI_MSWIN)
5281 return mch_system_g(cmd, options);
5282#else
5283 return mch_system_c(cmd, options);
5284#endif
5285}
5286
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005287#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
5288/*
5289 * Use a terminal window to run a shell command in.
5290 */
5291 static int
5292mch_call_shell_terminal(
5293 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005294 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005295{
5296 jobopt_T opt;
5297 char_u *newcmd = NULL;
5298 typval_T argvar[2];
5299 long_u cmdlen;
5300 int retval = -1;
5301 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005302 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005303 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005304 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005305
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005306 if (cmd == NULL)
5307 cmdlen = STRLEN(p_sh) + 1;
5308 else
5309 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005310 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005311 if (newcmd == NULL)
5312 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005313 if (cmd == NULL)
5314 {
5315 STRCPY(newcmd, p_sh);
5316 ch_log(NULL, "starting terminal to run a shell");
5317 }
5318 else
5319 {
5320 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
5321 ch_log(NULL, "starting terminal for system command '%s'", cmd);
5322 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005323
5324 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005325
5326 argvar[0].v_type = VAR_STRING;
5327 argvar[0].vval.v_string = newcmd;
5328 argvar[1].v_type = VAR_UNKNOWN;
5329 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005330 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01005331 {
5332 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005333 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01005334 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005335
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005336 job = term_getjob(buf->b_term);
5337 ++job->jv_refcount;
5338
Bram Moolenaar0f873732019-12-05 20:28:46 +01005339 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005340 aucmd_prepbuf(&aco, buf);
Bram Moolenaare76062c2022-11-28 18:51:43 +00005341 if (curbuf == buf)
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005342 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005343 // Only do this when a window was found for "buf".
5344 clear_oparg(&oa);
5345 while (term_use_loop())
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005346 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005347 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
5348 {
5349 // If terminal_loop() returns OK we got a key that is handled
5350 // in Normal model. We don't do redrawing anyway.
5351 if (terminal_loop(TRUE) == OK)
5352 normal_cmd(&oa, TRUE);
5353 }
5354 else
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005355 normal_cmd(&oa, TRUE);
5356 }
Bram Moolenaare76062c2022-11-28 18:51:43 +00005357 retval = job->jv_exitval;
5358 ch_log(NULL, "system command finished");
5359
5360 job_unref(job);
5361
5362 // restore curwin/curbuf and a few other things
5363 aucmd_restbuf(&aco);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005364 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005365
5366 wait_return(TRUE);
5367 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
5368
5369 vim_free(newcmd);
5370 return retval;
5371}
5372#endif
5373
Bram Moolenaar071d4272004-06-13 20:20:40 +00005374/*
5375 * Either execute a command by calling the shell or start a new shell
5376 */
5377 int
5378mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005379 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005380 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00005381{
5382 int x = 0;
5383 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005384 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02005385
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00005386#ifdef FEAT_EVAL
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01005387 ch_log(NULL, "executing shell command: %s", cmd);
5388#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01005389 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02005390 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005391 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005392 if (cmd == NULL)
5393 wcscat(szShellTitle, L" :sh");
5394 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005395 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005396 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005397
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005398 if (wn != NULL)
5399 {
5400 wcscat(szShellTitle, L" - !");
5401 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02005402 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005403 wcscat(szShellTitle, wn);
5404 SetConsoleTitleW(szShellTitle);
5405 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005406 }
5407 }
5408 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005409
5410 out_flush();
5411
5412#ifdef MCH_WRITE_DUMP
5413 if (fdDump)
5414 {
5415 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
5416 fflush(fdDump);
5417 }
5418#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005419#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005420 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005421 if (
5422# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005423 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005424# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005425 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005426 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
5427 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005428 char_u *cmdbase = cmd;
5429
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02005430 if (cmdbase != NULL)
5431 // Skip a leading quote and (.
5432 while (*cmdbase == '"' || *cmdbase == '(')
5433 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005434
5435 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01005436 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
5437 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005438 {
5439 // Use a terminal window to run the command in.
5440 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005441 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005442 return x;
5443 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005444 }
5445#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005446
5447 /*
5448 * Catch all deadly signals while running the external command, because a
5449 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5450 */
ichizok378447f2023-05-11 22:25:42 +01005451 mch_signal(SIGINT, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005452#if defined(__GNUC__) && !defined(__MINGW32__)
ichizok378447f2023-05-11 22:25:42 +01005453 mch_signal(SIGKILL, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005454#else
ichizok378447f2023-05-11 22:25:42 +01005455 mch_signal(SIGBREAK, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005456#endif
ichizok378447f2023-05-11 22:25:42 +01005457 mch_signal(SIGILL, SIG_IGN);
5458 mch_signal(SIGFPE, SIG_IGN);
5459 mch_signal(SIGSEGV, SIG_IGN);
5460 mch_signal(SIGTERM, SIG_IGN);
5461 mch_signal(SIGABRT, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005462
5463 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005464 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00005465
5466 if (cmd == NULL)
5467 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005468 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005469 }
5470 else
5471 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005472 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005473 char_u *newcmd = NULL;
5474 char_u *cmdbase = cmd;
5475 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005476
Bram Moolenaar0f873732019-12-05 20:28:46 +01005477 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005478 if (*cmdbase == '"' )
5479 ++cmdbase;
5480 if (*cmdbase == '(')
5481 ++cmdbase;
5482
Bram Moolenaar1c465442017-03-12 20:10:05 +01005483 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005484 {
5485 STARTUPINFO si;
5486 PROCESS_INFORMATION pi;
5487 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005488 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005489 char_u *p;
5490
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005491 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005492 si.cb = sizeof(si);
5493 si.lpReserved = NULL;
5494 si.lpDesktop = NULL;
5495 si.lpTitle = NULL;
5496 si.dwFlags = 0;
5497 si.cbReserved2 = 0;
5498 si.lpReserved2 = NULL;
5499
5500 cmdbase = skipwhite(cmdbase + 5);
5501 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005502 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005503 {
5504 cmdbase = skipwhite(cmdbase + 4);
5505 si.dwFlags = STARTF_USESHOWWINDOW;
5506 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005507 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005508 }
5509 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005510 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005511 {
5512 cmdbase = skipwhite(cmdbase + 2);
5513 flags = CREATE_NO_WINDOW;
5514 si.dwFlags = STARTF_USESTDHANDLES;
5515 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005516 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005517 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005518 NULL, // Security att.
5519 OPEN_EXISTING, // Open flags
5520 FILE_ATTRIBUTE_NORMAL, // File att.
5521 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005522 si.hStdOutput = si.hStdInput;
5523 si.hStdError = si.hStdInput;
5524 }
5525
Bram Moolenaar0f873732019-12-05 20:28:46 +01005526 // Remove a trailing ", ) and )" if they have a match
5527 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005528 if (cmdbase > cmd)
5529 {
5530 p = cmdbase + STRLEN(cmdbase);
5531 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5532 *--p = NUL;
5533 if (p > cmdbase && p[-1] == ')'
5534 && (*cmd =='(' || cmd[1] == '('))
5535 *--p = NUL;
5536 }
5537
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005538 newcmd = cmdbase;
5539 unescape_shellxquote(cmdbase, p_sxe);
5540
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005541 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005542 * If creating new console, arguments are passed to the
5543 * 'cmd.exe' as-is. If it's not, arguments are not treated
5544 * correctly for current 'cmd.exe'. So unescape characters in
5545 * shellxescape except '|' for avoiding to be treated as
5546 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005547 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005548 if (flags != CREATE_NEW_CONSOLE)
5549 {
5550 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005551 char_u *cmd_shell = mch_getenv("COMSPEC");
5552
5553 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005554 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005555
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005556 subcmd = vim_strsave_escaped_ext(cmdbase,
5557 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005558 if (subcmd != NULL)
5559 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005560 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005561 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005562 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005563 if (newcmd != NULL)
5564 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005565 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005566 else
5567 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005568 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005569 }
5570 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005571
5572 /*
5573 * Now, start the command as a process, so that it doesn't
5574 * inherit our handles which causes unpleasant dangling swap
5575 * files if we exit before the spawned process
5576 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005577 if (vim_create_process((char *)newcmd, FALSE, flags,
5578 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005579 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005580 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5581 > (HINSTANCE)32)
5582 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005583 else
5584 {
5585 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005586#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005587# ifdef VIMDLL
5588 if (gui.in_use)
5589# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005590 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005591#endif
5592 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005593
5594 if (newcmd != cmdbase)
5595 vim_free(newcmd);
5596
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005597 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005598 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005599 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005600 CloseHandle(si.hStdInput);
5601 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005602 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005603 CloseHandle(pi.hThread);
5604 CloseHandle(pi.hProcess);
5605 }
5606 else
5607 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005608 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005609#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005610 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005611 (!s_dont_use_vimrun && p_stmp ?
5612 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5613 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005614#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005615 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005616
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005617 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005618 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005619 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005620#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005621 if (
5622# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005623 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005624# endif
5625 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005626 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005627 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5628 "External commands will not pause after completion.\n"
5629 "See :help win32-vimrun for more information.");
5630 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005631 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5632 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005633
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005634 if (wmsg != NULL && wtitle != NULL)
5635 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5636 vim_free(wmsg);
5637 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005638 need_vimrun_warning = FALSE;
5639 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005640 if (
5641# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005642 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005643# endif
5644 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005645 // Use vimrun to execute the command. It opens a console
5646 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005647 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005648 vimrun_path,
5649 (msg_silent != 0 || (options & SHELL_DOOUT))
5650 ? "-s " : "",
5651 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005652 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005653# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005654 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005655# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005656 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005657 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005658 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5659 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005660 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005661#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005662 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005663 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005664 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005665 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005666 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005667 }
5668 }
5669
5670 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005671 {
5672 // The shell may have messed with the mode, always set it.
5673 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005674 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005675 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005676
Bram Moolenaar0f873732019-12-05 20:28:46 +01005677 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005678 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005679#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005680 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005681 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005682#endif
5683 )
5684 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005685 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005686 msg_putchar('\n');
5687 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005688 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005689
ichizok378447f2023-05-11 22:25:42 +01005690 mch_signal(SIGINT, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005691#if defined(__GNUC__) && !defined(__MINGW32__)
ichizok378447f2023-05-11 22:25:42 +01005692 mch_signal(SIGKILL, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005693#else
ichizok378447f2023-05-11 22:25:42 +01005694 mch_signal(SIGBREAK, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005695#endif
ichizok378447f2023-05-11 22:25:42 +01005696 mch_signal(SIGILL, SIG_DFL);
5697 mch_signal(SIGFPE, SIG_DFL);
5698 mch_signal(SIGSEGV, SIG_DFL);
5699 mch_signal(SIGTERM, SIG_DFL);
5700 mch_signal(SIGABRT, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005701
5702 return x;
5703}
5704
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005705#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005706 static HANDLE
5707job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005708 char_u *fname,
5709 DWORD dwDesiredAccess,
5710 DWORD dwShareMode,
5711 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5712 DWORD dwCreationDisposition,
5713 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005714{
5715 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005716 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005717
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005718 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005719 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005720 return INVALID_HANDLE_VALUE;
5721
5722 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5723 lpSecurityAttributes, dwCreationDisposition,
5724 dwFlagsAndAttributes, NULL);
5725 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005726 return h;
5727}
5728
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005729/*
5730 * Turn the dictionary "env" into a NUL separated list that can be used as the
5731 * environment argument of vim_create_process().
5732 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005733 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005734win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005735{
5736 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005737 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005738 LPVOID base = GetEnvironmentStringsW();
5739
Bram Moolenaar0f873732019-12-05 20:28:46 +01005740 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005741 if (ga_grow(gap, 1) == FAIL)
5742 return;
5743
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005744 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005745 {
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00005746 FOR_ALL_HASHTAB_ITEMS(&env->dv_hashtab, hi, todo)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005747 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005748 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005749 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005750 typval_T *item = &dict_lookup(hi)->di_tv;
5751 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005752 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005753 --todo;
5754 if (wkey != NULL && wval != NULL)
5755 {
5756 size_t n;
5757 size_t lkey = wcslen(wkey);
5758 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005759
Yegappan Lakshmananfadc02a2023-01-27 21:03:12 +00005760 if (ga_grow(gap, (int)(lkey + lval + 2)) == FAIL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005761 continue;
5762 for (n = 0; n < lkey; n++)
5763 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5764 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5765 for (n = 0; n < lval; n++)
5766 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5767 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5768 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005769 vim_free(wkey);
5770 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005771 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005772 }
5773 }
5774
Bram Moolenaar355757a2020-02-10 22:06:32 +01005775 if (base)
5776 {
5777 WCHAR *p = (WCHAR*) base;
5778
5779 // for last \0
5780 if (ga_grow(gap, 1) == FAIL)
5781 return;
5782
5783 while (*p != 0 || *(p + 1) != 0)
5784 {
5785 if (ga_grow(gap, 1) == OK)
5786 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5787 p++;
5788 }
5789 FreeEnvironmentStrings(base);
5790 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5791 }
5792
Bram Moolenaar493359e2018-06-12 20:25:52 +02005793# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005794 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005795# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005796 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005797 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005798# endif
5799# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005800 char_u *version = get_vim_var_str(VV_VERSION);
5801 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005802# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005803 // size of "VIM_SERVERNAME=" and value,
5804 // plus "VIM_TERMINAL=" and value,
5805 // plus two terminating NULs
5806 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005807# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005808 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005809# endif
5810# ifdef FEAT_TERMINAL
5811 + 13 + version_len + 2
5812# endif
5813 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005814
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005815 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005816 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005817# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005818 for (n = 0; n < 15; n++)
5819 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5820 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005821 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005822 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5823 (WCHAR)servername[n];
5824 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005825# endif
5826# ifdef FEAT_TERMINAL
5827 if (is_terminal)
5828 {
5829 for (n = 0; n < 13; n++)
5830 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5831 (WCHAR)"VIM_TERMINAL="[n];
5832 for (n = 0; n < version_len; n++)
5833 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5834 (WCHAR)version[n];
5835 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5836 }
5837# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005838 }
5839 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005840# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005841}
5842
Bram Moolenaarb091f302019-01-19 14:37:00 +01005843/*
5844 * Create a pair of pipes.
5845 * Return TRUE for success, FALSE for failure.
5846 */
5847 static BOOL
5848create_pipe_pair(HANDLE handles[2])
5849{
5850 static LONG s;
5851 char name[64];
5852 SECURITY_ATTRIBUTES sa;
5853
5854 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5855 GetCurrentProcessId(),
5856 InterlockedIncrement(&s));
5857
5858 // Create named pipe. Max size of named pipe is 65535.
5859 handles[1] = CreateNamedPipe(
5860 name,
5861 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5862 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005863 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005864
5865 if (handles[1] == INVALID_HANDLE_VALUE)
5866 return FALSE;
5867
5868 sa.nLength = sizeof(sa);
5869 sa.bInheritHandle = TRUE;
5870 sa.lpSecurityDescriptor = NULL;
5871
5872 handles[0] = CreateFile(name,
5873 FILE_GENERIC_READ,
5874 FILE_SHARE_READ, &sa,
5875 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5876
5877 if (handles[0] == INVALID_HANDLE_VALUE)
5878 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005879 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005880 return FALSE;
5881 }
5882
5883 return TRUE;
5884}
5885
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005886 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005887mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005888{
5889 STARTUPINFO si;
5890 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005891 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005892 SECURITY_ATTRIBUTES saAttr;
5893 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005894 HANDLE ifd[2];
5895 HANDLE ofd[2];
5896 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005897 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005898
5899 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5900 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5901 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5902 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5903 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5904 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5905 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5906
5907 if (use_out_for_err && use_null_for_out)
5908 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005909
5910 ifd[0] = INVALID_HANDLE_VALUE;
5911 ifd[1] = INVALID_HANDLE_VALUE;
5912 ofd[0] = INVALID_HANDLE_VALUE;
5913 ofd[1] = INVALID_HANDLE_VALUE;
5914 efd[0] = INVALID_HANDLE_VALUE;
5915 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005916 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005917
Bram Moolenaar14207f42016-10-27 21:13:10 +02005918 jo = CreateJobObject(NULL, NULL);
5919 if (jo == NULL)
5920 {
5921 job->jv_status = JOB_FAILED;
5922 goto failed;
5923 }
5924
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005925 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005926 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005927
Bram Moolenaar76467df2016-02-12 19:30:26 +01005928 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005929 ZeroMemory(&si, sizeof(si));
5930 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005931 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005932 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005933
Bram Moolenaard8070362016-02-15 21:56:54 +01005934 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5935 saAttr.bInheritHandle = TRUE;
5936 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005937
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005938 if (use_file_for_in)
5939 {
5940 char_u *fname = options->jo_io_name[PART_IN];
5941
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005942 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5943 FILE_SHARE_READ | FILE_SHARE_WRITE,
5944 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5945 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005946 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005947 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005948 goto failed;
5949 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005950 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005951 else if (!use_null_for_in
5952 && (!create_pipe_pair(ifd)
5953 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005954 goto failed;
5955
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005956 if (use_file_for_out)
5957 {
5958 char_u *fname = options->jo_io_name[PART_OUT];
5959
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005960 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5961 FILE_SHARE_READ | FILE_SHARE_WRITE,
5962 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5963 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005964 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005965 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005966 goto failed;
5967 }
5968 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005969 else if (!use_null_for_out &&
5970 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005971 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005972 goto failed;
5973
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005974 if (use_file_for_err)
5975 {
5976 char_u *fname = options->jo_io_name[PART_ERR];
5977
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005978 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5979 FILE_SHARE_READ | FILE_SHARE_WRITE,
5980 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5981 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005982 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005983 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005984 goto failed;
5985 }
5986 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005987 else if (!use_out_for_err && !use_null_for_err &&
5988 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005989 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005990 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005991
Bram Moolenaard8070362016-02-15 21:56:54 +01005992 si.dwFlags |= STARTF_USESTDHANDLES;
5993 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005994 si.hStdOutput = ofd[1];
5995 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5996
5997 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5998 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005999 if (options->jo_set & JO_CHANNEL)
6000 {
6001 channel = options->jo_channel;
6002 if (channel != NULL)
6003 ++channel->ch_refcount;
6004 }
6005 else
6006 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006007 if (channel == NULL)
6008 goto failed;
6009 }
Bram Moolenaard8070362016-02-15 21:56:54 +01006010
6011 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02006012 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006013 CREATE_DEFAULT_ERROR_MODE |
6014 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006015 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01006016 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006017 &si, &pi,
6018 ga.ga_data,
6019 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01006020 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02006021 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006022 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006023 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006024 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006025
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006026 ga_clear(&ga);
6027
Bram Moolenaar14207f42016-10-27 21:13:10 +02006028 if (!AssignProcessToJobObject(jo, pi.hProcess))
6029 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006030 // if failing, switch the way to terminate
6031 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02006032 CloseHandle(jo);
6033 jo = NULL;
6034 }
6035 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01006036 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006037 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02006038 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006039 job->jv_status = JOB_STARTED;
6040
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02006041 CloseHandle(ifd[0]);
6042 CloseHandle(ofd[1]);
6043 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01006044 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01006045
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006046 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006047 if (channel != NULL)
6048 {
6049 channel_set_pipes(channel,
6050 use_file_for_in || use_null_for_in
6051 ? INVALID_FD : (sock_T)ifd[1],
6052 use_file_for_out || use_null_for_out
6053 ? INVALID_FD : (sock_T)ofd[0],
6054 use_out_for_err || use_file_for_err || use_null_for_err
6055 ? INVALID_FD : (sock_T)efd[0]);
6056 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006057 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006058 return;
6059
6060failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01006061 CloseHandle(ifd[0]);
6062 CloseHandle(ofd[0]);
6063 CloseHandle(efd[0]);
6064 CloseHandle(ifd[1]);
6065 CloseHandle(ofd[1]);
6066 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01006067 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006068 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006069}
6070
6071 char *
6072mch_job_status(job_T *job)
6073{
6074 DWORD dwExitCode = 0;
6075
Bram Moolenaar76467df2016-02-12 19:30:26 +01006076 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
6077 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006078 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01006079 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01006080 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02006081 {
6082 ch_log(job->jv_channel, "Job ended");
6083 job->jv_status = JOB_ENDED;
6084 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006085 return "dead";
6086 }
6087 return "run";
6088}
6089
Bram Moolenaar97792de2016-10-15 18:36:49 +02006090 job_T *
6091mch_detect_ended_job(job_T *job_list)
6092{
6093 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
6094 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
6095 job_T *job = job_list;
6096
6097 while (job != NULL)
6098 {
6099 DWORD n;
6100 DWORD result;
6101
6102 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
6103 && job != NULL; job = job->jv_next)
6104 {
6105 if (job->jv_status == JOB_STARTED)
6106 {
6107 jobHandles[n] = job->jv_proc_info.hProcess;
6108 jobArray[n] = job;
6109 ++n;
6110 }
6111 }
6112 if (n == 0)
6113 continue;
6114 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
6115 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
6116 {
6117 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
6118
6119 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
6120 return wait_job;
6121 }
6122 }
6123 return NULL;
6124}
6125
Bram Moolenaarfb630902016-10-29 14:55:00 +02006126 static BOOL
6127terminate_all(HANDLE process, int code)
6128{
6129 PROCESSENTRY32 pe;
6130 HANDLE h = INVALID_HANDLE_VALUE;
6131 DWORD pid = GetProcessId(process);
6132
6133 if (pid != 0)
6134 {
6135 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
6136 if (h != INVALID_HANDLE_VALUE)
6137 {
6138 pe.dwSize = sizeof(PROCESSENTRY32);
6139 if (!Process32First(h, &pe))
6140 goto theend;
6141
6142 do
6143 {
6144 if (pe.th32ParentProcessID == pid)
6145 {
6146 HANDLE ph = OpenProcess(
6147 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
6148 if (ph != NULL)
6149 {
6150 terminate_all(ph, code);
6151 CloseHandle(ph);
6152 }
6153 }
6154 } while (Process32Next(h, &pe));
6155
6156 CloseHandle(h);
6157 }
6158 }
6159
6160theend:
6161 return TerminateProcess(process, code);
6162}
6163
6164/*
6165 * Send a (deadly) signal to "job".
6166 * Return FAIL if it didn't work.
6167 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006168 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02006169mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006170{
Bram Moolenaar923d9262016-02-25 20:56:01 +01006171 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006172
Bram Moolenaar923d9262016-02-25 20:56:01 +01006173 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01006174 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006175 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02006176 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006177 {
6178 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
6179 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00006180 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006181 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01006182 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006183 }
6184
6185 if (!AttachConsole(job->jv_proc_info.dwProcessId))
6186 return FAIL;
6187 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01006188 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
6189 job->jv_proc_info.dwProcessId)
6190 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006191 FreeConsole();
6192 return ret;
6193}
6194
6195/*
6196 * Clear the data related to "job".
6197 */
6198 void
6199mch_clear_job(job_T *job)
6200{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00006201 if (job->jv_status == JOB_FAILED)
6202 return;
6203
6204 if (job->jv_job_object != NULL)
6205 CloseHandle(job->jv_job_object);
6206 CloseHandle(job->jv_proc_info.hProcess);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006207}
6208#endif
6209
Bram Moolenaar071d4272004-06-13 20:20:40 +00006210
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006211#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006212
6213/*
6214 * Start termcap mode
6215 */
6216 static void
6217termcap_mode_start(void)
6218{
6219 DWORD cmodein;
6220
6221 if (g_fTermcapMode)
6222 return;
6223
6224 SaveConsoleBuffer(&g_cbNonTermcap);
6225
6226 if (g_cbTermcap.IsValid)
6227 {
6228 /*
6229 * We've been in termcap mode before. Restore certain screen
6230 * characteristics, including the buffer size and the window
6231 * size. Since we will be redrawing the screen, we don't need
6232 * to restore the actual contents of the buffer.
6233 */
6234 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006235 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006236 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
6237 Rows = g_cbTermcap.Info.dwSize.Y;
6238 Columns = g_cbTermcap.Info.dwSize.X;
6239 }
6240 else
6241 {
6242 /*
6243 * This is our first time entering termcap mode. Clear the console
6244 * screen buffer, and resize the buffer to match the current window
6245 * size. We will use this as the size of our editing environment.
6246 */
6247 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006248 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006249 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
6250 }
6251
Bram Moolenaar071d4272004-06-13 20:20:40 +00006252 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006253
6254 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006255 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006256 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006257 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006258 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
6259 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006260 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006261 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006262 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006263 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6264 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006265 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006266 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006267
6268 redraw_later_clear();
6269 g_fTermcapMode = TRUE;
6270}
6271
6272
6273/*
6274 * End termcap mode
6275 */
6276 static void
6277termcap_mode_end(void)
6278{
6279 DWORD cmodein;
6280 ConsoleBuffer *cb;
6281 COORD coord;
6282 DWORD dwDummy;
6283
6284 if (!g_fTermcapMode)
6285 return;
6286
6287 SaveConsoleBuffer(&g_cbTermcap);
6288
6289 GetConsoleMode(g_hConIn, &cmodein);
6290 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006291 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6292 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006293
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006294# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01006295 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006296# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006297 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006298# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006299 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01006300 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006301
Christopher Plewright1140b512022-11-12 18:46:05 +00006302 // Switch back to main screen buffer.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00006303 if (exiting && use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00006304 vtp_printf("\033[?1049l");
6305
6306 if (!USE_WT && (p_rs || exiting))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006307 {
6308 /*
6309 * Clear anything that happens to be on the current line.
6310 */
6311 coord.X = 0;
6312 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006313 FillConsoleOutputCharacter(g_hConOut, ' ',
6314 cb->Info.dwSize.X, coord, &dwDummy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006315 /*
6316 * The following is just for aesthetics. If we are exiting without
6317 * restoring the screen, then we want to have a prompt string
6318 * appear at the bottom line. However, the command interpreter
6319 * seems to always advance the cursor one line before displaying
6320 * the prompt string, which causes the screen to scroll. To
6321 * counter this, move the cursor up one line before exiting.
6322 */
6323 if (exiting && !p_rs)
6324 coord.Y--;
6325 /*
6326 * Position the cursor at the leftmost column of the desired row.
6327 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006328 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006329 }
Christopher Plewright1140b512022-11-12 18:46:05 +00006330 SetConsoleCursorInfo(g_hConOut, &g_cci);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006331 g_fTermcapMode = FALSE;
6332}
Christopher Plewright38804d62022-11-09 23:55:52 +00006333#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006334
6335
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006336#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006337 void
6338mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01006339 char_u *s UNUSED,
6340 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006341{
Bram Moolenaar0f873732019-12-05 20:28:46 +01006342 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00006343}
6344
6345#else
6346
6347/*
6348 * clear `n' chars, starting from `coord'
6349 */
6350 static void
6351clear_chars(
6352 COORD coord,
6353 DWORD n)
6354{
Christopher Plewright38804d62022-11-09 23:55:52 +00006355 if (!vtp_working)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006356 {
6357 DWORD dwDummy;
6358
6359 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
6360 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
6361 &dwDummy);
6362 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006363 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02006364 {
6365 set_console_color_rgb();
6366 gotoxy(coord.X + 1, coord.Y + 1);
6367 vtp_printf("\033[%dX", n);
6368 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006369}
6370
6371
6372/*
6373 * Clear the screen
6374 */
6375 static void
6376clear_screen(void)
6377{
6378 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006379
Christopher Plewright38804d62022-11-09 23:55:52 +00006380 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006381 clear_chars(g_coord, Rows * Columns);
6382 else
6383 {
6384 set_console_color_rgb();
6385 gotoxy(1, 1);
6386 vtp_printf("\033[2J");
6387 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006388}
6389
6390
6391/*
6392 * Clear to end of display
6393 */
6394 static void
6395clear_to_end_of_display(void)
6396{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006397 COORD save = g_coord;
6398
Christopher Plewright38804d62022-11-09 23:55:52 +00006399 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006400 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006401 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006402 else
6403 {
6404 set_console_color_rgb();
6405 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6406 vtp_printf("\033[0J");
6407
6408 gotoxy(save.X + 1, save.Y + 1);
6409 g_coord = save;
6410 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006411}
6412
6413
6414/*
6415 * Clear to end of line
6416 */
6417 static void
6418clear_to_end_of_line(void)
6419{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006420 COORD save = g_coord;
6421
Christopher Plewright38804d62022-11-09 23:55:52 +00006422 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006423 clear_chars(g_coord, Columns - g_coord.X);
6424 else
6425 {
6426 set_console_color_rgb();
6427 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6428 vtp_printf("\033[0K");
6429
6430 gotoxy(save.X + 1, save.Y + 1);
6431 g_coord = save;
6432 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006433}
6434
6435
6436/*
6437 * Scroll the scroll region up by `cLines' lines
6438 */
6439 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006440scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006441{
6442 COORD oldcoord = g_coord;
6443
6444 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6445 delete_lines(cLines);
6446
6447 g_coord = oldcoord;
6448}
6449
6450
6451/*
6452 * Set the scroll region
6453 */
6454 static void
6455set_scroll_region(
6456 unsigned left,
6457 unsigned top,
6458 unsigned right,
6459 unsigned bottom)
6460{
6461 if (left >= right
6462 || top >= bottom
6463 || right > (unsigned) Columns - 1
6464 || bottom > (unsigned) Rows - 1)
6465 return;
6466
6467 g_srScrollRegion.Left = left;
6468 g_srScrollRegion.Top = top;
6469 g_srScrollRegion.Right = right;
6470 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006471}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006472
Bram Moolenaar6982f422019-02-16 16:48:01 +01006473 static void
6474set_scroll_region_tb(
6475 unsigned top,
6476 unsigned bottom)
6477{
6478 if (top >= bottom || bottom > (unsigned)Rows - 1)
6479 return;
6480
6481 g_srScrollRegion.Top = top;
6482 g_srScrollRegion.Bottom = bottom;
6483}
6484
6485 static void
6486set_scroll_region_lr(
6487 unsigned left,
6488 unsigned right)
6489{
6490 if (left >= right || right > (unsigned)Columns - 1)
6491 return;
6492
6493 g_srScrollRegion.Left = left;
6494 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006495}
6496
6497
6498/*
6499 * Insert `cLines' lines at the current cursor position
6500 */
6501 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006502insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006503{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006504 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006505 COORD dest;
6506 CHAR_INFO fill;
6507
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006508 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6509
Bram Moolenaar6982f422019-02-16 16:48:01 +01006510 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006511 dest.Y = g_coord.Y + cLines;
6512
Bram Moolenaar6982f422019-02-16 16:48:01 +01006513 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006514 source.Top = g_coord.Y;
6515 source.Right = g_srScrollRegion.Right;
6516 source.Bottom = g_srScrollRegion.Bottom - cLines;
6517
Bram Moolenaar6982f422019-02-16 16:48:01 +01006518 clip.Left = g_srScrollRegion.Left;
6519 clip.Top = g_coord.Y;
6520 clip.Right = g_srScrollRegion.Right;
6521 clip.Bottom = g_srScrollRegion.Bottom;
6522
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006523 fill.Char.AsciiChar = ' ';
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006524 if (!USE_VTP)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006525 fill.Attributes = g_attrCurrent;
6526 else
6527 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006528
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006529 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006530
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006531 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6532
Bram Moolenaar6982f422019-02-16 16:48:01 +01006533 // Here we have to deal with a win32 console flake: If the scroll
6534 // region looks like abc and we scroll c to a and fill with d we get
6535 // cbd... if we scroll block c one line at a time to a, we get cdd...
6536 // vim expects cdd consistently... So we have to deal with that
6537 // here... (this also occurs scrolling the same way in the other
6538 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006539
6540 if (source.Bottom < dest.Y)
6541 {
6542 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006543 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006544
Bram Moolenaar6982f422019-02-16 16:48:01 +01006545 coord.X = source.Left;
6546 for (i = clip.Top; i < dest.Y; ++i)
6547 {
6548 coord.Y = i;
6549 clear_chars(coord, source.Right - source.Left + 1);
6550 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006551 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006552
Christopher Plewright38804d62022-11-09 23:55:52 +00006553 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006554 {
6555 COORD coord;
6556 int i;
6557
6558 coord.X = source.Left;
6559 for (i = source.Top; i < dest.Y; ++i)
6560 {
6561 coord.Y = i;
6562 clear_chars(coord, source.Right - source.Left + 1);
6563 }
6564 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006565}
6566
6567
6568/*
6569 * Delete `cLines' lines at the current cursor position
6570 */
6571 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006572delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006573{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006574 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006575 COORD dest;
6576 CHAR_INFO fill;
6577 int nb;
6578
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006579 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6580
Bram Moolenaar6982f422019-02-16 16:48:01 +01006581 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006582 dest.Y = g_coord.Y;
6583
Bram Moolenaar6982f422019-02-16 16:48:01 +01006584 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006585 source.Top = g_coord.Y + cLines;
6586 source.Right = g_srScrollRegion.Right;
6587 source.Bottom = g_srScrollRegion.Bottom;
6588
Bram Moolenaar6982f422019-02-16 16:48:01 +01006589 clip.Left = g_srScrollRegion.Left;
6590 clip.Top = g_coord.Y;
6591 clip.Right = g_srScrollRegion.Right;
6592 clip.Bottom = g_srScrollRegion.Bottom;
6593
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006594 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006595 if (!vtp_working)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006596 fill.Attributes = g_attrCurrent;
6597 else
6598 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006599
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006600 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006601
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006602 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6603
Bram Moolenaar6982f422019-02-16 16:48:01 +01006604 // Here we have to deal with a win32 console flake; See insert_lines()
6605 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006606
6607 nb = dest.Y + (source.Bottom - source.Top) + 1;
6608
6609 if (nb < source.Top)
6610 {
6611 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006612 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006613
Bram Moolenaar6982f422019-02-16 16:48:01 +01006614 coord.X = source.Left;
6615 for (i = nb; i < clip.Bottom; ++i)
6616 {
6617 coord.Y = i;
6618 clear_chars(coord, source.Right - source.Left + 1);
6619 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006620 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006621
Christopher Plewright38804d62022-11-09 23:55:52 +00006622 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006623 {
6624 COORD coord;
6625 int i;
6626
6627 coord.X = source.Left;
6628 for (i = nb; i <= source.Bottom; ++i)
6629 {
6630 coord.Y = i;
6631 clear_chars(coord, source.Right - source.Left + 1);
6632 }
6633 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006634}
6635
6636
6637/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006638 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006639 */
6640 static void
6641gotoxy(
6642 unsigned x,
6643 unsigned y)
6644{
6645 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6646 return;
6647
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006648 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006649 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006650 // There are reports of double-width characters not displayed
6651 // correctly. This workaround should fix it, similar to how it's done
6652 // for VTP.
6653 g_coord.X = 0;
6654 SetConsoleCursorPosition(g_hConOut, g_coord);
6655
Bram Moolenaar2313b612019-09-27 14:14:32 +02006656 // external cursor coords are 1-based; internal are 0-based
6657 g_coord.X = x - 1;
6658 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006659 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006660 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006661 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006662 {
6663 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006664 // destruction. Insider build bug. Always enabled because it's cheap
6665 // and avoids mistakes with recognizing the build.
6666 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006667
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006668 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006669
6670 g_coord.X = x - 1;
6671 g_coord.Y = y - 1;
6672 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006673}
6674
6675
6676/*
6677 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006678 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006679 */
6680 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006681textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006682{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006683 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006684
6685 SetConsoleTextAttribute(g_hConOut, wAttr);
6686}
6687
6688
6689 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006690textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006691{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006692 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006693
Christopher Plewright38804d62022-11-09 23:55:52 +00006694 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006695 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6696 else
6697 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006698}
6699
6700
6701 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006702textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006703{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006704 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006705
Christopher Plewright38804d62022-11-09 23:55:52 +00006706 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006707 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6708 else
6709 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006710}
6711
6712
6713/*
6714 * restore the default text attribute (whatever we started with)
6715 */
6716 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006717normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006718{
Christopher Plewright38804d62022-11-09 23:55:52 +00006719 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006720 textattr(g_attrDefault);
6721 else
6722 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006723}
6724
6725
6726static WORD g_attrPreStandout = 0;
6727
6728/*
6729 * Make the text standout, by brightening it
6730 */
6731 static void
6732standout(void)
6733{
6734 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006735
Bram Moolenaar071d4272004-06-13 20:20:40 +00006736 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6737}
6738
6739
6740/*
6741 * Turn off standout mode
6742 */
6743 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006744standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006745{
6746 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006747 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006748
6749 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006750}
6751
6752
6753/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006754 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006755 */
6756 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006757mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006758{
6759 char_u *p;
6760 int n;
6761
6762 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6763 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006764 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006765# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006766 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006767# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006768 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006769 {
6770 p = T_ME + 2;
6771 n = getdigits(&p);
6772 if (*p == 'm' && n > 0)
6773 {
6774 cterm_normal_fg_color = (n & 0xf) + 1;
6775 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6776 }
6777 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006778# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006779 cterm_normal_fg_gui_color = INVALCOLOR;
6780 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006781# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006782}
6783
6784
6785/*
6786 * visual bell: flash the screen
6787 */
6788 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006789visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006790{
6791 COORD coordOrigin = {0, 0};
6792 WORD attrFlash = ~g_attrCurrent & 0xff;
6793
6794 DWORD dwDummy;
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006795 LPWORD oldattrs = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006796
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006797# ifdef FEAT_TERMGUICOLORS
6798 if (!(p_tgc || t_colors >= 256))
6799# endif
6800 {
6801 oldattrs = ALLOC_MULT(WORD, Rows * Columns);
6802 if (oldattrs == NULL)
6803 return;
6804 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006805 coordOrigin, &dwDummy);
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006806 }
6807
Bram Moolenaar071d4272004-06-13 20:20:40 +00006808 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6809 coordOrigin, &dwDummy);
6810
Bram Moolenaar0f873732019-12-05 20:28:46 +01006811 Sleep(15); // wait for 15 msec
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006812
6813 if (oldattrs != NULL)
6814 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006815 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006816 coordOrigin, &dwDummy);
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006817 vim_free(oldattrs);
6818 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006819}
6820
6821
6822/*
6823 * Make the cursor visible or invisible
6824 */
6825 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006826cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006827{
6828 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006829
Christopher Plewright38804d62022-11-09 23:55:52 +00006830 if (vtp_working)
Bram Moolenaar2695de62020-04-17 21:13:01 +02006831 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6832
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006833# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006834 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006835# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006836}
6837
6838
6839/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006840 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006841 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006842 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006843 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006844write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006845 char_u *pchBuf,
6846 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006847{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006848 COORD coord = g_coord;
6849 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006850 DWORD n, cchwritten;
6851 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006852 static WCHAR *unicodebuf = NULL;
6853 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006854 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006855 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006856 static WCHAR *utf8spbuf = NULL;
6857 static int utf8splength;
6858 static DWORD utf8spcells;
6859 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006860
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006861 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006862 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006863 utf8usingbuf = &unicodebuf;
6864 do
6865 {
6866 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6867 unicodebuf, unibuflen);
6868 if (length && length <= unibuflen)
6869 break;
6870 vim_free(unicodebuf);
6871 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6872 unibuflen = unibuflen ? 0 : length;
Bram Moolenaarc9471b12023-05-09 15:00:00 +01006873 } while (TRUE);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006874 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006875 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006876 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6877 {
6878 if (utf8usingbuf != &utf8spbuf)
6879 {
6880 if (utf8spbuf == NULL)
6881 {
6882 cells = mb_string2cells((char_u *)" ", 1);
6883 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6884 utf8spbuf = LALLOC_MULT(WCHAR, length);
6885 if (utf8spbuf != NULL)
6886 {
6887 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6888 utf8usingbuf = &utf8spbuf;
6889 utf8splength = length;
6890 utf8spcells = cells;
6891 }
6892 }
6893 else
6894 {
6895 utf8usingbuf = &utf8spbuf;
6896 length = utf8splength;
6897 cells = utf8spcells;
6898 }
6899 }
6900 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006901
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006902 if (!USE_VTP)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006903 {
6904 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6905 coord, &written);
6906 // When writing fails or didn't write a single character, pretend one
6907 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006908 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006909 coord, &cchwritten) == 0
6910 || cchwritten == 0 || cchwritten == (DWORD)-1)
6911 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006912 }
6913 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006914 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006915 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006916 NULL) == 0 || cchwritten == 0)
6917 cchwritten = 1;
6918 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006919
K.Takata135e1522022-01-29 15:27:58 +00006920 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006921 {
6922 written = cbToWrite;
6923 g_coord.X += (SHORT)cells;
6924 }
6925 else
6926 {
6927 char_u *p = pchBuf;
6928 for (n = 0; n < cchwritten; n++)
6929 MB_CPTR_ADV(p);
6930 written = p - pchBuf;
6931 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006932 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006933
6934 while (g_coord.X > g_srScrollRegion.Right)
6935 {
6936 g_coord.X -= (SHORT) Columns;
6937 if (g_coord.Y < g_srScrollRegion.Bottom)
6938 g_coord.Y++;
6939 }
6940
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006941 // Cursor under VTP is always in the correct position, no need to reset.
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006942 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006943 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006944
6945 return written;
6946}
6947
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006948 static char_u *
6949get_seq(
6950 int *args,
6951 int *count,
6952 char_u *head)
6953{
6954 int argc;
6955 char_u *p;
6956
6957 if (head == NULL || *head != '\033')
6958 return NULL;
6959
6960 argc = 0;
6961 p = head;
6962 ++p;
6963 do
6964 {
6965 ++p;
6966 args[argc] = getdigits(&p);
6967 argc += (argc < 15) ? 1 : 0;
6968 } while (*p == ';');
6969 *count = argc;
6970
6971 return p;
6972}
6973
6974 static char_u *
6975get_sgr(
6976 int *args,
6977 int *count,
6978 char_u *head)
6979{
6980 char_u *p = get_seq(args, count, head);
6981
6982 return (p && *p == 'm') ? ++p : NULL;
6983}
6984
6985/*
6986 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6987 */
6988 static char_u *
6989sgrn2(
6990 char_u *head,
6991 int n)
6992{
6993 int argc;
6994 int args[16];
6995 char_u *p = get_sgr(args, &argc, head);
6996
6997 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6998}
6999
7000/*
7001 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
7002 */
7003 static char_u *
7004sgrnc(
7005 char_u *head,
7006 int n)
7007{
7008 int argc;
7009 int args[16];
7010 char_u *p = get_sgr(args, &argc, head);
7011
7012 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
7013 ? p : NULL;
7014}
7015
7016 static char_u *
7017skipblank(char_u *q)
7018{
7019 char_u *p = q;
7020
7021 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
7022 ++p;
7023 return p;
7024}
7025
7026/*
7027 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
7028 * NULL.
7029 */
7030 static char_u *
7031sgrn2c(
7032 char_u *head,
7033 int n)
7034{
7035 char_u *p = sgrn2(head, n);
7036
7037 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
7038}
7039
7040/*
7041 * If there is only a newline between the sequence immediately following it,
7042 * a pointer to the character following the newline is returned.
7043 * Otherwise NULL.
7044 */
7045 static char_u *
7046sgrn2cn(
7047 char_u *head,
7048 int n)
7049{
7050 char_u *p = sgrn2(head, n);
7051
7052 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
7053}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007054
7055/*
7056 * mch_write(): write the output buffer to the screen, translating ESC
7057 * sequences into calls to console output routines.
7058 */
7059 void
7060mch_write(
7061 char_u *s,
7062 int len)
7063{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007064 char_u *end = s + len;
7065
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007066# ifdef VIMDLL
7067 if (gui.in_use)
7068 return;
7069# endif
7070
Bram Moolenaar071d4272004-06-13 20:20:40 +00007071 if (!term_console)
7072 {
7073 write(1, s, (unsigned)len);
7074 return;
7075 }
7076
Bram Moolenaar0f873732019-12-05 20:28:46 +01007077 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00007078 while (len--)
7079 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007080 int prefix = -1;
7081 char_u ch;
7082
7083 // While processing a sequence, on rare occasions it seems that another
7084 // sequence may be inserted asynchronously.
7085 if (len < 0)
7086 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01007087 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007088 return;
7089 }
7090
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007091 while (s + ++prefix < end)
7092 {
7093 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007094 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
7095 && ch != '\a' && ch != '\033'))
7096 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007097 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007098
7099 if (p_wd)
7100 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007101 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007102 if (prefix != 0)
7103 prefix = 1;
7104 }
7105
7106 if (prefix != 0)
7107 {
7108 DWORD nWritten;
7109
7110 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007111# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007112 if (fdDump)
7113 {
7114 fputc('>', fdDump);
7115 fwrite(s, sizeof(char_u), nWritten, fdDump);
7116 fputs("<\n", fdDump);
7117 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007118# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007119 len -= (nWritten - 1);
7120 s += nWritten;
7121 }
7122 else if (s[0] == '\n')
7123 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007124 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00007125 if (g_coord.Y == g_srScrollRegion.Bottom)
7126 {
7127 scroll(1);
7128 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
7129 }
7130 else
7131 {
7132 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
7133 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007134# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007135 if (fdDump)
7136 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007137# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007138 s++;
7139 }
7140 else if (s[0] == '\r')
7141 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007142 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00007143 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007144# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007145 if (fdDump)
7146 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007147# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007148 s++;
7149 }
7150 else if (s[0] == '\b')
7151 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007152 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00007153 if (g_coord.X > g_srScrollRegion.Left)
7154 g_coord.X--;
7155 else if (g_coord.Y > g_srScrollRegion.Top)
7156 {
7157 g_coord.X = g_srScrollRegion.Right;
7158 g_coord.Y--;
7159 }
7160 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007161# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007162 if (fdDump)
7163 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007164# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007165 s++;
7166 }
7167 else if (s[0] == '\a')
7168 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007169 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00007170 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007171# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007172 if (fdDump)
7173 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007174# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007175 s++;
7176 }
7177 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
7178 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007179# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007180 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007181# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007182 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007183 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007184 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007185
7186 switch (s[2])
7187 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007188 case '0': case '1': case '2': case '3': case '4':
7189 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007190 if (*(p = get_seq(args, &argc, s)) != 'm')
7191 goto notsgr;
7192
7193 p = s;
7194
7195 // Handling frequent optional sequences. Output to the screen
7196 // takes too long, so do not output as much as possible.
7197
7198 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
7199 // resetFG,FG,BG are omitted.
7200 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007201 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007202 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
7203 len = len + 1 - (int)(p - s);
7204 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007205 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007206 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007207
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007208 // If FG,BG,BG,FG of SGR are connected, the first FG can be
7209 // omitted.
7210 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
7211 p = sp;
7212
7213 // If FG,BG,FG,BG of SGR are connected, the first FG can be
7214 // omitted.
7215 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
7216 p = sp;
7217
7218 // If BG,BG of SGR are connected, the first BG can be omitted.
7219 if (sgrn2((sp = sgrn2(p, 48)), 48))
7220 p = sp;
7221
7222 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007223 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007224 if (sgrn2((sp = sgrnc(p, 39)), 38))
7225 p = sp;
7226
7227 p = get_seq(args, &argc, p);
7228
7229notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007230 arg1 = args[0];
7231 arg2 = args[1];
7232 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007233 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007234 if (argc == 1 && args[0] == 0)
7235 normvideo();
7236 else if (argc == 1)
7237 {
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00007238 if (USE_VTP)
Christopher Plewright38804d62022-11-09 23:55:52 +00007239 textcolor((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007240 else
Christopher Plewright38804d62022-11-09 23:55:52 +00007241 textattr((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007242 }
Christopher Plewright38804d62022-11-09 23:55:52 +00007243 else if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007244 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007245 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007246 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007247 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007248 gotoxy(arg2, arg1);
7249 }
7250 else if (argc == 2 && *p == 'r')
7251 {
7252 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
7253 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01007254 else if (argc == 2 && *p == 'R')
7255 {
7256 set_scroll_region_tb(arg1, arg2);
7257 }
7258 else if (argc == 2 && *p == 'V')
7259 {
7260 set_scroll_region_lr(arg1, arg2);
7261 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007262 else if (argc == 1 && *p == 'A')
7263 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007264 gotoxy(g_coord.X + 1,
7265 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
7266 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007267 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007268 {
7269 textbackground((WORD) arg1);
7270 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007271 else if (argc == 1 && *p == 'C')
7272 {
7273 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
7274 g_coord.Y + 1);
7275 }
7276 else if (argc == 1 && *p == 'f')
7277 {
7278 textcolor((WORD) arg1);
7279 }
7280 else if (argc == 1 && *p == 'H')
7281 {
7282 gotoxy(1, arg1);
7283 }
7284 else if (argc == 1 && *p == 'L')
7285 {
7286 insert_lines(arg1);
7287 }
7288 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007289 {
7290 delete_lines(arg1);
7291 }
7292
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007293 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007294 s = p + 1;
7295 break;
7296
Bram Moolenaar071d4272004-06-13 20:20:40 +00007297 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007298 gotoxy(g_coord.X + 1,
7299 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
7300 goto got3;
7301
7302 case 'B':
7303 visual_bell();
7304 goto got3;
7305
7306 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007307 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
7308 g_coord.Y + 1);
7309 goto got3;
7310
7311 case 'E':
7312 termcap_mode_end();
7313 goto got3;
7314
7315 case 'F':
7316 standout();
7317 goto got3;
7318
7319 case 'f':
7320 standend();
7321 goto got3;
7322
7323 case 'H':
7324 gotoxy(1, 1);
7325 goto got3;
7326
7327 case 'j':
7328 clear_to_end_of_display();
7329 goto got3;
7330
7331 case 'J':
7332 clear_screen();
7333 goto got3;
7334
7335 case 'K':
7336 clear_to_end_of_line();
7337 goto got3;
7338
7339 case 'L':
7340 insert_lines(1);
7341 goto got3;
7342
7343 case 'M':
7344 delete_lines(1);
7345 goto got3;
7346
7347 case 'S':
7348 termcap_mode_start();
7349 goto got3;
7350
7351 case 'V':
7352 cursor_visible(TRUE);
7353 goto got3;
7354
7355 case 'v':
7356 cursor_visible(FALSE);
7357 goto got3;
7358
7359 got3:
7360 s += 3;
7361 len -= 2;
7362 }
7363
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007364# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007365 if (fdDump)
7366 {
7367 fputs("ESC | ", fdDump);
7368 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
7369 fputc('\n', fdDump);
7370 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007371# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007372 }
K.Takatadf5320c2022-09-01 13:20:16 +01007373 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
7374 {
7375 int l = 2;
7376
7377 if (isdigit(s[l]))
7378 l++;
7379 if (s[l] == ' ' && s[l + 1] == 'q')
7380 {
7381 // DECSCUSR (cursor style) sequences
Christopher Plewright38804d62022-11-09 23:55:52 +00007382 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01007383 vtp_printf("%.*s", l + 2, s); // Pass through
7384 s += l + 2;
7385 len -= l + 1;
7386 }
7387 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007388 else
7389 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007390 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00007391 DWORD nWritten;
7392
7393 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007394# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007395 if (fdDump)
7396 {
7397 fputc('>', fdDump);
7398 fwrite(s, sizeof(char_u), nWritten, fdDump);
7399 fputs("<\n", fdDump);
7400 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007401# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007402
7403 len -= (nWritten - 1);
7404 s += nWritten;
7405 }
7406 }
7407
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007408# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007409 if (fdDump)
7410 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007411# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007412}
7413
Bram Moolenaar0f873732019-12-05 20:28:46 +01007414#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00007415
7416
7417/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01007418 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007419 */
7420 void
7421mch_delay(
7422 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02007423 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007424{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007425#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007426 Sleep((int)msec); // never wait for input
7427#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007428# ifdef VIMDLL
7429 if (gui.in_use)
7430 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007431 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007432 return;
7433 }
7434# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02007435 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007436# ifdef FEAT_MZSCHEME
7437 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
7438 {
7439 int towait = p_mzq;
7440
Bram Moolenaar0f873732019-12-05 20:28:46 +01007441 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007442 while (msec > 0)
7443 {
7444 mzvim_check_threads();
7445 if (msec < towait)
7446 towait = msec;
7447 Sleep(towait);
7448 msec -= towait;
7449 }
7450 }
7451 else
7452# endif
7453 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007454 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007455 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007456#endif
7457}
7458
7459
7460/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01007461 * This version of remove is not scared by a readonly (backup) file.
7462 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007463 * Return 0 for success, -1 for failure.
7464 */
7465 int
7466mch_remove(char_u *name)
7467{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007468 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007469 int n;
7470
Bram Moolenaar203258c2016-01-17 22:15:16 +01007471 /*
7472 * On Windows, deleting a directory's symbolic link is done by
7473 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
7474 */
7475 if (mch_isdir(name) && mch_is_symbolic_link(name))
7476 return mch_rmdir(name);
7477
Bram Moolenaar12b559e2013-06-12 22:41:37 +02007478 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
7479
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007480 wn = enc_to_utf16(name, NULL);
7481 if (wn == NULL)
7482 return -1;
7483
7484 n = DeleteFileW(wn) ? 0 : -1;
7485 vim_free(wn);
7486 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007487}
7488
7489
7490/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007491 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007492 */
7493 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007494mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007495{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007496#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7497# ifdef VIMDLL
7498 if (!gui.in_use)
7499# endif
7500 if (g_fCtrlCPressed || g_fCBrkPressed)
7501 {
7502 ctrl_break_was_pressed = g_fCBrkPressed;
7503 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7504 got_int = TRUE;
7505 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007506#endif
7507}
7508
Bram Moolenaar0f873732019-12-05 20:28:46 +01007509// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007510#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007511
7512/*
7513 * How much main memory in KiB that can be used by VIM.
7514 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007515 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007516mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007517{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007518 MEMORYSTATUSEX ms;
7519
Bram Moolenaar0f873732019-12-05 20:28:46 +01007520 // Need to use GlobalMemoryStatusEx() when there is more memory than
7521 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007522 ms.dwLength = sizeof(MEMORYSTATUSEX);
7523 GlobalMemoryStatusEx(&ms);
7524 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007525 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007526 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007527 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007528 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007529 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007530 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007531 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007532 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007533 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007534 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007535 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007536}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007537
Bram Moolenaar071d4272004-06-13 20:20:40 +00007538/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007539 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00007540 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
7541 * file whose short file name is "FOO.BAR" (its long file name will
7542 * be correct: "foo.bar~"). Because a file can be accessed by
7543 * either its SFN or its LFN, "foo.bar" has effectively been
7544 * renamed to "foo.bar", which is not at all what was wanted. This
7545 * seems to happen only when renaming files with three-character
7546 * extensions by appending a suffix that does not include ".".
7547 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
7548 *
7549 * There is another problem, which isn't really a bug but isn't right either:
7550 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
7551 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
7552 * service pack 6. Doesn't seem to happen on Windows 98.
7553 *
7554 * Like rename(), returns 0 upon success, non-zero upon failure.
7555 * Should probably set errno appropriately when errors occur.
7556 */
7557 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007558mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007559{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007560 WCHAR *p;
7561 int i;
7562 WCHAR szTempFile[_MAX_PATH + 1];
7563 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007564 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007565
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007566 // No need to play tricks unless the file name contains a "~" as the
7567 // seventh character.
7568 p = wold;
7569 for (i = 0; wold[i] != NUL; ++i)
7570 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
7571 && wold[i + 1] != 0)
7572 p = wold + i + 1;
7573 if ((int)(wold + i - p) < 8 || p[6] != '~')
7574 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007575
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007576 // Get base path of new file name. Undocumented feature: If pszNewFile is
7577 // a directory, no error is returned and pszFilePart will be NULL.
7578 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007579 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007580 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007581
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007582 // Get (and create) a unique temporary file name in directory of new file
7583 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007584 return -2;
7585
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007586 // blow the temp file away
7587 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007588 return -3;
7589
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007590 // rename old file to the temp file
7591 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007592 return -4;
7593
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007594 // now create an empty file called pszOldFile; this prevents the operating
7595 // system using pszOldFile as an alias (SFN) if we're renaming within the
7596 // same directory. For example, we're editing a file called
7597 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7598 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7599 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7600 // cause all sorts of problems later in buf_write(). So, we create an
7601 // empty file called filena~1.txt and the system will have to find some
7602 // other SFN for filena~1.txt~, such as filena~2.txt
7603 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007604 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7605 return -5;
7606 if (!CloseHandle(hf))
7607 return -6;
7608
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007609 // rename the temp file to the new file
7610 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007611 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007612 // Renaming failed. Rename the file back to its old name, so that it
7613 // looks like nothing happened.
7614 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007615 return -7;
7616 }
7617
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007618 // Seems to be left around on Novell filesystems
7619 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007620
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007621 // finally, remove the empty old file
7622 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007623 return -8;
7624
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007625 return 0;
7626}
7627
7628
7629/*
7630 * Converts the filenames to UTF-16, then call mch_wrename().
7631 * Like rename(), returns 0 upon success, non-zero upon failure.
7632 */
7633 int
7634mch_rename(
7635 const char *pszOldFile,
7636 const char *pszNewFile)
7637{
7638 WCHAR *wold = NULL;
7639 WCHAR *wnew = NULL;
7640 int retval = -1;
7641
7642 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7643 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7644 if (wold != NULL && wnew != NULL)
7645 retval = mch_wrename(wold, wnew);
7646 vim_free(wold);
7647 vim_free(wnew);
7648 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007649}
7650
7651/*
7652 * Get the default shell for the current hardware platform
7653 */
7654 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007655default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007656{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007657 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007658}
7659
7660/*
7661 * mch_access() extends access() to do more detailed check on network drives.
7662 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7663 */
7664 int
7665mch_access(char *n, int p)
7666{
7667 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007668 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007669 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007670
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007671 wn = enc_to_utf16((char_u *)n, NULL);
7672 if (wn == NULL)
7673 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007674
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007675 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007676 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007677 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007678
7679 if (p & R_OK)
7680 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007681 // Read check is performed by seeing if we can do a find file on
7682 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007683 int i;
7684 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007685
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007686 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7687 TempNameW[i] = wn[i];
7688 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7689 TempNameW[i++] = '\\';
7690 TempNameW[i++] = '*';
7691 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007692
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007693 hFile = FindFirstFileW(TempNameW, &d);
7694 if (hFile == INVALID_HANDLE_VALUE)
7695 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007696 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007697 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007698 }
7699
7700 if (p & W_OK)
7701 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007702 // Trying to create a temporary file in the directory should catch
7703 // directories on read-only network shares. However, in
7704 // directories whose ACL allows writes but denies deletes will end
7705 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007706 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7707 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007708 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007709 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007710 }
7711 }
7712 else
7713 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007714 // Don't consider a file read-only if another process has opened it.
7715 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7716
Bram Moolenaar0f873732019-12-05 20:28:46 +01007717 // Trying to open the file for the required access does ACL, read-only
7718 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007719 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7720 | ((p & R_OK) ? GENERIC_READ : 0);
7721
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007722 hFile = CreateFileW(wn, access_mode, share_mode,
7723 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007724 if (hFile == INVALID_HANDLE_VALUE)
7725 goto getout;
7726 CloseHandle(hFile);
7727 }
7728
Bram Moolenaar0f873732019-12-05 20:28:46 +01007729 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007730getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007731 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007732 return retval;
7733}
7734
Bram Moolenaar071d4272004-06-13 20:20:40 +00007735/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007736 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007737 */
7738 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007739mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007740{
7741 WCHAR *wn;
7742 int f;
7743
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007744 wn = enc_to_utf16((char_u *)name, NULL);
7745 if (wn == NULL)
7746 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007747
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007748 f = _wopen(wn, flags, mode);
7749 vim_free(wn);
7750 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007751}
7752
7753/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007754 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007755 */
7756 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007757mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007758{
7759 WCHAR *wn, *wm;
7760 FILE *f = NULL;
7761
Bram Moolenaara12a1612019-01-24 16:39:02 +01007762#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007763 // Work around an annoying assertion in the Microsoft debug CRT
7764 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007765 char newMode = mode[strlen(mode) - 1];
7766 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007767
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007768 _get_fmode(&oldMode);
7769 if (newMode == 't')
7770 _set_fmode(_O_TEXT);
7771 else if (newMode == 'b')
7772 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007773#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007774 wn = enc_to_utf16((char_u *)name, NULL);
7775 wm = enc_to_utf16((char_u *)mode, NULL);
7776 if (wn != NULL && wm != NULL)
7777 f = _wfopen(wn, wm);
7778 vim_free(wn);
7779 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007780
Bram Moolenaara12a1612019-01-24 16:39:02 +01007781#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007782 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007783#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007784 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007785}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007786
Bram Moolenaar071d4272004-06-13 20:20:40 +00007787/*
7788 * SUB STREAM (aka info stream) handling:
7789 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007790 * NTFS can have sub streams for each file. The normal contents of a file is
7791 * stored in the main stream, and extra contents (author information, title and
7792 * so on) can be stored in a sub stream. After Windows 2000, the user can
7793 * access and store this information in sub streams via an explorer's property
7794 * menu item in the right click menu. This information in sub streams was lost
7795 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007796 *
7797 * Incomplete explanation:
7798 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7799 * More useful info and an example:
7800 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7801 */
7802
7803/*
7804 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7805 * and write to stream "substream" of file "to".
7806 * Errors are ignored.
7807 */
7808 static void
7809copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7810{
7811 HANDLE hTo;
7812 WCHAR *to_name;
7813
7814 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7815 wcscpy(to_name, to);
7816 wcscat(to_name, substream);
7817
7818 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7819 FILE_ATTRIBUTE_NORMAL, NULL);
7820 if (hTo != INVALID_HANDLE_VALUE)
7821 {
7822 long done;
7823 DWORD todo;
7824 DWORD readcnt, written;
7825 char buf[4096];
7826
Bram Moolenaar0f873732019-12-05 20:28:46 +01007827 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007828 for (done = 0; done < len; done += written)
7829 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007830 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007831 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7832 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007833 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7834 FALSE, FALSE, context)
7835 || readcnt != todo
7836 || !WriteFile(hTo, buf, todo, &written, NULL)
7837 || written != todo)
7838 break;
7839 }
7840 CloseHandle(hTo);
7841 }
7842
7843 free(to_name);
7844}
7845
7846/*
7847 * Copy info streams from file "from" to file "to".
7848 */
7849 static void
7850copy_infostreams(char_u *from, char_u *to)
7851{
7852 WCHAR *fromw;
7853 WCHAR *tow;
7854 HANDLE sh;
7855 WIN32_STREAM_ID sid;
7856 int headersize;
7857 WCHAR streamname[_MAX_PATH];
7858 DWORD readcount;
7859 void *context = NULL;
7860 DWORD lo, hi;
7861 int len;
7862
Bram Moolenaar0f873732019-12-05 20:28:46 +01007863 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007864 fromw = enc_to_utf16(from, NULL);
7865 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007866 if (fromw != NULL && tow != NULL)
7867 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007868 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007869 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7870 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7871 if (sh != INVALID_HANDLE_VALUE)
7872 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007873 // Use BackupRead() to find the info streams. Repeat until we
7874 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007875 for (;;)
7876 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007877 // Get the header to find the length of the stream name. If
7878 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007879 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007880 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007881 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7882 &readcount, FALSE, FALSE, &context)
7883 || readcount == 0)
7884 break;
7885
Bram Moolenaar0f873732019-12-05 20:28:46 +01007886 // We only deal with streams that have a name. The normal
7887 // file data appears to be without a name, even though docs
7888 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007889 if (sid.dwStreamNameSize > 0)
7890 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007891 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007892 if (!BackupRead(sh, (LPBYTE)streamname,
7893 sid.dwStreamNameSize,
7894 &readcount, FALSE, FALSE, &context))
7895 break;
7896
Bram Moolenaar0f873732019-12-05 20:28:46 +01007897 // Copy an info stream with a name ":anything:$DATA".
7898 // Skip "::$DATA", it has no stream name (examples suggest
7899 // it might be used for the normal file contents).
7900 // Note that BackupRead() counts bytes, but the name is in
7901 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007902 len = readcount / sizeof(WCHAR);
7903 streamname[len] = 0;
7904 if (len > 7 && wcsicmp(streamname + len - 6,
7905 L":$DATA") == 0)
7906 {
7907 streamname[len - 6] = 0;
7908 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007909 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007910 }
7911 }
7912
Bram Moolenaar0f873732019-12-05 20:28:46 +01007913 // Advance to the next stream. We might try seeking too far,
7914 // but BackupSeek() doesn't skip over stream borders, thus
7915 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007916 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007917 &lo, &hi, &context);
7918 }
7919
Bram Moolenaar0f873732019-12-05 20:28:46 +01007920 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007921 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7922
7923 CloseHandle(sh);
7924 }
7925 }
7926 vim_free(fromw);
7927 vim_free(tow);
7928}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007929
7930/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007931 * ntdll.dll definitions
7932 */
7933#define FileEaInformation 7
7934#ifndef STATUS_SUCCESS
7935# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7936#endif
7937
7938typedef struct _FILE_FULL_EA_INFORMATION_ {
7939 ULONG NextEntryOffset;
7940 UCHAR Flags;
7941 UCHAR EaNameLength;
7942 USHORT EaValueLength;
7943 CHAR EaName[1];
7944} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7945
7946typedef struct _FILE_EA_INFORMATION_ {
7947 ULONG EaSize;
7948} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7949
Paul Ollis65745772022-06-05 16:55:54 +01007950#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007951typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7952 PHANDLE FileHandle,
7953 ACCESS_MASK DesiredAccess,
7954 POBJECT_ATTRIBUTES ObjectAttributes,
7955 PIO_STATUS_BLOCK IoStatusBlock,
7956 ULONG ShareAccess,
7957 ULONG OpenOptions);
7958typedef NTSTATUS (NTAPI *PfnNtClose)(
7959 HANDLE Handle);
7960typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007961 HANDLE FileHandle,
7962 PIO_STATUS_BLOCK IoStatusBlock,
7963 PVOID Buffer,
7964 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007965typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7966 HANDLE FileHandle,
7967 PIO_STATUS_BLOCK IoStatusBlock,
7968 PVOID Buffer,
7969 ULONG Length,
7970 BOOLEAN ReturnSingleEntry,
7971 PVOID EaList,
7972 ULONG EaListLength,
7973 PULONG EaIndex,
7974 BOOLEAN RestartScan);
7975typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007976 HANDLE FileHandle,
7977 PIO_STATUS_BLOCK IoStatusBlock,
7978 PVOID FileInformation,
7979 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007980 FILE_INFORMATION_CLASS FileInformationClass);
7981typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7982 PUNICODE_STRING DestinationString,
7983 PCWSTR SourceString);
7984
7985PfnNtOpenFile pNtOpenFile = NULL;
7986PfnNtClose pNtClose = NULL;
7987PfnNtSetEaFile pNtSetEaFile = NULL;
7988PfnNtQueryEaFile pNtQueryEaFile = NULL;
7989PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7990PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01007991#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007992
7993/*
7994 * Load ntdll.dll functions.
7995 */
7996 static BOOL
7997load_ntdll(void)
7998{
7999 static int loaded = -1;
8000
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008001 if (loaded != -1)
8002 return (BOOL) loaded;
8003
8004 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
8005 if (hNtdll != NULL)
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008006 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008007 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
8008 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
8009 pNtSetEaFile = (PfnNtSetEaFile)
8010 GetProcAddress(hNtdll, "NtSetEaFile");
8011 pNtQueryEaFile = (PfnNtQueryEaFile)
8012 GetProcAddress(hNtdll, "NtQueryEaFile");
8013 pNtQueryInformationFile = (PfnNtQueryInformationFile)
8014 GetProcAddress(hNtdll, "NtQueryInformationFile");
8015 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
8016 GetProcAddress(hNtdll, "RtlInitUnicodeString");
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008017 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008018 if (pNtOpenFile == NULL
8019 || pNtClose == NULL
8020 || pNtSetEaFile == NULL
8021 || pNtQueryEaFile == NULL
8022 || pNtQueryInformationFile == NULL
8023 || pRtlInitUnicodeString == NULL)
8024 loaded = FALSE;
8025 else
8026 loaded = TRUE;
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008027 return (BOOL) loaded;
8028}
8029
8030/*
8031 * Copy extended attributes (EA) from file "from" to file "to".
8032 */
8033 static void
8034copy_extattr(char_u *from, char_u *to)
8035{
8036 char_u *fromf = NULL;
8037 char_u *tof = NULL;
8038 WCHAR *fromw = NULL;
8039 WCHAR *tow = NULL;
8040 UNICODE_STRING u;
8041 HANDLE h;
8042 OBJECT_ATTRIBUTES oa;
8043 IO_STATUS_BLOCK iosb;
8044 FILE_EA_INFORMATION_ eainfo = {0};
8045 void *ea = NULL;
8046
8047 if (!load_ntdll())
8048 return;
8049
8050 // Convert the file names to the fully qualified object names.
8051 fromf = alloc(STRLEN(from) + 5);
8052 tof = alloc(STRLEN(to) + 5);
8053 if (fromf == NULL || tof == NULL)
8054 goto theend;
8055 STRCPY(fromf, "\\??\\");
8056 STRCAT(fromf, from);
8057 STRCPY(tof, "\\??\\");
8058 STRCAT(tof, to);
8059
8060 // Convert the names to wide characters.
8061 fromw = enc_to_utf16(fromf, NULL);
8062 tow = enc_to_utf16(tof, NULL);
8063 if (fromw == NULL || tow == NULL)
8064 goto theend;
8065
8066 // Get the EA.
8067 pRtlInitUnicodeString(&u, fromw);
8068 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8069 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
8070 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8071 goto theend;
8072 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
8073 FileEaInformation);
8074 if (eainfo.EaSize != 0)
8075 {
8076 ea = alloc(eainfo.EaSize);
8077 if (ea != NULL)
8078 {
8079 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
8080 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
8081 {
Yegappan Lakshmanan960dcbd2023-03-07 17:45:11 +00008082 VIM_CLEAR(ea);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008083 }
8084 }
8085 }
8086 pNtClose(h);
8087
8088 // Set the EA.
8089 if (ea != NULL)
8090 {
8091 pRtlInitUnicodeString(&u, tow);
8092 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8093 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
8094 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8095 goto theend;
8096
8097 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
8098 pNtClose(h);
8099 }
8100
8101theend:
8102 vim_free(fromf);
8103 vim_free(tof);
8104 vim_free(fromw);
8105 vim_free(tow);
8106 vim_free(ea);
8107}
8108
8109/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008110 * Copy file attributes from file "from" to file "to".
8111 * For Windows NT and later we copy info streams.
8112 * Always returns zero, errors are ignored.
8113 */
8114 int
8115mch_copy_file_attribute(char_u *from, char_u *to)
8116{
Bram Moolenaar0f873732019-12-05 20:28:46 +01008117 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02008118 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008119 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008120 return 0;
8121}
8122
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008123
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008124/*
K.Takatadc73b4b2021-06-08 18:32:36 +02008125 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008126 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008127static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008128static LPWSTR *ArglistW = NULL;
8129static int global_argc = 0;
8130static char **global_argv;
8131
Bram Moolenaar0f873732019-12-05 20:28:46 +01008132static int used_file_argc = 0; // last argument in global_argv[] used
8133 // for the argument list.
8134static int *used_file_indexes = NULL; // indexes in global_argv[] for
8135 // command line arguments added to
8136 // the argument list
8137static int used_file_count = 0; // nr of entries in used_file_indexes
8138static int used_file_literal = FALSE; // take file names literally
8139static int used_file_full_path = FALSE; // file name was full path
8140static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008141static int used_alist_count = 0;
8142
8143
8144/*
8145 * Get the command line arguments. Unicode version.
8146 * Returns argc. Zero when something fails.
8147 */
8148 int
8149get_cmd_argsW(char ***argvp)
8150{
8151 char **argv = NULL;
8152 int argc = 0;
8153 int i;
8154
Bram Moolenaar14993322014-09-09 12:25:33 +02008155 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008156 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
8157 if (ArglistW != NULL)
8158 {
8159 argv = malloc((nArgsW + 1) * sizeof(char *));
8160 if (argv != NULL)
8161 {
8162 argc = nArgsW;
8163 argv[argc] = NULL;
8164 for (i = 0; i < argc; ++i)
8165 {
8166 int len;
8167
K.Takatadc73b4b2021-06-08 18:32:36 +02008168 // Convert each Unicode argument to UTF-8.
8169 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008170 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008171 (LPSTR *)&argv[i], &len, 0, 0);
8172 if (argv[i] == NULL)
8173 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008174 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008175 while (i > 0)
8176 free(argv[--i]);
8177 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01008178 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008179 argc = 0;
8180 }
8181 }
8182 }
8183 }
8184
8185 global_argc = argc;
8186 global_argv = argv;
8187 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02008188 {
8189 if (used_file_indexes != NULL)
8190 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008191 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02008192 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008193
8194 if (argvp != NULL)
8195 *argvp = argv;
8196 return argc;
8197}
8198
8199 void
8200free_cmd_argsW(void)
8201{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008202 if (ArglistW == NULL)
8203 return;
8204
8205 GlobalFree(ArglistW);
8206 ArglistW = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008207}
8208
8209/*
8210 * Remember "name" is an argument that was added to the argument list.
8211 * This avoids that we have to re-parse the argument list when fix_arg_enc()
8212 * is called.
8213 */
8214 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008215used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008216{
8217 int i;
8218
8219 if (used_file_indexes == NULL)
8220 return;
8221 for (i = used_file_argc + 1; i < global_argc; ++i)
8222 if (STRCMP(global_argv[i], name) == 0)
8223 {
8224 used_file_argc = i;
8225 used_file_indexes[used_file_count++] = i;
8226 break;
8227 }
8228 used_file_literal = literal;
8229 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008230 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008231}
8232
8233/*
8234 * Remember the length of the argument list as it was. If it changes then we
8235 * leave it alone when 'encoding' is set.
8236 */
8237 void
8238set_alist_count(void)
8239{
8240 used_alist_count = GARGCOUNT;
8241}
8242
8243/*
8244 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02008245 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008246 * and convert them to 'encoding'.
8247 */
8248 void
8249fix_arg_enc(void)
8250{
8251 int i;
8252 int idx;
8253 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00008254 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008255
Bram Moolenaar0f873732019-12-05 20:28:46 +01008256 // Safety checks:
8257 // - if argument count differs between the wide and non-wide argument
8258 // list, something must be wrong.
8259 // - the file name arguments must have been located.
8260 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008261 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008262 || ArglistW == NULL
8263 || used_file_indexes == NULL
8264 || used_file_count == 0
8265 || used_alist_count != GARGCOUNT)
8266 return;
8267
Bram Moolenaar0f873732019-12-05 20:28:46 +01008268 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02008269 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008270 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008271 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00008272 for (i = 0; i < GARGCOUNT; ++i)
8273 fnum_list[i] = GARGLIST[i].ae_fnum;
8274
Bram Moolenaar0f873732019-12-05 20:28:46 +01008275 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008276 alist_clear(&global_alist);
8277 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008278 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008279
8280 for (i = 0; i < used_file_count; ++i)
8281 {
8282 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008283 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008284 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00008285 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008286 int literal = used_file_literal;
8287
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008288#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01008289 // When using diff mode may need to concatenate file name to
8290 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008291 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
8292 && !mch_isdir(alist_name(&GARGLIST[0])))
8293 {
8294 char_u *r;
8295
8296 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
8297 if (r != NULL)
8298 {
8299 vim_free(str);
8300 str = r;
8301 }
8302 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008303#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01008304 // Re-use the old buffer by renaming it. When not using literal
8305 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00008306 if (used_file_literal)
8307 buf_set_name(fnum_list[i], str);
8308
Bram Moolenaar0f873732019-12-05 20:28:46 +01008309 // Check backtick literal. backtick literal is already expanded in
8310 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008311 if (literal == FALSE)
8312 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02008313 size_t len = STRLEN(str);
8314
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008315 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
8316 literal = TRUE;
8317 }
8318 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008319 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008320 }
8321
8322 if (!used_file_literal)
8323 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008324 // Now expand wildcards in the arguments.
8325 // Temporarily add '(' and ')' to 'isfname'. These are valid
8326 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00008327 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01008328 // Also, unset wildignore to not be influenced by this option.
8329 // The arguments specified in command-line should be kept even if
8330 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00008331 // Use :legacy so that it also works when in Vim9 script.
8332 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
8333 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00008334 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00008335 do_cmdline_cmd(
8336 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
8337 do_cmdline_cmd(
8338 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008339 }
8340
Bram Moolenaar0f873732019-12-05 20:28:46 +01008341 // If wildcard expansion failed, we are editing the first file of the
8342 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008343 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
8344 {
8345 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00008346 if (GARGCOUNT == 1 && used_file_full_path
8347 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
8348 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008349 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00008350
8351 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008352}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008353
8354 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02008355mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008356{
8357 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008358 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008359
Bram Moolenaar964b3742019-05-24 18:54:09 +02008360 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008361 if (envbuf == NULL)
8362 return -1;
8363
8364 sprintf((char *)envbuf, "%s=%s", var, value);
8365
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008366 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008367
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008368 vim_free(envbuf);
8369 if (p == NULL)
8370 return -1;
8371 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008372#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008373 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008374#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008375 // Unlike Un*x systems, we can free the string for _wputenv().
8376 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008377
8378 return 0;
8379}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008380
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008381/*
8382 * Support for 256 colors and 24-bit colors was added in Windows 10
8383 * version 1703 (Creators update).
8384 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008385#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
8386
8387/*
8388 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02008389 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008390 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008391#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008392
8393/*
8394 * ConPTY differences between versions, need different logic.
8395 * version 1903 (May 2019 update).
8396 */
8397#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
8398
8399/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008400 * version 1909 (November 2019 update).
8401 */
8402#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
8403
8404/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008405 * Stay ahead of the next update, and when it's done, fix this.
8406 * version ? (2020 update, temporarily use the build number of insider preview)
8407 */
8408#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
8409
8410/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02008411 * Confirm until this version. Also the logic changes.
8412 * insider preview.
8413 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02008414#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008415
8416/*
8417 * Not stable now.
8418 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008419#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Christopher Plewright1140b512022-11-12 18:46:05 +00008420// Notes:
8421// Win 10 22H2 Final is build 19045, it's conpty is widely used.
8422// Strangely, 19045 is newer but is a lower build number than the 2020 insider
8423// preview which had a build 19587. And, not sure how stable that was?
8424// Win Server 2022 (May 10, 2022) is build 20348, its conpty is widely used.
8425// Win 11 starts from build 22000, even though the major version says 10!
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008426
8427 static void
8428vtp_flag_init(void)
8429{
8430 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008431#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008432 DWORD mode;
8433 HANDLE out;
8434
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008435# ifdef VIMDLL
8436 if (!gui.in_use)
8437# endif
8438 {
8439 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008440
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008441 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
8442 GetConsoleMode(out, &mode);
8443 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
8444 if (SetConsoleMode(out, mode) == 0)
8445 vtp_working = 0;
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008446
8447 // VTP uses alternate screen buffer.
8448 // But, not if running in a nested terminal
8449 use_alternate_screen_buffer = win10_22H2_or_later && p_rs && vtp_working
8450 && !mch_getenv("VIM_TERMINAL");
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008451 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008452#endif
8453
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008454 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008455 conpty_working = 1;
8456 if (ver >= CONPTY_STABLE_BUILD)
8457 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008458
Bram Moolenaar57da6982019-09-13 22:30:11 +02008459 if (ver <= CONPTY_INSIDER_BUILD)
8460 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008461 if (ver <= CONPTY_1909_BUILD)
8462 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02008463 if (ver <= CONPTY_1903_BUILD)
8464 conpty_type = 2;
8465 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
8466 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008467
8468 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
8469 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008470}
8471
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008472#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008473
8474 static void
8475vtp_init(void)
8476{
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008477# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightd343c602023-01-22 18:58:30 +00008478 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8479 csbi.cbSize = sizeof(csbi);
8480 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8481 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
8482 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
8483 store_console_bg_rgb = save_console_bg_rgb;
8484 store_console_fg_rgb = save_console_fg_rgb;
Christopher Plewright38804d62022-11-09 23:55:52 +00008485
Christopher Plewrightd343c602023-01-22 18:58:30 +00008486 COLORREF bg;
8487 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
8488 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8489 default_console_color_bg = bg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008490
Christopher Plewrightd343c602023-01-22 18:58:30 +00008491 COLORREF fg;
8492 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
8493 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8494 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008495# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008496 set_console_color_rgb();
8497}
8498
8499 static void
8500vtp_exit(void)
8501{
Bram Moolenaardf543822020-01-30 11:53:59 +01008502 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008503}
8504
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008505 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008506vtp_printf(
8507 char *format,
8508 ...)
8509{
8510 char_u buf[100];
8511 va_list list;
8512 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008513 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008514
8515 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008516 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008517 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008518 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008519 return (int)result;
8520}
8521
8522 static void
8523vtp_sgr_bulk(
8524 int arg)
8525{
8526 int args[1];
8527
8528 args[0] = arg;
8529 vtp_sgr_bulks(1, args);
8530}
8531
K.Takata6e1d31e2022-02-03 13:05:32 +00008532# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008533 if ((*p-- = "0123456789"[(n = x % 10)]) \
8534 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8535 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8536
K.Takata6e1d31e2022-02-03 13:05:32 +00008537# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008538 case x: \
8539 FAST256(newargs[x - 1]);
8540
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008541 static void
8542vtp_sgr_bulks(
8543 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008544 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008545{
K.Takata6e1d31e2022-02-03 13:05:32 +00008546# define MAXSGR 16
8547# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008548 char_u buf[SGRBUFSIZE];
8549 char_u *p;
8550 int in, out;
8551 int newargs[16];
8552 static int sgrfgr = -1, sgrfgg, sgrfgb;
8553 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008554
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008555 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008556 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008557 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008558 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008559 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008560 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008561
8562 in = out = 0;
8563 while (in < argc)
8564 {
8565 int s = args[in];
8566 int copylen = 1;
8567
8568 if (s == 38)
8569 {
8570 if (argc - in >= 5 && args[in + 1] == 2)
8571 {
8572 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8573 && sgrfgb == args[in + 4])
8574 {
8575 in += 5;
8576 copylen = 0;
8577 }
8578 else
8579 {
8580 sgrfgr = args[in + 2];
8581 sgrfgg = args[in + 3];
8582 sgrfgb = args[in + 4];
8583 copylen = 5;
8584 }
8585 }
8586 else if (argc - in >= 3 && args[in + 1] == 5)
8587 {
8588 sgrfgr = -1;
8589 copylen = 3;
8590 }
8591 }
8592 else if (s == 48)
8593 {
8594 if (argc - in >= 5 && args[in + 1] == 2)
8595 {
8596 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8597 && sgrbgb == args[in + 4])
8598 {
8599 in += 5;
8600 copylen = 0;
8601 }
8602 else
8603 {
8604 sgrbgr = args[in + 2];
8605 sgrbgg = args[in + 3];
8606 sgrbgb = args[in + 4];
8607 copylen = 5;
8608 }
8609 }
8610 else if (argc - in >= 3 && args[in + 1] == 5)
8611 {
8612 sgrbgr = -1;
8613 copylen = 3;
8614 }
8615 }
8616 else if (30 <= s && s <= 39)
8617 sgrfgr = -1;
8618 else if (90 <= s && s <= 97)
8619 sgrfgr = -1;
8620 else if (40 <= s && s <= 49)
8621 sgrbgr = -1;
8622 else if (100 <= s && s <= 107)
8623 sgrbgr = -1;
8624 else if (s == 0)
8625 sgrfgr = sgrbgr = -1;
8626
8627 while (copylen--)
8628 newargs[out++] = args[in++];
8629 }
8630
8631 p = &buf[sizeof(buf) - 1];
8632 *p-- = 'm';
8633
8634 switch (out)
8635 {
8636 int n, m;
8637 DWORD r;
8638
8639 FAST256CASE(16);
8640 *p-- = ';';
8641 FAST256CASE(15);
8642 *p-- = ';';
8643 FAST256CASE(14);
8644 *p-- = ';';
8645 FAST256CASE(13);
8646 *p-- = ';';
8647 FAST256CASE(12);
8648 *p-- = ';';
8649 FAST256CASE(11);
8650 *p-- = ';';
8651 FAST256CASE(10);
8652 *p-- = ';';
8653 FAST256CASE(9);
8654 *p-- = ';';
8655 FAST256CASE(8);
8656 *p-- = ';';
8657 FAST256CASE(7);
8658 *p-- = ';';
8659 FAST256CASE(6);
8660 *p-- = ';';
8661 FAST256CASE(5);
8662 *p-- = ';';
8663 FAST256CASE(4);
8664 *p-- = ';';
8665 FAST256CASE(3);
8666 *p-- = ';';
8667 FAST256CASE(2);
8668 *p-- = ';';
8669 FAST256CASE(1);
8670 *p-- = '[';
8671 *p = '\033';
8672 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8673 default:
8674 break;
8675 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008676}
8677
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008678 static void
8679wt_init(void)
8680{
Christopher Plewright1140b512022-11-12 18:46:05 +00008681 wt_working = mch_getenv("WT_SESSION") != NULL;
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008682}
8683
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008684# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008685 static int
8686ctermtoxterm(
8687 int cterm)
8688{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008689 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008690
8691 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8692 return (((int)r << 16) | ((int)g << 8) | (int)b);
8693}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008694# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008695
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008696 static void
8697set_console_color_rgb(void)
8698{
8699# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008700 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008701 guicolor_T fg, bg;
8702 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008703
Christopher Plewright38804d62022-11-09 23:55:52 +00008704 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008705 return;
8706
Bram Moolenaara050b942019-12-02 21:35:31 +01008707 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8708
Christopher Plewright38804d62022-11-09 23:55:52 +00008709 if (p_tgc || t_colors >= 256)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008710 {
8711 term_fg_rgb_color(fg);
8712 term_bg_rgb_color(bg);
8713 return;
8714 }
8715
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008716 if (use_alternate_screen_buffer)
8717 return;
8718
Christopher Plewrightd343c602023-01-22 18:58:30 +00008719 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8720 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008721
Christopher Plewrightd343c602023-01-22 18:58:30 +00008722 csbi.cbSize = sizeof(csbi);
8723 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008724
Christopher Plewrightd343c602023-01-22 18:58:30 +00008725 csbi.cbSize = sizeof(csbi);
8726 csbi.srWindow.Right += 1;
8727 csbi.srWindow.Bottom += 1;
8728 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8729 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
8730 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8731 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
8732 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008733# endif
8734}
8735
Bram Moolenaara050b942019-12-02 21:35:31 +01008736# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8737 void
8738get_default_console_color(
8739 int *cterm_fg,
8740 int *cterm_bg,
8741 guicolor_T *gui_fg,
8742 guicolor_T *gui_bg)
8743{
8744 int id;
8745 guicolor_T guifg = INVALCOLOR;
8746 guicolor_T guibg = INVALCOLOR;
8747 int ctermfg = 0;
8748 int ctermbg = 0;
Christopher Plewright38804d62022-11-09 23:55:52 +00008749 int dummynull = 0;
Bram Moolenaara050b942019-12-02 21:35:31 +01008750
8751 id = syn_name2id((char_u *)"Normal");
8752 if (id > 0 && p_tgc)
8753 syn_id2colors(id, &guifg, &guibg);
8754 if (guifg == INVALCOLOR)
8755 {
8756 ctermfg = -1;
8757 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008758 syn_id2cterm_bg(id, &ctermfg, &dummynull);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008759 if (ctermfg != -1)
8760 guifg = ctermtoxterm(ctermfg);
Christopher Plewright38804d62022-11-09 23:55:52 +00008761 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008762 guifg = USE_WT ? INVALCOLOR : default_console_color_fg;
8763 cterm_normal_fg_gui_color = guifg;
8764 ctermfg = ctermfg < 0 ? 0 : ctermfg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008765 }
8766 if (guibg == INVALCOLOR)
8767 {
8768 ctermbg = -1;
8769 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008770 syn_id2cterm_bg(id, &dummynull, &ctermbg);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008771 if (ctermbg != -1)
8772 guibg = ctermtoxterm(ctermbg);
K.Takatae53a0d42022-09-05 21:45:11 +01008773 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008774 guibg = USE_WT ? INVALCOLOR : default_console_color_bg;
8775 cterm_normal_bg_gui_color = guibg;
8776 ctermbg = ctermbg < 0 ? 0 : ctermbg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008777 }
8778
8779 *cterm_fg = ctermfg;
8780 *cterm_bg = ctermbg;
8781 *gui_fg = guifg;
8782 *gui_bg = guibg;
8783}
8784# endif
8785
Bram Moolenaardf543822020-01-30 11:53:59 +01008786/*
8787 * Set the console colors to the original colors or the last set colors.
8788 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008789 static void
8790reset_console_color_rgb(void)
8791{
8792# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008793 if (use_alternate_screen_buffer)
8794 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008795
Christopher Plewright38804d62022-11-09 23:55:52 +00008796 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8797
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008798 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008799 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008800
8801 csbi.cbSize = sizeof(csbi);
8802 csbi.srWindow.Right += 1;
8803 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008804 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8805 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008806 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008807# endif
8808}
8809
8810/*
8811 * Set the console colors to the original colors.
8812 */
8813 static void
8814restore_console_color_rgb(void)
8815{
8816# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008817 if (use_alternate_screen_buffer)
8818 return;
Christopher Plewright38804d62022-11-09 23:55:52 +00008819
K.Takata27b53be2022-09-18 12:25:49 +01008820 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008821
8822 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008823 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008824
8825 csbi.cbSize = sizeof(csbi);
8826 csbi.srWindow.Right += 1;
8827 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008828 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8829 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008830 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008831# endif
8832}
8833
8834 void
8835control_console_color_rgb(void)
8836{
Christopher Plewright38804d62022-11-09 23:55:52 +00008837 if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008838 set_console_color_rgb();
8839 else
8840 reset_console_color_rgb();
8841}
8842
8843 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008844use_vtp(void)
8845{
8846 return USE_VTP;
8847}
8848
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008849 int
8850is_term_win32(void)
8851{
8852 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8853}
8854
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008855 int
8856has_vtp_working(void)
8857{
8858 return vtp_working;
8859}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008860
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008861#endif
8862
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008863 int
8864has_conpty_working(void)
8865{
8866 return conpty_working;
8867}
8868
8869 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008870get_conpty_type(void)
8871{
8872 return conpty_type;
8873}
8874
8875 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008876is_conpty_stable(void)
8877{
8878 return conpty_stable;
8879}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008880
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008881 int
8882get_conpty_fix_type(void)
8883{
8884 return conpty_fix_type;
8885}
8886
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008887#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008888 void
8889resize_console_buf(void)
8890{
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008891 if (use_alternate_screen_buffer)
8892 return;
8893
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008894 CONSOLE_SCREEN_BUFFER_INFO csbi;
8895 COORD coord;
8896 SMALL_RECT newsize;
8897
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008898 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8899 return;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008900
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008901 coord.X = SRWIDTH(csbi.srWindow);
8902 coord.Y = SRHEIGHT(csbi.srWindow);
8903 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008904
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008905 newsize.Left = 0;
8906 newsize.Top = 0;
8907 newsize.Right = coord.X - 1;
8908 newsize.Bottom = coord.Y - 1;
8909 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8910
8911 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008912}
8913#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008914
8915 char *
8916GetWin32Error(void)
8917{
K.Takatad68b2fc2022-02-12 11:18:37 +00008918 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008919 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008920
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008921 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8922 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008923 if (oldmsg != NULL)
8924 LocalFree(oldmsg);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008925 if (msg == NULL)
8926 return NULL;
8927
8928 // remove trailing \r\n
8929 char *pcrlf = strstr(msg, "\r\n");
8930 if (pcrlf != NULL)
8931 *pcrlf = '\0';
8932 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008933 return msg;
8934}
Paul Ollis65745772022-06-05 16:55:54 +01008935
8936#if defined(FEAT_RELTIME) || defined(PROTO)
8937static HANDLE timer_handle;
8938static int timer_active = FALSE;
8939
8940/*
8941 * Calls to start_timeout alternate the return value pointer between the two
8942 * entries in timeout_flags. If the previously active timeout is very close to
8943 * expiring when start_timeout() is called then a race condition means that the
8944 * set_flag() function may still be invoked after the previous timer is
8945 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8946 * timeouts.
8947 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008948static sig_atomic_t timeout_flags[2];
8949static int timeout_flag_idx = 0;
8950static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01008951
8952
8953 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01008954set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01008955{
8956 int *timeout_flag = (int *)param;
8957
8958 *timeout_flag = TRUE;
8959}
8960
8961/*
8962 * Stop any active timeout.
8963 */
8964 void
8965stop_timeout(void)
8966{
8967 if (timer_active)
8968 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01008969 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01008970 timer_active = FALSE;
8971 if (!ret && GetLastError() != ERROR_IO_PENDING)
8972 {
8973 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
8974 }
8975 }
8976 *timeout_flag = FALSE;
8977}
8978
8979/*
8980 * Start the timeout timer.
8981 *
8982 * The period is defined in milliseconds.
8983 *
8984 * The return value is a pointer to a flag that is initialised to 0. If the
8985 * timeout expires, the flag is set to 1. This will only return pointers to
8986 * static memory; i.e. any pointer returned by this function may always be
8987 * safely dereferenced.
8988 *
8989 * This function is not expected to fail, but if it does it still returns a
8990 * valid flag pointer; the flag will remain stuck at zero.
8991 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008992 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01008993start_timeout(long msec)
8994{
Paul Ollis65745772022-06-05 16:55:54 +01008995 BOOL ret;
8996
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008997 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01008998
8999 stop_timeout();
9000 ret = CreateTimerQueueTimer(
9001 &timer_handle, NULL, set_flag, timeout_flag,
9002 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
9003 if (!ret)
9004 {
9005 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
9006 }
9007 else
9008 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01009009 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01009010 timer_active = TRUE;
9011 *timeout_flag = FALSE;
9012 }
9013 return timeout_flag;
9014}
9015#endif