blob: 550a335bd5415614948e9f0fb9a2ed62057bf21d [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
469 // as the maximum length that works (plus a NUL byte).
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100470#define MAX_ENV_PATH_LEN 8192
471 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200472 char_u *p;
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();
485 if (exe_name != NULL)
486 vim_free(exe_name);
487 exe_name = utf16_to_enc(buf, NULL);
488 enc_prev = enc_codepage;
489
490 WCHAR *wp = wcsrchr(buf, '\\');
491 if (wp != NULL)
492 *wp = NUL;
493 if (exe_pathw != NULL)
494 vim_free(exe_pathw);
495 exe_pathw = _wcsdup(buf);
496 updated = TRUE;
497 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000498 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000499
K.Takatace3189d2023-02-15 19:13:43 +0000500 if (exe_pathw == NULL || !updated)
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000501 return;
502
K.Takatace3189d2023-02-15 19:13:43 +0000503 char_u *exe_path = utf16_to_enc(exe_pathw, NULL);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000504 if (exe_path == NULL)
505 return;
506
507 // Append our starting directory to $PATH, so that when doing
508 // "!xxd" it's found in our starting directory. Needed because
509 // SearchPath() also looks there.
510 p = mch_getenv("PATH");
511 if (p == NULL
512 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000513 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000514 if (p == NULL || *p == NUL)
515 temp[0] = NUL;
516 else
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000517 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000518 STRCPY(temp, p);
519 STRCAT(temp, ";");
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000520 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000521 STRCAT(temp, exe_path);
522 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000523 }
K.Takatace3189d2023-02-15 19:13:43 +0000524 vim_free(exe_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000525}
526
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200527/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100528 * Unescape characters in "p" that appear in "escaped".
529 */
530 static void
531unescape_shellxquote(char_u *p, char_u *escaped)
532{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100533 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100534 int n;
535
536 while (*p != NUL)
537 {
538 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
539 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100540 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100541 p += n;
542 l -= n;
543 }
544}
545
546/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200547 * Load library "name".
548 */
549 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000550vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200551{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200552 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200553
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200554 // No need to load any library when registering OLE.
555 if (found_register_arg)
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000556 return NULL;
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200557
Bram Moolenaar0f873732019-12-05 20:28:46 +0100558 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
559 // vimLoadLib() recursively, which causes a stack overflow.
K.Takatace3189d2023-02-15 19:13:43 +0000560 if (exe_pathw == NULL)
561 mch_get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200562
K.Takatace3189d2023-02-15 19:13:43 +0000563 if (exe_pathw == NULL)
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000564 return NULL;
565
566 WCHAR old_dirw[MAXPATHL];
567
568 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) == 0)
569 return NULL;
570
571 // Change directory to where the executable is, both to make
572 // sure we find a .dll there and to avoid looking for a .dll
573 // in the current directory.
K.Takatace3189d2023-02-15 19:13:43 +0000574 SetCurrentDirectoryW(exe_pathw);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000575 dll = LoadLibrary(name);
576 SetCurrentDirectoryW(old_dirw);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200577 return dll;
578}
579
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200580#if defined(VIMDLL) || defined(PROTO)
581/*
582 * Check if the current executable file is for the GUI subsystem.
583 */
584 int
585mch_is_gui_executable(void)
586{
587 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
588 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
589 PIMAGE_NT_HEADERS pPE;
590
591 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
592 return FALSE;
593 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
594 if (pPE->Signature != IMAGE_NT_SIGNATURE)
595 return FALSE;
596 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
597 return TRUE;
598 return FALSE;
599}
600#endif
601
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000602#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
603 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100604/*
605 * Get related information about 'funcname' which is imported by 'hInst'.
606 * If 'info' is 0, return the function address.
607 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000608 * If 'info' is 2, hook the function with 'ptr', and return the original
609 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100610 */
611 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000612get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
613 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100614{
615 PBYTE pImage = (PBYTE)hInst;
616 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
617 PIMAGE_NT_HEADERS pPE;
618 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100619 PIMAGE_THUNK_DATA pIAT; // Import Address Table
620 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100621 PIMAGE_IMPORT_BY_NAME pImpName;
622
623 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
624 return NULL;
625 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
626 if (pPE->Signature != IMAGE_NT_SIGNATURE)
627 return NULL;
628 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
629 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
630 .VirtualAddress);
631 for (; pImpDesc->FirstThunk; ++pImpDesc)
632 {
633 if (!pImpDesc->OriginalFirstThunk)
634 continue;
635 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
636 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
637 for (; pIAT->u1.Function; ++pIAT, ++pINT)
638 {
639 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
640 continue;
641 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
642 + (UINT_PTR)(pINT->u1.AddressOfData));
643 if (strcmp((char *)pImpName->Name, funcname) == 0)
644 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000645 void *original;
646 DWORD old, new = PAGE_READWRITE;
647
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100648 switch (info)
649 {
650 case 0:
651 return (void *)pIAT->u1.Function;
652 case 1:
653 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000654 case 2:
655 original = (void *)pIAT->u1.Function;
656 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
657 new, &old);
658 pIAT->u1.Function = (UINT_PTR)ptr;
659 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
660 old, &new);
661 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100662 default:
663 return NULL;
664 }
665 }
666 }
667 }
668 return NULL;
669}
670
671/*
672 * Get the module handle which 'funcname' in 'hInst' is imported from.
673 */
674 HINSTANCE
675find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
676{
677 char *modulename;
678
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000679 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100680 if (modulename != NULL)
681 return GetModuleHandleA(modulename);
682 return NULL;
683}
684
685/*
686 * Get the address of 'funcname' which is imported by 'hInst' DLL.
687 */
688 void *
689get_dll_import_func(HINSTANCE hInst, const char *funcname)
690{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000691 return get_imported_func_info(hInst, funcname, 0, NULL);
692}
693
694/*
695 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
696 * and return the original function address.
697 */
698 void *
699hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
700{
701 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100702}
703#endif
704
Bram Moolenaar071d4272004-06-13 20:20:40 +0000705#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
706# ifndef GETTEXT_DLL
707# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200708# define GETTEXT_DLL_ALT1 "libintl-8.dll"
709# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000710# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100711// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000712static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200713static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000714static char *null_libintl_textdomain(const char *);
715static char *null_libintl_bindtextdomain(const char *, const char *);
716static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100717static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000718
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200719static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000720char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200721char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
722 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000723char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
724char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000725 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000726char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
727 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100728int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000729
730 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100731dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000732{
733 int i;
734 static struct
735 {
736 char *name;
737 FARPROC *ptr;
738 } libintl_entry[] =
739 {
740 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200741 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000742 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
743 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
744 {NULL, NULL}
745 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100746 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000747
Bram Moolenaar7554c542018-10-06 15:03:15 +0200748 // No need to initialize twice.
749 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000750 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200751 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100752 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100753# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100754 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200755 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100756# endif
757# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200758 if (!hLibintlDLL)
759 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100760# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100761 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000762 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200763 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000764 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200765 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000766 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200767 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000768 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200769 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000770 }
771 for (i = 0; libintl_entry[i].name != NULL
772 && libintl_entry[i].ptr != NULL; ++i)
773 {
K.Takata54119102022-02-03 13:33:03 +0000774 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000775 libintl_entry[i].name)) == NULL)
776 {
777 dyn_libintl_end();
778 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000779 {
780 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000781 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000782 verbose_leave();
783 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000784 return 0;
785 }
786 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000787
Bram Moolenaar0f873732019-12-05 20:28:46 +0100788 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100789 dyn_libintl_bind_textdomain_codeset = (char *(*)(const char *, const char *))
790 GetProcAddress(hLibintlDLL, "bind_textdomain_codeset");
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000791 if (dyn_libintl_bind_textdomain_codeset == NULL)
792 dyn_libintl_bind_textdomain_codeset =
793 null_libintl_bind_textdomain_codeset;
794
Bram Moolenaar0f873732019-12-05 20:28:46 +0100795 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100796 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
797 if (hmsvcrt != NULL)
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100798 dyn_libintl_wputenv = (int (*)(const wchar_t *))
799 GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100800 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
801 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100802
Bram Moolenaar071d4272004-06-13 20:20:40 +0000803 return 1;
804}
805
806 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100807dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000808{
809 if (hLibintlDLL)
810 FreeLibrary(hLibintlDLL);
811 hLibintlDLL = NULL;
812 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200813 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000814 dyn_libintl_textdomain = null_libintl_textdomain;
815 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000816 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100817 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000818}
819
820 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000821null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000822{
823 return (char*)msgid;
824}
825
826 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200827null_libintl_ngettext(
828 const char *msgid,
829 const char *msgid_plural,
830 unsigned long n)
831{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200832 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200833}
834
Bram Moolenaaree695f72016-08-03 22:08:45 +0200835 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100836null_libintl_bindtextdomain(
837 const char *domainname UNUSED,
838 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000839{
840 return NULL;
841}
842
843 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100844null_libintl_bind_textdomain_codeset(
845 const char *domainname UNUSED,
846 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000847{
848 return NULL;
849}
850
851 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100852null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000853{
854 return NULL;
855}
856
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200857 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100858null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100859{
860 return 0;
861}
862
Bram Moolenaar0f873732019-12-05 20:28:46 +0100863#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000864
Bram Moolenaar0f873732019-12-05 20:28:46 +0100865// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000866
867#ifndef VER_PLATFORM_WIN32_WINDOWS
868# define VER_PLATFORM_WIN32_WINDOWS 1
869#endif
870
Bram Moolenaar071d4272004-06-13 20:20:40 +0000871#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100872# ifndef PROTO
873# include <aclapi.h>
874# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200875# ifndef PROTECTED_DACL_SECURITY_INFORMATION
876# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
877# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000878#endif
879
Bram Moolenaar27515922013-06-29 15:36:26 +0200880#ifdef HAVE_ACL
881/*
882 * Enables or disables the specified privilege.
883 */
884 static BOOL
885win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
886{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100887 BOOL bResult;
888 LUID luid;
889 HANDLE hToken;
890 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200891
892 if (!OpenProcessToken(GetCurrentProcess(),
893 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
894 return FALSE;
895
896 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
897 {
898 CloseHandle(hToken);
899 return FALSE;
900 }
901
Bram Moolenaar45500912014-07-09 20:51:07 +0200902 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200903 tokenPrivileges.Privileges[0].Luid = luid;
904 tokenPrivileges.Privileges[0].Attributes = bEnable ?
905 SE_PRIVILEGE_ENABLED : 0;
906
907 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
908 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
909
910 CloseHandle(hToken);
911
912 return bResult && GetLastError() == ERROR_SUCCESS;
913}
914#endif
915
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100916#ifdef _MSC_VER
917// Suppress the deprecation warning for using GetVersionEx().
918// It is needed for implementing "windowsversion()".
919# pragma warning(push)
920# pragma warning(disable: 4996)
921#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000922/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200923 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000924 */
925 void
926PlatformId(void)
927{
928 static int done = FALSE;
929
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000930 if (done)
931 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000932
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000933 OSVERSIONINFO ovi;
934
935 ovi.dwOSVersionInfoSize = sizeof(ovi);
936 GetVersionEx(&ovi);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000937
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200938#ifdef FEAT_EVAL
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000939 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
940 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200941#endif
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000942 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
943 || ovi.dwMajorVersion > 6)
944 win8_or_later = TRUE;
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100945
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000946 if ((ovi.dwMajorVersion == 10 && ovi.dwBuildNumber >= 19045)
947 || ovi.dwMajorVersion > 10)
948 win10_22H2_or_later = TRUE;
Christopher Plewright1140b512022-11-12 18:46:05 +0000949
Bram Moolenaar071d4272004-06-13 20:20:40 +0000950#ifdef HAVE_ACL
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000951 // Enable privilege for getting or setting SACLs.
952 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000953#endif
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000954 done = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000955}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100956#ifdef _MSC_VER
957# pragma warning(pop)
958#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000959
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200960#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000961
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100962# define SHIFT (SHIFT_PRESSED)
963# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
964# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
965# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000966
967
Bram Moolenaar0f873732019-12-05 20:28:46 +0100968// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
969// We map function keys to their ANSI terminal equivalents, as produced
970// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
971// ANSI key with a value >= '\300' is nonstandard, but provided anyway
972// so that the user can have access to all SHIFT-, CTRL-, and ALT-
973// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000974
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000975static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000976{
977 WORD wVirtKey;
978 BOOL fAnsiKey;
979 int chAlone;
980 int chShift;
981 int chCtrl;
982 int chAlt;
983} VirtKeyMap[] =
984{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200985// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000986 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
987
988 { VK_F1, TRUE, ';', 'T', '^', 'h', },
989 { VK_F2, TRUE, '<', 'U', '_', 'i', },
990 { VK_F3, TRUE, '=', 'V', '`', 'j', },
991 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
992 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
993 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
994 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
995 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
996 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
997 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200998 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
999 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001000
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001001 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
1002 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
1003 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
1004 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
1005 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
1006 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
1007 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
1008 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
1009 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
1010 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001011 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +00001012
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001013 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +00001014
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001015# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001016 // Most people don't have F13-F20, but what the hell...
1017 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
1018 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
1019 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
1020 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
1021 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
1022 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
1023 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
1024 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001025# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001026 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
1027 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
1028 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
1029 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001030
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001031 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
1032 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
1033 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
1034 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
1035 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
1036 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
1037 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
1038 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
1039 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
1040 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001041 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001042};
1043
1044
Bram Moolenaar0f873732019-12-05 20:28:46 +01001045/*
1046 * The return code indicates key code size.
1047 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001048 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001049win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001050 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001051{
1052 UINT uMods = pker->dwControlKeyState;
1053 static int s_iIsDead = 0;
1054 static WORD awAnsiCode[2];
1055 static BYTE abKeystate[256];
1056
1057
1058 if (s_iIsDead == 2)
1059 {
K.Takata972db232022-02-04 10:45:38 +00001060 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001061 s_iIsDead = 0;
1062 return 1;
1063 }
1064
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001065 // check if it already has a valid unicode character.
Christopher Plewright566f76e2023-01-10 13:43:04 +00001066 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001067 return 1;
1068
Bram Moolenaara80faa82020-04-12 19:37:17 +02001069 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001070
Bram Moolenaar0f873732019-12-05 20:28:46 +01001071 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001072 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001073
1074 if (uMods & SHIFT_PRESSED)
1075 abKeystate[VK_SHIFT] = 0x80;
1076 if (uMods & CAPSLOCK_ON)
1077 abKeystate[VK_CAPITAL] = 1;
1078
1079 if ((uMods & ALT_GR) == ALT_GR)
1080 {
1081 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1082 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1083 }
1084
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001085 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1086 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001087
1088 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001089 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001090
1091 return s_iIsDead;
1092}
1093
Bram Moolenaar071d4272004-06-13 20:20:40 +00001094static BOOL g_fJustGotFocus = FALSE;
1095
1096/*
1097 * Decode a KEY_EVENT into one or two keystrokes
1098 */
1099 static BOOL
1100decode_key_event(
1101 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001102 WCHAR *pch,
1103 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001104 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001105 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001106{
1107 int i;
1108 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1109
1110 *pch = *pch2 = NUL;
1111 g_fJustGotFocus = FALSE;
1112
Bram Moolenaar0f873732019-12-05 20:28:46 +01001113 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001114 if (!pker->bKeyDown)
1115 return FALSE;
1116
Bram Moolenaar0f873732019-12-05 20:28:46 +01001117 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001118 switch (pker->wVirtualKeyCode)
1119 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001120 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001121 case VK_SHIFT:
1122 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001123 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001124 return FALSE;
1125
1126 default:
1127 break;
1128 }
1129
Bram Moolenaar0f873732019-12-05 20:28:46 +01001130 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001131 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1132 {
1133 *pch = K_NUL;
1134 *pch2 = '\017';
1135 return TRUE;
1136 }
1137
K.Takataeeec2542021-06-02 13:28:16 +02001138 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001139 {
1140 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1141 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001142 *pch = VirtKeyMap[i].chAlone;
1143 if ((nModifs & SHIFT) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001144 *pch = VirtKeyMap[i].chShift;
1145 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1146 *pch = VirtKeyMap[i].chCtrl;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001147 else if ((nModifs & ALT) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001148 *pch = VirtKeyMap[i].chAlt;
1149
1150 if (*pch != 0)
1151 {
1152 if (VirtKeyMap[i].fAnsiKey)
1153 {
1154 *pch2 = *pch;
1155 *pch = K_NUL;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001156 if (pmodifiers)
1157 {
1158 if (pker->wVirtualKeyCode >= VK_F1
1159 && pker->wVirtualKeyCode <= VK_F12)
1160 {
1161 if ((nModifs & ALT) != 0)
1162 {
1163 *pmodifiers |= MOD_MASK_ALT;
1164 if ((nModifs & SHIFT) == 0)
1165 *pch2 = VirtKeyMap[i].chAlone;
1166 }
1167 if ((nModifs & CTRL) != 0)
1168 {
1169 *pmodifiers |= MOD_MASK_CTRL;
1170 if ((nModifs & SHIFT) == 0)
1171 *pch2 = VirtKeyMap[i].chAlone;
1172 }
1173 }
1174 else if (pker->wVirtualKeyCode >= VK_END
1175 && pker->wVirtualKeyCode <= VK_DOWN)
1176 {
Christopher Plewright566f76e2023-01-10 13:43:04 +00001177 // (0x23 - 0x28): VK_END, VK_HOME,
1178 // VK_LEFT, VK_UP, VK_RIGHT, VK_DOWN
1179
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001180 *pmodifiers = 0;
1181 *pch2 = VirtKeyMap[i].chAlone;
1182 if ((nModifs & SHIFT) != 0
1183 && (nModifs & ~SHIFT) == 0)
1184 {
1185 *pch2 = VirtKeyMap[i].chShift;
1186 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001187 if ((nModifs & CTRL) != 0
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001188 && (nModifs & ~CTRL) == 0)
1189 {
1190 *pch2 = VirtKeyMap[i].chCtrl;
1191 if (pker->wVirtualKeyCode == VK_UP
1192 || pker->wVirtualKeyCode == VK_DOWN)
1193 {
1194 *pmodifiers |= MOD_MASK_CTRL;
1195 *pch2 = VirtKeyMap[i].chAlone;
1196 }
1197 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001198 if ((nModifs & SHIFT) != 0
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001199 && (nModifs & CTRL) != 0)
1200 {
1201 *pmodifiers |= MOD_MASK_CTRL;
1202 *pch2 = VirtKeyMap[i].chShift;
1203 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001204 if ((nModifs & ALT) != 0)
1205 {
1206 *pch2 = VirtKeyMap[i].chAlt;
1207 *pmodifiers |= MOD_MASK_ALT;
1208 if ((nModifs & ~ALT) == 0)
1209 {
1210 *pch2 = VirtKeyMap[i].chAlone;
1211 }
1212 else if ((nModifs & SHIFT) != 0)
1213 {
1214 *pch2 = VirtKeyMap[i].chShift;
1215 }
1216 else if ((nModifs & CTRL) != 0)
1217 {
1218 if (pker->wVirtualKeyCode == VK_UP
1219 || pker->wVirtualKeyCode == VK_DOWN)
1220 {
1221 *pmodifiers |= MOD_MASK_CTRL;
1222 *pch2 = VirtKeyMap[i].chAlone;
1223 }
1224 else
1225 {
1226 *pch2 = VirtKeyMap[i].chCtrl;
1227 }
1228 }
1229 }
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001230 }
1231 else
1232 {
1233 *pch2 = VirtKeyMap[i].chAlone;
1234 if ((nModifs & SHIFT) != 0)
1235 *pmodifiers |= MOD_MASK_SHIFT;
1236 if ((nModifs & CTRL) != 0)
1237 *pmodifiers |= MOD_MASK_CTRL;
1238 if ((nModifs & ALT) != 0)
1239 *pmodifiers |= MOD_MASK_ALT;
1240 }
1241 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001242 }
1243
1244 return TRUE;
1245 }
1246 }
1247 }
1248
1249 i = win32_kbd_patch_key(pker);
1250
1251 if (i < 0)
1252 *pch = NUL;
1253 else
1254 {
K.Takata972db232022-02-04 10:45:38 +00001255 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001256
1257 if (pmodifiers != NULL)
1258 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001259 // Pass on the ALT key as a modifier, but only when not combined
1260 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001261 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1262 *pmodifiers |= MOD_MASK_ALT;
1263
Bram Moolenaar0f873732019-12-05 20:28:46 +01001264 // Pass on SHIFT only for special keys, because we don't know when
1265 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001266 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1267 *pmodifiers |= MOD_MASK_SHIFT;
1268
Bram Moolenaar0f873732019-12-05 20:28:46 +01001269 // Pass on CTRL only for non-special keys, because we don't know
1270 // when it's already included with the character. And not when
1271 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001272 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1273 && *pch >= 0x20 && *pch < 0x80)
1274 *pmodifiers |= MOD_MASK_CTRL;
1275 }
1276 }
1277
1278 return (*pch != NUL);
1279}
1280
Christopher Plewright20b795e2022-12-20 20:01:58 +00001281# if defined(FEAT_EVAL)
1282 static int
1283encode_key_event(dict_T *args, INPUT_RECORD *ir)
1284{
1285 static int s_dwMods = 0;
1286
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001287 char_u *action = dict_get_string(args, "event", TRUE);
1288 if (action && (STRICMP(action, "keydown") == 0
1289 || STRICMP(action, "keyup") == 0))
Christopher Plewright20b795e2022-12-20 20:01:58 +00001290 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001291 BOOL isKeyDown = STRICMP(action, "keydown") == 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001292 WORD vkCode = dict_get_number_def(args, "keycode", 0);
1293 if (vkCode <= 0 || vkCode >= 0xFF)
1294 {
1295 semsg(_(e_invalid_argument_nr), (long)vkCode);
1296 return FALSE;
1297 }
1298
1299 ir->EventType = KEY_EVENT;
1300 KEY_EVENT_RECORD ker;
1301 ZeroMemory(&ker, sizeof(ker));
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001302 ker.bKeyDown = isKeyDown;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001303 ker.wRepeatCount = 1;
1304 ker.wVirtualScanCode = 0;
1305 ker.dwControlKeyState = 0;
1306 int mods = (int)dict_get_number(args, "modifiers");
1307 // Encode the win32 console key modifiers from Vim keyboard modifiers.
1308 if (mods)
1309 {
1310 // If "modifiers" is explicitly set in the args, then we reset any
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00001311 // remembered modifier key state that may have been set from
1312 // earlier mod-key-down events, even if they are not yet unset by
1313 // earlier mod-key-up events.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001314 s_dwMods = 0;
1315 if (mods & MOD_MASK_SHIFT)
1316 ker.dwControlKeyState |= SHIFT_PRESSED;
1317 if (mods & MOD_MASK_CTRL)
1318 ker.dwControlKeyState |= LEFT_CTRL_PRESSED;
1319 if (mods & MOD_MASK_ALT)
1320 ker.dwControlKeyState |= LEFT_ALT_PRESSED;
1321 }
1322
1323 if (vkCode == VK_LSHIFT || vkCode == VK_RSHIFT || vkCode == VK_SHIFT)
1324 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001325 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001326 s_dwMods |= SHIFT_PRESSED;
1327 else
1328 s_dwMods &= ~SHIFT_PRESSED;
1329 }
1330 else if (vkCode == VK_LCONTROL || vkCode == VK_CONTROL)
1331 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001332 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001333 s_dwMods |= LEFT_CTRL_PRESSED;
1334 else
1335 s_dwMods &= ~LEFT_CTRL_PRESSED;
1336 }
1337 else if (vkCode == VK_RCONTROL)
1338 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001339 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001340 s_dwMods |= RIGHT_CTRL_PRESSED;
1341 else
1342 s_dwMods &= ~RIGHT_CTRL_PRESSED;
1343 }
1344 else if (vkCode == VK_LMENU || vkCode == VK_MENU)
1345 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001346 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001347 s_dwMods |= LEFT_ALT_PRESSED;
1348 else
1349 s_dwMods &= ~LEFT_ALT_PRESSED;
1350 }
1351 else if (vkCode == VK_RMENU)
1352 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001353 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001354 s_dwMods |= RIGHT_ALT_PRESSED;
1355 else
1356 s_dwMods &= ~RIGHT_ALT_PRESSED;
1357 }
1358 ker.dwControlKeyState |= s_dwMods;
1359 ker.wVirtualKeyCode = vkCode;
Christopher Plewright566f76e2023-01-10 13:43:04 +00001360 ker.uChar.UnicodeChar = 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001361 ir->Event.KeyEvent = ker;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001362 vim_free(action);
Christopher Plewright20b795e2022-12-20 20:01:58 +00001363 }
1364 else
1365 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001366 if (action == NULL)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001367 {
1368 semsg(_(e_missing_argument_str), "event");
1369 }
1370 else
1371 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001372 semsg(_(e_invalid_value_for_argument_str_str), "event", action);
1373 vim_free(action);
Christopher Plewright20b795e2022-12-20 20:01:58 +00001374 }
1375 return FALSE;
1376 }
1377 return TRUE;
1378}
1379# endif // FEAT_EVAL
1380#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00001381
1382
Bram Moolenaar071d4272004-06-13 20:20:40 +00001383/*
1384 * For the GUI the mouse handling is in gui_w32.c.
1385 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001386#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001387 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001388mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001389{
1390}
Christopher Plewright20b795e2022-12-20 20:01:58 +00001391#else // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar0f873732019-12-05 20:28:46 +01001392static int g_fMouseAvail = FALSE; // mouse present
1393static int g_fMouseActive = FALSE; // mouse enabled
1394static int g_nMouseClick = -1; // mouse status
1395static int g_xMouse; // mouse x coordinate
1396static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001397static DWORD g_cmodein = 0; // Original console input mode
1398static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001399
1400/*
1401 * Enable or disable mouse input
1402 */
1403 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001404mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001405{
1406 DWORD cmodein;
1407
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001408# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001409 if (gui.in_use)
1410 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001411# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001412 if (!g_fMouseAvail)
1413 return;
1414
1415 g_fMouseActive = on;
1416 GetConsoleMode(g_hConIn, &cmodein);
1417
1418 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001419 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001420 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001421 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1422 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001423 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001424 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001425 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001426 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1427 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001428
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001429 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001430}
1431
Bram Moolenaar157d8132018-03-06 17:09:20 +01001432
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001433# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001434/*
1435 * Called when 'balloonevalterm' changed.
1436 */
1437 void
1438mch_bevalterm_changed(void)
1439{
1440 mch_setmouse(g_fMouseActive);
1441}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001442# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001443
Christopher Plewright2a46f812022-10-16 19:47:45 +01001444/*
1445 * Win32 console mouse scroll event handler.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001446 * Console version of the _OnMouseWheel() function in gui_w32.c
Christopher Plewright2a46f812022-10-16 19:47:45 +01001447 *
1448 * This encodes the mouse scroll direction and keyboard modifiers into
1449 * g_nMouseClick, and the mouse position into g_xMouse and g_yMouse
1450 *
1451 * The direction of the scroll is decoded from two fields of the win32 console
1452 * mouse event record;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001453 * 1. The orientation - vertical or horizontal flag - from dwEventFlags
Christopher Plewright2a46f812022-10-16 19:47:45 +01001454 * 2. The sign - positive or negative (aka delta flag) - from dwButtonState
1455 *
Christopher Plewright20b795e2022-12-20 20:01:58 +00001456 * When scroll orientation is HORIZONTAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001457 * - If the high word of the dwButtonState member contains a positive
1458 * value, the wheel was rotated to the right.
1459 * - Otherwise, the wheel was rotated to the left.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001460 * When scroll orientation is VERTICAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001461 * - If the high word of the dwButtonState member contains a positive value,
1462 * the wheel was rotated forward, away from the user.
1463 * - Otherwise, the wheel was rotated backward, toward the user.
1464 */
1465 static void
1466decode_mouse_wheel(MOUSE_EVENT_RECORD *pmer)
1467{
Christopher Plewright2a46f812022-10-16 19:47:45 +01001468 int horizontal = (pmer->dwEventFlags == MOUSE_HWHEELED);
1469 int zDelta = pmer->dwButtonState;
1470
1471 g_xMouse = pmer->dwMousePosition.X;
1472 g_yMouse = pmer->dwMousePosition.Y;
1473
K.Takata161b6ac2022-11-14 15:31:07 +00001474# ifdef FEAT_PROP_POPUP
Christopher Plewright605d02a2022-10-19 11:54:46 +01001475 int lcol = g_xMouse;
1476 int lrow = g_yMouse;
Christopher Plewright38804d62022-11-09 23:55:52 +00001477 win_T *wp = mouse_find_win(&lrow, &lcol, FIND_POPUP);
Christopher Plewright2a46f812022-10-16 19:47:45 +01001478 if (wp != NULL && popup_is_popup(wp))
1479 {
1480 g_nMouseClick = -1;
1481 cmdarg_T cap;
1482 oparg_T oa;
1483 CLEAR_FIELD(cap);
1484 clear_oparg(&oa);
1485 cap.oap = &oa;
1486 if (horizontal)
1487 {
1488 cap.arg = zDelta < 0 ? MSCR_LEFT : MSCR_RIGHT;
1489 cap.cmdchar = zDelta < 0 ? K_MOUSELEFT : K_MOUSERIGHT;
1490 }
1491 else
1492 {
1493 cap.cmdchar = zDelta < 0 ? K_MOUSEUP : K_MOUSEDOWN;
1494 cap.arg = zDelta < 0 ? MSCR_UP : MSCR_DOWN;
1495 }
1496
1497 // Mouse hovers over popup window, scroll it if possible.
1498 mouse_row = wp->w_winrow;
1499 mouse_col = wp->w_wincol;
1500 nv_mousescroll(&cap);
1501 update_screen(0);
1502 setcursor();
1503 out_flush();
1504 return;
1505 }
K.Takata161b6ac2022-11-14 15:31:07 +00001506# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01001507 mouse_col = g_xMouse;
1508 mouse_row = g_yMouse;
1509
1510 char_u modifiers = 0;
1511 char_u direction = 0;
1512
1513 // Decode the direction into an event that Vim can process
1514 if (horizontal)
1515 direction = zDelta >= 0 ? KE_MOUSELEFT : KE_MOUSERIGHT;
1516 else
1517 direction = zDelta >= 0 ? KE_MOUSEDOWN : KE_MOUSEUP;
1518
dundargocc57b5bc2022-11-02 13:30:51 +00001519 // Decode the win32 console key modifiers into Vim mouse modifiers.
Christopher Plewright2a46f812022-10-16 19:47:45 +01001520 if (pmer->dwControlKeyState & SHIFT_PRESSED)
Christopher Plewright605d02a2022-10-19 11:54:46 +01001521 modifiers |= MOD_MASK_SHIFT; // MOUSE_SHIFT;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001522 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
Christopher Plewright605d02a2022-10-19 11:54:46 +01001523 modifiers |= MOD_MASK_CTRL; // MOUSE_CTRL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001524 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1525 modifiers |= MOD_MASK_ALT; // MOUSE_ALT;
1526
1527 // add (bitwise or) the scroll direction and the key modifier chars
1528 // together.
1529 g_nMouseClick = ((direction << 8) | modifiers);
1530
1531 return;
1532}
1533
Bram Moolenaar071d4272004-06-13 20:20:40 +00001534/*
1535 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1536 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1537 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1538 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1539 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1540 * and we return the mouse position in g_xMouse and g_yMouse.
1541 *
1542 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1543 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1544 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1545 *
1546 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1547 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1548 *
1549 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1550 * moves, even if it stays within the same character cell. We ignore
1551 * all MOUSE_MOVED messages if the position hasn't really changed, and
1552 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1553 * we're only interested in MOUSE_DRAG).
1554 *
1555 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1556 * 2-button mouses by pressing the left & right buttons simultaneously.
1557 * In practice, it's almost impossible to click both at the same time,
1558 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1559 * in such cases, if the user is clicking quickly.
1560 */
1561 static BOOL
1562decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001563 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001564{
1565 static int s_nOldButton = -1;
1566 static int s_nOldMouseClick = -1;
1567 static int s_xOldMouse = -1;
1568 static int s_yOldMouse = -1;
1569 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001570# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001571 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001572# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001573 static int s_cClicks = 1;
1574 static BOOL s_fReleased = TRUE;
1575 static DWORD s_dwLastClickTime = 0;
1576 static BOOL s_fNextIsMiddle = FALSE;
1577
Bram Moolenaar0f873732019-12-05 20:28:46 +01001578 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001579
1580 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1581 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1582 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1583 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1584
1585 int nButton;
1586
1587 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1588 cButtons = 2;
1589
1590 if (!g_fMouseAvail || !g_fMouseActive)
1591 {
1592 g_nMouseClick = -1;
1593 return FALSE;
1594 }
1595
Bram Moolenaar0f873732019-12-05 20:28:46 +01001596 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001597 if (g_fJustGotFocus)
1598 {
1599 g_fJustGotFocus = FALSE;
1600 return FALSE;
1601 }
1602
Christopher Plewright605d02a2022-10-19 11:54:46 +01001603 // If there is an unprocessed mouse click drop this one.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001604 if (g_nMouseClick != -1)
1605 return TRUE;
Christopher Plewright605d02a2022-10-19 11:54:46 +01001606
Christopher Plewright2a46f812022-10-16 19:47:45 +01001607 if (pmer->dwEventFlags == MOUSE_WHEELED
1608 || pmer->dwEventFlags == MOUSE_HWHEELED)
1609 {
1610 decode_mouse_wheel(pmer);
1611 return TRUE; // we now should have a mouse scroll in g_nMouseClick
1612 }
Christopher Plewright605d02a2022-10-19 11:54:46 +01001613
Bram Moolenaar071d4272004-06-13 20:20:40 +00001614 nButton = -1;
1615 g_xMouse = pmer->dwMousePosition.X;
1616 g_yMouse = pmer->dwMousePosition.Y;
1617
1618 if (pmer->dwEventFlags == MOUSE_MOVED)
1619 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001620 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1621 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001622 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1623 return FALSE;
1624 }
1625
Bram Moolenaar0f873732019-12-05 20:28:46 +01001626 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001627 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1628 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001629 nButton = MOUSE_RELEASE;
1630
Bram Moolenaar0f873732019-12-05 20:28:46 +01001631 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001632 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001633 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001634# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001635 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001636 if (p_bevalterm)
1637 nButton = MOUSE_DRAG;
1638 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001639# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001640 return FALSE;
1641 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001642
Bram Moolenaar071d4272004-06-13 20:20:40 +00001643 s_fReleased = TRUE;
1644 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001645 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001646 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001647 // on a 2-button mouse, hold down left and right buttons
1648 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001649
1650 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1651 {
1652 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1653
Bram Moolenaar0f873732019-12-05 20:28:46 +01001654 // if either left or right button only is pressed, see if the
1655 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001656 if (dwLR == LEFT || dwLR == RIGHT)
1657 {
1658 for (;;)
1659 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001660 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001661 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1662 != WAIT_OBJECT_0)
1663 break;
1664 else
1665 {
1666 DWORD cRecords = 0;
1667 INPUT_RECORD ir;
1668 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1669
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001670 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001671
1672 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1673 || !(pmer2->dwButtonState & LEFT_RIGHT))
1674 break;
1675 else
1676 {
1677 if (pmer2->dwEventFlags != MOUSE_MOVED)
1678 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001679 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001680
1681 return decode_mouse_event(pmer2);
1682 }
1683 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1684 s_yOldMouse == pmer2->dwMousePosition.Y)
1685 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001686 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001687 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001688
Bram Moolenaar0f873732019-12-05 20:28:46 +01001689 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001690 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001691
1692 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1693 break;
1694 }
1695 else
1696 break;
1697 }
1698 }
1699 }
1700 }
1701 }
1702
1703 if (s_fNextIsMiddle)
1704 {
1705 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1706 ? MOUSE_DRAG : MOUSE_MIDDLE;
1707 s_fNextIsMiddle = FALSE;
1708 }
1709 else if (cButtons == 2 &&
1710 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1711 {
1712 nButton = MOUSE_MIDDLE;
1713
1714 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1715 {
1716 s_fNextIsMiddle = TRUE;
1717 nButton = MOUSE_RELEASE;
1718 }
1719 }
1720 else if ((pmer->dwButtonState & LEFT) == LEFT)
1721 nButton = MOUSE_LEFT;
1722 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1723 nButton = MOUSE_MIDDLE;
1724 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1725 nButton = MOUSE_RIGHT;
1726
1727 if (! s_fReleased && ! s_fNextIsMiddle
1728 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1729 return FALSE;
1730
1731 s_fReleased = s_fNextIsMiddle;
1732 }
1733
1734 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1735 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001736 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001737 if (nButton != -1 && nButton != MOUSE_RELEASE)
1738 {
1739 DWORD dwCurrentTime = GetTickCount();
1740
1741 if (s_xOldMouse != g_xMouse
1742 || s_yOldMouse != g_yMouse
1743 || s_nOldButton != nButton
1744 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001745# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001746 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001747# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001748 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1749 {
1750 s_cClicks = 1;
1751 }
1752 else if (++s_cClicks > 4)
1753 {
1754 s_cClicks = 1;
1755 }
1756
1757 s_dwLastClickTime = dwCurrentTime;
1758 }
1759 }
1760 else if (pmer->dwEventFlags == MOUSE_MOVED)
1761 {
1762 if (nButton != -1 && nButton != MOUSE_RELEASE)
1763 nButton = MOUSE_DRAG;
1764
1765 s_cClicks = 1;
1766 }
1767
1768 if (nButton == -1)
1769 return FALSE;
1770
1771 if (nButton != MOUSE_RELEASE)
1772 s_nOldButton = nButton;
1773
1774 g_nMouseClick = nButton;
1775
1776 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1777 g_nMouseClick |= MOUSE_SHIFT;
1778 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1779 g_nMouseClick |= MOUSE_CTRL;
1780 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1781 g_nMouseClick |= MOUSE_ALT;
1782
1783 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1784 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1785
Bram Moolenaar0f873732019-12-05 20:28:46 +01001786 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001787 if (s_xOldMouse == g_xMouse
1788 && s_yOldMouse == g_yMouse
1789 && s_nOldMouseClick == g_nMouseClick)
1790 {
1791 g_nMouseClick = -1;
1792 return FALSE;
1793 }
1794
1795 s_xOldMouse = g_xMouse;
1796 s_yOldMouse = g_yMouse;
1797 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001798# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001799 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001800# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001801 s_nOldMouseClick = g_nMouseClick;
1802
1803 return TRUE;
1804}
1805
Christopher Plewright20b795e2022-12-20 20:01:58 +00001806# ifdef FEAT_EVAL
1807 static int
1808encode_mouse_event(dict_T *args, INPUT_RECORD *ir)
1809{
1810 int button;
1811 int row;
1812 int col;
1813 int repeated_click;
Bram Moolenaar9b8a3652022-12-20 20:47:28 +00001814 int_u mods = 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001815 int move;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001816
Christopher Plewright20b795e2022-12-20 20:01:58 +00001817 if (!dict_has_key(args, "row") || !dict_has_key(args, "col"))
1818 return FALSE;
1819
1820 // Note: "move" is optional, requires fewer arguments
1821 move = (int)dict_get_bool(args, "move", FALSE);
1822 if (!move && (!dict_has_key(args, "button")
1823 || !dict_has_key(args, "multiclick")
1824 || !dict_has_key(args, "modifiers")))
1825 return FALSE;
1826
1827 row = (int)dict_get_number(args, "row") - 1;
1828 col = (int)dict_get_number(args, "col") - 1;
1829
1830 ir->EventType = MOUSE_EVENT;
1831 MOUSE_EVENT_RECORD mer;
1832 ZeroMemory(&mer, sizeof(mer));
1833 mer.dwMousePosition.X = col;
1834 mer.dwMousePosition.Y = row;
1835
1836 if (move)
1837 {
1838 mer.dwButtonState = 0;
1839 mer.dwEventFlags = MOUSE_MOVED;
1840 }
1841 else
1842 {
1843 button = (int)dict_get_number(args, "button");
1844 repeated_click = (int)dict_get_number(args, "multiclick");
1845 mods = (int)dict_get_number(args, "modifiers");
1846 // Reset the scroll values to known values.
1847 // XXX: Remove this when/if the scroll step is made configurable.
1848 mouse_set_hor_scroll_step(6);
1849 mouse_set_vert_scroll_step(3);
1850
1851 switch (button)
1852 {
1853 case MOUSE_LEFT:
1854 mer.dwButtonState = FROM_LEFT_1ST_BUTTON_PRESSED;
1855 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1856 break;
1857 case MOUSE_MIDDLE:
1858 mer.dwButtonState = FROM_LEFT_2ND_BUTTON_PRESSED;
1859 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1860 break;
1861 case MOUSE_RIGHT:
1862 mer.dwButtonState = RIGHTMOST_BUTTON_PRESSED;
1863 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1864 break;
1865 case MOUSE_RELEASE:
1866 // umm? Assume Left Release?
1867 mer.dwEventFlags = 0;
1868
1869 case MOUSE_MOVE:
1870 mer.dwButtonState = 0;
1871 mer.dwEventFlags = MOUSE_MOVED;
1872 break;
1873 case MOUSE_X1:
1874 mer.dwButtonState = FROM_LEFT_3RD_BUTTON_PRESSED;
1875 break;
1876 case MOUSE_X2:
1877 mer.dwButtonState = FROM_LEFT_4TH_BUTTON_PRESSED;
1878 break;
1879 case MOUSE_4: // KE_MOUSEDOWN;
1880 mer.dwButtonState = -1;
1881 mer.dwEventFlags = MOUSE_WHEELED;
1882 break;
1883 case MOUSE_5: // KE_MOUSEUP;
1884 mer.dwButtonState = +1;
1885 mer.dwEventFlags = MOUSE_WHEELED;
1886 break;
1887 case MOUSE_6: // KE_MOUSELEFT;
1888 mer.dwButtonState = -1;
1889 mer.dwEventFlags = MOUSE_HWHEELED;
1890 break;
1891 case MOUSE_7: // KE_MOUSERIGHT;
1892 mer.dwButtonState = +1;
1893 mer.dwEventFlags = MOUSE_HWHEELED;
1894 break;
1895 default:
1896 semsg(_(e_invalid_argument_str), "button");
1897 return FALSE;
1898 }
1899 }
1900
1901 mer.dwControlKeyState = 0;
1902 if (mods != 0)
1903 {
1904 // Encode the win32 console key modifiers from Vim MOUSE modifiers.
1905 if (mods & MOUSE_SHIFT)
1906 mer.dwControlKeyState |= SHIFT_PRESSED;
1907 if (mods & MOUSE_CTRL)
1908 mer.dwControlKeyState |= LEFT_CTRL_PRESSED;
1909 if (mods & MOUSE_ALT)
1910 mer.dwControlKeyState |= LEFT_ALT_PRESSED;
1911 }
1912 ir->Event.MouseEvent = mer;
1913 return TRUE;
1914}
1915# endif // FEAT_EVAL
1916
1917 static int
1918write_input_record_buffer(INPUT_RECORD* irEvents, int nLength)
1919{
1920 int nCount = 0;
1921 while (nCount < nLength)
1922 {
1923 input_record_buffer.length++;
1924 input_record_buffer_node_T *event_node =
1925 malloc(sizeof(input_record_buffer_node_T));
1926 event_node->ir = irEvents[nCount++];
1927 event_node->next = NULL;
1928 if (input_record_buffer.tail == NULL)
1929 {
1930 input_record_buffer.head = event_node;
1931 input_record_buffer.tail = event_node;
1932 }
1933 else
1934 {
1935 input_record_buffer.tail->next = event_node;
1936 input_record_buffer.tail = input_record_buffer.tail->next;
1937 }
1938 }
1939 return nCount;
1940}
1941
1942 static int
1943read_input_record_buffer(INPUT_RECORD* irEvents, int nMaxLength)
1944{
1945 int nCount = 0;
1946 while (nCount < nMaxLength && input_record_buffer.head != NULL)
1947 {
1948 input_record_buffer.length--;
1949 input_record_buffer_node_T *pop_head = input_record_buffer.head;
1950 irEvents[nCount++] = pop_head->ir;
1951 input_record_buffer.head = pop_head->next;
1952 vim_free(pop_head);
1953 if (input_record_buffer.length == 0)
1954 input_record_buffer.tail = NULL;
1955 }
1956 return nCount;
1957}
Christopher Plewright20b795e2022-12-20 20:01:58 +00001958#endif // !FEAT_GUI_MSWIN || VIMDLL
1959
1960#ifdef FEAT_EVAL
1961/*
1962 * The 'test_mswin_event' function is for testing Vim's low-level handling of
1963 * user input events. ie, this manages the encoding of INPUT_RECORD events
1964 * so that we have a way to test how Vim decodes INPUT_RECORD events in Windows
1965 * consoles.
1966 *
1967 * The 'test_mswin_event' function is based on 'test_gui_event'. In fact, when
1968 * the Windows GUI is running, the arguments; 'event' and 'args', are the same.
1969 * So, it acts as an alias for 'test_gui_event' for the Windows GUI.
1970 *
1971 * When the Windows console is running, the arguments; 'event' and 'args', are
1972 * a subset of what 'test_gui_event' handles, ie, only "key" and "mouse"
1973 * events are encoded as INPUT_RECORD events.
1974 *
1975 * Note: INPUT_RECORDs are only used by the Windows console, not the GUI. The
1976 * GUI sends MSG structs instead.
1977 */
1978 int
1979test_mswin_event(char_u *event, dict_T *args)
1980{
1981 int lpEventsWritten = 0;
1982
1983# if defined(VIMDLL) || defined(FEAT_GUI_MSWIN)
1984 if (gui.in_use)
1985 return test_gui_w32_sendevent(event, args);
1986# endif
1987
1988# if defined(VIMDLL) || !defined(FEAT_GUI_MSWIN)
1989
1990// Currently implemented event record types are; KEY_EVENT and MOUSE_EVENT
1991// Potentially could also implement: FOCUS_EVENT and WINDOW_BUFFER_SIZE_EVENT
1992// Maybe also: MENU_EVENT
1993
1994 INPUT_RECORD ir;
1995 BOOL input_encoded = FALSE;
Christopher Plewright7b0afc12022-12-30 16:54:58 +00001996 BOOL execute = FALSE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001997 if (STRCMP(event, "key") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00001998 {
1999 execute = dict_get_bool(args, "execute", FALSE);
2000 if (dict_has_key(args, "event"))
2001 input_encoded = encode_key_event(args, &ir);
2002 else if (!execute)
2003 {
2004 semsg(_(e_missing_argument_str), "event");
2005 return FALSE;
2006 }
2007 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002008 else if (STRCMP(event, "mouse") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002009 {
2010 execute = TRUE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00002011 input_encoded = encode_mouse_event(args, &ir);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002012 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002013 else
2014 {
2015 semsg(_(e_invalid_value_for_argument_str_str), "event", event);
2016 return FALSE;
2017 }
2018
2019 // Ideally, WriteConsoleInput would be used to inject these low-level
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00002020 // events. But, this doesn't work well in the CI test environment. So
Christopher Plewright20b795e2022-12-20 20:01:58 +00002021 // implementing an input_record_buffer instead.
2022 if (input_encoded)
2023 lpEventsWritten = write_input_record_buffer(&ir, 1);
2024
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002025 // Set flags to execute the event, ie. like feedkeys mode X.
2026 if (execute)
2027 {
2028 int save_msg_scroll = msg_scroll;
2029 // Avoid a 1 second delay when the keys start Insert mode.
2030 msg_scroll = FALSE;
2031 ch_log(NULL, "test_mswin_event() executing");
Christopher Plewright20b795e2022-12-20 20:01:58 +00002032 exec_normal(TRUE, TRUE, TRUE);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002033 msg_scroll |= save_msg_scroll;
2034 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002035
2036# endif
2037 return lpEventsWritten;
2038}
2039#endif // FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002040
2041#ifdef MCH_CURSOR_SHAPE
2042/*
2043 * Set the shape of the cursor.
2044 * 'thickness' can be from 1 (thin) to 99 (block)
2045 */
2046 static void
2047mch_set_cursor_shape(int thickness)
2048{
Christopher Plewright38804d62022-11-09 23:55:52 +00002049 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01002050 {
2051 if (*T_CSI == NUL)
2052 {
2053 // If 't_SI' is not set, use the default cursor styles.
2054 if (thickness < 50)
2055 vtp_printf("\033[3 q"); // underline
2056 else
2057 vtp_printf("\033[0 q"); // default
2058 }
2059 }
2060 else
2061 {
2062 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
2063 ConsoleCursorInfo.dwSize = thickness;
2064 ConsoleCursorInfo.bVisible = s_cursor_visible;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002065
K.Takatadf5320c2022-09-01 13:20:16 +01002066 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
2067 if (s_cursor_visible)
2068 SetConsoleCursorPosition(g_hConOut, g_coord);
2069 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002070}
2071
2072 void
2073mch_update_cursor(void)
2074{
2075 int idx;
2076 int thickness;
2077
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002078# ifdef VIMDLL
2079 if (gui.in_use)
2080 return;
2081# endif
2082
Bram Moolenaar071d4272004-06-13 20:20:40 +00002083 /*
2084 * How the cursor is drawn depends on the current mode.
2085 */
2086 idx = get_shape_idx(FALSE);
2087
2088 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002089 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00002090 else
2091 thickness = shape_table[idx].percentage;
2092 mch_set_cursor_shape(thickness);
2093}
2094#endif
2095
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002096#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002097/*
2098 * Handle FOCUS_EVENT.
2099 */
2100 static void
2101handle_focus_event(INPUT_RECORD ir)
2102{
2103 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
2104 ui_focus_change((int)g_fJustGotFocus);
2105}
2106
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002107static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
2108
Bram Moolenaar071d4272004-06-13 20:20:40 +00002109/*
2110 * Wait until console input from keyboard or mouse is available,
2111 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002112 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002113 * Return TRUE if something is available FALSE if not.
2114 */
2115 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002116WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002117{
2118 DWORD dwNow = 0, dwEndTime = 0;
2119 INPUT_RECORD ir;
2120 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002121 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002122# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02002123 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002124# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002125
2126 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002127 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002128 dwEndTime = GetTickCount() + msec;
2129 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002130 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002131 dwEndTime = INFINITE;
2132
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002133 // We need to loop until the end of the time period, because
2134 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002135 for (;;)
2136 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002137 // Only process messages when waiting.
2138 if (msec != 0)
2139 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002140# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002141 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002142# endif
2143# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002144 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002145# endif
2146# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002147 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002148# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002149 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002150
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02002151 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002152# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002153 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002154# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002155 )
2156 return TRUE;
2157
2158 if (msec > 0)
2159 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002160 // If the specified wait time has passed, return. Beware that
2161 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002162 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02002163 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002164 break;
2165 }
2166 if (msec != 0)
2167 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00002168 DWORD dwWaitTime = dwEndTime - dwNow;
2169
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002170 // Don't wait for more than 11 msec to avoid dropping characters,
2171 // check channel while waiting for input and handle a callback from
2172 // 'balloonexpr'.
2173 if (dwWaitTime > 11)
2174 dwWaitTime = 11;
2175
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002176# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002177 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002178 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002179# endif
2180# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002181 // When waiting very briefly don't trigger timers.
2182 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002183 {
2184 long due_time;
2185
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002186 // Trigger timers and then get the time in msec until the next
2187 // one is due. Wait up to that time.
2188 due_time = check_due_timer();
2189 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002190 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002191 // timer may have used feedkeys().
2192 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002193 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002194 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
2195 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002196 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002197# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002198 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002199# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002200 // Wait for either an event on the console input or a
2201 // message in the client-server window.
2202 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
2203 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002204# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002205 wait_for_single_object(g_hConIn, dwWaitTime)
2206 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002207# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002208 )
2209 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002210 }
2211
2212 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002213 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002214
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002215# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02002216 // May have to redraw if the cursor ends up in the wrong place.
2217 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01002218 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002219 {
2220 CONSOLE_SCREEN_BUFFER_INFO csbi;
2221
2222 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2223 {
2224 if (csbi.dwCursorPosition.Y != msg_row)
2225 {
matveyte08795e2021-05-07 15:00:17 +02002226 // The screen is now messed up, must redraw the command
2227 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002228 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02002229 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002230 redrawcmd();
2231 }
2232 }
2233 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002234# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002235
2236 if (cRecords > 0)
2237 {
2238 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
2239 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002240# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01002241 // Windows IME sends two '\n's with only one 'ENTER'. First:
2242 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00002243 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002244 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
2245 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002246 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002247 continue;
2248 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002249# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002250 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
2251 NULL, FALSE))
2252 return TRUE;
2253 }
2254
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002255 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002256
2257 if (ir.EventType == FOCUS_EVENT)
2258 handle_focus_event(ir);
2259 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002260 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002261 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
2262
Bram Moolenaar36698e32019-12-11 22:57:40 +01002263 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002264 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002265 if (dwSize.X != Columns || dwSize.Y != Rows)
2266 {
2267 CONSOLE_SCREEN_BUFFER_INFO csbi;
2268 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01002269 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002270 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01002271 if (dwSize.X != Columns || dwSize.Y != Rows)
2272 {
2273 ResizeConBuf(g_hConOut, dwSize);
2274 shell_resized();
2275 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002276 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002277 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002278 else if (ir.EventType == MOUSE_EVENT
2279 && decode_mouse_event(&ir.Event.MouseEvent))
2280 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002281 }
2282 else if (msec == 0)
2283 break;
2284 }
2285
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002286# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01002287 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002288 if (input_available())
2289 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002290# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002291
Bram Moolenaar071d4272004-06-13 20:20:40 +00002292 return FALSE;
2293}
2294
Bram Moolenaar071d4272004-06-13 20:20:40 +00002295/*
2296 * return non-zero if a character is available
2297 */
2298 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002299mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002300{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002301# ifdef VIMDLL
2302 if (gui.in_use)
2303 return TRUE;
2304# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002305 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002306}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002307
2308# if defined(FEAT_TERMINAL) || defined(PROTO)
2309/*
2310 * Check for any pending input or messages.
2311 */
2312 int
2313mch_check_messages(void)
2314{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002315# ifdef VIMDLL
2316 if (gui.in_use)
2317 return TRUE;
2318# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002319 return WaitForChar(0L, TRUE);
2320}
2321# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002322
2323/*
2324 * Create the console input. Used when reading stdin doesn't work.
2325 */
2326 static void
2327create_conin(void)
2328{
2329 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
2330 FILE_SHARE_READ|FILE_SHARE_WRITE,
2331 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002332 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002333 did_create_conin = TRUE;
2334}
2335
2336/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002337 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002338 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002339 static WCHAR
2340tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002341{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002342 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002343
2344 for (;;)
2345 {
2346 INPUT_RECORD ir;
2347 DWORD cRecords = 0;
2348
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002349# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002350 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002351 if (input_available())
2352 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002353 if (g_nMouseClick != -1)
2354 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002355# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002356 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002357 {
2358 if (did_create_conin)
2359 read_error_exit();
2360 create_conin();
2361 continue;
2362 }
2363
2364 if (ir.EventType == KEY_EVENT)
2365 {
2366 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
2367 pmodifiers, TRUE))
2368 return ch;
2369 }
2370 else if (ir.EventType == FOCUS_EVENT)
2371 handle_focus_event(ir);
2372 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
2373 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002374 else if (ir.EventType == MOUSE_EVENT)
2375 {
2376 if (decode_mouse_event(&ir.Event.MouseEvent))
2377 return 0;
2378 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002379 }
2380}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002381#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002382
2383
2384/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02002385 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002386 * Get one or more characters from the keyboard or the mouse.
2387 * If time == 0, do not wait for characters.
2388 * If time == n, wait a short time for characters.
2389 * If time == -1, wait forever for characters.
2390 * Returns the number of characters read into buf.
2391 */
2392 int
2393mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002394 char_u *buf UNUSED,
2395 int maxlen UNUSED,
2396 long time UNUSED,
2397 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002398{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002399#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002400
2401 int len;
2402 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002403# ifdef VIMDLL
2404// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
2405# define TYPEAHEADSPACE 6
2406# else
2407# define TYPEAHEADSPACE 0
2408# endif
2409# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002410 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002411 static int typeaheadlen = 0;
2412
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002413# ifdef VIMDLL
2414 if (gui.in_use)
2415 return 0;
2416# endif
2417
Bram Moolenaar0f873732019-12-05 20:28:46 +01002418 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002419 if (typeaheadlen > 0)
2420 goto theend;
2421
Bram Moolenaar071d4272004-06-13 20:20:40 +00002422 if (time >= 0)
2423 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002424 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00002425 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002426 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01002427 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00002428 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002429 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00002430
Bram Moolenaar3918c952005-03-15 22:34:55 +00002431 /*
2432 * If there is no character available within 2 seconds (default)
2433 * write the autoscript file to disk. Or cause the CursorHold event
2434 * to be triggered.
2435 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002436 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002437 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00002438 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002439 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00002440 buf[0] = K_SPECIAL;
2441 buf[1] = KS_EXTRA;
2442 buf[2] = (int)KE_CURSORHOLD;
2443 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002444 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00002445 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002446 }
2447 }
2448
2449 /*
2450 * Try to read as many characters as there are, until the buffer is full.
2451 */
2452
Bram Moolenaar0f873732019-12-05 20:28:46 +01002453 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002454 g_fCBrkPressed = FALSE;
2455
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002456# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002457 if (fdDump)
2458 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002459# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002460
Bram Moolenaar0f873732019-12-05 20:28:46 +01002461 // Keep looping until there is something in the typeahead buffer and more
2462 // to get and still room in the buffer (up to two bytes for a char and
2463 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002464 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01002465 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002466 {
2467 if (typebuf_changed(tb_change_cnt))
2468 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002469 // "buf" may be invalid now if a client put something in the
2470 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002471 typeaheadlen = 0;
2472 break;
2473 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002474 if (g_nMouseClick != -1)
2475 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002476# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002477 if (fdDump)
2478 fprintf(fdDump, "{%02x @ %d, %d}",
2479 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002480# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01002481 char_u modifiers = ((char_u *)(&g_nMouseClick))[0];
2482 char_u scroll_dir = ((char_u *)(&g_nMouseClick))[1];
2483
2484 if (scroll_dir == KE_MOUSEDOWN
2485 || scroll_dir == KE_MOUSEUP
2486 || scroll_dir == KE_MOUSELEFT
2487 || scroll_dir == KE_MOUSERIGHT)
2488 {
2489 if (modifiers > 0)
2490 {
Christopher Plewright03193062022-11-22 12:58:27 +00002491 // use K_SPECIAL instead of CSI to make mappings work
2492 typeahead[typeaheadlen++] = K_SPECIAL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002493 typeahead[typeaheadlen++] = KS_MODIFIER;
2494 typeahead[typeaheadlen++] = modifiers;
2495 }
2496 typeahead[typeaheadlen++] = CSI;
2497 typeahead[typeaheadlen++] = KS_EXTRA;
2498 typeahead[typeaheadlen++] = scroll_dir;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002499 }
2500 else
2501 {
2502 typeahead[typeaheadlen++] = ESC + 128;
2503 typeahead[typeaheadlen++] = 'M';
2504 typeahead[typeaheadlen++] = g_nMouseClick;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002505 }
Christopher Plewright36446bb2022-11-23 22:28:08 +00002506
2507 // Pass the pointer coordinates of the mouse event in 2 bytes,
2508 // allowing for > 223 columns. Both for click and scroll events.
2509 // This is the same as what is used for the GUI.
2510 typeahead[typeaheadlen++] = (char_u)(g_xMouse / 128 + ' ' + 1);
2511 typeahead[typeaheadlen++] = (char_u)(g_xMouse % 128 + ' ' + 1);
2512 typeahead[typeaheadlen++] = (char_u)(g_yMouse / 128 + ' ' + 1);
2513 typeahead[typeaheadlen++] = (char_u)(g_yMouse % 128 + ' ' + 1);
2514
2515 g_nMouseClick = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002516 }
2517 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002518 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002519 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002520 int modifiers = 0;
2521
2522 c = tgetch(&modifiers, &ch2);
2523
Christopher Plewrightc8b20492023-01-04 18:06:00 +00002524 c = simplify_key(c, &modifiers);
2525
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002526 // Some chars need adjustment when the Ctrl modifier is used.
2527 ++no_reduce_keys;
2528 c = may_adjust_key_for_ctrl(modifiers, c);
2529 --no_reduce_keys;
2530
2531 // remove the SHIFT modifier for keys where it's already included,
2532 // e.g., '(' and '*'
2533 modifiers = may_remove_shift_modifier(modifiers, c);
2534
Bram Moolenaar071d4272004-06-13 20:20:40 +00002535 if (typebuf_changed(tb_change_cnt))
2536 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002537 // "buf" may be invalid now if a client put something in the
2538 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002539 typeaheadlen = 0;
2540 break;
2541 }
2542
2543 if (c == Ctrl_C && ctrl_c_interrupts)
2544 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002545# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002546 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002547# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002548 got_int = TRUE;
2549 }
2550
Bram Moolenaar071d4272004-06-13 20:20:40 +00002551 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002552 {
2553 int n = 1;
2554
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002555 if (ch2 == NUL)
2556 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002557 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002558 char_u *p;
2559 WCHAR ch[2];
2560
2561 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002562 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002563 {
2564 ch[1] = tgetch(&modifiers, &ch2);
2565 n++;
2566 }
2567 p = utf16_to_enc(ch, &n);
2568 if (p != NULL)
2569 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002570 for (i = 0, j = 0; i < n; i++)
2571 {
2572 typeahead[typeaheadlen + j++] = p[i];
2573# ifdef VIMDLL
2574 if (p[i] == CSI)
2575 {
2576 typeahead[typeaheadlen + j++] = KS_EXTRA;
2577 typeahead[typeaheadlen + j++] = KE_CSI;
2578 }
2579# endif
2580 }
2581 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002582 vim_free(p);
2583 }
2584 }
2585 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002586 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002587 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002588# ifdef VIMDLL
2589 if (c == CSI)
2590 {
2591 typeahead[typeaheadlen + 1] = KS_EXTRA;
2592 typeahead[typeaheadlen + 2] = KE_CSI;
2593 n = 3;
2594 }
2595# endif
2596 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002597 if (ch2 != NUL)
2598 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002599 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002600 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002601 switch (ch2)
2602 {
2603 case (WCHAR)'\324': // SHIFT+Insert
2604 case (WCHAR)'\325': // CTRL+Insert
2605 case (WCHAR)'\327': // SHIFT+Delete
2606 case (WCHAR)'\330': // CTRL+Delete
2607 typeahead[typeaheadlen + n] = (char_u)ch2;
2608 n++;
2609 break;
2610
2611 default:
2612 typeahead[typeaheadlen + n] = 3;
2613 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2614 n += 2;
2615 break;
2616 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002617 }
2618 else
2619 {
2620 typeahead[typeaheadlen + n] = 3;
2621 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2622 n += 2;
2623 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002624 }
2625
Bram Moolenaar0f873732019-12-05 20:28:46 +01002626 // Use the ALT key to set the 8th bit of the character
2627 // when it's one byte, the 8th bit isn't set yet and not
2628 // using a double-byte encoding (would become a lead
2629 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002630 if ((modifiers & MOD_MASK_ALT)
2631 && n == 1
2632 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002633 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002634 )
2635 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002636 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2637 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002638 modifiers &= ~MOD_MASK_ALT;
2639 }
2640
2641 if (modifiers != 0)
2642 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002643 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002644 mch_memmove(typeahead + typeaheadlen + 3,
2645 typeahead + typeaheadlen, n);
2646 typeahead[typeaheadlen++] = K_SPECIAL;
2647 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2648 typeahead[typeaheadlen++] = modifiers;
2649 }
2650
2651 typeaheadlen += n;
2652
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002653# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002654 if (fdDump)
2655 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002656# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002657 }
2658 }
2659 }
2660
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002661# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002662 if (fdDump)
2663 {
2664 fputs("]\n", fdDump);
2665 fflush(fdDump);
2666 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002667# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002668
Bram Moolenaar071d4272004-06-13 20:20:40 +00002669theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002670 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002671 len = 0;
2672 while (len < maxlen && typeaheadlen > 0)
2673 {
2674 buf[len++] = typeahead[0];
2675 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2676 }
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00002677# ifdef FEAT_EVAL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002678 if (len > 0)
2679 {
2680 buf[len] = NUL;
2681 ch_log(NULL, "raw key input: \"%s\"", buf);
2682 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002683# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002684 return len;
2685
Bram Moolenaar0f873732019-12-05 20:28:46 +01002686#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002687 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002688#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002689}
2690
Bram Moolenaar82881492012-11-20 16:53:39 +01002691#ifndef PROTO
2692# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002693# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002694# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002695#endif
2696
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002697/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002698 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002699 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2700 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002701 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002702 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002703 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002704executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002705{
LemonBoy40fd7e62022-05-05 20:18:16 +01002706 int attrs = win32_getattrs((char_u *)name);
2707
2708 // The file doesn't exist or is a folder.
2709 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2710 return FALSE;
2711 // Check if the file is an AppExecLink, a special alias used by Windows
2712 // Store for its apps.
2713 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002714 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002715 char_u *res = resolve_appexeclink((char_u *)name);
2716 if (res == NULL)
2717 return FALSE;
2718 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002719 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002720 *path = res;
2721 else
2722 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002723 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002724 else if (path != NULL)
2725 *path = FullName_save((char_u *)name, FALSE);
2726 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002727}
2728
2729/*
2730 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2731 * If "use_path" is FALSE: Return TRUE if "name" exists.
2732 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2733 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2734 * the allocated memory.
2735 */
2736 static int
2737executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2738{
2739 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2740 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2741 // UTF-8.
2742 char_u buf[_MAX_PATH * 3];
2743 size_t len = STRLEN(name);
2744 size_t tmplen;
2745 char_u *p, *e, *e2;
2746 char_u *pathbuf = NULL;
2747 char_u *pathext = NULL;
2748 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002749 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002750 int noext = FALSE;
2751 int retval = FALSE;
2752
2753 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002754 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002755
2756 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002757 shname = gettail(p_sh);
2758 if (strstr((char *)shname, "sh") != NULL &&
2759 !(strstr((char *)shname, "powershell") != NULL
2760 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002761 noext = TRUE;
2762
2763 if (use_pathext)
2764 {
2765 pathext = mch_getenv("PATHEXT");
2766 if (pathext == NULL)
2767 pathext = (char_u *)".com;.exe;.bat;.cmd";
2768
2769 if (noext == FALSE)
2770 {
2771 /*
2772 * Loop over all extensions in $PATHEXT.
2773 * Check "name" ends with extension.
2774 */
2775 p = pathext;
2776 while (*p)
2777 {
2778 if (p[0] == ';'
2779 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2780 {
2781 // Skip empty or single ".".
2782 ++p;
2783 continue;
2784 }
2785 e = vim_strchr(p, ';');
2786 if (e == NULL)
2787 e = p + STRLEN(p);
2788 tmplen = e - p;
2789
2790 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2791 {
2792 noext = TRUE;
2793 break;
2794 }
2795
2796 p = e;
2797 }
2798 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002799 }
2800
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002801 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002802 if (pathext == NULL)
2803 pathext = (char_u *)".";
2804 else if (noext == TRUE)
2805 {
2806 if (pathextbuf == NULL)
2807 pathextbuf = alloc(STRLEN(pathext) + 3);
2808 if (pathextbuf == NULL)
2809 {
2810 retval = FALSE;
2811 goto theend;
2812 }
2813 STRCPY(pathextbuf, ".;");
2814 STRCAT(pathextbuf, pathext);
2815 pathext = pathextbuf;
2816 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002817
Bram Moolenaar95da1362020-05-30 18:37:55 +02002818 // Use $PATH when "use_path" is TRUE and "name" is basename.
2819 if (use_path && gettail((char_u *)name) == (char_u *)name)
2820 {
2821 p = mch_getenv("PATH");
2822 if (p != NULL)
2823 {
2824 pathbuf = alloc(STRLEN(p) + 3);
2825 if (pathbuf == NULL)
2826 {
2827 retval = FALSE;
2828 goto theend;
2829 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002830
2831 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2832 STRCPY(pathbuf, ".;");
2833 else
2834 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002835 STRCAT(pathbuf, p);
2836 }
2837 }
2838
2839 /*
2840 * Walk through all entries in $PATH to check if "name" exists there and
2841 * is an executable file.
2842 */
2843 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2844 while (*p)
2845 {
2846 if (*p == ';') // Skip empty entry
2847 {
2848 ++p;
2849 continue;
2850 }
2851 e = vim_strchr(p, ';');
2852 if (e == NULL)
2853 e = p + STRLEN(p);
2854
2855 if (e - p + len + 2 > sizeof(buf))
2856 {
2857 retval = FALSE;
2858 goto theend;
2859 }
2860 // A single "." that means current dir.
2861 if (e - p == 1 && *p == '.')
2862 STRCPY(buf, name);
2863 else
2864 {
2865 vim_strncpy(buf, p, e - p);
2866 add_pathsep(buf);
2867 STRCAT(buf, name);
2868 }
2869 tmplen = STRLEN(buf);
2870
2871 /*
2872 * Loop over all extensions in $PATHEXT.
2873 * Check "name" with extension added.
2874 */
2875 p = pathext;
2876 while (*p)
2877 {
2878 if (*p == ';')
2879 {
2880 // Skip empty entry
2881 ++p;
2882 continue;
2883 }
2884 e2 = vim_strchr(p, (int)';');
2885 if (e2 == NULL)
2886 e2 = p + STRLEN(p);
2887
2888 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2889 {
2890 // Not a single "." that means no extension is added.
2891 if (e2 - p + tmplen + 1 > sizeof(buf))
2892 {
2893 retval = FALSE;
2894 goto theend;
2895 }
2896 vim_strncpy(buf + tmplen, p, e2 - p);
2897 }
2898 if (executable_file((char *)buf, path))
2899 {
2900 retval = TRUE;
2901 goto theend;
2902 }
2903
2904 p = e2;
2905 }
2906
2907 p = e;
2908 }
2909
2910theend:
2911 free(pathextbuf);
2912 free(pathbuf);
2913 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002914}
2915
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002916#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2917 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002918/*
2919 * Bad parameter handler.
2920 *
2921 * Certain MS CRT functions will intentionally crash when passed invalid
2922 * parameters to highlight possible security holes. Setting this function as
2923 * the bad parameter handler will prevent the crash.
2924 *
2925 * In debug builds the parameters contain CRT information that might help track
2926 * down the source of a problem, but in non-debug builds the arguments are all
2927 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2928 * worth allowing these to make debugging of issues easier.
2929 */
2930 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002931bad_param_handler(const wchar_t *expression UNUSED,
2932 const wchar_t *function UNUSED,
2933 const wchar_t *file UNUSED,
2934 unsigned int line UNUSED,
2935 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002936{
2937}
2938
2939# define SET_INVALID_PARAM_HANDLER \
2940 ((void)_set_invalid_parameter_handler(bad_param_handler))
2941#else
2942# define SET_INVALID_PARAM_HANDLER
2943#endif
2944
Bram Moolenaar4f974752019-02-17 17:44:42 +01002945#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002946
2947/*
2948 * GUI version of mch_init().
2949 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002950 static void
2951mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002952{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002953# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002954 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002955# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002956
Bram Moolenaar0f873732019-12-05 20:28:46 +01002957 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002958 SET_INVALID_PARAM_HANDLER;
2959
Bram Moolenaar0f873732019-12-05 20:28:46 +01002960 // Let critical errors result in a failure, not in a dialog box. Required
2961 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002962 SetErrorMode(SEM_FAILCRITICALERRORS);
2963
Bram Moolenaar0f873732019-12-05 20:28:46 +01002964 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002965
Bram Moolenaar0f873732019-12-05 20:28:46 +01002966 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002967 Rows = 25;
2968 Columns = 80;
2969
Bram Moolenaar0f873732019-12-05 20:28:46 +01002970 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002971 {
2972 char_u vimrun_location[_MAX_PATH + 4];
2973
Bram Moolenaar0f873732019-12-05 20:28:46 +01002974 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002975 STRCPY(vimrun_location, exe_name);
2976 STRCPY(gettail(vimrun_location), "vimrun.exe");
2977 if (mch_getperm(vimrun_location) >= 0)
2978 {
2979 if (*skiptowhite(vimrun_location) != NUL)
2980 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002981 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002982 mch_memmove(vimrun_location + 1, vimrun_location,
2983 STRLEN(vimrun_location) + 1);
2984 *vimrun_location = '"';
2985 STRCPY(gettail(vimrun_location), "vimrun\" ");
2986 }
2987 else
2988 STRCPY(gettail(vimrun_location), "vimrun ");
2989
2990 vimrun_path = (char *)vim_strsave(vimrun_location);
2991 s_dont_use_vimrun = FALSE;
2992 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002993 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002994 s_dont_use_vimrun = FALSE;
2995
Bram Moolenaar0f873732019-12-05 20:28:46 +01002996 // Don't give the warning for a missing vimrun.exe right now, but only
2997 // when vimrun was supposed to be used. Don't bother people that do
2998 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002999 if (s_dont_use_vimrun)
3000 need_vimrun_warning = TRUE;
3001 }
3002
3003 /*
3004 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
3005 * Otherwise the default "findstr /n" is used.
3006 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02003007 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01003008 set_option_value_give_err((char_u *)"grepprg",
3009 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003010
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003011# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003012 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003013# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003014
3015 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003016}
3017
3018
Bram Moolenaar0f873732019-12-05 20:28:46 +01003019#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003020
3021#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003022
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003023# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
3024# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025
3026/*
3027 * ClearConsoleBuffer()
3028 * Description:
3029 * Clears the entire contents of the console screen buffer, using the
3030 * specified attribute.
3031 * Returns:
3032 * TRUE on success
3033 */
3034 static BOOL
3035ClearConsoleBuffer(WORD wAttribute)
3036{
3037 CONSOLE_SCREEN_BUFFER_INFO csbi;
3038 COORD coord;
3039 DWORD NumCells, dummy;
3040
3041 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3042 return FALSE;
3043
3044 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
3045 coord.X = 0;
3046 coord.Y = 0;
3047 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
3048 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003049 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003050 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
3051 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003052 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003053
3054 return TRUE;
3055}
3056
3057/*
3058 * FitConsoleWindow()
3059 * Description:
3060 * Checks if the console window will fit within given buffer dimensions.
3061 * Also, if requested, will shrink the window to fit.
3062 * Returns:
3063 * TRUE on success
3064 */
3065 static BOOL
3066FitConsoleWindow(
3067 COORD dwBufferSize,
3068 BOOL WantAdjust)
3069{
3070 CONSOLE_SCREEN_BUFFER_INFO csbi;
3071 COORD dwWindowSize;
3072 BOOL NeedAdjust = FALSE;
3073
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003074 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3075 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003076
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003077 /*
3078 * A buffer resize will fail if the current console window does
3079 * not lie completely within that buffer. To avoid this, we might
3080 * have to move and possibly shrink the window.
3081 */
3082 if (csbi.srWindow.Right >= dwBufferSize.X)
3083 {
3084 dwWindowSize.X = SRWIDTH(csbi.srWindow);
3085 if (dwWindowSize.X > dwBufferSize.X)
3086 dwWindowSize.X = dwBufferSize.X;
3087 csbi.srWindow.Right = dwBufferSize.X - 1;
3088 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
3089 NeedAdjust = TRUE;
3090 }
3091 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
3092 {
3093 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
3094 if (dwWindowSize.Y > dwBufferSize.Y)
3095 dwWindowSize.Y = dwBufferSize.Y;
3096 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
3097 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
3098 NeedAdjust = TRUE;
3099 }
3100 if (NeedAdjust && WantAdjust)
3101 {
3102 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
3103 return FALSE;
3104 }
3105 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003106}
3107
3108typedef struct ConsoleBufferStruct
3109{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003110 BOOL IsValid;
3111 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003112 PCHAR_INFO Buffer;
3113 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003114 PSMALL_RECT Regions;
3115 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003116} ConsoleBuffer;
3117
3118/*
3119 * SaveConsoleBuffer()
3120 * Description:
3121 * Saves important information about the console buffer, including the
3122 * actual buffer contents. The saved information is suitable for later
3123 * restoration by RestoreConsoleBuffer().
3124 * Returns:
3125 * TRUE if all information was saved; FALSE otherwise
3126 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
3127 */
3128 static BOOL
3129SaveConsoleBuffer(
3130 ConsoleBuffer *cb)
3131{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003132 DWORD NumCells;
3133 COORD BufferCoord;
3134 SMALL_RECT ReadRegion;
3135 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003136 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003137
Bram Moolenaar071d4272004-06-13 20:20:40 +00003138 if (cb == NULL)
3139 return FALSE;
3140
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003141 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003142 {
3143 cb->IsValid = FALSE;
3144 return FALSE;
3145 }
3146 cb->IsValid = TRUE;
3147
Christopher Plewright1140b512022-11-12 18:46:05 +00003148 // VTP uses alternate screen buffer.
3149 // No need to save buffer contents for restoration.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003150 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003151 return TRUE;
3152
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003153 /*
3154 * Allocate a buffer large enough to hold the entire console screen
3155 * buffer. If this ConsoleBuffer structure has already been initialized
3156 * with a buffer of the correct size, then just use that one.
3157 */
3158 if (!cb->IsValid || cb->Buffer == NULL ||
3159 cb->BufferSize.X != cb->Info.dwSize.X ||
3160 cb->BufferSize.Y != cb->Info.dwSize.Y)
3161 {
3162 cb->BufferSize.X = cb->Info.dwSize.X;
3163 cb->BufferSize.Y = cb->Info.dwSize.Y;
3164 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
3165 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003166 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003167 if (cb->Buffer == NULL)
3168 return FALSE;
3169 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003170
3171 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003172 * We will now copy the console screen buffer into our buffer.
3173 * ReadConsoleOutput() seems to be limited as far as how much you
3174 * can read at a time. Empirically, this number seems to be about
3175 * 12000 cells (rows * columns). Start at position (0, 0) and copy
3176 * in chunks until it is all copied. The chunks will all have the
3177 * same horizontal characteristics, so initialize them now. The
3178 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003179 */
Bram Moolenaar61594242015-09-01 20:23:37 +02003180 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003181 ReadRegion.Left = 0;
3182 ReadRegion.Right = cb->Info.dwSize.X - 1;
3183 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003184
3185 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
3186 if (cb->Regions == NULL || numregions != cb->NumRegions)
3187 {
3188 cb->NumRegions = numregions;
3189 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003190 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003191 if (cb->Regions == NULL)
3192 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003193 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003194 return FALSE;
3195 }
3196 }
3197
3198 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003199 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003200 /*
3201 * Read into position (0, Y) in our buffer.
3202 */
3203 BufferCoord.Y = Y;
3204 /*
3205 * Read the region whose top left corner is (0, Y) and whose bottom
3206 * right corner is (width - 1, Y + Y_incr - 1). This should define
3207 * a region of size width by Y_incr. Don't worry if this region is
3208 * too large for the remaining buffer; it will be cropped.
3209 */
3210 ReadRegion.Top = Y;
3211 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003212 if (!ReadConsoleOutputW(g_hConOut, // output handle
3213 cb->Buffer, // our buffer
3214 cb->BufferSize, // dimensions of our buffer
3215 BufferCoord, // offset in our buffer
3216 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003217 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003218 VIM_CLEAR(cb->Buffer);
3219 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003220 return FALSE;
3221 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02003222 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003223 }
3224
3225 return TRUE;
3226}
3227
3228/*
3229 * RestoreConsoleBuffer()
3230 * Description:
3231 * Restores important information about the console buffer, including the
3232 * actual buffer contents, if desired. The information to restore is in
3233 * the same format used by SaveConsoleBuffer().
3234 * Returns:
3235 * TRUE on success
3236 */
3237 static BOOL
3238RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003239 ConsoleBuffer *cb,
3240 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003241{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003242 COORD BufferCoord;
3243 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003244 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003245
Christopher Plewright1140b512022-11-12 18:46:05 +00003246 // VTP uses alternate screen buffer.
3247 // No need to restore buffer contents.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003248 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003249 return TRUE;
3250
Bram Moolenaar071d4272004-06-13 20:20:40 +00003251 if (cb == NULL || !cb->IsValid)
3252 return FALSE;
3253
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003254 /*
3255 * Before restoring the buffer contents, clear the current buffer, and
3256 * restore the cursor position and window information. Doing this now
3257 * prevents old buffer contents from "flashing" onto the screen.
3258 */
3259 if (RestoreScreen)
3260 ClearConsoleBuffer(cb->Info.wAttributes);
3261
3262 FitConsoleWindow(cb->Info.dwSize, TRUE);
3263 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
3264 return FALSE;
3265 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
3266 return FALSE;
3267
3268 if (!RestoreScreen)
3269 {
3270 /*
3271 * No need to restore the screen buffer contents, so we're done.
3272 */
3273 return TRUE;
3274 }
3275
3276 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
3277 return FALSE;
3278 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
3279 return FALSE;
3280
3281 /*
3282 * Restore the screen buffer contents.
3283 */
3284 if (cb->Buffer != NULL)
3285 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003286 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003287 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003288 BufferCoord.X = cb->Regions[i].Left;
3289 BufferCoord.Y = cb->Regions[i].Top;
3290 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01003291 if (!WriteConsoleOutputW(g_hConOut, // output handle
3292 cb->Buffer, // our buffer
3293 cb->BufferSize, // dimensions of our buffer
3294 BufferCoord, // offset in our buffer
3295 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02003296 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003297 }
3298 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003299
3300 return TRUE;
3301}
3302
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003303# define FEAT_RESTORE_ORIG_SCREEN
3304# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003305static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003306# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003307static ConsoleBuffer g_cbNonTermcap = { 0 };
3308static ConsoleBuffer g_cbTermcap = { 0 };
3309
Bram Moolenaar071d4272004-06-13 20:20:40 +00003310char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01003311HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00003312static HICON g_hOrigIconSmall = NULL;
3313static HICON g_hOrigIcon = NULL;
3314static HICON g_hVimIcon = NULL;
3315static BOOL g_fCanChangeIcon = FALSE;
3316
Bram Moolenaar071d4272004-06-13 20:20:40 +00003317/*
3318 * GetConsoleIcon()
3319 * Description:
3320 * Attempts to retrieve the small icon and/or the big icon currently in
3321 * use by a given window.
3322 * Returns:
3323 * TRUE on success
3324 */
3325 static BOOL
3326GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003327 HWND hWnd,
3328 HICON *phIconSmall,
3329 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003330{
3331 if (hWnd == NULL)
3332 return FALSE;
3333
3334 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003335 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
3336 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003337 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003338 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
3339 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003340 return TRUE;
3341}
3342
3343/*
3344 * SetConsoleIcon()
3345 * Description:
3346 * Attempts to change the small icon and/or the big icon currently in
3347 * use by a given window.
3348 * Returns:
3349 * TRUE on success
3350 */
3351 static BOOL
3352SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003353 HWND hWnd,
3354 HICON hIconSmall,
3355 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003356{
Bram Moolenaar071d4272004-06-13 20:20:40 +00003357 if (hWnd == NULL)
3358 return FALSE;
3359
3360 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003361 SendMessage(hWnd, WM_SETICON,
3362 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003363 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003364 SendMessage(hWnd, WM_SETICON,
3365 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003366 return TRUE;
3367}
3368
3369/*
3370 * SaveConsoleTitleAndIcon()
3371 * Description:
3372 * Saves the current console window title in g_szOrigTitle, for later
3373 * restoration. Also, attempts to obtain a handle to the console window,
3374 * and use it to save the small and big icons currently in use by the
3375 * console window. This is not always possible on some versions of Windows;
3376 * nor is it possible when running Vim remotely using Telnet (since the
3377 * console window the user sees is owned by a remote process).
3378 */
3379 static void
3380SaveConsoleTitleAndIcon(void)
3381{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003382 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003383 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
3384 return;
3385
3386 /*
3387 * Obtain a handle to the console window using GetConsoleWindow() from
3388 * KERNEL32.DLL; we need to handle in order to change the window icon.
3389 * This function only exists on NT-based Windows, starting with Windows
3390 * 2000. On older operating systems, we can't change the window icon
3391 * anyway.
3392 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003393 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003394 if (g_hWnd == NULL)
3395 return;
3396
Bram Moolenaar0f873732019-12-05 20:28:46 +01003397 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003398 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
3399 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
3400 return;
3401
Bram Moolenaar0f873732019-12-05 20:28:46 +01003402 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01003403 if (
3404# ifdef FEAT_LIBCALL
3405 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
3406# endif
3407 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003408 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003409 if (g_hVimIcon != NULL)
3410 g_fCanChangeIcon = TRUE;
3411}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003412
3413static int g_fWindInitCalled = FALSE;
3414static int g_fTermcapMode = FALSE;
3415static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003416
3417/*
3418 * non-GUI version of mch_init().
3419 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003420 static void
3421mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003422{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003423# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003424 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003425# endif
3426# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00003427 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003428# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003429
Bram Moolenaar0f873732019-12-05 20:28:46 +01003430 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02003431 SET_INVALID_PARAM_HANDLER;
3432
Bram Moolenaar0f873732019-12-05 20:28:46 +01003433 // Let critical errors result in a failure, not in a dialog box. Required
3434 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003435 SetErrorMode(SEM_FAILCRITICALERRORS);
3436
Bram Moolenaar0f873732019-12-05 20:28:46 +01003437 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00003438 out_flush();
3439
Bram Moolenaar0f873732019-12-05 20:28:46 +01003440 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00003441 if (read_cmd_fd == 0)
3442 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
3443 else
3444 create_conin();
3445 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
3446
Christopher Plewright38804d62022-11-09 23:55:52 +00003447 wt_init();
3448 vtp_flag_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003449# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01003450 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003451 SaveConsoleBuffer(&g_cbOrig);
3452 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003453# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01003454 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003455 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
3456 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003457# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003458 if (cterm_normal_fg_color == 0)
3459 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
3460 if (cterm_normal_bg_color == 0)
3461 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
3462
Bram Moolenaarbdace832019-03-02 10:13:42 +01003463 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02003464 g_color_index_fg = g_attrDefault & 0xf;
3465 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
3466
Bram Moolenaar0f873732019-12-05 20:28:46 +01003467 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00003468 update_tcap(g_attrCurrent);
3469
3470 GetConsoleCursorInfo(g_hConOut, &g_cci);
3471 GetConsoleMode(g_hConIn, &g_cmodein);
3472 GetConsoleMode(g_hConOut, &g_cmodeout);
3473
Bram Moolenaar071d4272004-06-13 20:20:40 +00003474 SaveConsoleTitleAndIcon();
3475 /*
3476 * Set both the small and big icons of the console window to Vim's icon.
3477 * Note that Vim presently only has one size of icon (32x32), but it
3478 * automatically gets scaled down to 16x16 when setting the small icon.
3479 */
3480 if (g_fCanChangeIcon)
3481 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003482
3483 ui_get_shellsize();
3484
Christopher Plewrightd343c602023-01-22 18:58:30 +00003485 vtp_init();
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00003486 // Switch to a new alternate screen buffer.
3487 if (use_alternate_screen_buffer)
3488 vtp_printf("\033[?1049h");
Christopher Plewrightd343c602023-01-22 18:58:30 +00003489
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003490# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003491 fdDump = fopen("dump", "wt");
3492
3493 if (fdDump)
3494 {
3495 time_t t;
3496
3497 time(&t);
3498 fputs(ctime(&t), fdDump);
3499 fflush(fdDump);
3500 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003501# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003502
3503 g_fWindInitCalled = TRUE;
3504
Bram Moolenaar071d4272004-06-13 20:20:40 +00003505 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003506
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003507# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003508 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003509# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003510}
3511
3512/*
3513 * non-GUI version of mch_exit().
3514 * Shut down and exit with status `r'
3515 * Careful: mch_exit() may be called before mch_init()!
3516 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003517 static void
3518mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003519{
Bram Moolenaar955f1982017-02-05 15:10:51 +01003520 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003521
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003522 vtp_exit();
3523
Bram Moolenaar955f1982017-02-05 15:10:51 +01003524 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003525 if (g_fWindInitCalled)
3526 settmode(TMODE_COOK);
3527
Bram Moolenaar0f873732019-12-05 20:28:46 +01003528 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00003529
3530 if (g_fWindInitCalled)
3531 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02003532 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003533 /*
3534 * Restore both the small and big icons of the console window to
3535 * what they were at startup. Don't do this when the window is
3536 * closed, Vim would hang here.
3537 */
3538 if (g_fCanChangeIcon && !g_fForceExit)
3539 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003540
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003541# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003542 if (fdDump)
3543 {
3544 time_t t;
3545
3546 time(&t);
3547 fputs(ctime(&t), fdDump);
3548 fclose(fdDump);
3549 }
3550 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003551# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003552 }
3553
3554 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003555 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003556 SetConsoleMode(g_hConOut, g_cmodeout);
3557
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003558# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003559 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003560# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003561
3562 exit(r);
3563}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003564#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003565
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003566 void
3567mch_init(void)
3568{
3569#ifdef VIMDLL
3570 if (gui.starting)
3571 mch_init_g();
3572 else
3573 mch_init_c();
3574#elif defined(FEAT_GUI_MSWIN)
3575 mch_init_g();
3576#else
3577 mch_init_c();
3578#endif
3579}
3580
3581 void
3582mch_exit(int r)
3583{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003584#ifdef FEAT_NETBEANS_INTG
3585 netbeans_send_disconnect();
3586#endif
3587
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003588#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003589 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003590 mch_exit_g(r);
3591 else
3592 mch_exit_c(r);
3593#elif defined(FEAT_GUI_MSWIN)
3594 mch_exit_g(r);
3595#else
3596 mch_exit_c(r);
3597#endif
3598}
3599
Bram Moolenaar071d4272004-06-13 20:20:40 +00003600/*
3601 * Do we have an interactive window?
3602 */
3603 int
3604mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003605 int argc UNUSED,
3606 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003607{
K.Takatace3189d2023-02-15 19:13:43 +00003608 mch_get_exe_name();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003609
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003610#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003611 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003612#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003613# ifdef VIMDLL
3614 if (gui.in_use)
3615 return OK;
3616# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003617 if (isatty(1))
3618 return OK;
3619 return FAIL;
3620#endif
3621}
3622
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003623/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003624 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003625 * When "len" is > 0, also expand short to long filenames.
3626 */
3627 void
3628fname_case(
3629 char_u *name,
3630 int len)
3631{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003632 int flen;
3633 WCHAR *p;
3634 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003635
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003636 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003637 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003638 return;
3639
3640 slash_adjust(name);
3641
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003642 p = enc_to_utf16(name, NULL);
3643 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003644 return;
3645
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003646 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003647 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003648 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003649
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003650 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003651 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003652 if (len > 0 || flen >= (int)STRLEN(q))
3653 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3654 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003655 }
3656 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003657 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003658}
3659
3660
3661/*
3662 * Insert user name in s[len].
3663 */
3664 int
3665mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003666 char_u *s,
3667 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003668{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003669 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003670 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003671
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003672 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003673 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003674 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003675
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003676 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003677 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003678 vim_strncpy(s, p, len - 1);
3679 vim_free(p);
3680 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003681 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003682 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003683 s[0] = NUL;
3684 return FAIL;
3685}
3686
3687
3688/*
3689 * Insert host name in s[len].
3690 */
3691 void
3692mch_get_host_name(
3693 char_u *s,
3694 int len)
3695{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003696 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003697 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003698
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003699 if (!GetComputerNameW(wszHostName, &wcch))
3700 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003701
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003702 char_u *p = utf16_to_enc(wszHostName, NULL);
3703 if (p == NULL)
3704 return;
3705
3706 vim_strncpy(s, p, len - 1);
3707 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003708}
3709
3710
3711/*
3712 * return process ID
3713 */
3714 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003715mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003716{
3717 return (long)GetCurrentProcessId();
3718}
3719
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003720/*
3721 * return TRUE if process "pid" is still running
3722 */
3723 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003724mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003725{
3726 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3727 DWORD status = 0;
3728 int ret = FALSE;
3729
3730 if (hProcess == NULL)
3731 return FALSE; // might not have access
3732 if (GetExitCodeProcess(hProcess, &status) )
3733 ret = status == STILL_ACTIVE;
3734 CloseHandle(hProcess);
3735 return ret;
3736}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003737
3738/*
3739 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3740 * Return OK for success, FAIL for failure.
3741 */
3742 int
3743mch_dirname(
3744 char_u *buf,
3745 int len)
3746{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003747 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003748
Bram Moolenaar071d4272004-06-13 20:20:40 +00003749 /*
3750 * Originally this was:
3751 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3752 * But the Win32s known bug list says that getcwd() doesn't work
3753 * so use the Win32 system call instead. <Negri>
3754 */
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003755 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) == 0)
3756 return FAIL;
3757
3758 WCHAR wcbuf[_MAX_PATH + 1];
3759 char_u *p = NULL;
3760
3761 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003762 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003763 p = utf16_to_enc(wcbuf, NULL);
3764 if (STRLEN(p) >= (size_t)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003765 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003766 // long path name is too long, fall back to short one
Yegappan Lakshmanan960dcbd2023-03-07 17:45:11 +00003767 VIM_CLEAR(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003768 }
3769 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003770 if (p == NULL)
3771 p = utf16_to_enc(wbuf, NULL);
3772
3773 if (p == NULL)
3774 return FAIL;
3775
3776 vim_strncpy(buf, p, len - 1);
3777 vim_free(p);
3778 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003779}
3780
3781/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003782 * Get file permissions for "name".
3783 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003784 */
3785 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003786mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003787{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003788 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003789 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003790
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003791 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003792 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003793}
3794
3795
3796/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003797 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003798 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003799 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003800 */
3801 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003802mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003803{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003804 long n;
3805 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003806
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003807 p = enc_to_utf16(name, NULL);
3808 if (p == NULL)
3809 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003810
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003811 n = _wchmod(p, perm);
3812 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003813 if (n == -1)
3814 return FAIL;
3815
3816 win32_set_archive(name);
3817
3818 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003819}
3820
3821/*
3822 * Set hidden flag for "name".
3823 */
3824 void
3825mch_hide(char_u *name)
3826{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003827 int attrs = win32_getattrs(name);
3828 if (attrs == -1)
3829 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003830
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003831 attrs |= FILE_ATTRIBUTE_HIDDEN;
3832 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003833}
3834
3835/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003836 * Return TRUE if file "name" exists and is hidden.
3837 */
3838 int
3839mch_ishidden(char_u *name)
3840{
3841 int f = win32_getattrs(name);
3842
3843 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003844 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003845
3846 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3847}
3848
3849/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003850 * return TRUE if "name" is a directory
3851 * return FALSE if "name" is not a directory or upon error
3852 */
3853 int
3854mch_isdir(char_u *name)
3855{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003856 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003857
3858 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003859 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003860
3861 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3862}
3863
3864/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003865 * return TRUE if "name" is a directory, NOT a symlink to a directory
3866 * return FALSE if "name" is not a directory
3867 * return FALSE for error
3868 */
3869 int
3870mch_isrealdir(char_u *name)
3871{
3872 return mch_isdir(name) && !mch_is_symbolic_link(name);
3873}
3874
3875/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003876 * Create directory "name".
3877 * Return 0 on success, -1 on error.
3878 */
3879 int
3880mch_mkdir(char_u *name)
3881{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003882 WCHAR *p;
3883 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003884
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003885 p = enc_to_utf16(name, NULL);
3886 if (p == NULL)
3887 return -1;
3888 retval = _wmkdir(p);
3889 vim_free(p);
3890 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003891}
3892
3893/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003894 * Delete directory "name".
3895 * Return 0 on success, -1 on error.
3896 */
3897 int
3898mch_rmdir(char_u *name)
3899{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003900 WCHAR *p;
3901 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003902
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003903 p = enc_to_utf16(name, NULL);
3904 if (p == NULL)
3905 return -1;
3906 retval = _wrmdir(p);
3907 vim_free(p);
3908 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003909}
3910
3911/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003912 * Return TRUE if file "fname" has more than one link.
3913 */
3914 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003915mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003916{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003917 BY_HANDLE_FILE_INFORMATION info;
3918
3919 return win32_fileinfo(fname, &info) == FILEINFO_OK
3920 && info.nNumberOfLinks > 1;
3921}
3922
3923/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003924 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003925 */
3926 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003927mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003928{
3929 HANDLE hFind;
3930 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003931 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003932 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003933 WIN32_FIND_DATAW findDataW;
3934
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003935 wn = enc_to_utf16(name, NULL);
3936 if (wn == NULL)
3937 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003938
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003939 hFind = FindFirstFileW(wn, &findDataW);
3940 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003941 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003942 {
3943 fileFlags = findDataW.dwFileAttributes;
3944 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003945 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003946 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003947
3948 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003949 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3950 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003951 res = TRUE;
3952
3953 return res;
3954}
3955
3956/*
3957 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3958 * link.
3959 */
3960 int
3961mch_is_linked(char_u *fname)
3962{
3963 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3964 return TRUE;
3965 return FALSE;
3966}
3967
3968/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003969 * Get the by-handle-file-information for "fname".
3970 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003971 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003972 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3973 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3974 */
3975 int
3976win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3977{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003978 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003979 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003980 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003981
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003982 wn = enc_to_utf16(fname, NULL);
3983 if (wn == NULL)
3984 return FILEINFO_ENC_FAIL;
3985
3986 hFile = CreateFileW(wn, // file name
3987 GENERIC_READ, // access mode
3988 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3989 NULL, // security descriptor
3990 OPEN_EXISTING, // creation disposition
3991 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3992 NULL); // handle to template file
3993 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003994
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003995 if (hFile == INVALID_HANDLE_VALUE)
3996 return FILEINFO_READ_FAIL;
3997
3998 if (GetFileInformationByHandle(hFile, info) != 0)
3999 res = FILEINFO_OK;
4000 else
4001 res = FILEINFO_INFO_FAIL;
4002 CloseHandle(hFile);
Bram Moolenaar03f48552006-02-28 23:52:23 +00004003
Bram Moolenaar03f48552006-02-28 23:52:23 +00004004 return res;
4005}
4006
4007/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004008 * get file attributes for `name'
4009 * -1 : error
4010 * else FILE_ATTRIBUTE_* defined in winnt.h
4011 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01004012 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004013win32_getattrs(char_u *name)
4014{
4015 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004016 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004017
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004018 p = enc_to_utf16(name, NULL);
4019 if (p == NULL)
4020 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004021
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004022 attr = GetFileAttributesW(p);
4023 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004024
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004025 return attr;
4026}
4027
4028/*
4029 * set file attributes for `name' to `attrs'
4030 *
4031 * return -1 for failure, 0 otherwise
4032 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004033 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004034win32_setattrs(char_u *name, int attrs)
4035{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004036 int res;
4037 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004038
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004039 p = enc_to_utf16(name, NULL);
4040 if (p == NULL)
4041 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004042
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004043 res = SetFileAttributesW(p, attrs);
4044 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004045
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004046 return res ? 0 : -1;
4047}
4048
4049/*
4050 * Set archive flag for "name".
4051 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004052 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004053win32_set_archive(char_u *name)
4054{
4055 int attrs = win32_getattrs(name);
4056 if (attrs == -1)
4057 return -1;
4058
4059 attrs |= FILE_ATTRIBUTE_ARCHIVE;
4060 return win32_setattrs(name, attrs);
4061}
4062
4063/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004064 * Return TRUE if file or directory "name" is writable (not readonly).
4065 * Strange semantics of Win32: a readonly directory is writable, but you can't
4066 * delete a file. Let's say this means it is writable.
4067 */
4068 int
4069mch_writable(char_u *name)
4070{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004071 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004072
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004073 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
4074 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004075}
4076
Bram Moolenaar071d4272004-06-13 20:20:40 +00004077/*
Bram Moolenaar43663192017-03-05 14:29:12 +01004078 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01004079 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01004080 * When returning TRUE and "path" is not NULL save the path and set "*path" to
4081 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004082 */
4083 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01004084mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004085{
Bram Moolenaar95da1362020-05-30 18:37:55 +02004086 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004087}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004088
4089/*
4090 * Check what "name" is:
4091 * NODE_NORMAL: file or directory (or doesn't exist)
4092 * NODE_WRITABLE: writable device, socket, fifo, etc.
4093 * NODE_OTHER: non-writable things
4094 */
4095 int
4096mch_nodetype(char_u *name)
4097{
4098 HANDLE hFile;
4099 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004100 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004101
Bram Moolenaar0f873732019-12-05 20:28:46 +01004102 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
4103 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
4104 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00004105 if (STRNCMP(name, "\\\\.\\", 4) == 0)
4106 return NODE_WRITABLE;
4107
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004108 wn = enc_to_utf16(name, NULL);
4109 if (wn == NULL)
4110 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004111
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004112 hFile = CreateFileW(wn, // file name
4113 GENERIC_WRITE, // access mode
4114 0, // share mode
4115 NULL, // security descriptor
4116 OPEN_EXISTING, // creation disposition
4117 0, // file attributes
4118 NULL); // handle to template file
4119 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004120 if (hFile == INVALID_HANDLE_VALUE)
4121 return NODE_NORMAL;
4122
4123 type = GetFileType(hFile);
4124 CloseHandle(hFile);
4125 if (type == FILE_TYPE_CHAR)
4126 return NODE_WRITABLE;
4127 if (type == FILE_TYPE_DISK)
4128 return NODE_NORMAL;
4129 return NODE_OTHER;
4130}
4131
4132#ifdef HAVE_ACL
4133struct my_acl
4134{
4135 PSECURITY_DESCRIPTOR pSecurityDescriptor;
4136 PSID pSidOwner;
4137 PSID pSidGroup;
4138 PACL pDacl;
4139 PACL pSacl;
4140};
4141#endif
4142
4143/*
4144 * Return a pointer to the ACL of file "fname" in allocated memory.
4145 * Return NULL if the ACL is not available for whatever reason.
4146 */
4147 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004148mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004149{
4150#ifndef HAVE_ACL
4151 return (vim_acl_T)NULL;
4152#else
4153 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02004154 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004155
Bram Moolenaarc799fe22019-05-28 23:08:19 +02004156 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004157 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004158 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004159 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02004160
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004161 wn = enc_to_utf16(fname, NULL);
4162 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004163 {
4164 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004165 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004166 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004167
4168 // Try to retrieve the entire security descriptor.
4169 err = GetNamedSecurityInfoW(
4170 wn, // Abstract filename
4171 SE_FILE_OBJECT, // File Object
4172 OWNER_SECURITY_INFORMATION |
4173 GROUP_SECURITY_INFORMATION |
4174 DACL_SECURITY_INFORMATION |
4175 SACL_SECURITY_INFORMATION,
4176 &p->pSidOwner, // Ownership information.
4177 &p->pSidGroup, // Group membership.
4178 &p->pDacl, // Discretionary information.
4179 &p->pSacl, // For auditing purposes.
4180 &p->pSecurityDescriptor);
4181 if (err == ERROR_ACCESS_DENIED ||
4182 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004183 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004184 // Retrieve only DACL.
4185 (void)GetNamedSecurityInfoW(
4186 wn,
4187 SE_FILE_OBJECT,
4188 DACL_SECURITY_INFORMATION,
4189 NULL,
4190 NULL,
4191 &p->pDacl,
4192 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004193 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004194 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004195 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004196 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004197 mch_free_acl((vim_acl_T)p);
4198 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004199 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004200 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004201 }
4202
4203 return (vim_acl_T)p;
4204#endif
4205}
4206
Bram Moolenaar27515922013-06-29 15:36:26 +02004207#ifdef HAVE_ACL
4208/*
4209 * Check if "acl" contains inherited ACE.
4210 */
4211 static BOOL
4212is_acl_inherited(PACL acl)
4213{
4214 DWORD i;
4215 ACL_SIZE_INFORMATION acl_info;
4216 PACCESS_ALLOWED_ACE ace;
4217
4218 acl_info.AceCount = 0;
4219 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
4220 for (i = 0; i < acl_info.AceCount; i++)
4221 {
4222 GetAce(acl, i, (LPVOID *)&ace);
4223 if (ace->Header.AceFlags & INHERITED_ACE)
4224 return TRUE;
4225 }
4226 return FALSE;
4227}
4228#endif
4229
Bram Moolenaar071d4272004-06-13 20:20:40 +00004230/*
4231 * Set the ACL of file "fname" to "acl" (unless it's NULL).
4232 * Errors are ignored.
4233 * This must only be called with "acl" equal to what mch_get_acl() returned.
4234 */
4235 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004236mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004237{
4238#ifdef HAVE_ACL
4239 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02004240 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004241 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004242
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004243 if (p == NULL)
4244 return;
4245
4246 wn = enc_to_utf16(fname, NULL);
4247 if (wn == NULL)
4248 return;
4249
4250 // Set security flags
4251 if (p->pSidOwner)
4252 sec_info |= OWNER_SECURITY_INFORMATION;
4253 if (p->pSidGroup)
4254 sec_info |= GROUP_SECURITY_INFORMATION;
4255 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02004256 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004257 sec_info |= DACL_SECURITY_INFORMATION;
4258 // Do not inherit its parent's DACL.
4259 // If the DACL is inherited, Cygwin permissions would be changed.
4260 if (!is_acl_inherited(p->pDacl))
4261 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02004262 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004263 if (p->pSacl)
4264 sec_info |= SACL_SECURITY_INFORMATION;
4265
4266 (void)SetNamedSecurityInfoW(
4267 wn, // Abstract filename
4268 SE_FILE_OBJECT, // File Object
4269 sec_info,
4270 p->pSidOwner, // Ownership information.
4271 p->pSidGroup, // Group membership.
4272 p->pDacl, // Discretionary information.
4273 p->pSacl // For auditing purposes.
4274 );
4275 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004276#endif
4277}
4278
4279 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004280mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004281{
4282#ifdef HAVE_ACL
4283 struct my_acl *p = (struct my_acl *)acl;
4284
4285 if (p != NULL)
4286 {
4287 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
4288 vim_free(p);
4289 }
4290#endif
4291}
4292
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004293#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004294
4295/*
4296 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
4297 */
4298 static BOOL WINAPI
4299handler_routine(
4300 DWORD dwCtrlType)
4301{
Bram Moolenaar589b1102017-08-12 16:39:05 +02004302 INPUT_RECORD ir;
4303 DWORD out;
4304
Bram Moolenaar071d4272004-06-13 20:20:40 +00004305 switch (dwCtrlType)
4306 {
4307 case CTRL_C_EVENT:
4308 if (ctrl_c_interrupts)
4309 g_fCtrlCPressed = TRUE;
4310 return TRUE;
4311
4312 case CTRL_BREAK_EVENT:
4313 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02004314 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004315 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02004316 ir.EventType = KEY_EVENT;
4317 ir.Event.KeyEvent.bKeyDown = TRUE;
4318 ir.Event.KeyEvent.wRepeatCount = 1;
4319 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
4320 ir.Event.KeyEvent.wVirtualScanCode = 0;
4321 ir.Event.KeyEvent.dwControlKeyState = 0;
4322 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
4323 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004324 return TRUE;
4325
Bram Moolenaar0f873732019-12-05 20:28:46 +01004326 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00004327 case CTRL_CLOSE_EVENT:
4328 case CTRL_LOGOFF_EVENT:
4329 case CTRL_SHUTDOWN_EVENT:
4330 windgoto((int)Rows - 1, 0);
4331 g_fForceExit = TRUE;
4332
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004333 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004334 (dwCtrlType == CTRL_CLOSE_EVENT
4335 ? _("close")
4336 : dwCtrlType == CTRL_LOGOFF_EVENT
4337 ? _("logoff")
4338 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004339# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00004340 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004341# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004342
Bram Moolenaar0f873732019-12-05 20:28:46 +01004343 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00004344
Bram Moolenaar0f873732019-12-05 20:28:46 +01004345 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00004346
4347 default:
4348 return FALSE;
4349 }
4350}
4351
4352
4353/*
4354 * set the tty in (raw) ? "raw" : "cooked" mode
4355 */
4356 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02004357mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004358{
4359 DWORD cmodein;
4360 DWORD cmodeout;
4361 BOOL bEnableHandler;
4362
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004363# ifdef VIMDLL
4364 if (gui.in_use)
4365 return;
4366# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004367 GetConsoleMode(g_hConIn, &cmodein);
4368 GetConsoleMode(g_hConOut, &cmodeout);
4369 if (tmode == TMODE_RAW)
4370 {
4371 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4372 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004373 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004374 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004375 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004376 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
4377 }
4378 else
4379 {
4380 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
4381 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004382 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004383# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01004384 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
4385 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004386 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004387# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004388 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004389# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004390 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004391 bEnableHandler = TRUE;
4392 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004393 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00004394 {
4395 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4396 ENABLE_ECHO_INPUT);
4397 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
4398 bEnableHandler = FALSE;
4399 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004400 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004401 SetConsoleMode(g_hConOut, cmodeout);
4402 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
4403
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004404# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004405 if (fdDump)
4406 {
4407 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
4408 tmode == TMODE_RAW ? "raw" :
4409 tmode == TMODE_COOK ? "cooked" : "normal",
4410 cmodein, cmodeout);
4411 fflush(fdDump);
4412 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004413# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004414}
4415
4416
4417/*
4418 * Get the size of the current window in `Rows' and `Columns'
4419 * Return OK when size could be determined, FAIL otherwise.
4420 */
4421 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004422mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004423{
4424 CONSOLE_SCREEN_BUFFER_INFO csbi;
4425
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004426# ifdef VIMDLL
4427 if (gui.in_use)
4428 return OK;
4429# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004430 if (!g_fTermcapMode && g_cbTermcap.IsValid)
4431 {
4432 /*
4433 * For some reason, we are trying to get the screen dimensions
4434 * even though we are not in termcap mode. The 'Rows' and 'Columns'
4435 * variables are really intended to mean the size of Vim screen
4436 * while in termcap mode.
4437 */
4438 Rows = g_cbTermcap.Info.dwSize.Y;
4439 Columns = g_cbTermcap.Info.dwSize.X;
4440 }
4441 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4442 {
4443 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4444 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4445 }
4446 else
4447 {
4448 Rows = 25;
4449 Columns = 80;
4450 }
4451 return OK;
4452}
4453
4454/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004455 * Resize console buffer to 'COORD'
4456 */
4457 static void
4458ResizeConBuf(
4459 HANDLE hConsole,
4460 COORD coordScreen)
4461{
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00004462 if (use_alternate_screen_buffer)
4463 return;
4464
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004465 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4466 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004467# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004468 if (fdDump)
4469 {
4470 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4471 GetLastError());
4472 fflush(fdDump);
4473 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004474# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004475 }
4476}
4477
4478/*
4479 * Resize console window size to 'srWindowRect'
4480 */
4481 static void
4482ResizeWindow(
4483 HANDLE hConsole,
4484 SMALL_RECT srWindowRect)
4485{
4486 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4487 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004488# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004489 if (fdDump)
4490 {
4491 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4492 GetLastError());
4493 fflush(fdDump);
4494 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004495# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004496 }
4497}
4498
4499/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004500 * Set a console window to `xSize' * `ySize'
4501 */
4502 static void
4503ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004504 HANDLE hConsole,
4505 int xSize,
4506 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004507{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004508 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
4509 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004510 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004511 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004512 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004513
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004514# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004515 if (fdDump)
4516 {
4517 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4518 fflush(fdDump);
4519 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004520# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004521
Bram Moolenaar0f873732019-12-05 20:28:46 +01004522 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00004523 coordScreen = GetLargestConsoleWindowSize(hConsole);
4524
Bram Moolenaar0f873732019-12-05 20:28:46 +01004525 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00004526 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4527 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4528 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4529
4530 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4531 {
4532 int sx, sy;
4533
4534 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4535 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4536 if (sy < ySize || sx < xSize)
4537 {
4538 /*
4539 * Increasing number of lines/columns, do buffer first.
4540 * Use the maximal size in x and y direction.
4541 */
4542 if (sy < ySize)
4543 coordScreen.Y = ySize;
4544 else
4545 coordScreen.Y = sy;
4546 if (sx < xSize)
4547 coordScreen.X = xSize;
4548 else
4549 coordScreen.X = sx;
4550 SetConsoleScreenBufferSize(hConsole, coordScreen);
4551 }
4552 }
4553
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004554 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004555 coordScreen.X = xSize;
4556 coordScreen.Y = ySize;
4557
Bram Moolenaar2551c032018-08-23 22:38:31 +02004558 // In the new console call API, only the first time in reverse order
4559 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004560 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004561 ResizeWindow(hConsole, srWindowRect);
4562 ResizeConBuf(hConsole, coordScreen);
4563 }
4564 else
4565 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004566 // Workaround for a Windows 10 bug
4567 cursor.X = srWindowRect.Left;
4568 cursor.Y = srWindowRect.Top;
4569 SetConsoleCursorPosition(hConsole, cursor);
4570
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004571 ResizeConBuf(hConsole, coordScreen);
4572 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004573 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004574 }
4575}
4576
4577
4578/*
4579 * Set the console window to `Rows' * `Columns'
4580 */
4581 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004582mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004583{
4584 COORD coordScreen;
4585
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004586# ifdef VIMDLL
4587 if (gui.in_use)
4588 return;
4589# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004590 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004591 if (suppress_winsize != 0)
4592 {
4593 suppress_winsize = 2;
4594 return;
4595 }
4596
4597 if (term_console)
4598 {
4599 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4600
Bram Moolenaar0f873732019-12-05 20:28:46 +01004601 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004602 if (Rows > coordScreen.Y)
4603 Rows = coordScreen.Y;
4604 if (Columns > coordScreen.X)
4605 Columns = coordScreen.X;
4606
4607 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4608 }
4609}
4610
4611/*
4612 * Rows and/or Columns has changed.
4613 */
4614 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004615mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004616{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004617# ifdef VIMDLL
4618 if (gui.in_use)
4619 return;
4620# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004621 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4622}
4623
4624
4625/*
4626 * Called when started up, to set the winsize that was delayed.
4627 */
4628 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004629mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004630{
4631 if (suppress_winsize == 2)
4632 {
4633 suppress_winsize = 0;
4634 mch_set_shellsize();
4635 shell_resized();
4636 }
4637 suppress_winsize = 0;
4638}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004639#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004640
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004641 static BOOL
4642vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004643 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004644 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004645 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004646 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004647 PROCESS_INFORMATION *pi,
4648 LPVOID *env,
4649 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004650{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004651 BOOL ret = FALSE;
4652 WCHAR *wcmd, *wcwd = NULL;
4653
4654 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4655 if (wcmd == NULL)
4656 return FALSE;
4657 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004658 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004659 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4660 if (wcwd == NULL)
4661 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004662 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004663
4664 ret = CreateProcessW(
4665 NULL, // Executable name
4666 wcmd, // Command to execute
4667 NULL, // Process security attributes
4668 NULL, // Thread security attributes
4669 inherit_handles, // Inherit handles
4670 flags, // Creation flags
4671 env, // Environment
4672 wcwd, // Current directory
4673 (LPSTARTUPINFOW)si, // Startup information
4674 pi); // Process information
4675theend:
4676 vim_free(wcmd);
4677 vim_free(wcwd);
4678 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004679}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004680
4681
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004682 static HINSTANCE
4683vim_shell_execute(
4684 char *cmd,
4685 INT n_show_cmd)
4686{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004687 HINSTANCE ret;
4688 WCHAR *wcmd;
4689
4690 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4691 if (wcmd == NULL)
4692 return (HINSTANCE) 0;
4693
4694 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4695 vim_free(wcmd);
4696 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004697}
4698
4699
Bram Moolenaar4f974752019-02-17 17:44:42 +01004700#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004701
4702/*
4703 * Specialised version of system() for Win32 GUI mode.
4704 * This version proceeds as follows:
4705 * 1. Create a console window for use by the subprocess
4706 * 2. Run the subprocess (it gets the allocated console by default)
4707 * 3. Wait for the subprocess to terminate and get its exit code
4708 * 4. Prompt the user to press a key to close the console window
4709 */
4710 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004711mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004712{
4713 STARTUPINFO si;
4714 PROCESS_INFORMATION pi;
4715 DWORD ret = 0;
4716 HWND hwnd = GetFocus();
4717
4718 si.cb = sizeof(si);
4719 si.lpReserved = NULL;
4720 si.lpDesktop = NULL;
4721 si.lpTitle = NULL;
4722 si.dwFlags = STARTF_USESHOWWINDOW;
4723 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004724 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004725 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004726 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004727 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004728 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004729 else
4730 si.wShowWindow = SW_SHOWNORMAL;
4731 si.cbReserved2 = 0;
4732 si.lpReserved2 = NULL;
4733
Bram Moolenaar0f873732019-12-05 20:28:46 +01004734 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004735 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004736 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4737 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004738
Bram Moolenaar0f873732019-12-05 20:28:46 +01004739 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004740 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004741# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004742 int delay = 1;
4743
Bram Moolenaar0f873732019-12-05 20:28:46 +01004744 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004745 for (;;)
4746 {
4747 MSG msg;
4748
K.Takatab7057bd2022-01-21 11:37:07 +00004749 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004750 {
4751 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004752 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004753 delay = 1;
4754 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004755 }
4756 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4757 break;
4758
Bram Moolenaar0f873732019-12-05 20:28:46 +01004759 // We start waiting for a very short time and then increase it, so
4760 // that we respond quickly when the process is quick, and don't
4761 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004762 if (delay < 50)
4763 delay += 10;
4764 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004765# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004766 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004767# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004768
Bram Moolenaar0f873732019-12-05 20:28:46 +01004769 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004770 GetExitCodeProcess(pi.hProcess, &ret);
4771 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004772
Bram Moolenaar0f873732019-12-05 20:28:46 +01004773 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004774 CloseHandle(pi.hThread);
4775 CloseHandle(pi.hProcess);
4776
Bram Moolenaar0f873732019-12-05 20:28:46 +01004777 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004778 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4779
4780 return ret;
4781}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004782
4783/*
4784 * Thread launched by the gui to send the current buffer data to the
4785 * process. This way avoid to hang up vim totally if the children
4786 * process take a long time to process the lines.
4787 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004788 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004789sub_process_writer(LPVOID param)
4790{
4791 HANDLE g_hChildStd_IN_Wr = param;
4792 linenr_T lnum = curbuf->b_op_start.lnum;
4793 DWORD len = 0;
4794 DWORD l;
4795 char_u *lp = ml_get(lnum);
4796 char_u *s;
4797 int written = 0;
4798
4799 for (;;)
4800 {
4801 l = (DWORD)STRLEN(lp + written);
4802 if (l == 0)
4803 len = 0;
4804 else if (lp[written] == NL)
4805 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004806 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004807 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4808 }
4809 else
4810 {
4811 s = vim_strchr(lp + written, NL);
4812 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4813 s == NULL ? l : (DWORD)(s - (lp + written)),
4814 &len, NULL);
4815 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004816 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004817 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004818 // Finished a line, add a NL, unless this line should not have
4819 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004820 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004821 || (!curbuf->b_p_bin
4822 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004823 || (lnum != curbuf->b_no_eol_lnum
4824 && (lnum != curbuf->b_ml.ml_line_count
4825 || curbuf->b_p_eol)))
4826 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004827 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4828 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004829 }
4830
4831 ++lnum;
4832 if (lnum > curbuf->b_op_end.lnum)
4833 break;
4834
4835 lp = ml_get(lnum);
4836 written = 0;
4837 }
4838 else if (len > 0)
4839 written += len;
4840 }
4841
Bram Moolenaar0f873732019-12-05 20:28:46 +01004842 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004843 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004844 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004845}
4846
4847
Bram Moolenaar0f873732019-12-05 20:28:46 +01004848# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004849
4850/*
4851 * This function read from the children's stdout and write the
4852 * data on screen or in the buffer accordingly.
4853 */
4854 static void
4855dump_pipe(int options,
4856 HANDLE g_hChildStd_OUT_Rd,
4857 garray_T *ga,
4858 char_u buffer[],
4859 DWORD *buffer_off)
4860{
4861 DWORD availableBytes = 0;
4862 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004863 int ret;
4864 DWORD len;
4865 DWORD toRead;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004866
Bram Moolenaar0f873732019-12-05 20:28:46 +01004867 // we query the pipe to see if there is any data to read
4868 // to avoid to perform a blocking read
4869 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4870 NULL, // optional buffer
4871 0, // buffer size
4872 NULL, // number of read bytes
4873 &availableBytes, // available bytes total
4874 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004875
Bram Moolenaar0f873732019-12-05 20:28:46 +01004876 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004877 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004878 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01004879 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004880 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004881 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004882
Bram Moolenaar0f873732019-12-05 20:28:46 +01004883 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004884 if (len == 0)
4885 break;
4886
4887 availableBytes -= len;
4888
4889 if (options & SHELL_READ)
4890 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004891 // Do NUL -> NL translation, append NL separated
4892 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004893 for (i = 0; i < len; ++i)
4894 {
4895 if (buffer[i] == NL)
4896 append_ga_line(ga);
4897 else if (buffer[i] == NUL)
4898 ga_append(ga, NL);
4899 else
4900 ga_append(ga, buffer[i]);
4901 }
4902 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004903 else if (has_mbyte)
4904 {
4905 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004906 int c;
4907 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004908
4909 len += *buffer_off;
4910 buffer[len] = NUL;
4911
Bram Moolenaar0f873732019-12-05 20:28:46 +01004912 // Check if the last character in buffer[] is
4913 // incomplete, keep these bytes for the next
4914 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004915 for (p = buffer; p < buffer + len; p += l)
4916 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004917 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004918 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004919 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004920 else if (MB_BYTE2LEN(*p) != l)
4921 break;
4922 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004923 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004924 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004925 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004926 if (len >= 12)
4927 ++p;
4928 else
4929 {
4930 *buffer_off = len;
4931 return;
4932 }
4933 }
4934 c = *p;
4935 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004936 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004937 if (p < buffer + len)
4938 {
4939 *p = c;
4940 *buffer_off = (DWORD)((buffer + len) - p);
4941 mch_memmove(buffer, p, *buffer_off);
4942 return;
4943 }
4944 *buffer_off = 0;
4945 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004946 else
4947 {
4948 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004949 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004950 }
4951
4952 windgoto(msg_row, msg_col);
4953 cursor_on();
4954 out_flush();
4955 }
4956}
4957
4958/*
4959 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4960 * for communication and doesn't open any new window.
4961 */
4962 static int
4963mch_system_piped(char *cmd, int options)
4964{
4965 STARTUPINFO si;
4966 PROCESS_INFORMATION pi;
4967 DWORD ret = 0;
4968
4969 HANDLE g_hChildStd_IN_Rd = NULL;
4970 HANDLE g_hChildStd_IN_Wr = NULL;
4971 HANDLE g_hChildStd_OUT_Rd = NULL;
4972 HANDLE g_hChildStd_OUT_Wr = NULL;
4973
Bram Moolenaar0f873732019-12-05 20:28:46 +01004974 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004975 DWORD len;
4976
Bram Moolenaar0f873732019-12-05 20:28:46 +01004977 // buffer used to receive keys
4978 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4979 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004980
4981 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004982 int noread_cnt = 0;
4983 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004984 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004985 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004986 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004987
4988 SECURITY_ATTRIBUTES saAttr;
4989
Bram Moolenaar0f873732019-12-05 20:28:46 +01004990 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004991 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4992 saAttr.bInheritHandle = TRUE;
4993 saAttr.lpSecurityDescriptor = NULL;
4994
4995 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004996 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004997 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004998 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004999 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005000 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005001 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005002 {
5003 CloseHandle(g_hChildStd_IN_Rd);
5004 CloseHandle(g_hChildStd_IN_Wr);
5005 CloseHandle(g_hChildStd_OUT_Rd);
5006 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01005007 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005008 }
5009
5010 si.cb = sizeof(si);
5011 si.lpReserved = NULL;
5012 si.lpDesktop = NULL;
5013 si.lpTitle = NULL;
5014 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
5015
Bram Moolenaar0f873732019-12-05 20:28:46 +01005016 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005017 si.hStdError = g_hChildStd_OUT_Wr;
5018 si.hStdOutput = g_hChildStd_OUT_Wr;
5019 si.hStdInput = g_hChildStd_IN_Rd;
5020 si.wShowWindow = SW_HIDE;
5021 si.cbReserved2 = 0;
5022 si.lpReserved2 = NULL;
5023
5024 if (options & SHELL_READ)
5025 ga_init2(&ga, 1, BUFLEN);
5026
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005027 if (cmd != NULL)
5028 {
5029 p = (char *)vim_strsave((char_u *)cmd);
5030 if (p != NULL)
5031 unescape_shellxquote((char_u *)p, p_sxe);
5032 else
5033 p = cmd;
5034 }
5035
Bram Moolenaar0f873732019-12-05 20:28:46 +01005036 // Now, run the command.
5037 // About "Inherit handles" being TRUE: this command can be litigious,
5038 // handle inheritance was deactivated for pending temp file, but, if we
5039 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005040 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
5041 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005042
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005043 if (p != cmd)
5044 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005045
Bram Moolenaar0f873732019-12-05 20:28:46 +01005046 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005047 CloseHandle(g_hChildStd_IN_Rd);
5048 CloseHandle(g_hChildStd_OUT_Wr);
5049
5050 if (options & SHELL_WRITE)
5051 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02005052 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005053 _beginthreadex(NULL, // security attributes
5054 0, // default stack size
5055 sub_process_writer, // function to be executed
5056 g_hChildStd_IN_Wr, // parameter
5057 0, // creation flag, start immediately
5058 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005059 CloseHandle(thread);
5060 g_hChildStd_IN_Wr = NULL;
5061 }
5062
Bram Moolenaar0f873732019-12-05 20:28:46 +01005063 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005064 for (;;)
5065 {
5066 MSG msg;
5067
K.Takatab7057bd2022-01-21 11:37:07 +00005068 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005069 {
5070 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00005071 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005072 }
5073
Bram Moolenaar0f873732019-12-05 20:28:46 +01005074 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005075 if ((options & (SHELL_READ|SHELL_WRITE))
5076# ifdef FEAT_GUI
5077 || gui.in_use
5078# endif
5079 )
5080 {
5081 len = 0;
5082 if (!(options & SHELL_EXPAND)
5083 && ((options &
5084 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
5085 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
5086# ifdef FEAT_GUI
5087 || gui.in_use
5088# endif
5089 )
5090 && (ta_len > 0 || noread_cnt > 4))
5091 {
5092 if (ta_len == 0)
5093 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005094 // Get extra characters when we don't have any. Reset the
5095 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005096 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005097 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
5098 }
5099 if (ta_len > 0 || len > 0)
5100 {
5101 /*
5102 * For pipes: Check for CTRL-C: send interrupt signal to
5103 * child. Check for CTRL-D: EOF, close pipe to child.
5104 */
5105 if (len == 1 && cmd != NULL)
5106 {
5107 if (ta_buf[ta_len] == Ctrl_C)
5108 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005109 // Learn what exit code is expected, for
5110 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005111 TerminateProcess(pi.hProcess, 9);
5112 }
5113 if (ta_buf[ta_len] == Ctrl_D)
5114 {
5115 CloseHandle(g_hChildStd_IN_Wr);
5116 g_hChildStd_IN_Wr = NULL;
5117 }
5118 }
5119
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01005120 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005121
5122 /*
5123 * For pipes: echo the typed characters. For a pty this
5124 * does not seem to work.
5125 */
5126 for (i = ta_len; i < ta_len + len; ++i)
5127 {
5128 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
5129 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005130 else if (has_mbyte)
5131 {
5132 int l = (*mb_ptr2len)(ta_buf + i);
5133
5134 msg_outtrans_len(ta_buf + i, l);
5135 i += l - 1;
5136 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005137 else
5138 msg_outtrans_len(ta_buf + i, 1);
5139 }
5140 windgoto(msg_row, msg_col);
5141 out_flush();
5142
5143 ta_len += len;
5144
5145 /*
5146 * Write the characters to the child, unless EOF has been
5147 * typed for pipes. Write one character at a time, to
5148 * avoid losing too much typeahead. When writing buffer
5149 * lines, drop the typed characters (only check for
5150 * CTRL-C).
5151 */
5152 if (options & SHELL_WRITE)
5153 ta_len = 0;
5154 else if (g_hChildStd_IN_Wr != NULL)
5155 {
5156 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
5157 1, &len, NULL);
5158 // if we are typing in, we want to keep things reactive
5159 delay = 1;
5160 if (len > 0)
5161 {
5162 ta_len -= len;
5163 mch_memmove(ta_buf, ta_buf + len, ta_len);
5164 }
5165 }
5166 }
5167 }
5168 }
5169
5170 if (ta_len)
5171 ui_inchar_undo(ta_buf, ta_len);
5172
5173 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
5174 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005175 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005176 break;
5177 }
5178
5179 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005180 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005181
Bram Moolenaar0f873732019-12-05 20:28:46 +01005182 // We start waiting for a very short time and then increase it, so
5183 // that we respond quickly when the process is quick, and don't
5184 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005185 if (delay < 50)
5186 delay += 10;
5187 }
5188
Bram Moolenaar0f873732019-12-05 20:28:46 +01005189 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005190 CloseHandle(g_hChildStd_OUT_Rd);
5191 if (g_hChildStd_IN_Wr != NULL)
5192 CloseHandle(g_hChildStd_IN_Wr);
5193
5194 WaitForSingleObject(pi.hProcess, INFINITE);
5195
Bram Moolenaar0f873732019-12-05 20:28:46 +01005196 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005197 GetExitCodeProcess(pi.hProcess, &ret);
5198
5199 if (options & SHELL_READ)
5200 {
5201 if (ga.ga_len > 0)
5202 {
5203 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01005204 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005205 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
5206 }
5207 else
5208 curbuf->b_no_eol_lnum = 0;
5209 ga_clear(&ga);
5210 }
5211
Bram Moolenaar0f873732019-12-05 20:28:46 +01005212 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005213 CloseHandle(pi.hThread);
5214 CloseHandle(pi.hProcess);
5215
5216 return ret;
5217}
5218
5219 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005220mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005221{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005222 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005223 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005224 return mch_system_piped(cmd, options);
5225 else
5226 return mch_system_classic(cmd, options);
5227}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005228#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005229
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005230#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005231 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02005232mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005233{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005234 int ret;
5235 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005236 char_u *buf;
5237 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005238
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005239 // If the command starts and ends with double quotes, enclose the command
5240 // in parentheses.
5241 len = STRLEN(cmd);
5242 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
5243 {
5244 len += 3;
5245 buf = alloc(len);
5246 if (buf == NULL)
5247 return -1;
5248 vim_snprintf((char *)buf, len, "(%s)", cmd);
5249 wcmd = enc_to_utf16(buf, NULL);
5250 free(buf);
5251 }
5252 else
5253 wcmd = enc_to_utf16((char_u *)cmd, NULL);
5254
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005255 if (wcmd == NULL)
5256 return -1;
5257
5258 ret = _wsystem(wcmd);
5259 vim_free(wcmd);
5260 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005261}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005262
5263#endif
5264
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005265 static int
5266mch_system(char *cmd, int options)
5267{
5268#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005269 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005270 return mch_system_g(cmd, options);
5271 else
5272 return mch_system_c(cmd, options);
5273#elif defined(FEAT_GUI_MSWIN)
5274 return mch_system_g(cmd, options);
5275#else
5276 return mch_system_c(cmd, options);
5277#endif
5278}
5279
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005280#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
5281/*
5282 * Use a terminal window to run a shell command in.
5283 */
5284 static int
5285mch_call_shell_terminal(
5286 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005287 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005288{
5289 jobopt_T opt;
5290 char_u *newcmd = NULL;
5291 typval_T argvar[2];
5292 long_u cmdlen;
5293 int retval = -1;
5294 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005295 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005296 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005297 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005298
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005299 if (cmd == NULL)
5300 cmdlen = STRLEN(p_sh) + 1;
5301 else
5302 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005303 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005304 if (newcmd == NULL)
5305 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005306 if (cmd == NULL)
5307 {
5308 STRCPY(newcmd, p_sh);
5309 ch_log(NULL, "starting terminal to run a shell");
5310 }
5311 else
5312 {
5313 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
5314 ch_log(NULL, "starting terminal for system command '%s'", cmd);
5315 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005316
5317 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005318
5319 argvar[0].v_type = VAR_STRING;
5320 argvar[0].vval.v_string = newcmd;
5321 argvar[1].v_type = VAR_UNKNOWN;
5322 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005323 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01005324 {
5325 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005326 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01005327 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005328
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005329 job = term_getjob(buf->b_term);
5330 ++job->jv_refcount;
5331
Bram Moolenaar0f873732019-12-05 20:28:46 +01005332 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005333 aucmd_prepbuf(&aco, buf);
Bram Moolenaare76062c2022-11-28 18:51:43 +00005334 if (curbuf == buf)
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005335 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005336 // Only do this when a window was found for "buf".
5337 clear_oparg(&oa);
5338 while (term_use_loop())
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005339 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005340 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
5341 {
5342 // If terminal_loop() returns OK we got a key that is handled
5343 // in Normal model. We don't do redrawing anyway.
5344 if (terminal_loop(TRUE) == OK)
5345 normal_cmd(&oa, TRUE);
5346 }
5347 else
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005348 normal_cmd(&oa, TRUE);
5349 }
Bram Moolenaare76062c2022-11-28 18:51:43 +00005350 retval = job->jv_exitval;
5351 ch_log(NULL, "system command finished");
5352
5353 job_unref(job);
5354
5355 // restore curwin/curbuf and a few other things
5356 aucmd_restbuf(&aco);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005357 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005358
5359 wait_return(TRUE);
5360 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
5361
5362 vim_free(newcmd);
5363 return retval;
5364}
5365#endif
5366
Bram Moolenaar071d4272004-06-13 20:20:40 +00005367/*
5368 * Either execute a command by calling the shell or start a new shell
5369 */
5370 int
5371mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005372 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005373 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00005374{
5375 int x = 0;
5376 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005377 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02005378
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00005379#ifdef FEAT_EVAL
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01005380 ch_log(NULL, "executing shell command: %s", cmd);
5381#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01005382 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02005383 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005384 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005385 if (cmd == NULL)
5386 wcscat(szShellTitle, L" :sh");
5387 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005388 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005389 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005390
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005391 if (wn != NULL)
5392 {
5393 wcscat(szShellTitle, L" - !");
5394 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02005395 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005396 wcscat(szShellTitle, wn);
5397 SetConsoleTitleW(szShellTitle);
5398 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005399 }
5400 }
5401 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005402
5403 out_flush();
5404
5405#ifdef MCH_WRITE_DUMP
5406 if (fdDump)
5407 {
5408 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
5409 fflush(fdDump);
5410 }
5411#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005412#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005413 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005414 if (
5415# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005416 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005417# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005418 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005419 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
5420 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005421 char_u *cmdbase = cmd;
5422
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02005423 if (cmdbase != NULL)
5424 // Skip a leading quote and (.
5425 while (*cmdbase == '"' || *cmdbase == '(')
5426 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005427
5428 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01005429 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
5430 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005431 {
5432 // Use a terminal window to run the command in.
5433 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005434 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005435 return x;
5436 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005437 }
5438#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005439
5440 /*
5441 * Catch all deadly signals while running the external command, because a
5442 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5443 */
ichizok378447f2023-05-11 22:25:42 +01005444 mch_signal(SIGINT, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005445#if defined(__GNUC__) && !defined(__MINGW32__)
ichizok378447f2023-05-11 22:25:42 +01005446 mch_signal(SIGKILL, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005447#else
ichizok378447f2023-05-11 22:25:42 +01005448 mch_signal(SIGBREAK, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005449#endif
ichizok378447f2023-05-11 22:25:42 +01005450 mch_signal(SIGILL, SIG_IGN);
5451 mch_signal(SIGFPE, SIG_IGN);
5452 mch_signal(SIGSEGV, SIG_IGN);
5453 mch_signal(SIGTERM, SIG_IGN);
5454 mch_signal(SIGABRT, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005455
5456 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005457 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00005458
5459 if (cmd == NULL)
5460 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005461 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005462 }
5463 else
5464 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005465 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005466 char_u *newcmd = NULL;
5467 char_u *cmdbase = cmd;
5468 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005469
Bram Moolenaar0f873732019-12-05 20:28:46 +01005470 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005471 if (*cmdbase == '"' )
5472 ++cmdbase;
5473 if (*cmdbase == '(')
5474 ++cmdbase;
5475
Bram Moolenaar1c465442017-03-12 20:10:05 +01005476 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005477 {
5478 STARTUPINFO si;
5479 PROCESS_INFORMATION pi;
5480 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005481 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005482 char_u *p;
5483
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005484 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005485 si.cb = sizeof(si);
5486 si.lpReserved = NULL;
5487 si.lpDesktop = NULL;
5488 si.lpTitle = NULL;
5489 si.dwFlags = 0;
5490 si.cbReserved2 = 0;
5491 si.lpReserved2 = NULL;
5492
5493 cmdbase = skipwhite(cmdbase + 5);
5494 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005495 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005496 {
5497 cmdbase = skipwhite(cmdbase + 4);
5498 si.dwFlags = STARTF_USESHOWWINDOW;
5499 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005500 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005501 }
5502 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005503 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005504 {
5505 cmdbase = skipwhite(cmdbase + 2);
5506 flags = CREATE_NO_WINDOW;
5507 si.dwFlags = STARTF_USESTDHANDLES;
5508 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005509 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005510 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005511 NULL, // Security att.
5512 OPEN_EXISTING, // Open flags
5513 FILE_ATTRIBUTE_NORMAL, // File att.
5514 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005515 si.hStdOutput = si.hStdInput;
5516 si.hStdError = si.hStdInput;
5517 }
5518
Bram Moolenaar0f873732019-12-05 20:28:46 +01005519 // Remove a trailing ", ) and )" if they have a match
5520 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005521 if (cmdbase > cmd)
5522 {
5523 p = cmdbase + STRLEN(cmdbase);
5524 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5525 *--p = NUL;
5526 if (p > cmdbase && p[-1] == ')'
5527 && (*cmd =='(' || cmd[1] == '('))
5528 *--p = NUL;
5529 }
5530
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005531 newcmd = cmdbase;
5532 unescape_shellxquote(cmdbase, p_sxe);
5533
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005534 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005535 * If creating new console, arguments are passed to the
5536 * 'cmd.exe' as-is. If it's not, arguments are not treated
5537 * correctly for current 'cmd.exe'. So unescape characters in
5538 * shellxescape except '|' for avoiding to be treated as
5539 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005540 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005541 if (flags != CREATE_NEW_CONSOLE)
5542 {
5543 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005544 char_u *cmd_shell = mch_getenv("COMSPEC");
5545
5546 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005547 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005548
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005549 subcmd = vim_strsave_escaped_ext(cmdbase,
5550 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005551 if (subcmd != NULL)
5552 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005553 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005554 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005555 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005556 if (newcmd != NULL)
5557 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005558 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005559 else
5560 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005561 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005562 }
5563 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005564
5565 /*
5566 * Now, start the command as a process, so that it doesn't
5567 * inherit our handles which causes unpleasant dangling swap
5568 * files if we exit before the spawned process
5569 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005570 if (vim_create_process((char *)newcmd, FALSE, flags,
5571 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005572 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005573 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5574 > (HINSTANCE)32)
5575 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005576 else
5577 {
5578 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005579#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005580# ifdef VIMDLL
5581 if (gui.in_use)
5582# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005583 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005584#endif
5585 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005586
5587 if (newcmd != cmdbase)
5588 vim_free(newcmd);
5589
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005590 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005591 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005592 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005593 CloseHandle(si.hStdInput);
5594 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005595 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005596 CloseHandle(pi.hThread);
5597 CloseHandle(pi.hProcess);
5598 }
5599 else
5600 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005601 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005602#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005603 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005604 (!s_dont_use_vimrun && p_stmp ?
5605 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5606 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005607#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005608 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005609
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005610 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005611 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005612 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005613#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005614 if (
5615# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005616 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005617# endif
5618 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005619 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005620 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5621 "External commands will not pause after completion.\n"
5622 "See :help win32-vimrun for more information.");
5623 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005624 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5625 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005626
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005627 if (wmsg != NULL && wtitle != NULL)
5628 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5629 vim_free(wmsg);
5630 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005631 need_vimrun_warning = FALSE;
5632 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005633 if (
5634# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005635 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005636# endif
5637 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005638 // Use vimrun to execute the command. It opens a console
5639 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005640 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005641 vimrun_path,
5642 (msg_silent != 0 || (options & SHELL_DOOUT))
5643 ? "-s " : "",
5644 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005645 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005646# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005647 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005648# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005649 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005650 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005651 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5652 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005653 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005654#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005655 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005656 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005657 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005658 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005659 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005660 }
5661 }
5662
5663 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005664 {
5665 // The shell may have messed with the mode, always set it.
5666 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005667 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005668 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005669
Bram Moolenaar0f873732019-12-05 20:28:46 +01005670 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005671 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005672#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005673 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005674 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005675#endif
5676 )
5677 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005678 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005679 msg_putchar('\n');
5680 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005681 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005682
ichizok378447f2023-05-11 22:25:42 +01005683 mch_signal(SIGINT, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005684#if defined(__GNUC__) && !defined(__MINGW32__)
ichizok378447f2023-05-11 22:25:42 +01005685 mch_signal(SIGKILL, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005686#else
ichizok378447f2023-05-11 22:25:42 +01005687 mch_signal(SIGBREAK, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005688#endif
ichizok378447f2023-05-11 22:25:42 +01005689 mch_signal(SIGILL, SIG_DFL);
5690 mch_signal(SIGFPE, SIG_DFL);
5691 mch_signal(SIGSEGV, SIG_DFL);
5692 mch_signal(SIGTERM, SIG_DFL);
5693 mch_signal(SIGABRT, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005694
5695 return x;
5696}
5697
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005698#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005699 static HANDLE
5700job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005701 char_u *fname,
5702 DWORD dwDesiredAccess,
5703 DWORD dwShareMode,
5704 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5705 DWORD dwCreationDisposition,
5706 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005707{
5708 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005709 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005710
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005711 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005712 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005713 return INVALID_HANDLE_VALUE;
5714
5715 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5716 lpSecurityAttributes, dwCreationDisposition,
5717 dwFlagsAndAttributes, NULL);
5718 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005719 return h;
5720}
5721
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005722/*
5723 * Turn the dictionary "env" into a NUL separated list that can be used as the
5724 * environment argument of vim_create_process().
5725 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005726 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005727win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005728{
5729 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005730 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005731 LPVOID base = GetEnvironmentStringsW();
5732
Bram Moolenaar0f873732019-12-05 20:28:46 +01005733 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005734 if (ga_grow(gap, 1) == FAIL)
5735 return;
5736
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005737 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005738 {
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00005739 FOR_ALL_HASHTAB_ITEMS(&env->dv_hashtab, hi, todo)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005740 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005741 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005742 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005743 typval_T *item = &dict_lookup(hi)->di_tv;
5744 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005745 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005746 --todo;
5747 if (wkey != NULL && wval != NULL)
5748 {
5749 size_t n;
5750 size_t lkey = wcslen(wkey);
5751 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005752
Yegappan Lakshmananfadc02a2023-01-27 21:03:12 +00005753 if (ga_grow(gap, (int)(lkey + lval + 2)) == FAIL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005754 continue;
5755 for (n = 0; n < lkey; n++)
5756 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5757 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5758 for (n = 0; n < lval; n++)
5759 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5760 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5761 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005762 vim_free(wkey);
5763 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005764 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005765 }
5766 }
5767
Bram Moolenaar355757a2020-02-10 22:06:32 +01005768 if (base)
5769 {
5770 WCHAR *p = (WCHAR*) base;
5771
5772 // for last \0
5773 if (ga_grow(gap, 1) == FAIL)
5774 return;
5775
5776 while (*p != 0 || *(p + 1) != 0)
5777 {
5778 if (ga_grow(gap, 1) == OK)
5779 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5780 p++;
5781 }
5782 FreeEnvironmentStrings(base);
5783 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5784 }
5785
Bram Moolenaar493359e2018-06-12 20:25:52 +02005786# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005787 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005788# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005789 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005790 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005791# endif
5792# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005793 char_u *version = get_vim_var_str(VV_VERSION);
5794 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005795# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005796 // size of "VIM_SERVERNAME=" and value,
5797 // plus "VIM_TERMINAL=" and value,
5798 // plus two terminating NULs
5799 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005800# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005801 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005802# endif
5803# ifdef FEAT_TERMINAL
5804 + 13 + version_len + 2
5805# endif
5806 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005807
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005808 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005809 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005810# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005811 for (n = 0; n < 15; n++)
5812 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5813 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005814 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005815 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5816 (WCHAR)servername[n];
5817 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005818# endif
5819# ifdef FEAT_TERMINAL
5820 if (is_terminal)
5821 {
5822 for (n = 0; n < 13; n++)
5823 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5824 (WCHAR)"VIM_TERMINAL="[n];
5825 for (n = 0; n < version_len; n++)
5826 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5827 (WCHAR)version[n];
5828 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5829 }
5830# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005831 }
5832 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005833# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005834}
5835
Bram Moolenaarb091f302019-01-19 14:37:00 +01005836/*
5837 * Create a pair of pipes.
5838 * Return TRUE for success, FALSE for failure.
5839 */
5840 static BOOL
5841create_pipe_pair(HANDLE handles[2])
5842{
5843 static LONG s;
5844 char name[64];
5845 SECURITY_ATTRIBUTES sa;
5846
5847 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5848 GetCurrentProcessId(),
5849 InterlockedIncrement(&s));
5850
5851 // Create named pipe. Max size of named pipe is 65535.
5852 handles[1] = CreateNamedPipe(
5853 name,
5854 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5855 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005856 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005857
5858 if (handles[1] == INVALID_HANDLE_VALUE)
5859 return FALSE;
5860
5861 sa.nLength = sizeof(sa);
5862 sa.bInheritHandle = TRUE;
5863 sa.lpSecurityDescriptor = NULL;
5864
5865 handles[0] = CreateFile(name,
5866 FILE_GENERIC_READ,
5867 FILE_SHARE_READ, &sa,
5868 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5869
5870 if (handles[0] == INVALID_HANDLE_VALUE)
5871 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005872 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005873 return FALSE;
5874 }
5875
5876 return TRUE;
5877}
5878
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005879 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005880mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005881{
5882 STARTUPINFO si;
5883 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005884 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005885 SECURITY_ATTRIBUTES saAttr;
5886 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005887 HANDLE ifd[2];
5888 HANDLE ofd[2];
5889 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005890 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005891
5892 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5893 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5894 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5895 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5896 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5897 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5898 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5899
5900 if (use_out_for_err && use_null_for_out)
5901 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005902
5903 ifd[0] = INVALID_HANDLE_VALUE;
5904 ifd[1] = INVALID_HANDLE_VALUE;
5905 ofd[0] = INVALID_HANDLE_VALUE;
5906 ofd[1] = INVALID_HANDLE_VALUE;
5907 efd[0] = INVALID_HANDLE_VALUE;
5908 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005909 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005910
Bram Moolenaar14207f42016-10-27 21:13:10 +02005911 jo = CreateJobObject(NULL, NULL);
5912 if (jo == NULL)
5913 {
5914 job->jv_status = JOB_FAILED;
5915 goto failed;
5916 }
5917
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005918 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005919 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005920
Bram Moolenaar76467df2016-02-12 19:30:26 +01005921 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005922 ZeroMemory(&si, sizeof(si));
5923 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005924 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005925 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005926
Bram Moolenaard8070362016-02-15 21:56:54 +01005927 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5928 saAttr.bInheritHandle = TRUE;
5929 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005930
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005931 if (use_file_for_in)
5932 {
5933 char_u *fname = options->jo_io_name[PART_IN];
5934
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005935 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5936 FILE_SHARE_READ | FILE_SHARE_WRITE,
5937 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5938 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005939 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005940 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005941 goto failed;
5942 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005943 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005944 else if (!use_null_for_in
5945 && (!create_pipe_pair(ifd)
5946 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005947 goto failed;
5948
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005949 if (use_file_for_out)
5950 {
5951 char_u *fname = options->jo_io_name[PART_OUT];
5952
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005953 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5954 FILE_SHARE_READ | FILE_SHARE_WRITE,
5955 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5956 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005957 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005958 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005959 goto failed;
5960 }
5961 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005962 else if (!use_null_for_out &&
5963 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005964 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005965 goto failed;
5966
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005967 if (use_file_for_err)
5968 {
5969 char_u *fname = options->jo_io_name[PART_ERR];
5970
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005971 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5972 FILE_SHARE_READ | FILE_SHARE_WRITE,
5973 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5974 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005975 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005976 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005977 goto failed;
5978 }
5979 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005980 else if (!use_out_for_err && !use_null_for_err &&
5981 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005982 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005983 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005984
Bram Moolenaard8070362016-02-15 21:56:54 +01005985 si.dwFlags |= STARTF_USESTDHANDLES;
5986 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005987 si.hStdOutput = ofd[1];
5988 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5989
5990 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5991 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005992 if (options->jo_set & JO_CHANNEL)
5993 {
5994 channel = options->jo_channel;
5995 if (channel != NULL)
5996 ++channel->ch_refcount;
5997 }
5998 else
5999 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006000 if (channel == NULL)
6001 goto failed;
6002 }
Bram Moolenaard8070362016-02-15 21:56:54 +01006003
6004 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02006005 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006006 CREATE_DEFAULT_ERROR_MODE |
6007 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006008 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01006009 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006010 &si, &pi,
6011 ga.ga_data,
6012 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01006013 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02006014 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006015 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006016 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006017 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006018
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006019 ga_clear(&ga);
6020
Bram Moolenaar14207f42016-10-27 21:13:10 +02006021 if (!AssignProcessToJobObject(jo, pi.hProcess))
6022 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006023 // if failing, switch the way to terminate
6024 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02006025 CloseHandle(jo);
6026 jo = NULL;
6027 }
6028 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01006029 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006030 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02006031 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006032 job->jv_status = JOB_STARTED;
6033
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02006034 CloseHandle(ifd[0]);
6035 CloseHandle(ofd[1]);
6036 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01006037 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01006038
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006039 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006040 if (channel != NULL)
6041 {
6042 channel_set_pipes(channel,
6043 use_file_for_in || use_null_for_in
6044 ? INVALID_FD : (sock_T)ifd[1],
6045 use_file_for_out || use_null_for_out
6046 ? INVALID_FD : (sock_T)ofd[0],
6047 use_out_for_err || use_file_for_err || use_null_for_err
6048 ? INVALID_FD : (sock_T)efd[0]);
6049 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006050 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006051 return;
6052
6053failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01006054 CloseHandle(ifd[0]);
6055 CloseHandle(ofd[0]);
6056 CloseHandle(efd[0]);
6057 CloseHandle(ifd[1]);
6058 CloseHandle(ofd[1]);
6059 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01006060 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006061 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006062}
6063
6064 char *
6065mch_job_status(job_T *job)
6066{
6067 DWORD dwExitCode = 0;
6068
Bram Moolenaar76467df2016-02-12 19:30:26 +01006069 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
6070 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006071 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01006072 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01006073 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02006074 {
6075 ch_log(job->jv_channel, "Job ended");
6076 job->jv_status = JOB_ENDED;
6077 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006078 return "dead";
6079 }
6080 return "run";
6081}
6082
Bram Moolenaar97792de2016-10-15 18:36:49 +02006083 job_T *
6084mch_detect_ended_job(job_T *job_list)
6085{
6086 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
6087 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
6088 job_T *job = job_list;
6089
6090 while (job != NULL)
6091 {
6092 DWORD n;
6093 DWORD result;
6094
6095 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
6096 && job != NULL; job = job->jv_next)
6097 {
6098 if (job->jv_status == JOB_STARTED)
6099 {
6100 jobHandles[n] = job->jv_proc_info.hProcess;
6101 jobArray[n] = job;
6102 ++n;
6103 }
6104 }
6105 if (n == 0)
6106 continue;
6107 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
6108 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
6109 {
6110 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
6111
6112 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
6113 return wait_job;
6114 }
6115 }
6116 return NULL;
6117}
6118
Bram Moolenaarfb630902016-10-29 14:55:00 +02006119 static BOOL
6120terminate_all(HANDLE process, int code)
6121{
6122 PROCESSENTRY32 pe;
6123 HANDLE h = INVALID_HANDLE_VALUE;
6124 DWORD pid = GetProcessId(process);
6125
6126 if (pid != 0)
6127 {
6128 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
6129 if (h != INVALID_HANDLE_VALUE)
6130 {
6131 pe.dwSize = sizeof(PROCESSENTRY32);
6132 if (!Process32First(h, &pe))
6133 goto theend;
6134
6135 do
6136 {
6137 if (pe.th32ParentProcessID == pid)
6138 {
6139 HANDLE ph = OpenProcess(
6140 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
6141 if (ph != NULL)
6142 {
6143 terminate_all(ph, code);
6144 CloseHandle(ph);
6145 }
6146 }
6147 } while (Process32Next(h, &pe));
6148
6149 CloseHandle(h);
6150 }
6151 }
6152
6153theend:
6154 return TerminateProcess(process, code);
6155}
6156
6157/*
6158 * Send a (deadly) signal to "job".
6159 * Return FAIL if it didn't work.
6160 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006161 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02006162mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006163{
Bram Moolenaar923d9262016-02-25 20:56:01 +01006164 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006165
Bram Moolenaar923d9262016-02-25 20:56:01 +01006166 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01006167 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006168 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02006169 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006170 {
6171 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
6172 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00006173 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006174 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01006175 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006176 }
6177
6178 if (!AttachConsole(job->jv_proc_info.dwProcessId))
6179 return FAIL;
6180 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01006181 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
6182 job->jv_proc_info.dwProcessId)
6183 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006184 FreeConsole();
6185 return ret;
6186}
6187
6188/*
6189 * Clear the data related to "job".
6190 */
6191 void
6192mch_clear_job(job_T *job)
6193{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00006194 if (job->jv_status == JOB_FAILED)
6195 return;
6196
6197 if (job->jv_job_object != NULL)
6198 CloseHandle(job->jv_job_object);
6199 CloseHandle(job->jv_proc_info.hProcess);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006200}
6201#endif
6202
Bram Moolenaar071d4272004-06-13 20:20:40 +00006203
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006204#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006205
6206/*
6207 * Start termcap mode
6208 */
6209 static void
6210termcap_mode_start(void)
6211{
6212 DWORD cmodein;
6213
6214 if (g_fTermcapMode)
6215 return;
6216
6217 SaveConsoleBuffer(&g_cbNonTermcap);
6218
6219 if (g_cbTermcap.IsValid)
6220 {
6221 /*
6222 * We've been in termcap mode before. Restore certain screen
6223 * characteristics, including the buffer size and the window
6224 * size. Since we will be redrawing the screen, we don't need
6225 * to restore the actual contents of the buffer.
6226 */
6227 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006228 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006229 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
6230 Rows = g_cbTermcap.Info.dwSize.Y;
6231 Columns = g_cbTermcap.Info.dwSize.X;
6232 }
6233 else
6234 {
6235 /*
6236 * This is our first time entering termcap mode. Clear the console
6237 * screen buffer, and resize the buffer to match the current window
6238 * size. We will use this as the size of our editing environment.
6239 */
6240 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006241 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006242 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
6243 }
6244
Bram Moolenaar071d4272004-06-13 20:20:40 +00006245 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006246
6247 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006248 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006249 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006250 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006251 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
6252 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006253 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006254 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006255 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006256 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6257 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006258 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006259 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006260
6261 redraw_later_clear();
6262 g_fTermcapMode = TRUE;
6263}
6264
6265
6266/*
6267 * End termcap mode
6268 */
6269 static void
6270termcap_mode_end(void)
6271{
6272 DWORD cmodein;
6273 ConsoleBuffer *cb;
6274 COORD coord;
6275 DWORD dwDummy;
6276
6277 if (!g_fTermcapMode)
6278 return;
6279
6280 SaveConsoleBuffer(&g_cbTermcap);
6281
6282 GetConsoleMode(g_hConIn, &cmodein);
6283 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006284 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6285 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006286
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006287# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01006288 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006289# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006290 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006291# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006292 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01006293 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006294
Christopher Plewright1140b512022-11-12 18:46:05 +00006295 // Switch back to main screen buffer.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00006296 if (exiting && use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00006297 vtp_printf("\033[?1049l");
6298
6299 if (!USE_WT && (p_rs || exiting))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006300 {
6301 /*
6302 * Clear anything that happens to be on the current line.
6303 */
6304 coord.X = 0;
6305 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006306 FillConsoleOutputCharacter(g_hConOut, ' ',
6307 cb->Info.dwSize.X, coord, &dwDummy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006308 /*
6309 * The following is just for aesthetics. If we are exiting without
6310 * restoring the screen, then we want to have a prompt string
6311 * appear at the bottom line. However, the command interpreter
6312 * seems to always advance the cursor one line before displaying
6313 * the prompt string, which causes the screen to scroll. To
6314 * counter this, move the cursor up one line before exiting.
6315 */
6316 if (exiting && !p_rs)
6317 coord.Y--;
6318 /*
6319 * Position the cursor at the leftmost column of the desired row.
6320 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006321 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006322 }
Christopher Plewright1140b512022-11-12 18:46:05 +00006323 SetConsoleCursorInfo(g_hConOut, &g_cci);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006324 g_fTermcapMode = FALSE;
6325}
Christopher Plewright38804d62022-11-09 23:55:52 +00006326#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006327
6328
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006329#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006330 void
6331mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01006332 char_u *s UNUSED,
6333 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006334{
Bram Moolenaar0f873732019-12-05 20:28:46 +01006335 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00006336}
6337
6338#else
6339
6340/*
6341 * clear `n' chars, starting from `coord'
6342 */
6343 static void
6344clear_chars(
6345 COORD coord,
6346 DWORD n)
6347{
Christopher Plewright38804d62022-11-09 23:55:52 +00006348 if (!vtp_working)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006349 {
6350 DWORD dwDummy;
6351
6352 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
6353 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
6354 &dwDummy);
6355 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006356 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02006357 {
6358 set_console_color_rgb();
6359 gotoxy(coord.X + 1, coord.Y + 1);
6360 vtp_printf("\033[%dX", n);
6361 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006362}
6363
6364
6365/*
6366 * Clear the screen
6367 */
6368 static void
6369clear_screen(void)
6370{
6371 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006372
Christopher Plewright38804d62022-11-09 23:55:52 +00006373 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006374 clear_chars(g_coord, Rows * Columns);
6375 else
6376 {
6377 set_console_color_rgb();
6378 gotoxy(1, 1);
6379 vtp_printf("\033[2J");
6380 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006381}
6382
6383
6384/*
6385 * Clear to end of display
6386 */
6387 static void
6388clear_to_end_of_display(void)
6389{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006390 COORD save = g_coord;
6391
Christopher Plewright38804d62022-11-09 23:55:52 +00006392 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006393 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006394 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006395 else
6396 {
6397 set_console_color_rgb();
6398 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6399 vtp_printf("\033[0J");
6400
6401 gotoxy(save.X + 1, save.Y + 1);
6402 g_coord = save;
6403 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006404}
6405
6406
6407/*
6408 * Clear to end of line
6409 */
6410 static void
6411clear_to_end_of_line(void)
6412{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006413 COORD save = g_coord;
6414
Christopher Plewright38804d62022-11-09 23:55:52 +00006415 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006416 clear_chars(g_coord, Columns - g_coord.X);
6417 else
6418 {
6419 set_console_color_rgb();
6420 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6421 vtp_printf("\033[0K");
6422
6423 gotoxy(save.X + 1, save.Y + 1);
6424 g_coord = save;
6425 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006426}
6427
6428
6429/*
6430 * Scroll the scroll region up by `cLines' lines
6431 */
6432 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006433scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006434{
6435 COORD oldcoord = g_coord;
6436
6437 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6438 delete_lines(cLines);
6439
6440 g_coord = oldcoord;
6441}
6442
6443
6444/*
6445 * Set the scroll region
6446 */
6447 static void
6448set_scroll_region(
6449 unsigned left,
6450 unsigned top,
6451 unsigned right,
6452 unsigned bottom)
6453{
6454 if (left >= right
6455 || top >= bottom
6456 || right > (unsigned) Columns - 1
6457 || bottom > (unsigned) Rows - 1)
6458 return;
6459
6460 g_srScrollRegion.Left = left;
6461 g_srScrollRegion.Top = top;
6462 g_srScrollRegion.Right = right;
6463 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006464}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006465
Bram Moolenaar6982f422019-02-16 16:48:01 +01006466 static void
6467set_scroll_region_tb(
6468 unsigned top,
6469 unsigned bottom)
6470{
6471 if (top >= bottom || bottom > (unsigned)Rows - 1)
6472 return;
6473
6474 g_srScrollRegion.Top = top;
6475 g_srScrollRegion.Bottom = bottom;
6476}
6477
6478 static void
6479set_scroll_region_lr(
6480 unsigned left,
6481 unsigned right)
6482{
6483 if (left >= right || right > (unsigned)Columns - 1)
6484 return;
6485
6486 g_srScrollRegion.Left = left;
6487 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006488}
6489
6490
6491/*
6492 * Insert `cLines' lines at the current cursor position
6493 */
6494 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006495insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006496{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006497 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006498 COORD dest;
6499 CHAR_INFO fill;
6500
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006501 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6502
Bram Moolenaar6982f422019-02-16 16:48:01 +01006503 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006504 dest.Y = g_coord.Y + cLines;
6505
Bram Moolenaar6982f422019-02-16 16:48:01 +01006506 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006507 source.Top = g_coord.Y;
6508 source.Right = g_srScrollRegion.Right;
6509 source.Bottom = g_srScrollRegion.Bottom - cLines;
6510
Bram Moolenaar6982f422019-02-16 16:48:01 +01006511 clip.Left = g_srScrollRegion.Left;
6512 clip.Top = g_coord.Y;
6513 clip.Right = g_srScrollRegion.Right;
6514 clip.Bottom = g_srScrollRegion.Bottom;
6515
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006516 fill.Char.AsciiChar = ' ';
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006517 if (!USE_VTP)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006518 fill.Attributes = g_attrCurrent;
6519 else
6520 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006521
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006522 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006523
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006524 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6525
Bram Moolenaar6982f422019-02-16 16:48:01 +01006526 // Here we have to deal with a win32 console flake: If the scroll
6527 // region looks like abc and we scroll c to a and fill with d we get
6528 // cbd... if we scroll block c one line at a time to a, we get cdd...
6529 // vim expects cdd consistently... So we have to deal with that
6530 // here... (this also occurs scrolling the same way in the other
6531 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006532
6533 if (source.Bottom < dest.Y)
6534 {
6535 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006536 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006537
Bram Moolenaar6982f422019-02-16 16:48:01 +01006538 coord.X = source.Left;
6539 for (i = clip.Top; i < dest.Y; ++i)
6540 {
6541 coord.Y = i;
6542 clear_chars(coord, source.Right - source.Left + 1);
6543 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006544 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006545
Christopher Plewright38804d62022-11-09 23:55:52 +00006546 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006547 {
6548 COORD coord;
6549 int i;
6550
6551 coord.X = source.Left;
6552 for (i = source.Top; i < dest.Y; ++i)
6553 {
6554 coord.Y = i;
6555 clear_chars(coord, source.Right - source.Left + 1);
6556 }
6557 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006558}
6559
6560
6561/*
6562 * Delete `cLines' lines at the current cursor position
6563 */
6564 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006565delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006566{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006567 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006568 COORD dest;
6569 CHAR_INFO fill;
6570 int nb;
6571
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006572 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6573
Bram Moolenaar6982f422019-02-16 16:48:01 +01006574 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006575 dest.Y = g_coord.Y;
6576
Bram Moolenaar6982f422019-02-16 16:48:01 +01006577 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006578 source.Top = g_coord.Y + cLines;
6579 source.Right = g_srScrollRegion.Right;
6580 source.Bottom = g_srScrollRegion.Bottom;
6581
Bram Moolenaar6982f422019-02-16 16:48:01 +01006582 clip.Left = g_srScrollRegion.Left;
6583 clip.Top = g_coord.Y;
6584 clip.Right = g_srScrollRegion.Right;
6585 clip.Bottom = g_srScrollRegion.Bottom;
6586
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006587 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006588 if (!vtp_working)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006589 fill.Attributes = g_attrCurrent;
6590 else
6591 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006592
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006593 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006594
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006595 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6596
Bram Moolenaar6982f422019-02-16 16:48:01 +01006597 // Here we have to deal with a win32 console flake; See insert_lines()
6598 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006599
6600 nb = dest.Y + (source.Bottom - source.Top) + 1;
6601
6602 if (nb < source.Top)
6603 {
6604 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006605 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006606
Bram Moolenaar6982f422019-02-16 16:48:01 +01006607 coord.X = source.Left;
6608 for (i = nb; i < clip.Bottom; ++i)
6609 {
6610 coord.Y = i;
6611 clear_chars(coord, source.Right - source.Left + 1);
6612 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006613 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006614
Christopher Plewright38804d62022-11-09 23:55:52 +00006615 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006616 {
6617 COORD coord;
6618 int i;
6619
6620 coord.X = source.Left;
6621 for (i = nb; i <= source.Bottom; ++i)
6622 {
6623 coord.Y = i;
6624 clear_chars(coord, source.Right - source.Left + 1);
6625 }
6626 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006627}
6628
6629
6630/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006631 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006632 */
6633 static void
6634gotoxy(
6635 unsigned x,
6636 unsigned y)
6637{
6638 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6639 return;
6640
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006641 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006642 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006643 // There are reports of double-width characters not displayed
6644 // correctly. This workaround should fix it, similar to how it's done
6645 // for VTP.
6646 g_coord.X = 0;
6647 SetConsoleCursorPosition(g_hConOut, g_coord);
6648
Bram Moolenaar2313b612019-09-27 14:14:32 +02006649 // external cursor coords are 1-based; internal are 0-based
6650 g_coord.X = x - 1;
6651 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006652 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006653 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006654 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006655 {
6656 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006657 // destruction. Insider build bug. Always enabled because it's cheap
6658 // and avoids mistakes with recognizing the build.
6659 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006660
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006661 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006662
6663 g_coord.X = x - 1;
6664 g_coord.Y = y - 1;
6665 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006666}
6667
6668
6669/*
6670 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006671 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006672 */
6673 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006674textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006675{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006676 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006677
6678 SetConsoleTextAttribute(g_hConOut, wAttr);
6679}
6680
6681
6682 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006683textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006684{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006685 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006686
Christopher Plewright38804d62022-11-09 23:55:52 +00006687 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006688 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6689 else
6690 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006691}
6692
6693
6694 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006695textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006696{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006697 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006698
Christopher Plewright38804d62022-11-09 23:55:52 +00006699 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006700 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6701 else
6702 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006703}
6704
6705
6706/*
6707 * restore the default text attribute (whatever we started with)
6708 */
6709 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006710normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006711{
Christopher Plewright38804d62022-11-09 23:55:52 +00006712 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006713 textattr(g_attrDefault);
6714 else
6715 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006716}
6717
6718
6719static WORD g_attrPreStandout = 0;
6720
6721/*
6722 * Make the text standout, by brightening it
6723 */
6724 static void
6725standout(void)
6726{
6727 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006728
Bram Moolenaar071d4272004-06-13 20:20:40 +00006729 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6730}
6731
6732
6733/*
6734 * Turn off standout mode
6735 */
6736 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006737standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006738{
6739 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006740 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006741
6742 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006743}
6744
6745
6746/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006747 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006748 */
6749 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006750mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006751{
6752 char_u *p;
6753 int n;
6754
6755 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6756 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006757 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006758# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006759 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006760# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006761 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006762 {
6763 p = T_ME + 2;
6764 n = getdigits(&p);
6765 if (*p == 'm' && n > 0)
6766 {
6767 cterm_normal_fg_color = (n & 0xf) + 1;
6768 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6769 }
6770 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006771# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006772 cterm_normal_fg_gui_color = INVALCOLOR;
6773 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006774# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006775}
6776
6777
6778/*
6779 * visual bell: flash the screen
6780 */
6781 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006782visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006783{
6784 COORD coordOrigin = {0, 0};
6785 WORD attrFlash = ~g_attrCurrent & 0xff;
6786
6787 DWORD dwDummy;
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006788 LPWORD oldattrs = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006789
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006790# ifdef FEAT_TERMGUICOLORS
6791 if (!(p_tgc || t_colors >= 256))
6792# endif
6793 {
6794 oldattrs = ALLOC_MULT(WORD, Rows * Columns);
6795 if (oldattrs == NULL)
6796 return;
6797 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006798 coordOrigin, &dwDummy);
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006799 }
6800
Bram Moolenaar071d4272004-06-13 20:20:40 +00006801 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6802 coordOrigin, &dwDummy);
6803
Bram Moolenaar0f873732019-12-05 20:28:46 +01006804 Sleep(15); // wait for 15 msec
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006805
6806 if (oldattrs != NULL)
6807 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006808 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006809 coordOrigin, &dwDummy);
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006810 vim_free(oldattrs);
6811 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006812}
6813
6814
6815/*
6816 * Make the cursor visible or invisible
6817 */
6818 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006819cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006820{
6821 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006822
Christopher Plewright38804d62022-11-09 23:55:52 +00006823 if (vtp_working)
Bram Moolenaar2695de62020-04-17 21:13:01 +02006824 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6825
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006826# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006827 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006828# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006829}
6830
6831
6832/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006833 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006834 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006835 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006836 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006837write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006838 char_u *pchBuf,
6839 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006840{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006841 COORD coord = g_coord;
6842 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006843 DWORD n, cchwritten;
6844 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006845 static WCHAR *unicodebuf = NULL;
6846 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006847 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006848 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006849 static WCHAR *utf8spbuf = NULL;
6850 static int utf8splength;
6851 static DWORD utf8spcells;
6852 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006853
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006854 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006855 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006856 utf8usingbuf = &unicodebuf;
6857 do
6858 {
6859 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6860 unicodebuf, unibuflen);
6861 if (length && length <= unibuflen)
6862 break;
6863 vim_free(unicodebuf);
6864 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6865 unibuflen = unibuflen ? 0 : length;
Bram Moolenaarc9471b12023-05-09 15:00:00 +01006866 } while (TRUE);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006867 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006868 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006869 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6870 {
6871 if (utf8usingbuf != &utf8spbuf)
6872 {
6873 if (utf8spbuf == NULL)
6874 {
6875 cells = mb_string2cells((char_u *)" ", 1);
6876 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6877 utf8spbuf = LALLOC_MULT(WCHAR, length);
6878 if (utf8spbuf != NULL)
6879 {
6880 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6881 utf8usingbuf = &utf8spbuf;
6882 utf8splength = length;
6883 utf8spcells = cells;
6884 }
6885 }
6886 else
6887 {
6888 utf8usingbuf = &utf8spbuf;
6889 length = utf8splength;
6890 cells = utf8spcells;
6891 }
6892 }
6893 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006894
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006895 if (!USE_VTP)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006896 {
6897 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6898 coord, &written);
6899 // When writing fails or didn't write a single character, pretend one
6900 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006901 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006902 coord, &cchwritten) == 0
6903 || cchwritten == 0 || cchwritten == (DWORD)-1)
6904 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006905 }
6906 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006907 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006908 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006909 NULL) == 0 || cchwritten == 0)
6910 cchwritten = 1;
6911 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006912
K.Takata135e1522022-01-29 15:27:58 +00006913 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006914 {
6915 written = cbToWrite;
6916 g_coord.X += (SHORT)cells;
6917 }
6918 else
6919 {
6920 char_u *p = pchBuf;
6921 for (n = 0; n < cchwritten; n++)
6922 MB_CPTR_ADV(p);
6923 written = p - pchBuf;
6924 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006925 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006926
6927 while (g_coord.X > g_srScrollRegion.Right)
6928 {
6929 g_coord.X -= (SHORT) Columns;
6930 if (g_coord.Y < g_srScrollRegion.Bottom)
6931 g_coord.Y++;
6932 }
6933
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006934 // Cursor under VTP is always in the correct position, no need to reset.
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006935 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006936 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006937
6938 return written;
6939}
6940
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006941 static char_u *
6942get_seq(
6943 int *args,
6944 int *count,
6945 char_u *head)
6946{
6947 int argc;
6948 char_u *p;
6949
6950 if (head == NULL || *head != '\033')
6951 return NULL;
6952
6953 argc = 0;
6954 p = head;
6955 ++p;
6956 do
6957 {
6958 ++p;
6959 args[argc] = getdigits(&p);
6960 argc += (argc < 15) ? 1 : 0;
6961 } while (*p == ';');
6962 *count = argc;
6963
6964 return p;
6965}
6966
6967 static char_u *
6968get_sgr(
6969 int *args,
6970 int *count,
6971 char_u *head)
6972{
6973 char_u *p = get_seq(args, count, head);
6974
6975 return (p && *p == 'm') ? ++p : NULL;
6976}
6977
6978/*
6979 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6980 */
6981 static char_u *
6982sgrn2(
6983 char_u *head,
6984 int n)
6985{
6986 int argc;
6987 int args[16];
6988 char_u *p = get_sgr(args, &argc, head);
6989
6990 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6991}
6992
6993/*
6994 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6995 */
6996 static char_u *
6997sgrnc(
6998 char_u *head,
6999 int n)
7000{
7001 int argc;
7002 int args[16];
7003 char_u *p = get_sgr(args, &argc, head);
7004
7005 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
7006 ? p : NULL;
7007}
7008
7009 static char_u *
7010skipblank(char_u *q)
7011{
7012 char_u *p = q;
7013
7014 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
7015 ++p;
7016 return p;
7017}
7018
7019/*
7020 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
7021 * NULL.
7022 */
7023 static char_u *
7024sgrn2c(
7025 char_u *head,
7026 int n)
7027{
7028 char_u *p = sgrn2(head, n);
7029
7030 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
7031}
7032
7033/*
7034 * If there is only a newline between the sequence immediately following it,
7035 * a pointer to the character following the newline is returned.
7036 * Otherwise NULL.
7037 */
7038 static char_u *
7039sgrn2cn(
7040 char_u *head,
7041 int n)
7042{
7043 char_u *p = sgrn2(head, n);
7044
7045 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
7046}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007047
7048/*
7049 * mch_write(): write the output buffer to the screen, translating ESC
7050 * sequences into calls to console output routines.
7051 */
7052 void
7053mch_write(
7054 char_u *s,
7055 int len)
7056{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007057 char_u *end = s + len;
7058
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007059# ifdef VIMDLL
7060 if (gui.in_use)
7061 return;
7062# endif
7063
Bram Moolenaar071d4272004-06-13 20:20:40 +00007064 if (!term_console)
7065 {
7066 write(1, s, (unsigned)len);
7067 return;
7068 }
7069
Bram Moolenaar0f873732019-12-05 20:28:46 +01007070 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00007071 while (len--)
7072 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007073 int prefix = -1;
7074 char_u ch;
7075
7076 // While processing a sequence, on rare occasions it seems that another
7077 // sequence may be inserted asynchronously.
7078 if (len < 0)
7079 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01007080 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007081 return;
7082 }
7083
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007084 while (s + ++prefix < end)
7085 {
7086 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007087 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
7088 && ch != '\a' && ch != '\033'))
7089 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007090 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007091
7092 if (p_wd)
7093 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007094 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007095 if (prefix != 0)
7096 prefix = 1;
7097 }
7098
7099 if (prefix != 0)
7100 {
7101 DWORD nWritten;
7102
7103 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007104# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007105 if (fdDump)
7106 {
7107 fputc('>', fdDump);
7108 fwrite(s, sizeof(char_u), nWritten, fdDump);
7109 fputs("<\n", fdDump);
7110 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007111# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007112 len -= (nWritten - 1);
7113 s += nWritten;
7114 }
7115 else if (s[0] == '\n')
7116 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007117 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00007118 if (g_coord.Y == g_srScrollRegion.Bottom)
7119 {
7120 scroll(1);
7121 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
7122 }
7123 else
7124 {
7125 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
7126 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007127# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007128 if (fdDump)
7129 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007130# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007131 s++;
7132 }
7133 else if (s[0] == '\r')
7134 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007135 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00007136 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007137# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007138 if (fdDump)
7139 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007140# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007141 s++;
7142 }
7143 else if (s[0] == '\b')
7144 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007145 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00007146 if (g_coord.X > g_srScrollRegion.Left)
7147 g_coord.X--;
7148 else if (g_coord.Y > g_srScrollRegion.Top)
7149 {
7150 g_coord.X = g_srScrollRegion.Right;
7151 g_coord.Y--;
7152 }
7153 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007154# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007155 if (fdDump)
7156 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007157# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007158 s++;
7159 }
7160 else if (s[0] == '\a')
7161 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007162 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00007163 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007164# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007165 if (fdDump)
7166 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007167# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007168 s++;
7169 }
7170 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
7171 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007172# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007173 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007174# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007175 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007176 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007177 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007178
7179 switch (s[2])
7180 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007181 case '0': case '1': case '2': case '3': case '4':
7182 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007183 if (*(p = get_seq(args, &argc, s)) != 'm')
7184 goto notsgr;
7185
7186 p = s;
7187
7188 // Handling frequent optional sequences. Output to the screen
7189 // takes too long, so do not output as much as possible.
7190
7191 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
7192 // resetFG,FG,BG are omitted.
7193 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007194 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007195 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
7196 len = len + 1 - (int)(p - s);
7197 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007198 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007199 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007200
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007201 // If FG,BG,BG,FG of SGR are connected, the first FG can be
7202 // omitted.
7203 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
7204 p = sp;
7205
7206 // If FG,BG,FG,BG of SGR are connected, the first FG can be
7207 // omitted.
7208 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
7209 p = sp;
7210
7211 // If BG,BG of SGR are connected, the first BG can be omitted.
7212 if (sgrn2((sp = sgrn2(p, 48)), 48))
7213 p = sp;
7214
7215 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007216 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007217 if (sgrn2((sp = sgrnc(p, 39)), 38))
7218 p = sp;
7219
7220 p = get_seq(args, &argc, p);
7221
7222notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007223 arg1 = args[0];
7224 arg2 = args[1];
7225 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007226 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007227 if (argc == 1 && args[0] == 0)
7228 normvideo();
7229 else if (argc == 1)
7230 {
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00007231 if (USE_VTP)
Christopher Plewright38804d62022-11-09 23:55:52 +00007232 textcolor((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007233 else
Christopher Plewright38804d62022-11-09 23:55:52 +00007234 textattr((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007235 }
Christopher Plewright38804d62022-11-09 23:55:52 +00007236 else if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007237 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007238 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007239 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007240 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007241 gotoxy(arg2, arg1);
7242 }
7243 else if (argc == 2 && *p == 'r')
7244 {
7245 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
7246 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01007247 else if (argc == 2 && *p == 'R')
7248 {
7249 set_scroll_region_tb(arg1, arg2);
7250 }
7251 else if (argc == 2 && *p == 'V')
7252 {
7253 set_scroll_region_lr(arg1, arg2);
7254 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007255 else if (argc == 1 && *p == 'A')
7256 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007257 gotoxy(g_coord.X + 1,
7258 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
7259 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007260 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007261 {
7262 textbackground((WORD) arg1);
7263 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007264 else if (argc == 1 && *p == 'C')
7265 {
7266 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
7267 g_coord.Y + 1);
7268 }
7269 else if (argc == 1 && *p == 'f')
7270 {
7271 textcolor((WORD) arg1);
7272 }
7273 else if (argc == 1 && *p == 'H')
7274 {
7275 gotoxy(1, arg1);
7276 }
7277 else if (argc == 1 && *p == 'L')
7278 {
7279 insert_lines(arg1);
7280 }
7281 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007282 {
7283 delete_lines(arg1);
7284 }
7285
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007286 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007287 s = p + 1;
7288 break;
7289
Bram Moolenaar071d4272004-06-13 20:20:40 +00007290 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007291 gotoxy(g_coord.X + 1,
7292 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
7293 goto got3;
7294
7295 case 'B':
7296 visual_bell();
7297 goto got3;
7298
7299 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007300 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
7301 g_coord.Y + 1);
7302 goto got3;
7303
7304 case 'E':
7305 termcap_mode_end();
7306 goto got3;
7307
7308 case 'F':
7309 standout();
7310 goto got3;
7311
7312 case 'f':
7313 standend();
7314 goto got3;
7315
7316 case 'H':
7317 gotoxy(1, 1);
7318 goto got3;
7319
7320 case 'j':
7321 clear_to_end_of_display();
7322 goto got3;
7323
7324 case 'J':
7325 clear_screen();
7326 goto got3;
7327
7328 case 'K':
7329 clear_to_end_of_line();
7330 goto got3;
7331
7332 case 'L':
7333 insert_lines(1);
7334 goto got3;
7335
7336 case 'M':
7337 delete_lines(1);
7338 goto got3;
7339
7340 case 'S':
7341 termcap_mode_start();
7342 goto got3;
7343
7344 case 'V':
7345 cursor_visible(TRUE);
7346 goto got3;
7347
7348 case 'v':
7349 cursor_visible(FALSE);
7350 goto got3;
7351
7352 got3:
7353 s += 3;
7354 len -= 2;
7355 }
7356
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007357# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007358 if (fdDump)
7359 {
7360 fputs("ESC | ", fdDump);
7361 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
7362 fputc('\n', fdDump);
7363 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007364# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007365 }
K.Takatadf5320c2022-09-01 13:20:16 +01007366 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
7367 {
7368 int l = 2;
7369
7370 if (isdigit(s[l]))
7371 l++;
7372 if (s[l] == ' ' && s[l + 1] == 'q')
7373 {
7374 // DECSCUSR (cursor style) sequences
Christopher Plewright38804d62022-11-09 23:55:52 +00007375 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01007376 vtp_printf("%.*s", l + 2, s); // Pass through
7377 s += l + 2;
7378 len -= l + 1;
7379 }
7380 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007381 else
7382 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007383 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00007384 DWORD nWritten;
7385
7386 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007387# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007388 if (fdDump)
7389 {
7390 fputc('>', fdDump);
7391 fwrite(s, sizeof(char_u), nWritten, fdDump);
7392 fputs("<\n", fdDump);
7393 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007394# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007395
7396 len -= (nWritten - 1);
7397 s += nWritten;
7398 }
7399 }
7400
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007401# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007402 if (fdDump)
7403 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007404# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007405}
7406
Bram Moolenaar0f873732019-12-05 20:28:46 +01007407#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00007408
7409
7410/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01007411 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007412 */
7413 void
7414mch_delay(
7415 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02007416 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007417{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007418#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007419 Sleep((int)msec); // never wait for input
7420#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007421# ifdef VIMDLL
7422 if (gui.in_use)
7423 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007424 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007425 return;
7426 }
7427# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02007428 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007429# ifdef FEAT_MZSCHEME
7430 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
7431 {
7432 int towait = p_mzq;
7433
Bram Moolenaar0f873732019-12-05 20:28:46 +01007434 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007435 while (msec > 0)
7436 {
7437 mzvim_check_threads();
7438 if (msec < towait)
7439 towait = msec;
7440 Sleep(towait);
7441 msec -= towait;
7442 }
7443 }
7444 else
7445# endif
7446 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007447 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007448 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007449#endif
7450}
7451
7452
7453/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01007454 * This version of remove is not scared by a readonly (backup) file.
7455 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007456 * Return 0 for success, -1 for failure.
7457 */
7458 int
7459mch_remove(char_u *name)
7460{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007461 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007462 int n;
7463
Bram Moolenaar203258c2016-01-17 22:15:16 +01007464 /*
7465 * On Windows, deleting a directory's symbolic link is done by
7466 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
7467 */
7468 if (mch_isdir(name) && mch_is_symbolic_link(name))
7469 return mch_rmdir(name);
7470
Bram Moolenaar12b559e2013-06-12 22:41:37 +02007471 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
7472
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007473 wn = enc_to_utf16(name, NULL);
7474 if (wn == NULL)
7475 return -1;
7476
7477 n = DeleteFileW(wn) ? 0 : -1;
7478 vim_free(wn);
7479 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007480}
7481
7482
7483/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007484 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007485 */
7486 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007487mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007488{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007489#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7490# ifdef VIMDLL
7491 if (!gui.in_use)
7492# endif
7493 if (g_fCtrlCPressed || g_fCBrkPressed)
7494 {
7495 ctrl_break_was_pressed = g_fCBrkPressed;
7496 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7497 got_int = TRUE;
7498 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007499#endif
7500}
7501
Bram Moolenaar0f873732019-12-05 20:28:46 +01007502// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007503#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007504
7505/*
7506 * How much main memory in KiB that can be used by VIM.
7507 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007508 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007509mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007510{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007511 MEMORYSTATUSEX ms;
7512
Bram Moolenaar0f873732019-12-05 20:28:46 +01007513 // Need to use GlobalMemoryStatusEx() when there is more memory than
7514 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007515 ms.dwLength = sizeof(MEMORYSTATUSEX);
7516 GlobalMemoryStatusEx(&ms);
7517 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007518 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007519 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007520 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007521 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007522 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007523 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007524 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007525 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007526 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007527 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007528 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007529}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007530
Bram Moolenaar071d4272004-06-13 20:20:40 +00007531/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007532 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00007533 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
7534 * file whose short file name is "FOO.BAR" (its long file name will
7535 * be correct: "foo.bar~"). Because a file can be accessed by
7536 * either its SFN or its LFN, "foo.bar" has effectively been
7537 * renamed to "foo.bar", which is not at all what was wanted. This
7538 * seems to happen only when renaming files with three-character
7539 * extensions by appending a suffix that does not include ".".
7540 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
7541 *
7542 * There is another problem, which isn't really a bug but isn't right either:
7543 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
7544 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
7545 * service pack 6. Doesn't seem to happen on Windows 98.
7546 *
7547 * Like rename(), returns 0 upon success, non-zero upon failure.
7548 * Should probably set errno appropriately when errors occur.
7549 */
7550 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007551mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007552{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007553 WCHAR *p;
7554 int i;
7555 WCHAR szTempFile[_MAX_PATH + 1];
7556 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007557 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007558
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007559 // No need to play tricks unless the file name contains a "~" as the
7560 // seventh character.
7561 p = wold;
7562 for (i = 0; wold[i] != NUL; ++i)
7563 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
7564 && wold[i + 1] != 0)
7565 p = wold + i + 1;
7566 if ((int)(wold + i - p) < 8 || p[6] != '~')
7567 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007568
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007569 // Get base path of new file name. Undocumented feature: If pszNewFile is
7570 // a directory, no error is returned and pszFilePart will be NULL.
7571 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007572 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007573 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007574
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007575 // Get (and create) a unique temporary file name in directory of new file
7576 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007577 return -2;
7578
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007579 // blow the temp file away
7580 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007581 return -3;
7582
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007583 // rename old file to the temp file
7584 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007585 return -4;
7586
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007587 // now create an empty file called pszOldFile; this prevents the operating
7588 // system using pszOldFile as an alias (SFN) if we're renaming within the
7589 // same directory. For example, we're editing a file called
7590 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7591 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7592 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7593 // cause all sorts of problems later in buf_write(). So, we create an
7594 // empty file called filena~1.txt and the system will have to find some
7595 // other SFN for filena~1.txt~, such as filena~2.txt
7596 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007597 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7598 return -5;
7599 if (!CloseHandle(hf))
7600 return -6;
7601
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007602 // rename the temp file to the new file
7603 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007604 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007605 // Renaming failed. Rename the file back to its old name, so that it
7606 // looks like nothing happened.
7607 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007608 return -7;
7609 }
7610
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007611 // Seems to be left around on Novell filesystems
7612 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007613
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007614 // finally, remove the empty old file
7615 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007616 return -8;
7617
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007618 return 0;
7619}
7620
7621
7622/*
7623 * Converts the filenames to UTF-16, then call mch_wrename().
7624 * Like rename(), returns 0 upon success, non-zero upon failure.
7625 */
7626 int
7627mch_rename(
7628 const char *pszOldFile,
7629 const char *pszNewFile)
7630{
7631 WCHAR *wold = NULL;
7632 WCHAR *wnew = NULL;
7633 int retval = -1;
7634
7635 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7636 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7637 if (wold != NULL && wnew != NULL)
7638 retval = mch_wrename(wold, wnew);
7639 vim_free(wold);
7640 vim_free(wnew);
7641 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007642}
7643
7644/*
7645 * Get the default shell for the current hardware platform
7646 */
7647 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007648default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007649{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007650 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007651}
7652
7653/*
7654 * mch_access() extends access() to do more detailed check on network drives.
7655 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7656 */
7657 int
7658mch_access(char *n, int p)
7659{
7660 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007661 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007662 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007663
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007664 wn = enc_to_utf16((char_u *)n, NULL);
7665 if (wn == NULL)
7666 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007667
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007668 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007669 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007670 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007671
7672 if (p & R_OK)
7673 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007674 // Read check is performed by seeing if we can do a find file on
7675 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007676 int i;
7677 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007678
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007679 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7680 TempNameW[i] = wn[i];
7681 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7682 TempNameW[i++] = '\\';
7683 TempNameW[i++] = '*';
7684 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007685
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007686 hFile = FindFirstFileW(TempNameW, &d);
7687 if (hFile == INVALID_HANDLE_VALUE)
7688 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007689 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007690 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007691 }
7692
7693 if (p & W_OK)
7694 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007695 // Trying to create a temporary file in the directory should catch
7696 // directories on read-only network shares. However, in
7697 // directories whose ACL allows writes but denies deletes will end
7698 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007699 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7700 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007701 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007702 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007703 }
7704 }
7705 else
7706 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007707 // Don't consider a file read-only if another process has opened it.
7708 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7709
Bram Moolenaar0f873732019-12-05 20:28:46 +01007710 // Trying to open the file for the required access does ACL, read-only
7711 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007712 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7713 | ((p & R_OK) ? GENERIC_READ : 0);
7714
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007715 hFile = CreateFileW(wn, access_mode, share_mode,
7716 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007717 if (hFile == INVALID_HANDLE_VALUE)
7718 goto getout;
7719 CloseHandle(hFile);
7720 }
7721
Bram Moolenaar0f873732019-12-05 20:28:46 +01007722 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007723getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007724 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007725 return retval;
7726}
7727
Bram Moolenaar071d4272004-06-13 20:20:40 +00007728/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007729 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007730 */
7731 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007732mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007733{
7734 WCHAR *wn;
7735 int f;
7736
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007737 wn = enc_to_utf16((char_u *)name, NULL);
7738 if (wn == NULL)
7739 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007740
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007741 f = _wopen(wn, flags, mode);
7742 vim_free(wn);
7743 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007744}
7745
7746/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007747 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007748 */
7749 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007750mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007751{
7752 WCHAR *wn, *wm;
7753 FILE *f = NULL;
7754
Bram Moolenaara12a1612019-01-24 16:39:02 +01007755#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007756 // Work around an annoying assertion in the Microsoft debug CRT
7757 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007758 char newMode = mode[strlen(mode) - 1];
7759 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007760
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007761 _get_fmode(&oldMode);
7762 if (newMode == 't')
7763 _set_fmode(_O_TEXT);
7764 else if (newMode == 'b')
7765 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007766#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007767 wn = enc_to_utf16((char_u *)name, NULL);
7768 wm = enc_to_utf16((char_u *)mode, NULL);
7769 if (wn != NULL && wm != NULL)
7770 f = _wfopen(wn, wm);
7771 vim_free(wn);
7772 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007773
Bram Moolenaara12a1612019-01-24 16:39:02 +01007774#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007775 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007776#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007777 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007778}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007779
Bram Moolenaar071d4272004-06-13 20:20:40 +00007780/*
7781 * SUB STREAM (aka info stream) handling:
7782 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007783 * NTFS can have sub streams for each file. The normal contents of a file is
7784 * stored in the main stream, and extra contents (author information, title and
7785 * so on) can be stored in a sub stream. After Windows 2000, the user can
7786 * access and store this information in sub streams via an explorer's property
7787 * menu item in the right click menu. This information in sub streams was lost
7788 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007789 *
7790 * Incomplete explanation:
7791 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7792 * More useful info and an example:
7793 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7794 */
7795
7796/*
7797 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7798 * and write to stream "substream" of file "to".
7799 * Errors are ignored.
7800 */
7801 static void
7802copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7803{
7804 HANDLE hTo;
7805 WCHAR *to_name;
7806
7807 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7808 wcscpy(to_name, to);
7809 wcscat(to_name, substream);
7810
7811 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7812 FILE_ATTRIBUTE_NORMAL, NULL);
7813 if (hTo != INVALID_HANDLE_VALUE)
7814 {
7815 long done;
7816 DWORD todo;
7817 DWORD readcnt, written;
7818 char buf[4096];
7819
Bram Moolenaar0f873732019-12-05 20:28:46 +01007820 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007821 for (done = 0; done < len; done += written)
7822 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007823 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007824 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7825 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007826 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7827 FALSE, FALSE, context)
7828 || readcnt != todo
7829 || !WriteFile(hTo, buf, todo, &written, NULL)
7830 || written != todo)
7831 break;
7832 }
7833 CloseHandle(hTo);
7834 }
7835
7836 free(to_name);
7837}
7838
7839/*
7840 * Copy info streams from file "from" to file "to".
7841 */
7842 static void
7843copy_infostreams(char_u *from, char_u *to)
7844{
7845 WCHAR *fromw;
7846 WCHAR *tow;
7847 HANDLE sh;
7848 WIN32_STREAM_ID sid;
7849 int headersize;
7850 WCHAR streamname[_MAX_PATH];
7851 DWORD readcount;
7852 void *context = NULL;
7853 DWORD lo, hi;
7854 int len;
7855
Bram Moolenaar0f873732019-12-05 20:28:46 +01007856 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007857 fromw = enc_to_utf16(from, NULL);
7858 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007859 if (fromw != NULL && tow != NULL)
7860 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007861 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007862 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7863 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7864 if (sh != INVALID_HANDLE_VALUE)
7865 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007866 // Use BackupRead() to find the info streams. Repeat until we
7867 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007868 for (;;)
7869 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007870 // Get the header to find the length of the stream name. If
7871 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007872 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007873 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007874 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7875 &readcount, FALSE, FALSE, &context)
7876 || readcount == 0)
7877 break;
7878
Bram Moolenaar0f873732019-12-05 20:28:46 +01007879 // We only deal with streams that have a name. The normal
7880 // file data appears to be without a name, even though docs
7881 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007882 if (sid.dwStreamNameSize > 0)
7883 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007884 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007885 if (!BackupRead(sh, (LPBYTE)streamname,
7886 sid.dwStreamNameSize,
7887 &readcount, FALSE, FALSE, &context))
7888 break;
7889
Bram Moolenaar0f873732019-12-05 20:28:46 +01007890 // Copy an info stream with a name ":anything:$DATA".
7891 // Skip "::$DATA", it has no stream name (examples suggest
7892 // it might be used for the normal file contents).
7893 // Note that BackupRead() counts bytes, but the name is in
7894 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007895 len = readcount / sizeof(WCHAR);
7896 streamname[len] = 0;
7897 if (len > 7 && wcsicmp(streamname + len - 6,
7898 L":$DATA") == 0)
7899 {
7900 streamname[len - 6] = 0;
7901 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007902 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007903 }
7904 }
7905
Bram Moolenaar0f873732019-12-05 20:28:46 +01007906 // Advance to the next stream. We might try seeking too far,
7907 // but BackupSeek() doesn't skip over stream borders, thus
7908 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007909 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007910 &lo, &hi, &context);
7911 }
7912
Bram Moolenaar0f873732019-12-05 20:28:46 +01007913 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007914 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7915
7916 CloseHandle(sh);
7917 }
7918 }
7919 vim_free(fromw);
7920 vim_free(tow);
7921}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007922
7923/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007924 * ntdll.dll definitions
7925 */
7926#define FileEaInformation 7
7927#ifndef STATUS_SUCCESS
7928# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7929#endif
7930
7931typedef struct _FILE_FULL_EA_INFORMATION_ {
7932 ULONG NextEntryOffset;
7933 UCHAR Flags;
7934 UCHAR EaNameLength;
7935 USHORT EaValueLength;
7936 CHAR EaName[1];
7937} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7938
7939typedef struct _FILE_EA_INFORMATION_ {
7940 ULONG EaSize;
7941} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7942
Paul Ollis65745772022-06-05 16:55:54 +01007943#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007944typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7945 PHANDLE FileHandle,
7946 ACCESS_MASK DesiredAccess,
7947 POBJECT_ATTRIBUTES ObjectAttributes,
7948 PIO_STATUS_BLOCK IoStatusBlock,
7949 ULONG ShareAccess,
7950 ULONG OpenOptions);
7951typedef NTSTATUS (NTAPI *PfnNtClose)(
7952 HANDLE Handle);
7953typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007954 HANDLE FileHandle,
7955 PIO_STATUS_BLOCK IoStatusBlock,
7956 PVOID Buffer,
7957 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007958typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7959 HANDLE FileHandle,
7960 PIO_STATUS_BLOCK IoStatusBlock,
7961 PVOID Buffer,
7962 ULONG Length,
7963 BOOLEAN ReturnSingleEntry,
7964 PVOID EaList,
7965 ULONG EaListLength,
7966 PULONG EaIndex,
7967 BOOLEAN RestartScan);
7968typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007969 HANDLE FileHandle,
7970 PIO_STATUS_BLOCK IoStatusBlock,
7971 PVOID FileInformation,
7972 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007973 FILE_INFORMATION_CLASS FileInformationClass);
7974typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7975 PUNICODE_STRING DestinationString,
7976 PCWSTR SourceString);
7977
7978PfnNtOpenFile pNtOpenFile = NULL;
7979PfnNtClose pNtClose = NULL;
7980PfnNtSetEaFile pNtSetEaFile = NULL;
7981PfnNtQueryEaFile pNtQueryEaFile = NULL;
7982PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7983PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01007984#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007985
7986/*
7987 * Load ntdll.dll functions.
7988 */
7989 static BOOL
7990load_ntdll(void)
7991{
7992 static int loaded = -1;
7993
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00007994 if (loaded != -1)
7995 return (BOOL) loaded;
7996
7997 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7998 if (hNtdll != NULL)
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007999 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008000 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
8001 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
8002 pNtSetEaFile = (PfnNtSetEaFile)
8003 GetProcAddress(hNtdll, "NtSetEaFile");
8004 pNtQueryEaFile = (PfnNtQueryEaFile)
8005 GetProcAddress(hNtdll, "NtQueryEaFile");
8006 pNtQueryInformationFile = (PfnNtQueryInformationFile)
8007 GetProcAddress(hNtdll, "NtQueryInformationFile");
8008 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
8009 GetProcAddress(hNtdll, "RtlInitUnicodeString");
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008010 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008011 if (pNtOpenFile == NULL
8012 || pNtClose == NULL
8013 || pNtSetEaFile == NULL
8014 || pNtQueryEaFile == NULL
8015 || pNtQueryInformationFile == NULL
8016 || pRtlInitUnicodeString == NULL)
8017 loaded = FALSE;
8018 else
8019 loaded = TRUE;
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008020 return (BOOL) loaded;
8021}
8022
8023/*
8024 * Copy extended attributes (EA) from file "from" to file "to".
8025 */
8026 static void
8027copy_extattr(char_u *from, char_u *to)
8028{
8029 char_u *fromf = NULL;
8030 char_u *tof = NULL;
8031 WCHAR *fromw = NULL;
8032 WCHAR *tow = NULL;
8033 UNICODE_STRING u;
8034 HANDLE h;
8035 OBJECT_ATTRIBUTES oa;
8036 IO_STATUS_BLOCK iosb;
8037 FILE_EA_INFORMATION_ eainfo = {0};
8038 void *ea = NULL;
8039
8040 if (!load_ntdll())
8041 return;
8042
8043 // Convert the file names to the fully qualified object names.
8044 fromf = alloc(STRLEN(from) + 5);
8045 tof = alloc(STRLEN(to) + 5);
8046 if (fromf == NULL || tof == NULL)
8047 goto theend;
8048 STRCPY(fromf, "\\??\\");
8049 STRCAT(fromf, from);
8050 STRCPY(tof, "\\??\\");
8051 STRCAT(tof, to);
8052
8053 // Convert the names to wide characters.
8054 fromw = enc_to_utf16(fromf, NULL);
8055 tow = enc_to_utf16(tof, NULL);
8056 if (fromw == NULL || tow == NULL)
8057 goto theend;
8058
8059 // Get the EA.
8060 pRtlInitUnicodeString(&u, fromw);
8061 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8062 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
8063 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8064 goto theend;
8065 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
8066 FileEaInformation);
8067 if (eainfo.EaSize != 0)
8068 {
8069 ea = alloc(eainfo.EaSize);
8070 if (ea != NULL)
8071 {
8072 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
8073 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
8074 {
Yegappan Lakshmanan960dcbd2023-03-07 17:45:11 +00008075 VIM_CLEAR(ea);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008076 }
8077 }
8078 }
8079 pNtClose(h);
8080
8081 // Set the EA.
8082 if (ea != NULL)
8083 {
8084 pRtlInitUnicodeString(&u, tow);
8085 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8086 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
8087 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8088 goto theend;
8089
8090 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
8091 pNtClose(h);
8092 }
8093
8094theend:
8095 vim_free(fromf);
8096 vim_free(tof);
8097 vim_free(fromw);
8098 vim_free(tow);
8099 vim_free(ea);
8100}
8101
8102/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008103 * Copy file attributes from file "from" to file "to".
8104 * For Windows NT and later we copy info streams.
8105 * Always returns zero, errors are ignored.
8106 */
8107 int
8108mch_copy_file_attribute(char_u *from, char_u *to)
8109{
Bram Moolenaar0f873732019-12-05 20:28:46 +01008110 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02008111 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008112 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008113 return 0;
8114}
8115
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008116
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008117/*
K.Takatadc73b4b2021-06-08 18:32:36 +02008118 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008119 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008120static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008121static LPWSTR *ArglistW = NULL;
8122static int global_argc = 0;
8123static char **global_argv;
8124
Bram Moolenaar0f873732019-12-05 20:28:46 +01008125static int used_file_argc = 0; // last argument in global_argv[] used
8126 // for the argument list.
8127static int *used_file_indexes = NULL; // indexes in global_argv[] for
8128 // command line arguments added to
8129 // the argument list
8130static int used_file_count = 0; // nr of entries in used_file_indexes
8131static int used_file_literal = FALSE; // take file names literally
8132static int used_file_full_path = FALSE; // file name was full path
8133static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008134static int used_alist_count = 0;
8135
8136
8137/*
8138 * Get the command line arguments. Unicode version.
8139 * Returns argc. Zero when something fails.
8140 */
8141 int
8142get_cmd_argsW(char ***argvp)
8143{
8144 char **argv = NULL;
8145 int argc = 0;
8146 int i;
8147
Bram Moolenaar14993322014-09-09 12:25:33 +02008148 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008149 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
8150 if (ArglistW != NULL)
8151 {
8152 argv = malloc((nArgsW + 1) * sizeof(char *));
8153 if (argv != NULL)
8154 {
8155 argc = nArgsW;
8156 argv[argc] = NULL;
8157 for (i = 0; i < argc; ++i)
8158 {
8159 int len;
8160
K.Takatadc73b4b2021-06-08 18:32:36 +02008161 // Convert each Unicode argument to UTF-8.
8162 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008163 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008164 (LPSTR *)&argv[i], &len, 0, 0);
8165 if (argv[i] == NULL)
8166 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008167 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008168 while (i > 0)
8169 free(argv[--i]);
8170 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01008171 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008172 argc = 0;
8173 }
8174 }
8175 }
8176 }
8177
8178 global_argc = argc;
8179 global_argv = argv;
8180 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02008181 {
8182 if (used_file_indexes != NULL)
8183 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008184 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02008185 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008186
8187 if (argvp != NULL)
8188 *argvp = argv;
8189 return argc;
8190}
8191
8192 void
8193free_cmd_argsW(void)
8194{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008195 if (ArglistW == NULL)
8196 return;
8197
8198 GlobalFree(ArglistW);
8199 ArglistW = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008200}
8201
8202/*
8203 * Remember "name" is an argument that was added to the argument list.
8204 * This avoids that we have to re-parse the argument list when fix_arg_enc()
8205 * is called.
8206 */
8207 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008208used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008209{
8210 int i;
8211
8212 if (used_file_indexes == NULL)
8213 return;
8214 for (i = used_file_argc + 1; i < global_argc; ++i)
8215 if (STRCMP(global_argv[i], name) == 0)
8216 {
8217 used_file_argc = i;
8218 used_file_indexes[used_file_count++] = i;
8219 break;
8220 }
8221 used_file_literal = literal;
8222 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008223 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008224}
8225
8226/*
8227 * Remember the length of the argument list as it was. If it changes then we
8228 * leave it alone when 'encoding' is set.
8229 */
8230 void
8231set_alist_count(void)
8232{
8233 used_alist_count = GARGCOUNT;
8234}
8235
8236/*
8237 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02008238 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008239 * and convert them to 'encoding'.
8240 */
8241 void
8242fix_arg_enc(void)
8243{
8244 int i;
8245 int idx;
8246 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00008247 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008248
Bram Moolenaar0f873732019-12-05 20:28:46 +01008249 // Safety checks:
8250 // - if argument count differs between the wide and non-wide argument
8251 // list, something must be wrong.
8252 // - the file name arguments must have been located.
8253 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008254 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008255 || ArglistW == NULL
8256 || used_file_indexes == NULL
8257 || used_file_count == 0
8258 || used_alist_count != GARGCOUNT)
8259 return;
8260
Bram Moolenaar0f873732019-12-05 20:28:46 +01008261 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02008262 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008263 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008264 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00008265 for (i = 0; i < GARGCOUNT; ++i)
8266 fnum_list[i] = GARGLIST[i].ae_fnum;
8267
Bram Moolenaar0f873732019-12-05 20:28:46 +01008268 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008269 alist_clear(&global_alist);
8270 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008271 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008272
8273 for (i = 0; i < used_file_count; ++i)
8274 {
8275 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008276 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008277 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00008278 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008279 int literal = used_file_literal;
8280
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008281#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01008282 // When using diff mode may need to concatenate file name to
8283 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008284 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
8285 && !mch_isdir(alist_name(&GARGLIST[0])))
8286 {
8287 char_u *r;
8288
8289 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
8290 if (r != NULL)
8291 {
8292 vim_free(str);
8293 str = r;
8294 }
8295 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008296#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01008297 // Re-use the old buffer by renaming it. When not using literal
8298 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00008299 if (used_file_literal)
8300 buf_set_name(fnum_list[i], str);
8301
Bram Moolenaar0f873732019-12-05 20:28:46 +01008302 // Check backtick literal. backtick literal is already expanded in
8303 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008304 if (literal == FALSE)
8305 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02008306 size_t len = STRLEN(str);
8307
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008308 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
8309 literal = TRUE;
8310 }
8311 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008312 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008313 }
8314
8315 if (!used_file_literal)
8316 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008317 // Now expand wildcards in the arguments.
8318 // Temporarily add '(' and ')' to 'isfname'. These are valid
8319 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00008320 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01008321 // Also, unset wildignore to not be influenced by this option.
8322 // The arguments specified in command-line should be kept even if
8323 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00008324 // Use :legacy so that it also works when in Vim9 script.
8325 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
8326 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00008327 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00008328 do_cmdline_cmd(
8329 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
8330 do_cmdline_cmd(
8331 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008332 }
8333
Bram Moolenaar0f873732019-12-05 20:28:46 +01008334 // If wildcard expansion failed, we are editing the first file of the
8335 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008336 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
8337 {
8338 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00008339 if (GARGCOUNT == 1 && used_file_full_path
8340 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
8341 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008342 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00008343
8344 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008345}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008346
8347 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02008348mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008349{
8350 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008351 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008352
Bram Moolenaar964b3742019-05-24 18:54:09 +02008353 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008354 if (envbuf == NULL)
8355 return -1;
8356
8357 sprintf((char *)envbuf, "%s=%s", var, value);
8358
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008359 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008360
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008361 vim_free(envbuf);
8362 if (p == NULL)
8363 return -1;
8364 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008365#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008366 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008367#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008368 // Unlike Un*x systems, we can free the string for _wputenv().
8369 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008370
8371 return 0;
8372}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008373
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008374/*
8375 * Support for 256 colors and 24-bit colors was added in Windows 10
8376 * version 1703 (Creators update).
8377 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008378#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
8379
8380/*
8381 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02008382 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008383 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008384#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008385
8386/*
8387 * ConPTY differences between versions, need different logic.
8388 * version 1903 (May 2019 update).
8389 */
8390#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
8391
8392/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008393 * version 1909 (November 2019 update).
8394 */
8395#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
8396
8397/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008398 * Stay ahead of the next update, and when it's done, fix this.
8399 * version ? (2020 update, temporarily use the build number of insider preview)
8400 */
8401#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
8402
8403/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02008404 * Confirm until this version. Also the logic changes.
8405 * insider preview.
8406 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02008407#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008408
8409/*
8410 * Not stable now.
8411 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008412#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Christopher Plewright1140b512022-11-12 18:46:05 +00008413// Notes:
8414// Win 10 22H2 Final is build 19045, it's conpty is widely used.
8415// Strangely, 19045 is newer but is a lower build number than the 2020 insider
8416// preview which had a build 19587. And, not sure how stable that was?
8417// Win Server 2022 (May 10, 2022) is build 20348, its conpty is widely used.
8418// Win 11 starts from build 22000, even though the major version says 10!
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008419
8420 static void
8421vtp_flag_init(void)
8422{
8423 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008424#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008425 DWORD mode;
8426 HANDLE out;
8427
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008428# ifdef VIMDLL
8429 if (!gui.in_use)
8430# endif
8431 {
8432 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008433
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008434 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
8435 GetConsoleMode(out, &mode);
8436 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
8437 if (SetConsoleMode(out, mode) == 0)
8438 vtp_working = 0;
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008439
8440 // VTP uses alternate screen buffer.
8441 // But, not if running in a nested terminal
8442 use_alternate_screen_buffer = win10_22H2_or_later && p_rs && vtp_working
8443 && !mch_getenv("VIM_TERMINAL");
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008444 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008445#endif
8446
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008447 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008448 conpty_working = 1;
8449 if (ver >= CONPTY_STABLE_BUILD)
8450 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008451
Bram Moolenaar57da6982019-09-13 22:30:11 +02008452 if (ver <= CONPTY_INSIDER_BUILD)
8453 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008454 if (ver <= CONPTY_1909_BUILD)
8455 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02008456 if (ver <= CONPTY_1903_BUILD)
8457 conpty_type = 2;
8458 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
8459 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008460
8461 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
8462 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008463}
8464
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008465#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008466
8467 static void
8468vtp_init(void)
8469{
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008470# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightd343c602023-01-22 18:58:30 +00008471 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8472 csbi.cbSize = sizeof(csbi);
8473 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8474 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
8475 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
8476 store_console_bg_rgb = save_console_bg_rgb;
8477 store_console_fg_rgb = save_console_fg_rgb;
Christopher Plewright38804d62022-11-09 23:55:52 +00008478
Christopher Plewrightd343c602023-01-22 18:58:30 +00008479 COLORREF bg;
8480 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
8481 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8482 default_console_color_bg = bg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008483
Christopher Plewrightd343c602023-01-22 18:58:30 +00008484 COLORREF fg;
8485 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
8486 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8487 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008488# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008489 set_console_color_rgb();
8490}
8491
8492 static void
8493vtp_exit(void)
8494{
Bram Moolenaardf543822020-01-30 11:53:59 +01008495 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008496}
8497
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008498 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008499vtp_printf(
8500 char *format,
8501 ...)
8502{
8503 char_u buf[100];
8504 va_list list;
8505 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008506 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008507
8508 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008509 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008510 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008511 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008512 return (int)result;
8513}
8514
8515 static void
8516vtp_sgr_bulk(
8517 int arg)
8518{
8519 int args[1];
8520
8521 args[0] = arg;
8522 vtp_sgr_bulks(1, args);
8523}
8524
K.Takata6e1d31e2022-02-03 13:05:32 +00008525# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008526 if ((*p-- = "0123456789"[(n = x % 10)]) \
8527 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8528 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8529
K.Takata6e1d31e2022-02-03 13:05:32 +00008530# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008531 case x: \
8532 FAST256(newargs[x - 1]);
8533
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008534 static void
8535vtp_sgr_bulks(
8536 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008537 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008538{
K.Takata6e1d31e2022-02-03 13:05:32 +00008539# define MAXSGR 16
8540# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008541 char_u buf[SGRBUFSIZE];
8542 char_u *p;
8543 int in, out;
8544 int newargs[16];
8545 static int sgrfgr = -1, sgrfgg, sgrfgb;
8546 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008547
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008548 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008549 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008550 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008551 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008552 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008553 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008554
8555 in = out = 0;
8556 while (in < argc)
8557 {
8558 int s = args[in];
8559 int copylen = 1;
8560
8561 if (s == 38)
8562 {
8563 if (argc - in >= 5 && args[in + 1] == 2)
8564 {
8565 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8566 && sgrfgb == args[in + 4])
8567 {
8568 in += 5;
8569 copylen = 0;
8570 }
8571 else
8572 {
8573 sgrfgr = args[in + 2];
8574 sgrfgg = args[in + 3];
8575 sgrfgb = args[in + 4];
8576 copylen = 5;
8577 }
8578 }
8579 else if (argc - in >= 3 && args[in + 1] == 5)
8580 {
8581 sgrfgr = -1;
8582 copylen = 3;
8583 }
8584 }
8585 else if (s == 48)
8586 {
8587 if (argc - in >= 5 && args[in + 1] == 2)
8588 {
8589 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8590 && sgrbgb == args[in + 4])
8591 {
8592 in += 5;
8593 copylen = 0;
8594 }
8595 else
8596 {
8597 sgrbgr = args[in + 2];
8598 sgrbgg = args[in + 3];
8599 sgrbgb = args[in + 4];
8600 copylen = 5;
8601 }
8602 }
8603 else if (argc - in >= 3 && args[in + 1] == 5)
8604 {
8605 sgrbgr = -1;
8606 copylen = 3;
8607 }
8608 }
8609 else if (30 <= s && s <= 39)
8610 sgrfgr = -1;
8611 else if (90 <= s && s <= 97)
8612 sgrfgr = -1;
8613 else if (40 <= s && s <= 49)
8614 sgrbgr = -1;
8615 else if (100 <= s && s <= 107)
8616 sgrbgr = -1;
8617 else if (s == 0)
8618 sgrfgr = sgrbgr = -1;
8619
8620 while (copylen--)
8621 newargs[out++] = args[in++];
8622 }
8623
8624 p = &buf[sizeof(buf) - 1];
8625 *p-- = 'm';
8626
8627 switch (out)
8628 {
8629 int n, m;
8630 DWORD r;
8631
8632 FAST256CASE(16);
8633 *p-- = ';';
8634 FAST256CASE(15);
8635 *p-- = ';';
8636 FAST256CASE(14);
8637 *p-- = ';';
8638 FAST256CASE(13);
8639 *p-- = ';';
8640 FAST256CASE(12);
8641 *p-- = ';';
8642 FAST256CASE(11);
8643 *p-- = ';';
8644 FAST256CASE(10);
8645 *p-- = ';';
8646 FAST256CASE(9);
8647 *p-- = ';';
8648 FAST256CASE(8);
8649 *p-- = ';';
8650 FAST256CASE(7);
8651 *p-- = ';';
8652 FAST256CASE(6);
8653 *p-- = ';';
8654 FAST256CASE(5);
8655 *p-- = ';';
8656 FAST256CASE(4);
8657 *p-- = ';';
8658 FAST256CASE(3);
8659 *p-- = ';';
8660 FAST256CASE(2);
8661 *p-- = ';';
8662 FAST256CASE(1);
8663 *p-- = '[';
8664 *p = '\033';
8665 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8666 default:
8667 break;
8668 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008669}
8670
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008671 static void
8672wt_init(void)
8673{
Christopher Plewright1140b512022-11-12 18:46:05 +00008674 wt_working = mch_getenv("WT_SESSION") != NULL;
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008675}
8676
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008677# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008678 static int
8679ctermtoxterm(
8680 int cterm)
8681{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008682 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008683
8684 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8685 return (((int)r << 16) | ((int)g << 8) | (int)b);
8686}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008687# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008688
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008689 static void
8690set_console_color_rgb(void)
8691{
8692# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008693 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008694 guicolor_T fg, bg;
8695 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008696
Christopher Plewright38804d62022-11-09 23:55:52 +00008697 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008698 return;
8699
Bram Moolenaara050b942019-12-02 21:35:31 +01008700 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8701
Christopher Plewright38804d62022-11-09 23:55:52 +00008702 if (p_tgc || t_colors >= 256)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008703 {
8704 term_fg_rgb_color(fg);
8705 term_bg_rgb_color(bg);
8706 return;
8707 }
8708
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008709 if (use_alternate_screen_buffer)
8710 return;
8711
Christopher Plewrightd343c602023-01-22 18:58:30 +00008712 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8713 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008714
Christopher Plewrightd343c602023-01-22 18:58:30 +00008715 csbi.cbSize = sizeof(csbi);
8716 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008717
Christopher Plewrightd343c602023-01-22 18:58:30 +00008718 csbi.cbSize = sizeof(csbi);
8719 csbi.srWindow.Right += 1;
8720 csbi.srWindow.Bottom += 1;
8721 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8722 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
8723 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8724 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
8725 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008726# endif
8727}
8728
Bram Moolenaara050b942019-12-02 21:35:31 +01008729# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8730 void
8731get_default_console_color(
8732 int *cterm_fg,
8733 int *cterm_bg,
8734 guicolor_T *gui_fg,
8735 guicolor_T *gui_bg)
8736{
8737 int id;
8738 guicolor_T guifg = INVALCOLOR;
8739 guicolor_T guibg = INVALCOLOR;
8740 int ctermfg = 0;
8741 int ctermbg = 0;
Christopher Plewright38804d62022-11-09 23:55:52 +00008742 int dummynull = 0;
Bram Moolenaara050b942019-12-02 21:35:31 +01008743
8744 id = syn_name2id((char_u *)"Normal");
8745 if (id > 0 && p_tgc)
8746 syn_id2colors(id, &guifg, &guibg);
8747 if (guifg == INVALCOLOR)
8748 {
8749 ctermfg = -1;
8750 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008751 syn_id2cterm_bg(id, &ctermfg, &dummynull);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008752 if (ctermfg != -1)
8753 guifg = ctermtoxterm(ctermfg);
Christopher Plewright38804d62022-11-09 23:55:52 +00008754 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008755 guifg = USE_WT ? INVALCOLOR : default_console_color_fg;
8756 cterm_normal_fg_gui_color = guifg;
8757 ctermfg = ctermfg < 0 ? 0 : ctermfg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008758 }
8759 if (guibg == INVALCOLOR)
8760 {
8761 ctermbg = -1;
8762 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008763 syn_id2cterm_bg(id, &dummynull, &ctermbg);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008764 if (ctermbg != -1)
8765 guibg = ctermtoxterm(ctermbg);
K.Takatae53a0d42022-09-05 21:45:11 +01008766 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008767 guibg = USE_WT ? INVALCOLOR : default_console_color_bg;
8768 cterm_normal_bg_gui_color = guibg;
8769 ctermbg = ctermbg < 0 ? 0 : ctermbg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008770 }
8771
8772 *cterm_fg = ctermfg;
8773 *cterm_bg = ctermbg;
8774 *gui_fg = guifg;
8775 *gui_bg = guibg;
8776}
8777# endif
8778
Bram Moolenaardf543822020-01-30 11:53:59 +01008779/*
8780 * Set the console colors to the original colors or the last set colors.
8781 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008782 static void
8783reset_console_color_rgb(void)
8784{
8785# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008786 if (use_alternate_screen_buffer)
8787 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008788
Christopher Plewright38804d62022-11-09 23:55:52 +00008789 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8790
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008791 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008792 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008793
8794 csbi.cbSize = sizeof(csbi);
8795 csbi.srWindow.Right += 1;
8796 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008797 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8798 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008799 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008800# endif
8801}
8802
8803/*
8804 * Set the console colors to the original colors.
8805 */
8806 static void
8807restore_console_color_rgb(void)
8808{
8809# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008810 if (use_alternate_screen_buffer)
8811 return;
Christopher Plewright38804d62022-11-09 23:55:52 +00008812
K.Takata27b53be2022-09-18 12:25:49 +01008813 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008814
8815 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008816 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008817
8818 csbi.cbSize = sizeof(csbi);
8819 csbi.srWindow.Right += 1;
8820 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008821 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8822 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008823 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008824# endif
8825}
8826
8827 void
8828control_console_color_rgb(void)
8829{
Christopher Plewright38804d62022-11-09 23:55:52 +00008830 if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008831 set_console_color_rgb();
8832 else
8833 reset_console_color_rgb();
8834}
8835
8836 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008837use_vtp(void)
8838{
8839 return USE_VTP;
8840}
8841
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008842 int
8843is_term_win32(void)
8844{
8845 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8846}
8847
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008848 int
8849has_vtp_working(void)
8850{
8851 return vtp_working;
8852}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008853
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008854#endif
8855
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008856 int
8857has_conpty_working(void)
8858{
8859 return conpty_working;
8860}
8861
8862 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008863get_conpty_type(void)
8864{
8865 return conpty_type;
8866}
8867
8868 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008869is_conpty_stable(void)
8870{
8871 return conpty_stable;
8872}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008873
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008874 int
8875get_conpty_fix_type(void)
8876{
8877 return conpty_fix_type;
8878}
8879
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008880#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008881 void
8882resize_console_buf(void)
8883{
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008884 if (use_alternate_screen_buffer)
8885 return;
8886
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008887 CONSOLE_SCREEN_BUFFER_INFO csbi;
8888 COORD coord;
8889 SMALL_RECT newsize;
8890
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008891 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8892 return;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008893
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008894 coord.X = SRWIDTH(csbi.srWindow);
8895 coord.Y = SRHEIGHT(csbi.srWindow);
8896 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008897
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008898 newsize.Left = 0;
8899 newsize.Top = 0;
8900 newsize.Right = coord.X - 1;
8901 newsize.Bottom = coord.Y - 1;
8902 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8903
8904 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008905}
8906#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008907
8908 char *
8909GetWin32Error(void)
8910{
K.Takatad68b2fc2022-02-12 11:18:37 +00008911 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008912 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008913
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008914 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8915 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008916 if (oldmsg != NULL)
8917 LocalFree(oldmsg);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008918 if (msg == NULL)
8919 return NULL;
8920
8921 // remove trailing \r\n
8922 char *pcrlf = strstr(msg, "\r\n");
8923 if (pcrlf != NULL)
8924 *pcrlf = '\0';
8925 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008926 return msg;
8927}
Paul Ollis65745772022-06-05 16:55:54 +01008928
8929#if defined(FEAT_RELTIME) || defined(PROTO)
8930static HANDLE timer_handle;
8931static int timer_active = FALSE;
8932
8933/*
8934 * Calls to start_timeout alternate the return value pointer between the two
8935 * entries in timeout_flags. If the previously active timeout is very close to
8936 * expiring when start_timeout() is called then a race condition means that the
8937 * set_flag() function may still be invoked after the previous timer is
8938 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8939 * timeouts.
8940 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008941static sig_atomic_t timeout_flags[2];
8942static int timeout_flag_idx = 0;
8943static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01008944
8945
8946 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01008947set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01008948{
8949 int *timeout_flag = (int *)param;
8950
8951 *timeout_flag = TRUE;
8952}
8953
8954/*
8955 * Stop any active timeout.
8956 */
8957 void
8958stop_timeout(void)
8959{
8960 if (timer_active)
8961 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01008962 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01008963 timer_active = FALSE;
8964 if (!ret && GetLastError() != ERROR_IO_PENDING)
8965 {
8966 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
8967 }
8968 }
8969 *timeout_flag = FALSE;
8970}
8971
8972/*
8973 * Start the timeout timer.
8974 *
8975 * The period is defined in milliseconds.
8976 *
8977 * The return value is a pointer to a flag that is initialised to 0. If the
8978 * timeout expires, the flag is set to 1. This will only return pointers to
8979 * static memory; i.e. any pointer returned by this function may always be
8980 * safely dereferenced.
8981 *
8982 * This function is not expected to fail, but if it does it still returns a
8983 * valid flag pointer; the flag will remain stuck at zero.
8984 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008985 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01008986start_timeout(long msec)
8987{
Paul Ollis65745772022-06-05 16:55:54 +01008988 BOOL ret;
8989
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008990 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01008991
8992 stop_timeout();
8993 ret = CreateTimerQueueTimer(
8994 &timer_handle, NULL, set_flag, timeout_flag,
8995 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
8996 if (!ret)
8997 {
8998 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
8999 }
9000 else
9001 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01009002 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01009003 timer_active = TRUE;
9004 *timeout_flag = FALSE;
9005 }
9006 return timeout_flag;
9007}
9008#endif