blob: ba5d228b840ad0be5ce55a632dd7987ee340dc01 [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
12 * Used for both the console version and the Win32 GUI. A lot of code is for
Bram Moolenaar4f974752019-02-17 17:44:42 +010013 * the console version only, so there is a lot of "#ifndef FEAT_GUI_MSWIN".
Bram Moolenaar071d4272004-06-13 20:20:40 +000014 *
15 * Win32 (Windows NT and Windows 95) system-dependent routines.
16 * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17 * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18 *
19 * George V. Reilly <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
Bram Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010032
Bram Moolenaar0f873732019-12-05 20:28:46 +010033// cproto fails on missing include files
Bram Moolenaar82881492012-11-20 16:53:39 +010034#ifndef PROTO
35# include <process.h>
Bram Moolenaare7bebc42021-02-01 20:50:37 +010036# include <winternl.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010037#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000038
39#undef chdir
40#ifdef __GNUC__
41# ifndef __MINGW32__
42# include <dirent.h>
43# endif
44#else
45# include <direct.h>
46#endif
47
Bram Moolenaar82881492012-11-20 16:53:39 +010048#ifndef PROTO
Bram Moolenaar651fca82021-11-29 20:39:38 +000049# if !defined(FEAT_GUI_MSWIN)
Bram Moolenaar82881492012-11-20 16:53:39 +010050# include <shellapi.h>
51# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000052#endif
53
Bram Moolenaarfb630902016-10-29 14:55:00 +020054#ifdef FEAT_JOB_CHANNEL
55# include <tlhelp32.h>
56#endif
57
Bram Moolenaar071d4272004-06-13 20:20:40 +000058#ifdef __MINGW32__
59# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
60# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
61# endif
62# ifndef RIGHTMOST_BUTTON_PRESSED
63# define RIGHTMOST_BUTTON_PRESSED 0x0002
64# endif
65# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
66# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
67# endif
68# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
69# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
70# endif
71# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
72# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
73# endif
74
75/*
76 * EventFlags
77 */
78# ifndef MOUSE_MOVED
79# define MOUSE_MOVED 0x0001
80# endif
81# ifndef DOUBLE_CLICK
82# define DOUBLE_CLICK 0x0002
83# endif
84#endif
85
Bram Moolenaar0f873732019-12-05 20:28:46 +010086// Record all output and all keyboard & mouse input
87// #define MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +000088
89#ifdef MCH_WRITE_DUMP
90FILE* fdDump = NULL;
91#endif
92
93/*
94 * When generating prototypes for Win32 on Unix, these lines make the syntax
95 * errors disappear. They do not need to be correct.
96 */
97#ifdef PROTO
Bram Moolenaar912bc4a2019-12-01 18:58:11 +010098# define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000099typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000100typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000101typedef int ACCESS_MASK;
102typedef int BOOL;
Paul Ollis65745772022-06-05 16:55:54 +0100103typedef int BOOLEAN;
104typedef int CALLBACK;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000105typedef int COLORREF;
106typedef int CONSOLE_CURSOR_INFO;
107typedef int COORD;
108typedef int DWORD;
109typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100110typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000111typedef int HDC;
112typedef int HFONT;
113typedef int HICON;
114typedef int HINSTANCE;
115typedef int HWND;
116typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200117typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000118typedef int KEY_EVENT_RECORD;
119typedef int LOGFONT;
120typedef int LPBOOL;
121typedef int LPCTSTR;
122typedef int LPDWORD;
123typedef int LPSTR;
124typedef int LPTSTR;
125typedef int LPVOID;
126typedef int MOUSE_EVENT_RECORD;
127typedef int PACL;
128typedef int PDWORD;
129typedef int PHANDLE;
130typedef int PRINTDLG;
131typedef int PSECURITY_DESCRIPTOR;
132typedef int PSID;
133typedef int SECURITY_INFORMATION;
134typedef int SHORT;
135typedef int SMALL_RECT;
136typedef int TEXTMETRIC;
137typedef int TOKEN_INFORMATION_CLASS;
138typedef int TRUSTEE;
139typedef int WORD;
140typedef int WCHAR;
141typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100142typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200143typedef int SE_OBJECT_TYPE;
144typedef int PSNSECINFO;
145typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100146typedef int STARTUPINFO;
147typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200148typedef int LPSECURITY_ATTRIBUTES;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100149# define __stdcall // empty
Bram Moolenaar071d4272004-06-13 20:20:40 +0000150#endif
151
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200152#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100153// Win32 Console handles for input and output
Bram Moolenaar071d4272004-06-13 20:20:40 +0000154static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
155static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
156
Bram Moolenaar0f873732019-12-05 20:28:46 +0100157// Win32 Screen buffer,coordinate,console I/O information
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158static SMALL_RECT g_srScrollRegion;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100159static COORD g_coord; // 0-based, but external coords are 1-based
Bram Moolenaar071d4272004-06-13 20:20:40 +0000160
Bram Moolenaar0f873732019-12-05 20:28:46 +0100161// The attribute of the screen when the editor was started
162static WORD g_attrDefault = 7; // lightgray text on black background
Bram Moolenaar071d4272004-06-13 20:20:40 +0000163static WORD g_attrCurrent;
164
Bram Moolenaar0f873732019-12-05 20:28:46 +0100165static int g_fCBrkPressed = FALSE; // set by ctrl-break interrupt
166static int g_fCtrlCPressed = FALSE; // set when ctrl-C or ctrl-break detected
167static int g_fForceExit = FALSE; // set when forcefully exiting
Bram Moolenaar071d4272004-06-13 20:20:40 +0000168
Bram Moolenaar071d4272004-06-13 20:20:40 +0000169static void scroll(unsigned cLines);
170static void set_scroll_region(unsigned left, unsigned top,
171 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100172static void set_scroll_region_tb(unsigned top, unsigned bottom);
173static void set_scroll_region_lr(unsigned left, unsigned right);
174static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000175static void delete_lines(unsigned cLines);
176static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000177static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000178static int s_cursor_visible = TRUE;
179static int did_create_conin = FALSE;
Christopher Plewright20b795e2022-12-20 20:01:58 +0000180// The 'input_record_buffer' is an internal dynamic fifo queue of MS-Windows
181// console INPUT_RECORD events that are normally read from the console input
182// buffer. This provides an injection point for testing the low-level handling
183// of INPUT_RECORDs.
184typedef struct input_record_buffer_node_S
185{
186 INPUT_RECORD ir;
187 struct input_record_buffer_node_S *next;
188} input_record_buffer_node_T;
189typedef struct input_record_buffer_S
190{
191 input_record_buffer_node_T *head;
192 input_record_buffer_node_T *tail;
193 int length;
194} input_record_buffer_T;
195static input_record_buffer_T input_record_buffer;
Christopher Plewright20b795e2022-12-20 20:01:58 +0000196static int read_input_record_buffer(INPUT_RECORD* irEvents, int nMaxLength);
197static int write_input_record_buffer(INPUT_RECORD* irEvents, int nLength);
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200198#endif
199#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000200static int s_dont_use_vimrun = TRUE;
201static int need_vimrun_warning = FALSE;
202static char *vimrun_path = "vimrun ";
203#endif
204
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200205static int win32_getattrs(char_u *name);
206static int win32_setattrs(char_u *name, int attrs);
207static int win32_set_archive(char_u *name);
208
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100209static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200210static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100211static int conpty_stable = 0;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +0200212static int conpty_fix_type = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100213static void vtp_flag_init();
214
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200215#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100216static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100217static void vtp_init();
218static void vtp_exit();
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100219static void vtp_sgr_bulk(int arg);
220static void vtp_sgr_bulks(int argc, int *argv);
221
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200222static int wt_working = 0;
Christopher Plewright1140b512022-11-12 18:46:05 +0000223static void wt_init(void);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200224
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200225static int g_color_index_bg = 0;
226static int g_color_index_fg = 7;
227
228# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +0000229static guicolor_T save_console_bg_rgb;
230static guicolor_T save_console_fg_rgb;
231static guicolor_T store_console_bg_rgb;
232static guicolor_T store_console_fg_rgb;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +0100233static int default_console_color_bg = 0x000000; // black
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200234static int default_console_color_fg = 0xc0c0c0; // white
Christopher Plewright38804d62022-11-09 23:55:52 +0000235# define USE_VTP (vtp_working && is_term_win32())
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200236# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100237# else
238# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200239# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100240# endif
241
242static void set_console_color_rgb(void);
243static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100244static void restore_console_color_rgb(void);
Christopher Plewright20b795e2022-12-20 20:01:58 +0000245#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100246
Bram Moolenaar0f873732019-12-05 20:28:46 +0100247// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100248#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
249# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
250#endif
251
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200252#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100253static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000254#endif
255
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200256static char_u *exe_path = NULL;
257
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100258static BOOL win8_or_later = FALSE;
Christopher Plewrightc8b126d2022-12-22 13:45:23 +0000259static BOOL win10_22H2_or_later = FALSE;
Bram Moolenaar9fca1332022-12-22 21:06:41 +0000260#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Christopher Plewrightc8b126d2022-12-22 13:45:23 +0000261static BOOL use_alternate_screen_buffer = FALSE;
Bram Moolenaar9fca1332022-12-22 21:06:41 +0000262#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100263
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100264/*
265 * Get version number including build number
266 */
267typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100268#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100269 (((major) << 24) | ((minor) << 16) | (build))
270
271 static DWORD
272get_build_number(void)
273{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100274 OSVERSIONINFOW osver;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100275 HMODULE hNtdll;
276 PfnRtlGetVersion pRtlGetVersion;
277 DWORD ver = MAKE_VER(0, 0, 0);
278
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100279 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100280 hNtdll = GetModuleHandle("ntdll.dll");
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000281 if (hNtdll == NULL)
282 return ver;
283
284 pRtlGetVersion =
285 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
286 pRtlGetVersion(&osver);
287 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
288 min(osver.dwMinorVersion, 255),
289 min(osver.dwBuildNumber, 32767));
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100290 return ver;
291}
292
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200293#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200294 static BOOL
295is_ambiwidth_event(
296 INPUT_RECORD *ir)
297{
298 return ir->EventType == KEY_EVENT
299 && ir->Event.KeyEvent.bKeyDown
300 && ir->Event.KeyEvent.wRepeatCount == 1
301 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
302 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000303 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200304 && ir->Event.KeyEvent.dwControlKeyState == 2;
305}
306
307 static void
308make_ambiwidth_event(
309 INPUT_RECORD *down,
310 INPUT_RECORD *up)
311{
312 down->Event.KeyEvent.wVirtualKeyCode = 0;
313 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000314 down->Event.KeyEvent.uChar.UnicodeChar
315 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200316 down->Event.KeyEvent.dwControlKeyState = 0;
317}
318
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100319/*
320 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100321 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100322 */
323 static BOOL
324read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100325 HANDLE hInput,
326 INPUT_RECORD *lpBuffer,
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100327 int nLength,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100328 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100329{
330 enum
331 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100332 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100333 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100334 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100335 static DWORD s_dwIndex = 0;
336 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100337 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100338 int head;
339 int tail;
340 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200341 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100342
Christopher Plewright20b795e2022-12-20 20:01:58 +0000343 if (s_dwMax == 0 && input_record_buffer.length > 0)
344 {
345 dwEvents = read_input_record_buffer(s_irCache, IRSIZE);
346 s_dwIndex = 0;
347 s_dwMax = dwEvents;
348 }
349
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200350 if (nLength == -2)
351 return (s_dwMax > 0) ? TRUE : FALSE;
352
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100353 if (!win8_or_later)
354 {
355 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200356 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
357 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100358 }
359
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100360 if (s_dwMax == 0)
361 {
Christopher Plewright38804d62022-11-09 23:55:52 +0000362 if (!vtp_working && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200363 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200364 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
365 if (dwEvents == 0 && nLength == -1)
366 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
367 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100368 s_dwIndex = 0;
369 s_dwMax = dwEvents;
370 if (dwEvents == 0)
371 {
372 *lpEvents = 0;
373 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100374 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100375
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200376 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
377 if (is_ambiwidth_event(&s_irCache[i]))
378 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
379
Bram Moolenaardd415a62014-02-05 14:02:27 +0100380 if (s_dwMax > 1)
381 {
382 head = 0;
383 tail = s_dwMax - 1;
384 while (head != tail)
385 {
386 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
387 && s_irCache[head + 1].EventType
388 == WINDOW_BUFFER_SIZE_EVENT)
389 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100390 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100391 for (i = head; i < tail; ++i)
392 s_irCache[i] = s_irCache[i + 1];
393 --tail;
394 continue;
395 }
396 head++;
397 }
398 s_dwMax = tail + 1;
399 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100400 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100401
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200402 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
403 {
404 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
405 {
406 s_irPseudo = s_irCache[s_dwIndex];
407 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
408 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
409 *lpBuffer = s_irPseudo;
410 *lpEvents = 1;
411 return TRUE;
412 }
413 }
414
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100415 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200416 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100417 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100418 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100419 return TRUE;
420}
421
422/*
423 * Version of PeekConsoleInput() that works with IME.
424 */
425 static BOOL
426peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100427 HANDLE hInput,
428 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200429 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100430 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100431{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100432 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100433}
434
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100435# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200436 static DWORD
437msg_wait_for_multiple_objects(
438 DWORD nCount,
439 LPHANDLE pHandles,
440 BOOL fWaitAll,
441 DWORD dwMilliseconds,
442 DWORD dwWakeMask)
443{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100444 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200445 return WAIT_OBJECT_0;
446 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
447 dwMilliseconds, dwWakeMask);
448}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100449# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200450
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100451# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200452 static DWORD
453wait_for_single_object(
454 HANDLE hHandle,
455 DWORD dwMilliseconds)
456{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100457 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200458 return WAIT_OBJECT_0;
459 return WaitForSingleObject(hHandle, dwMilliseconds);
460}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100461# endif
Christopher Plewright20b795e2022-12-20 20:01:58 +0000462#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200463
Bram Moolenaar071d4272004-06-13 20:20:40 +0000464 static void
465get_exe_name(void)
466{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100467 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
468 // as the maximum length that works (plus a NUL byte).
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100469#define MAX_ENV_PATH_LEN 8192
470 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200471 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000472
473 if (exe_name == NULL)
474 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100475 // store the name of the executable, may be used for $VIM
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100476 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000477 if (*temp != NUL)
478 exe_name = FullName_save((char_u *)temp, FALSE);
479 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000480
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000481 if (exe_path != NULL || exe_name == NULL)
482 return;
483
484 exe_path = vim_strnsave(exe_name, gettail_sep(exe_name) - exe_name);
485 if (exe_path == NULL)
486 return;
487
488 // Append our starting directory to $PATH, so that when doing
489 // "!xxd" it's found in our starting directory. Needed because
490 // SearchPath() also looks there.
491 p = mch_getenv("PATH");
492 if (p == NULL
493 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000494 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000495 if (p == NULL || *p == NUL)
496 temp[0] = NUL;
497 else
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000498 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000499 STRCPY(temp, p);
500 STRCAT(temp, ";");
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000501 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000502 STRCAT(temp, exe_path);
503 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000504 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000505}
506
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200507/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100508 * Unescape characters in "p" that appear in "escaped".
509 */
510 static void
511unescape_shellxquote(char_u *p, char_u *escaped)
512{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100513 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100514 int n;
515
516 while (*p != NUL)
517 {
518 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
519 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100520 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100521 p += n;
522 l -= n;
523 }
524}
525
526/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200527 * Load library "name".
528 */
529 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000530vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200531{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200532 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200533
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200534 // No need to load any library when registering OLE.
535 if (found_register_arg)
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000536 return NULL;
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200537
Bram Moolenaar0f873732019-12-05 20:28:46 +0100538 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
539 // vimLoadLib() recursively, which causes a stack overflow.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200540 if (exe_path == NULL)
541 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200542
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000543 if (exe_path == NULL)
544 return NULL;
545
546 WCHAR old_dirw[MAXPATHL];
547
548 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) == 0)
549 return NULL;
550
551 // Change directory to where the executable is, both to make
552 // sure we find a .dll there and to avoid looking for a .dll
553 // in the current directory.
554 SetCurrentDirectory((LPCSTR)exe_path);
555 dll = LoadLibrary(name);
556 SetCurrentDirectoryW(old_dirw);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200557 return dll;
558}
559
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200560#if defined(VIMDLL) || defined(PROTO)
561/*
562 * Check if the current executable file is for the GUI subsystem.
563 */
564 int
565mch_is_gui_executable(void)
566{
567 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
568 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
569 PIMAGE_NT_HEADERS pPE;
570
571 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
572 return FALSE;
573 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
574 if (pPE->Signature != IMAGE_NT_SIGNATURE)
575 return FALSE;
576 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
577 return TRUE;
578 return FALSE;
579}
580#endif
581
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000582#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
583 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100584/*
585 * Get related information about 'funcname' which is imported by 'hInst'.
586 * If 'info' is 0, return the function address.
587 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000588 * If 'info' is 2, hook the function with 'ptr', and return the original
589 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100590 */
591 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000592get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
593 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100594{
595 PBYTE pImage = (PBYTE)hInst;
596 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
597 PIMAGE_NT_HEADERS pPE;
598 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100599 PIMAGE_THUNK_DATA pIAT; // Import Address Table
600 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100601 PIMAGE_IMPORT_BY_NAME pImpName;
602
603 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
604 return NULL;
605 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
606 if (pPE->Signature != IMAGE_NT_SIGNATURE)
607 return NULL;
608 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
609 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
610 .VirtualAddress);
611 for (; pImpDesc->FirstThunk; ++pImpDesc)
612 {
613 if (!pImpDesc->OriginalFirstThunk)
614 continue;
615 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
616 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
617 for (; pIAT->u1.Function; ++pIAT, ++pINT)
618 {
619 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
620 continue;
621 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
622 + (UINT_PTR)(pINT->u1.AddressOfData));
623 if (strcmp((char *)pImpName->Name, funcname) == 0)
624 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000625 void *original;
626 DWORD old, new = PAGE_READWRITE;
627
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100628 switch (info)
629 {
630 case 0:
631 return (void *)pIAT->u1.Function;
632 case 1:
633 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000634 case 2:
635 original = (void *)pIAT->u1.Function;
636 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
637 new, &old);
638 pIAT->u1.Function = (UINT_PTR)ptr;
639 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
640 old, &new);
641 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100642 default:
643 return NULL;
644 }
645 }
646 }
647 }
648 return NULL;
649}
650
651/*
652 * Get the module handle which 'funcname' in 'hInst' is imported from.
653 */
654 HINSTANCE
655find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
656{
657 char *modulename;
658
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000659 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100660 if (modulename != NULL)
661 return GetModuleHandleA(modulename);
662 return NULL;
663}
664
665/*
666 * Get the address of 'funcname' which is imported by 'hInst' DLL.
667 */
668 void *
669get_dll_import_func(HINSTANCE hInst, const char *funcname)
670{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000671 return get_imported_func_info(hInst, funcname, 0, NULL);
672}
673
674/*
675 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
676 * and return the original function address.
677 */
678 void *
679hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
680{
681 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100682}
683#endif
684
Bram Moolenaar071d4272004-06-13 20:20:40 +0000685#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
686# ifndef GETTEXT_DLL
687# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200688# define GETTEXT_DLL_ALT1 "libintl-8.dll"
689# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000690# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100691// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000692static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200693static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000694static char *null_libintl_textdomain(const char *);
695static char *null_libintl_bindtextdomain(const char *, const char *);
696static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100697static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000698
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200699static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000700char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200701char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
702 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000703char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
704char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000705 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000706char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
707 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100708int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000709
710 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100711dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000712{
713 int i;
714 static struct
715 {
716 char *name;
717 FARPROC *ptr;
718 } libintl_entry[] =
719 {
720 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200721 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000722 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
723 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
724 {NULL, NULL}
725 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100726 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000727
Bram Moolenaar7554c542018-10-06 15:03:15 +0200728 // No need to initialize twice.
729 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000730 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200731 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100732 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100733# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100734 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200735 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100736# endif
737# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200738 if (!hLibintlDLL)
739 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100740# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100741 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000742 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200743 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000744 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200745 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000746 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200747 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000748 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200749 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000750 }
751 for (i = 0; libintl_entry[i].name != NULL
752 && libintl_entry[i].ptr != NULL; ++i)
753 {
K.Takata54119102022-02-03 13:33:03 +0000754 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000755 libintl_entry[i].name)) == NULL)
756 {
757 dyn_libintl_end();
758 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000759 {
760 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000761 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000762 verbose_leave();
763 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000764 return 0;
765 }
766 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000767
Bram Moolenaar0f873732019-12-05 20:28:46 +0100768 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100769 dyn_libintl_bind_textdomain_codeset = (char *(*)(const char *, const char *))
770 GetProcAddress(hLibintlDLL, "bind_textdomain_codeset");
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000771 if (dyn_libintl_bind_textdomain_codeset == NULL)
772 dyn_libintl_bind_textdomain_codeset =
773 null_libintl_bind_textdomain_codeset;
774
Bram Moolenaar0f873732019-12-05 20:28:46 +0100775 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100776 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
777 if (hmsvcrt != NULL)
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100778 dyn_libintl_wputenv = (int (*)(const wchar_t *))
779 GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100780 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
781 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100782
Bram Moolenaar071d4272004-06-13 20:20:40 +0000783 return 1;
784}
785
786 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100787dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000788{
789 if (hLibintlDLL)
790 FreeLibrary(hLibintlDLL);
791 hLibintlDLL = NULL;
792 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200793 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000794 dyn_libintl_textdomain = null_libintl_textdomain;
795 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000796 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100797 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000798}
799
800 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000801null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000802{
803 return (char*)msgid;
804}
805
806 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200807null_libintl_ngettext(
808 const char *msgid,
809 const char *msgid_plural,
810 unsigned long n)
811{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200812 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200813}
814
Bram Moolenaaree695f72016-08-03 22:08:45 +0200815 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100816null_libintl_bindtextdomain(
817 const char *domainname UNUSED,
818 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000819{
820 return NULL;
821}
822
823 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100824null_libintl_bind_textdomain_codeset(
825 const char *domainname UNUSED,
826 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000827{
828 return NULL;
829}
830
831 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100832null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000833{
834 return NULL;
835}
836
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200837 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100838null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100839{
840 return 0;
841}
842
Bram Moolenaar0f873732019-12-05 20:28:46 +0100843#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000844
Bram Moolenaar0f873732019-12-05 20:28:46 +0100845// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000846
847#ifndef VER_PLATFORM_WIN32_WINDOWS
848# define VER_PLATFORM_WIN32_WINDOWS 1
849#endif
850
Bram Moolenaar071d4272004-06-13 20:20:40 +0000851#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100852# ifndef PROTO
853# include <aclapi.h>
854# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200855# ifndef PROTECTED_DACL_SECURITY_INFORMATION
856# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
857# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000858#endif
859
Bram Moolenaar27515922013-06-29 15:36:26 +0200860#ifdef HAVE_ACL
861/*
862 * Enables or disables the specified privilege.
863 */
864 static BOOL
865win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
866{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100867 BOOL bResult;
868 LUID luid;
869 HANDLE hToken;
870 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200871
872 if (!OpenProcessToken(GetCurrentProcess(),
873 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
874 return FALSE;
875
876 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
877 {
878 CloseHandle(hToken);
879 return FALSE;
880 }
881
Bram Moolenaar45500912014-07-09 20:51:07 +0200882 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200883 tokenPrivileges.Privileges[0].Luid = luid;
884 tokenPrivileges.Privileges[0].Attributes = bEnable ?
885 SE_PRIVILEGE_ENABLED : 0;
886
887 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
888 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
889
890 CloseHandle(hToken);
891
892 return bResult && GetLastError() == ERROR_SUCCESS;
893}
894#endif
895
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100896#ifdef _MSC_VER
897// Suppress the deprecation warning for using GetVersionEx().
898// It is needed for implementing "windowsversion()".
899# pragma warning(push)
900# pragma warning(disable: 4996)
901#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000902/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200903 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000904 */
905 void
906PlatformId(void)
907{
908 static int done = FALSE;
909
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000910 if (done)
911 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000912
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000913 OSVERSIONINFO ovi;
914
915 ovi.dwOSVersionInfoSize = sizeof(ovi);
916 GetVersionEx(&ovi);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000917
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200918#ifdef FEAT_EVAL
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000919 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
920 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200921#endif
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000922 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
923 || ovi.dwMajorVersion > 6)
924 win8_or_later = TRUE;
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100925
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000926 if ((ovi.dwMajorVersion == 10 && ovi.dwBuildNumber >= 19045)
927 || ovi.dwMajorVersion > 10)
928 win10_22H2_or_later = TRUE;
Christopher Plewright1140b512022-11-12 18:46:05 +0000929
Bram Moolenaar071d4272004-06-13 20:20:40 +0000930#ifdef HAVE_ACL
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000931 // Enable privilege for getting or setting SACLs.
932 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000933#endif
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000934 done = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000935}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100936#ifdef _MSC_VER
937# pragma warning(pop)
938#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000939
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200940#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000941
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100942# define SHIFT (SHIFT_PRESSED)
943# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
944# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
945# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000946
947
Bram Moolenaar0f873732019-12-05 20:28:46 +0100948// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
949// We map function keys to their ANSI terminal equivalents, as produced
950// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
951// ANSI key with a value >= '\300' is nonstandard, but provided anyway
952// so that the user can have access to all SHIFT-, CTRL-, and ALT-
953// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000954
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000955static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000956{
957 WORD wVirtKey;
958 BOOL fAnsiKey;
959 int chAlone;
960 int chShift;
961 int chCtrl;
962 int chAlt;
963} VirtKeyMap[] =
964{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200965// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000966 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
967
968 { VK_F1, TRUE, ';', 'T', '^', 'h', },
969 { VK_F2, TRUE, '<', 'U', '_', 'i', },
970 { VK_F3, TRUE, '=', 'V', '`', 'j', },
971 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
972 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
973 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
974 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
975 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
976 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
977 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200978 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
979 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000980
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200981 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
982 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
983 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
984 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
985 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
986 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
987 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
988 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
989 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
990 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100991 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000992
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200993 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000994
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100995# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200996 // Most people don't have F13-F20, but what the hell...
997 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
998 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
999 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
1000 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
1001 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
1002 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
1003 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
1004 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001005# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001006 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
1007 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
1008 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
1009 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001010
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001011 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
1012 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
1013 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
1014 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
1015 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
1016 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
1017 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
1018 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
1019 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
1020 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001021 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001022};
1023
1024
Bram Moolenaar0f873732019-12-05 20:28:46 +01001025/*
1026 * The return code indicates key code size.
1027 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001028 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001029win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001030 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001031{
1032 UINT uMods = pker->dwControlKeyState;
1033 static int s_iIsDead = 0;
1034 static WORD awAnsiCode[2];
1035 static BYTE abKeystate[256];
1036
1037
1038 if (s_iIsDead == 2)
1039 {
K.Takata972db232022-02-04 10:45:38 +00001040 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001041 s_iIsDead = 0;
1042 return 1;
1043 }
1044
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001045 // check if it already has a valid unicode character.
Christopher Plewright566f76e2023-01-10 13:43:04 +00001046 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001047 return 1;
1048
Bram Moolenaara80faa82020-04-12 19:37:17 +02001049 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001050
Bram Moolenaar0f873732019-12-05 20:28:46 +01001051 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001052 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001053
1054 if (uMods & SHIFT_PRESSED)
1055 abKeystate[VK_SHIFT] = 0x80;
1056 if (uMods & CAPSLOCK_ON)
1057 abKeystate[VK_CAPITAL] = 1;
1058
1059 if ((uMods & ALT_GR) == ALT_GR)
1060 {
1061 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1062 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1063 }
1064
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001065 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1066 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001067
1068 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001069 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001070
1071 return s_iIsDead;
1072}
1073
Bram Moolenaar071d4272004-06-13 20:20:40 +00001074static BOOL g_fJustGotFocus = FALSE;
1075
1076/*
1077 * Decode a KEY_EVENT into one or two keystrokes
1078 */
1079 static BOOL
1080decode_key_event(
1081 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001082 WCHAR *pch,
1083 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001084 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001085 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001086{
1087 int i;
1088 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1089
1090 *pch = *pch2 = NUL;
1091 g_fJustGotFocus = FALSE;
1092
Bram Moolenaar0f873732019-12-05 20:28:46 +01001093 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001094 if (!pker->bKeyDown)
1095 return FALSE;
1096
Bram Moolenaar0f873732019-12-05 20:28:46 +01001097 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001098 switch (pker->wVirtualKeyCode)
1099 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001100 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001101 case VK_SHIFT:
1102 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001103 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001104 return FALSE;
1105
1106 default:
1107 break;
1108 }
1109
Bram Moolenaar0f873732019-12-05 20:28:46 +01001110 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001111 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1112 {
1113 *pch = K_NUL;
1114 *pch2 = '\017';
1115 return TRUE;
1116 }
1117
K.Takataeeec2542021-06-02 13:28:16 +02001118 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001119 {
1120 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1121 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001122 *pch = VirtKeyMap[i].chAlone;
1123 if ((nModifs & SHIFT) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001124 *pch = VirtKeyMap[i].chShift;
1125 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1126 *pch = VirtKeyMap[i].chCtrl;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001127 else if ((nModifs & ALT) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001128 *pch = VirtKeyMap[i].chAlt;
1129
1130 if (*pch != 0)
1131 {
1132 if (VirtKeyMap[i].fAnsiKey)
1133 {
1134 *pch2 = *pch;
1135 *pch = K_NUL;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001136 if (pmodifiers)
1137 {
1138 if (pker->wVirtualKeyCode >= VK_F1
1139 && pker->wVirtualKeyCode <= VK_F12)
1140 {
1141 if ((nModifs & ALT) != 0)
1142 {
1143 *pmodifiers |= MOD_MASK_ALT;
1144 if ((nModifs & SHIFT) == 0)
1145 *pch2 = VirtKeyMap[i].chAlone;
1146 }
1147 if ((nModifs & CTRL) != 0)
1148 {
1149 *pmodifiers |= MOD_MASK_CTRL;
1150 if ((nModifs & SHIFT) == 0)
1151 *pch2 = VirtKeyMap[i].chAlone;
1152 }
1153 }
1154 else if (pker->wVirtualKeyCode >= VK_END
1155 && pker->wVirtualKeyCode <= VK_DOWN)
1156 {
Christopher Plewright566f76e2023-01-10 13:43:04 +00001157 // (0x23 - 0x28): VK_END, VK_HOME,
1158 // VK_LEFT, VK_UP, VK_RIGHT, VK_DOWN
1159
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001160 *pmodifiers = 0;
1161 *pch2 = VirtKeyMap[i].chAlone;
1162 if ((nModifs & SHIFT) != 0
1163 && (nModifs & ~SHIFT) == 0)
1164 {
1165 *pch2 = VirtKeyMap[i].chShift;
1166 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001167 if ((nModifs & CTRL) != 0
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001168 && (nModifs & ~CTRL) == 0)
1169 {
1170 *pch2 = VirtKeyMap[i].chCtrl;
1171 if (pker->wVirtualKeyCode == VK_UP
1172 || pker->wVirtualKeyCode == VK_DOWN)
1173 {
1174 *pmodifiers |= MOD_MASK_CTRL;
1175 *pch2 = VirtKeyMap[i].chAlone;
1176 }
1177 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001178 if ((nModifs & SHIFT) != 0
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001179 && (nModifs & CTRL) != 0)
1180 {
1181 *pmodifiers |= MOD_MASK_CTRL;
1182 *pch2 = VirtKeyMap[i].chShift;
1183 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001184 if ((nModifs & ALT) != 0)
1185 {
1186 *pch2 = VirtKeyMap[i].chAlt;
1187 *pmodifiers |= MOD_MASK_ALT;
1188 if ((nModifs & ~ALT) == 0)
1189 {
1190 *pch2 = VirtKeyMap[i].chAlone;
1191 }
1192 else if ((nModifs & SHIFT) != 0)
1193 {
1194 *pch2 = VirtKeyMap[i].chShift;
1195 }
1196 else if ((nModifs & CTRL) != 0)
1197 {
1198 if (pker->wVirtualKeyCode == VK_UP
1199 || pker->wVirtualKeyCode == VK_DOWN)
1200 {
1201 *pmodifiers |= MOD_MASK_CTRL;
1202 *pch2 = VirtKeyMap[i].chAlone;
1203 }
1204 else
1205 {
1206 *pch2 = VirtKeyMap[i].chCtrl;
1207 }
1208 }
1209 }
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001210 }
1211 else
1212 {
1213 *pch2 = VirtKeyMap[i].chAlone;
1214 if ((nModifs & SHIFT) != 0)
1215 *pmodifiers |= MOD_MASK_SHIFT;
1216 if ((nModifs & CTRL) != 0)
1217 *pmodifiers |= MOD_MASK_CTRL;
1218 if ((nModifs & ALT) != 0)
1219 *pmodifiers |= MOD_MASK_ALT;
1220 }
1221 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001222 }
1223
1224 return TRUE;
1225 }
1226 }
1227 }
1228
1229 i = win32_kbd_patch_key(pker);
1230
1231 if (i < 0)
1232 *pch = NUL;
1233 else
1234 {
K.Takata972db232022-02-04 10:45:38 +00001235 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001236
1237 if (pmodifiers != NULL)
1238 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001239 // Pass on the ALT key as a modifier, but only when not combined
1240 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001241 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1242 *pmodifiers |= MOD_MASK_ALT;
1243
Bram Moolenaar0f873732019-12-05 20:28:46 +01001244 // Pass on SHIFT only for special keys, because we don't know when
1245 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001246 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1247 *pmodifiers |= MOD_MASK_SHIFT;
1248
Bram Moolenaar0f873732019-12-05 20:28:46 +01001249 // Pass on CTRL only for non-special keys, because we don't know
1250 // when it's already included with the character. And not when
1251 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001252 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1253 && *pch >= 0x20 && *pch < 0x80)
1254 *pmodifiers |= MOD_MASK_CTRL;
1255 }
1256 }
1257
1258 return (*pch != NUL);
1259}
1260
Christopher Plewright20b795e2022-12-20 20:01:58 +00001261# if defined(FEAT_EVAL)
1262 static int
1263encode_key_event(dict_T *args, INPUT_RECORD *ir)
1264{
1265 static int s_dwMods = 0;
1266
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001267 char_u *action = dict_get_string(args, "event", TRUE);
1268 if (action && (STRICMP(action, "keydown") == 0
1269 || STRICMP(action, "keyup") == 0))
Christopher Plewright20b795e2022-12-20 20:01:58 +00001270 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001271 BOOL isKeyDown = STRICMP(action, "keydown") == 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001272 WORD vkCode = dict_get_number_def(args, "keycode", 0);
1273 if (vkCode <= 0 || vkCode >= 0xFF)
1274 {
1275 semsg(_(e_invalid_argument_nr), (long)vkCode);
1276 return FALSE;
1277 }
1278
1279 ir->EventType = KEY_EVENT;
1280 KEY_EVENT_RECORD ker;
1281 ZeroMemory(&ker, sizeof(ker));
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001282 ker.bKeyDown = isKeyDown;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001283 ker.wRepeatCount = 1;
1284 ker.wVirtualScanCode = 0;
1285 ker.dwControlKeyState = 0;
1286 int mods = (int)dict_get_number(args, "modifiers");
1287 // Encode the win32 console key modifiers from Vim keyboard modifiers.
1288 if (mods)
1289 {
1290 // If "modifiers" is explicitly set in the args, then we reset any
1291 // remembered modifer key state that may have been set from earlier
1292 // mod-key-down events, even if they are not yet unset by earlier
1293 // mod-key-up events.
1294 s_dwMods = 0;
1295 if (mods & MOD_MASK_SHIFT)
1296 ker.dwControlKeyState |= SHIFT_PRESSED;
1297 if (mods & MOD_MASK_CTRL)
1298 ker.dwControlKeyState |= LEFT_CTRL_PRESSED;
1299 if (mods & MOD_MASK_ALT)
1300 ker.dwControlKeyState |= LEFT_ALT_PRESSED;
1301 }
1302
1303 if (vkCode == VK_LSHIFT || vkCode == VK_RSHIFT || vkCode == VK_SHIFT)
1304 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001305 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001306 s_dwMods |= SHIFT_PRESSED;
1307 else
1308 s_dwMods &= ~SHIFT_PRESSED;
1309 }
1310 else if (vkCode == VK_LCONTROL || vkCode == VK_CONTROL)
1311 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001312 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001313 s_dwMods |= LEFT_CTRL_PRESSED;
1314 else
1315 s_dwMods &= ~LEFT_CTRL_PRESSED;
1316 }
1317 else if (vkCode == VK_RCONTROL)
1318 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001319 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001320 s_dwMods |= RIGHT_CTRL_PRESSED;
1321 else
1322 s_dwMods &= ~RIGHT_CTRL_PRESSED;
1323 }
1324 else if (vkCode == VK_LMENU || vkCode == VK_MENU)
1325 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001326 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001327 s_dwMods |= LEFT_ALT_PRESSED;
1328 else
1329 s_dwMods &= ~LEFT_ALT_PRESSED;
1330 }
1331 else if (vkCode == VK_RMENU)
1332 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001333 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001334 s_dwMods |= RIGHT_ALT_PRESSED;
1335 else
1336 s_dwMods &= ~RIGHT_ALT_PRESSED;
1337 }
1338 ker.dwControlKeyState |= s_dwMods;
1339 ker.wVirtualKeyCode = vkCode;
Christopher Plewright566f76e2023-01-10 13:43:04 +00001340 ker.uChar.UnicodeChar = 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001341 ir->Event.KeyEvent = ker;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001342 vim_free(action);
Christopher Plewright20b795e2022-12-20 20:01:58 +00001343 }
1344 else
1345 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001346 if (action == NULL)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001347 {
1348 semsg(_(e_missing_argument_str), "event");
1349 }
1350 else
1351 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001352 semsg(_(e_invalid_value_for_argument_str_str), "event", action);
1353 vim_free(action);
Christopher Plewright20b795e2022-12-20 20:01:58 +00001354 }
1355 return FALSE;
1356 }
1357 return TRUE;
1358}
1359# endif // FEAT_EVAL
1360#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00001361
1362
Bram Moolenaar071d4272004-06-13 20:20:40 +00001363/*
1364 * For the GUI the mouse handling is in gui_w32.c.
1365 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001366#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001367 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001368mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001369{
1370}
Christopher Plewright20b795e2022-12-20 20:01:58 +00001371#else // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar0f873732019-12-05 20:28:46 +01001372static int g_fMouseAvail = FALSE; // mouse present
1373static int g_fMouseActive = FALSE; // mouse enabled
1374static int g_nMouseClick = -1; // mouse status
1375static int g_xMouse; // mouse x coordinate
1376static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001377static DWORD g_cmodein = 0; // Original console input mode
1378static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001379
1380/*
1381 * Enable or disable mouse input
1382 */
1383 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001384mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001385{
1386 DWORD cmodein;
1387
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001388# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001389 if (gui.in_use)
1390 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001391# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001392 if (!g_fMouseAvail)
1393 return;
1394
1395 g_fMouseActive = on;
1396 GetConsoleMode(g_hConIn, &cmodein);
1397
1398 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001399 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001400 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001401 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1402 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001403 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001404 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001405 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001406 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1407 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001408
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001409 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001410}
1411
Bram Moolenaar157d8132018-03-06 17:09:20 +01001412
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001413# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001414/*
1415 * Called when 'balloonevalterm' changed.
1416 */
1417 void
1418mch_bevalterm_changed(void)
1419{
1420 mch_setmouse(g_fMouseActive);
1421}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001422# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001423
Christopher Plewright2a46f812022-10-16 19:47:45 +01001424/*
1425 * Win32 console mouse scroll event handler.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001426 * Console version of the _OnMouseWheel() function in gui_w32.c
Christopher Plewright2a46f812022-10-16 19:47:45 +01001427 *
1428 * This encodes the mouse scroll direction and keyboard modifiers into
1429 * g_nMouseClick, and the mouse position into g_xMouse and g_yMouse
1430 *
1431 * The direction of the scroll is decoded from two fields of the win32 console
1432 * mouse event record;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001433 * 1. The orientation - vertical or horizontal flag - from dwEventFlags
Christopher Plewright2a46f812022-10-16 19:47:45 +01001434 * 2. The sign - positive or negative (aka delta flag) - from dwButtonState
1435 *
Christopher Plewright20b795e2022-12-20 20:01:58 +00001436 * When scroll orientation is HORIZONTAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001437 * - If the high word of the dwButtonState member contains a positive
1438 * value, the wheel was rotated to the right.
1439 * - Otherwise, the wheel was rotated to the left.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001440 * When scroll orientation is VERTICAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001441 * - If the high word of the dwButtonState member contains a positive value,
1442 * the wheel was rotated forward, away from the user.
1443 * - Otherwise, the wheel was rotated backward, toward the user.
1444 */
1445 static void
1446decode_mouse_wheel(MOUSE_EVENT_RECORD *pmer)
1447{
Christopher Plewright2a46f812022-10-16 19:47:45 +01001448 int horizontal = (pmer->dwEventFlags == MOUSE_HWHEELED);
1449 int zDelta = pmer->dwButtonState;
1450
1451 g_xMouse = pmer->dwMousePosition.X;
1452 g_yMouse = pmer->dwMousePosition.Y;
1453
K.Takata161b6ac2022-11-14 15:31:07 +00001454# ifdef FEAT_PROP_POPUP
Christopher Plewright605d02a2022-10-19 11:54:46 +01001455 int lcol = g_xMouse;
1456 int lrow = g_yMouse;
Christopher Plewright38804d62022-11-09 23:55:52 +00001457 win_T *wp = mouse_find_win(&lrow, &lcol, FIND_POPUP);
Christopher Plewright2a46f812022-10-16 19:47:45 +01001458 if (wp != NULL && popup_is_popup(wp))
1459 {
1460 g_nMouseClick = -1;
1461 cmdarg_T cap;
1462 oparg_T oa;
1463 CLEAR_FIELD(cap);
1464 clear_oparg(&oa);
1465 cap.oap = &oa;
1466 if (horizontal)
1467 {
1468 cap.arg = zDelta < 0 ? MSCR_LEFT : MSCR_RIGHT;
1469 cap.cmdchar = zDelta < 0 ? K_MOUSELEFT : K_MOUSERIGHT;
1470 }
1471 else
1472 {
1473 cap.cmdchar = zDelta < 0 ? K_MOUSEUP : K_MOUSEDOWN;
1474 cap.arg = zDelta < 0 ? MSCR_UP : MSCR_DOWN;
1475 }
1476
1477 // Mouse hovers over popup window, scroll it if possible.
1478 mouse_row = wp->w_winrow;
1479 mouse_col = wp->w_wincol;
1480 nv_mousescroll(&cap);
1481 update_screen(0);
1482 setcursor();
1483 out_flush();
1484 return;
1485 }
K.Takata161b6ac2022-11-14 15:31:07 +00001486# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01001487 mouse_col = g_xMouse;
1488 mouse_row = g_yMouse;
1489
1490 char_u modifiers = 0;
1491 char_u direction = 0;
1492
1493 // Decode the direction into an event that Vim can process
1494 if (horizontal)
1495 direction = zDelta >= 0 ? KE_MOUSELEFT : KE_MOUSERIGHT;
1496 else
1497 direction = zDelta >= 0 ? KE_MOUSEDOWN : KE_MOUSEUP;
1498
dundargocc57b5bc2022-11-02 13:30:51 +00001499 // Decode the win32 console key modifiers into Vim mouse modifiers.
Christopher Plewright2a46f812022-10-16 19:47:45 +01001500 if (pmer->dwControlKeyState & SHIFT_PRESSED)
Christopher Plewright605d02a2022-10-19 11:54:46 +01001501 modifiers |= MOD_MASK_SHIFT; // MOUSE_SHIFT;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001502 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
Christopher Plewright605d02a2022-10-19 11:54:46 +01001503 modifiers |= MOD_MASK_CTRL; // MOUSE_CTRL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001504 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1505 modifiers |= MOD_MASK_ALT; // MOUSE_ALT;
1506
1507 // add (bitwise or) the scroll direction and the key modifier chars
1508 // together.
1509 g_nMouseClick = ((direction << 8) | modifiers);
1510
1511 return;
1512}
1513
Bram Moolenaar071d4272004-06-13 20:20:40 +00001514/*
1515 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1516 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1517 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1518 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1519 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1520 * and we return the mouse position in g_xMouse and g_yMouse.
1521 *
1522 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1523 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1524 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1525 *
1526 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1527 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1528 *
1529 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1530 * moves, even if it stays within the same character cell. We ignore
1531 * all MOUSE_MOVED messages if the position hasn't really changed, and
1532 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1533 * we're only interested in MOUSE_DRAG).
1534 *
1535 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1536 * 2-button mouses by pressing the left & right buttons simultaneously.
1537 * In practice, it's almost impossible to click both at the same time,
1538 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1539 * in such cases, if the user is clicking quickly.
1540 */
1541 static BOOL
1542decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001543 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001544{
1545 static int s_nOldButton = -1;
1546 static int s_nOldMouseClick = -1;
1547 static int s_xOldMouse = -1;
1548 static int s_yOldMouse = -1;
1549 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001550# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001551 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001552# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001553 static int s_cClicks = 1;
1554 static BOOL s_fReleased = TRUE;
1555 static DWORD s_dwLastClickTime = 0;
1556 static BOOL s_fNextIsMiddle = FALSE;
1557
Bram Moolenaar0f873732019-12-05 20:28:46 +01001558 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001559
1560 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1561 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1562 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1563 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1564
1565 int nButton;
1566
1567 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1568 cButtons = 2;
1569
1570 if (!g_fMouseAvail || !g_fMouseActive)
1571 {
1572 g_nMouseClick = -1;
1573 return FALSE;
1574 }
1575
Bram Moolenaar0f873732019-12-05 20:28:46 +01001576 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001577 if (g_fJustGotFocus)
1578 {
1579 g_fJustGotFocus = FALSE;
1580 return FALSE;
1581 }
1582
Christopher Plewright605d02a2022-10-19 11:54:46 +01001583 // If there is an unprocessed mouse click drop this one.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001584 if (g_nMouseClick != -1)
1585 return TRUE;
Christopher Plewright605d02a2022-10-19 11:54:46 +01001586
Christopher Plewright2a46f812022-10-16 19:47:45 +01001587 if (pmer->dwEventFlags == MOUSE_WHEELED
1588 || pmer->dwEventFlags == MOUSE_HWHEELED)
1589 {
1590 decode_mouse_wheel(pmer);
1591 return TRUE; // we now should have a mouse scroll in g_nMouseClick
1592 }
Christopher Plewright605d02a2022-10-19 11:54:46 +01001593
Bram Moolenaar071d4272004-06-13 20:20:40 +00001594 nButton = -1;
1595 g_xMouse = pmer->dwMousePosition.X;
1596 g_yMouse = pmer->dwMousePosition.Y;
1597
1598 if (pmer->dwEventFlags == MOUSE_MOVED)
1599 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001600 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1601 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001602 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1603 return FALSE;
1604 }
1605
Bram Moolenaar0f873732019-12-05 20:28:46 +01001606 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1608 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001609 nButton = MOUSE_RELEASE;
1610
Bram Moolenaar0f873732019-12-05 20:28:46 +01001611 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001612 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001613 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001614# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001615 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001616 if (p_bevalterm)
1617 nButton = MOUSE_DRAG;
1618 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001619# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001620 return FALSE;
1621 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001622
Bram Moolenaar071d4272004-06-13 20:20:40 +00001623 s_fReleased = TRUE;
1624 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001625 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001626 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001627 // on a 2-button mouse, hold down left and right buttons
1628 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001629
1630 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1631 {
1632 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1633
Bram Moolenaar0f873732019-12-05 20:28:46 +01001634 // if either left or right button only is pressed, see if the
1635 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001636 if (dwLR == LEFT || dwLR == RIGHT)
1637 {
1638 for (;;)
1639 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001640 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001641 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1642 != WAIT_OBJECT_0)
1643 break;
1644 else
1645 {
1646 DWORD cRecords = 0;
1647 INPUT_RECORD ir;
1648 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1649
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001650 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001651
1652 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1653 || !(pmer2->dwButtonState & LEFT_RIGHT))
1654 break;
1655 else
1656 {
1657 if (pmer2->dwEventFlags != MOUSE_MOVED)
1658 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001659 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001660
1661 return decode_mouse_event(pmer2);
1662 }
1663 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1664 s_yOldMouse == pmer2->dwMousePosition.Y)
1665 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001666 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001667 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001668
Bram Moolenaar0f873732019-12-05 20:28:46 +01001669 // are there any more mouse events in queue?
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 break;
1674 }
1675 else
1676 break;
1677 }
1678 }
1679 }
1680 }
1681 }
1682
1683 if (s_fNextIsMiddle)
1684 {
1685 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1686 ? MOUSE_DRAG : MOUSE_MIDDLE;
1687 s_fNextIsMiddle = FALSE;
1688 }
1689 else if (cButtons == 2 &&
1690 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1691 {
1692 nButton = MOUSE_MIDDLE;
1693
1694 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1695 {
1696 s_fNextIsMiddle = TRUE;
1697 nButton = MOUSE_RELEASE;
1698 }
1699 }
1700 else if ((pmer->dwButtonState & LEFT) == LEFT)
1701 nButton = MOUSE_LEFT;
1702 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1703 nButton = MOUSE_MIDDLE;
1704 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1705 nButton = MOUSE_RIGHT;
1706
1707 if (! s_fReleased && ! s_fNextIsMiddle
1708 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1709 return FALSE;
1710
1711 s_fReleased = s_fNextIsMiddle;
1712 }
1713
1714 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1715 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001716 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717 if (nButton != -1 && nButton != MOUSE_RELEASE)
1718 {
1719 DWORD dwCurrentTime = GetTickCount();
1720
1721 if (s_xOldMouse != g_xMouse
1722 || s_yOldMouse != g_yMouse
1723 || s_nOldButton != nButton
1724 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001725# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001726 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001727# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001728 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1729 {
1730 s_cClicks = 1;
1731 }
1732 else if (++s_cClicks > 4)
1733 {
1734 s_cClicks = 1;
1735 }
1736
1737 s_dwLastClickTime = dwCurrentTime;
1738 }
1739 }
1740 else if (pmer->dwEventFlags == MOUSE_MOVED)
1741 {
1742 if (nButton != -1 && nButton != MOUSE_RELEASE)
1743 nButton = MOUSE_DRAG;
1744
1745 s_cClicks = 1;
1746 }
1747
1748 if (nButton == -1)
1749 return FALSE;
1750
1751 if (nButton != MOUSE_RELEASE)
1752 s_nOldButton = nButton;
1753
1754 g_nMouseClick = nButton;
1755
1756 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1757 g_nMouseClick |= MOUSE_SHIFT;
1758 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1759 g_nMouseClick |= MOUSE_CTRL;
1760 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1761 g_nMouseClick |= MOUSE_ALT;
1762
1763 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1764 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1765
Bram Moolenaar0f873732019-12-05 20:28:46 +01001766 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001767 if (s_xOldMouse == g_xMouse
1768 && s_yOldMouse == g_yMouse
1769 && s_nOldMouseClick == g_nMouseClick)
1770 {
1771 g_nMouseClick = -1;
1772 return FALSE;
1773 }
1774
1775 s_xOldMouse = g_xMouse;
1776 s_yOldMouse = g_yMouse;
1777 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001778# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001779 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001780# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001781 s_nOldMouseClick = g_nMouseClick;
1782
1783 return TRUE;
1784}
1785
Christopher Plewright20b795e2022-12-20 20:01:58 +00001786# ifdef FEAT_EVAL
1787 static int
1788encode_mouse_event(dict_T *args, INPUT_RECORD *ir)
1789{
1790 int button;
1791 int row;
1792 int col;
1793 int repeated_click;
Bram Moolenaar9b8a3652022-12-20 20:47:28 +00001794 int_u mods = 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001795 int move;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001796
Christopher Plewright20b795e2022-12-20 20:01:58 +00001797 if (!dict_has_key(args, "row") || !dict_has_key(args, "col"))
1798 return FALSE;
1799
1800 // Note: "move" is optional, requires fewer arguments
1801 move = (int)dict_get_bool(args, "move", FALSE);
1802 if (!move && (!dict_has_key(args, "button")
1803 || !dict_has_key(args, "multiclick")
1804 || !dict_has_key(args, "modifiers")))
1805 return FALSE;
1806
1807 row = (int)dict_get_number(args, "row") - 1;
1808 col = (int)dict_get_number(args, "col") - 1;
1809
1810 ir->EventType = MOUSE_EVENT;
1811 MOUSE_EVENT_RECORD mer;
1812 ZeroMemory(&mer, sizeof(mer));
1813 mer.dwMousePosition.X = col;
1814 mer.dwMousePosition.Y = row;
1815
1816 if (move)
1817 {
1818 mer.dwButtonState = 0;
1819 mer.dwEventFlags = MOUSE_MOVED;
1820 }
1821 else
1822 {
1823 button = (int)dict_get_number(args, "button");
1824 repeated_click = (int)dict_get_number(args, "multiclick");
1825 mods = (int)dict_get_number(args, "modifiers");
1826 // Reset the scroll values to known values.
1827 // XXX: Remove this when/if the scroll step is made configurable.
1828 mouse_set_hor_scroll_step(6);
1829 mouse_set_vert_scroll_step(3);
1830
1831 switch (button)
1832 {
1833 case MOUSE_LEFT:
1834 mer.dwButtonState = FROM_LEFT_1ST_BUTTON_PRESSED;
1835 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1836 break;
1837 case MOUSE_MIDDLE:
1838 mer.dwButtonState = FROM_LEFT_2ND_BUTTON_PRESSED;
1839 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1840 break;
1841 case MOUSE_RIGHT:
1842 mer.dwButtonState = RIGHTMOST_BUTTON_PRESSED;
1843 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1844 break;
1845 case MOUSE_RELEASE:
1846 // umm? Assume Left Release?
1847 mer.dwEventFlags = 0;
1848
1849 case MOUSE_MOVE:
1850 mer.dwButtonState = 0;
1851 mer.dwEventFlags = MOUSE_MOVED;
1852 break;
1853 case MOUSE_X1:
1854 mer.dwButtonState = FROM_LEFT_3RD_BUTTON_PRESSED;
1855 break;
1856 case MOUSE_X2:
1857 mer.dwButtonState = FROM_LEFT_4TH_BUTTON_PRESSED;
1858 break;
1859 case MOUSE_4: // KE_MOUSEDOWN;
1860 mer.dwButtonState = -1;
1861 mer.dwEventFlags = MOUSE_WHEELED;
1862 break;
1863 case MOUSE_5: // KE_MOUSEUP;
1864 mer.dwButtonState = +1;
1865 mer.dwEventFlags = MOUSE_WHEELED;
1866 break;
1867 case MOUSE_6: // KE_MOUSELEFT;
1868 mer.dwButtonState = -1;
1869 mer.dwEventFlags = MOUSE_HWHEELED;
1870 break;
1871 case MOUSE_7: // KE_MOUSERIGHT;
1872 mer.dwButtonState = +1;
1873 mer.dwEventFlags = MOUSE_HWHEELED;
1874 break;
1875 default:
1876 semsg(_(e_invalid_argument_str), "button");
1877 return FALSE;
1878 }
1879 }
1880
1881 mer.dwControlKeyState = 0;
1882 if (mods != 0)
1883 {
1884 // Encode the win32 console key modifiers from Vim MOUSE modifiers.
1885 if (mods & MOUSE_SHIFT)
1886 mer.dwControlKeyState |= SHIFT_PRESSED;
1887 if (mods & MOUSE_CTRL)
1888 mer.dwControlKeyState |= LEFT_CTRL_PRESSED;
1889 if (mods & MOUSE_ALT)
1890 mer.dwControlKeyState |= LEFT_ALT_PRESSED;
1891 }
1892 ir->Event.MouseEvent = mer;
1893 return TRUE;
1894}
1895# endif // FEAT_EVAL
1896
1897 static int
1898write_input_record_buffer(INPUT_RECORD* irEvents, int nLength)
1899{
1900 int nCount = 0;
1901 while (nCount < nLength)
1902 {
1903 input_record_buffer.length++;
1904 input_record_buffer_node_T *event_node =
1905 malloc(sizeof(input_record_buffer_node_T));
1906 event_node->ir = irEvents[nCount++];
1907 event_node->next = NULL;
1908 if (input_record_buffer.tail == NULL)
1909 {
1910 input_record_buffer.head = event_node;
1911 input_record_buffer.tail = event_node;
1912 }
1913 else
1914 {
1915 input_record_buffer.tail->next = event_node;
1916 input_record_buffer.tail = input_record_buffer.tail->next;
1917 }
1918 }
1919 return nCount;
1920}
1921
1922 static int
1923read_input_record_buffer(INPUT_RECORD* irEvents, int nMaxLength)
1924{
1925 int nCount = 0;
1926 while (nCount < nMaxLength && input_record_buffer.head != NULL)
1927 {
1928 input_record_buffer.length--;
1929 input_record_buffer_node_T *pop_head = input_record_buffer.head;
1930 irEvents[nCount++] = pop_head->ir;
1931 input_record_buffer.head = pop_head->next;
1932 vim_free(pop_head);
1933 if (input_record_buffer.length == 0)
1934 input_record_buffer.tail = NULL;
1935 }
1936 return nCount;
1937}
Christopher Plewright20b795e2022-12-20 20:01:58 +00001938#endif // !FEAT_GUI_MSWIN || VIMDLL
1939
1940#ifdef FEAT_EVAL
1941/*
1942 * The 'test_mswin_event' function is for testing Vim's low-level handling of
1943 * user input events. ie, this manages the encoding of INPUT_RECORD events
1944 * so that we have a way to test how Vim decodes INPUT_RECORD events in Windows
1945 * consoles.
1946 *
1947 * The 'test_mswin_event' function is based on 'test_gui_event'. In fact, when
1948 * the Windows GUI is running, the arguments; 'event' and 'args', are the same.
1949 * So, it acts as an alias for 'test_gui_event' for the Windows GUI.
1950 *
1951 * When the Windows console is running, the arguments; 'event' and 'args', are
1952 * a subset of what 'test_gui_event' handles, ie, only "key" and "mouse"
1953 * events are encoded as INPUT_RECORD events.
1954 *
1955 * Note: INPUT_RECORDs are only used by the Windows console, not the GUI. The
1956 * GUI sends MSG structs instead.
1957 */
1958 int
1959test_mswin_event(char_u *event, dict_T *args)
1960{
1961 int lpEventsWritten = 0;
1962
1963# if defined(VIMDLL) || defined(FEAT_GUI_MSWIN)
1964 if (gui.in_use)
1965 return test_gui_w32_sendevent(event, args);
1966# endif
1967
1968# if defined(VIMDLL) || !defined(FEAT_GUI_MSWIN)
1969
1970// Currently implemented event record types are; KEY_EVENT and MOUSE_EVENT
1971// Potentially could also implement: FOCUS_EVENT and WINDOW_BUFFER_SIZE_EVENT
1972// Maybe also: MENU_EVENT
1973
1974 INPUT_RECORD ir;
1975 BOOL input_encoded = FALSE;
Christopher Plewright7b0afc12022-12-30 16:54:58 +00001976 BOOL execute = FALSE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001977 if (STRCMP(event, "key") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00001978 {
1979 execute = dict_get_bool(args, "execute", FALSE);
1980 if (dict_has_key(args, "event"))
1981 input_encoded = encode_key_event(args, &ir);
1982 else if (!execute)
1983 {
1984 semsg(_(e_missing_argument_str), "event");
1985 return FALSE;
1986 }
1987 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00001988 else if (STRCMP(event, "mouse") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00001989 {
1990 execute = TRUE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001991 input_encoded = encode_mouse_event(args, &ir);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00001992 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00001993 else
1994 {
1995 semsg(_(e_invalid_value_for_argument_str_str), "event", event);
1996 return FALSE;
1997 }
1998
1999 // Ideally, WriteConsoleInput would be used to inject these low-level
2000 // events. But, this doesnt work well in the CI test environment. So
2001 // implementing an input_record_buffer instead.
2002 if (input_encoded)
2003 lpEventsWritten = write_input_record_buffer(&ir, 1);
2004
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002005 // Set flags to execute the event, ie. like feedkeys mode X.
2006 if (execute)
2007 {
2008 int save_msg_scroll = msg_scroll;
2009 // Avoid a 1 second delay when the keys start Insert mode.
2010 msg_scroll = FALSE;
2011 ch_log(NULL, "test_mswin_event() executing");
Christopher Plewright20b795e2022-12-20 20:01:58 +00002012 exec_normal(TRUE, TRUE, TRUE);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002013 msg_scroll |= save_msg_scroll;
2014 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002015
2016# endif
2017 return lpEventsWritten;
2018}
2019#endif // FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002020
2021#ifdef MCH_CURSOR_SHAPE
2022/*
2023 * Set the shape of the cursor.
2024 * 'thickness' can be from 1 (thin) to 99 (block)
2025 */
2026 static void
2027mch_set_cursor_shape(int thickness)
2028{
Christopher Plewright38804d62022-11-09 23:55:52 +00002029 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01002030 {
2031 if (*T_CSI == NUL)
2032 {
2033 // If 't_SI' is not set, use the default cursor styles.
2034 if (thickness < 50)
2035 vtp_printf("\033[3 q"); // underline
2036 else
2037 vtp_printf("\033[0 q"); // default
2038 }
2039 }
2040 else
2041 {
2042 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
2043 ConsoleCursorInfo.dwSize = thickness;
2044 ConsoleCursorInfo.bVisible = s_cursor_visible;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002045
K.Takatadf5320c2022-09-01 13:20:16 +01002046 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
2047 if (s_cursor_visible)
2048 SetConsoleCursorPosition(g_hConOut, g_coord);
2049 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002050}
2051
2052 void
2053mch_update_cursor(void)
2054{
2055 int idx;
2056 int thickness;
2057
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002058# ifdef VIMDLL
2059 if (gui.in_use)
2060 return;
2061# endif
2062
Bram Moolenaar071d4272004-06-13 20:20:40 +00002063 /*
2064 * How the cursor is drawn depends on the current mode.
2065 */
2066 idx = get_shape_idx(FALSE);
2067
2068 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002069 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00002070 else
2071 thickness = shape_table[idx].percentage;
2072 mch_set_cursor_shape(thickness);
2073}
2074#endif
2075
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002076#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002077/*
2078 * Handle FOCUS_EVENT.
2079 */
2080 static void
2081handle_focus_event(INPUT_RECORD ir)
2082{
2083 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
2084 ui_focus_change((int)g_fJustGotFocus);
2085}
2086
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002087static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
2088
Bram Moolenaar071d4272004-06-13 20:20:40 +00002089/*
2090 * Wait until console input from keyboard or mouse is available,
2091 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002092 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002093 * Return TRUE if something is available FALSE if not.
2094 */
2095 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002096WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002097{
2098 DWORD dwNow = 0, dwEndTime = 0;
2099 INPUT_RECORD ir;
2100 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002101 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002102# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02002103 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002104# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002105
2106 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002107 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002108 dwEndTime = GetTickCount() + msec;
2109 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002110 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002111 dwEndTime = INFINITE;
2112
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002113 // We need to loop until the end of the time period, because
2114 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002115 for (;;)
2116 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002117 // Only process messages when waiting.
2118 if (msec != 0)
2119 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002120# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002121 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002122# endif
2123# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002124 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002125# endif
2126# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002127 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002128# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002129 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002130
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02002131 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002132# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002133 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002134# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002135 )
2136 return TRUE;
2137
2138 if (msec > 0)
2139 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002140 // If the specified wait time has passed, return. Beware that
2141 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002142 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02002143 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002144 break;
2145 }
2146 if (msec != 0)
2147 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00002148 DWORD dwWaitTime = dwEndTime - dwNow;
2149
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002150 // Don't wait for more than 11 msec to avoid dropping characters,
2151 // check channel while waiting for input and handle a callback from
2152 // 'balloonexpr'.
2153 if (dwWaitTime > 11)
2154 dwWaitTime = 11;
2155
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002156# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002157 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002158 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002159# endif
2160# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002161 // When waiting very briefly don't trigger timers.
2162 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002163 {
2164 long due_time;
2165
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002166 // Trigger timers and then get the time in msec until the next
2167 // one is due. Wait up to that time.
2168 due_time = check_due_timer();
2169 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002170 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002171 // timer may have used feedkeys().
2172 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002173 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002174 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
2175 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002176 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002177# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002178 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002179# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002180 // Wait for either an event on the console input or a
2181 // message in the client-server window.
2182 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
2183 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002184# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002185 wait_for_single_object(g_hConIn, dwWaitTime)
2186 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002187# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002188 )
2189 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002190 }
2191
2192 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002193 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002194
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002195# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02002196 // May have to redraw if the cursor ends up in the wrong place.
2197 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01002198 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002199 {
2200 CONSOLE_SCREEN_BUFFER_INFO csbi;
2201
2202 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2203 {
2204 if (csbi.dwCursorPosition.Y != msg_row)
2205 {
matveyte08795e2021-05-07 15:00:17 +02002206 // The screen is now messed up, must redraw the command
2207 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002208 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02002209 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002210 redrawcmd();
2211 }
2212 }
2213 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002214# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002215
2216 if (cRecords > 0)
2217 {
2218 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
2219 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002220# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01002221 // Windows IME sends two '\n's with only one 'ENTER'. First:
2222 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00002223 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002224 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
2225 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002226 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002227 continue;
2228 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002229# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002230 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
2231 NULL, FALSE))
2232 return TRUE;
2233 }
2234
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002235 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002236
2237 if (ir.EventType == FOCUS_EVENT)
2238 handle_focus_event(ir);
2239 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002240 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002241 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
2242
Bram Moolenaar36698e32019-12-11 22:57:40 +01002243 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002244 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002245 if (dwSize.X != Columns || dwSize.Y != Rows)
2246 {
2247 CONSOLE_SCREEN_BUFFER_INFO csbi;
2248 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01002249 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002250 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01002251 if (dwSize.X != Columns || dwSize.Y != Rows)
2252 {
2253 ResizeConBuf(g_hConOut, dwSize);
2254 shell_resized();
2255 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002256 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002257 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002258 else if (ir.EventType == MOUSE_EVENT
2259 && decode_mouse_event(&ir.Event.MouseEvent))
2260 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002261 }
2262 else if (msec == 0)
2263 break;
2264 }
2265
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002266# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01002267 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002268 if (input_available())
2269 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002270# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002271
Bram Moolenaar071d4272004-06-13 20:20:40 +00002272 return FALSE;
2273}
2274
Bram Moolenaar071d4272004-06-13 20:20:40 +00002275/*
2276 * return non-zero if a character is available
2277 */
2278 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002279mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002280{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002281# ifdef VIMDLL
2282 if (gui.in_use)
2283 return TRUE;
2284# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002285 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002286}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002287
2288# if defined(FEAT_TERMINAL) || defined(PROTO)
2289/*
2290 * Check for any pending input or messages.
2291 */
2292 int
2293mch_check_messages(void)
2294{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002295# ifdef VIMDLL
2296 if (gui.in_use)
2297 return TRUE;
2298# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002299 return WaitForChar(0L, TRUE);
2300}
2301# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002302
2303/*
2304 * Create the console input. Used when reading stdin doesn't work.
2305 */
2306 static void
2307create_conin(void)
2308{
2309 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
2310 FILE_SHARE_READ|FILE_SHARE_WRITE,
2311 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002312 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002313 did_create_conin = TRUE;
2314}
2315
2316/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002317 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002318 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002319 static WCHAR
2320tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002321{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002322 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002323
2324 for (;;)
2325 {
2326 INPUT_RECORD ir;
2327 DWORD cRecords = 0;
2328
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002329# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002330 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002331 if (input_available())
2332 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002333 if (g_nMouseClick != -1)
2334 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002335# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002336 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002337 {
2338 if (did_create_conin)
2339 read_error_exit();
2340 create_conin();
2341 continue;
2342 }
2343
2344 if (ir.EventType == KEY_EVENT)
2345 {
2346 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
2347 pmodifiers, TRUE))
2348 return ch;
2349 }
2350 else if (ir.EventType == FOCUS_EVENT)
2351 handle_focus_event(ir);
2352 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
2353 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002354 else if (ir.EventType == MOUSE_EVENT)
2355 {
2356 if (decode_mouse_event(&ir.Event.MouseEvent))
2357 return 0;
2358 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002359 }
2360}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002361#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002362
2363
2364/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02002365 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002366 * Get one or more characters from the keyboard or the mouse.
2367 * If time == 0, do not wait for characters.
2368 * If time == n, wait a short time for characters.
2369 * If time == -1, wait forever for characters.
2370 * Returns the number of characters read into buf.
2371 */
2372 int
2373mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002374 char_u *buf UNUSED,
2375 int maxlen UNUSED,
2376 long time UNUSED,
2377 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002378{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002379#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002380
2381 int len;
2382 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002383# ifdef VIMDLL
2384// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
2385# define TYPEAHEADSPACE 6
2386# else
2387# define TYPEAHEADSPACE 0
2388# endif
2389# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002390 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002391 static int typeaheadlen = 0;
2392
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002393# ifdef VIMDLL
2394 if (gui.in_use)
2395 return 0;
2396# endif
2397
Bram Moolenaar0f873732019-12-05 20:28:46 +01002398 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002399 if (typeaheadlen > 0)
2400 goto theend;
2401
Bram Moolenaar071d4272004-06-13 20:20:40 +00002402 if (time >= 0)
2403 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002404 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00002405 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002406 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01002407 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00002408 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002409 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00002410
Bram Moolenaar3918c952005-03-15 22:34:55 +00002411 /*
2412 * If there is no character available within 2 seconds (default)
2413 * write the autoscript file to disk. Or cause the CursorHold event
2414 * to be triggered.
2415 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002416 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002417 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00002418 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002419 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00002420 buf[0] = K_SPECIAL;
2421 buf[1] = KS_EXTRA;
2422 buf[2] = (int)KE_CURSORHOLD;
2423 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002424 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00002425 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002426 }
2427 }
2428
2429 /*
2430 * Try to read as many characters as there are, until the buffer is full.
2431 */
2432
Bram Moolenaar0f873732019-12-05 20:28:46 +01002433 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002434 g_fCBrkPressed = FALSE;
2435
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002436# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002437 if (fdDump)
2438 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002439# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002440
Bram Moolenaar0f873732019-12-05 20:28:46 +01002441 // Keep looping until there is something in the typeahead buffer and more
2442 // to get and still room in the buffer (up to two bytes for a char and
2443 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002444 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01002445 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002446 {
2447 if (typebuf_changed(tb_change_cnt))
2448 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002449 // "buf" may be invalid now if a client put something in the
2450 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002451 typeaheadlen = 0;
2452 break;
2453 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002454 if (g_nMouseClick != -1)
2455 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002456# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002457 if (fdDump)
2458 fprintf(fdDump, "{%02x @ %d, %d}",
2459 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002460# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01002461 char_u modifiers = ((char_u *)(&g_nMouseClick))[0];
2462 char_u scroll_dir = ((char_u *)(&g_nMouseClick))[1];
2463
2464 if (scroll_dir == KE_MOUSEDOWN
2465 || scroll_dir == KE_MOUSEUP
2466 || scroll_dir == KE_MOUSELEFT
2467 || scroll_dir == KE_MOUSERIGHT)
2468 {
2469 if (modifiers > 0)
2470 {
Christopher Plewright03193062022-11-22 12:58:27 +00002471 // use K_SPECIAL instead of CSI to make mappings work
2472 typeahead[typeaheadlen++] = K_SPECIAL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002473 typeahead[typeaheadlen++] = KS_MODIFIER;
2474 typeahead[typeaheadlen++] = modifiers;
2475 }
2476 typeahead[typeaheadlen++] = CSI;
2477 typeahead[typeaheadlen++] = KS_EXTRA;
2478 typeahead[typeaheadlen++] = scroll_dir;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002479 }
2480 else
2481 {
2482 typeahead[typeaheadlen++] = ESC + 128;
2483 typeahead[typeaheadlen++] = 'M';
2484 typeahead[typeaheadlen++] = g_nMouseClick;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002485 }
Christopher Plewright36446bb2022-11-23 22:28:08 +00002486
2487 // Pass the pointer coordinates of the mouse event in 2 bytes,
2488 // allowing for > 223 columns. Both for click and scroll events.
2489 // This is the same as what is used for the GUI.
2490 typeahead[typeaheadlen++] = (char_u)(g_xMouse / 128 + ' ' + 1);
2491 typeahead[typeaheadlen++] = (char_u)(g_xMouse % 128 + ' ' + 1);
2492 typeahead[typeaheadlen++] = (char_u)(g_yMouse / 128 + ' ' + 1);
2493 typeahead[typeaheadlen++] = (char_u)(g_yMouse % 128 + ' ' + 1);
2494
2495 g_nMouseClick = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002496 }
2497 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002498 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002499 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002500 int modifiers = 0;
2501
2502 c = tgetch(&modifiers, &ch2);
2503
Christopher Plewrightc8b20492023-01-04 18:06:00 +00002504 c = simplify_key(c, &modifiers);
2505
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002506 // Some chars need adjustment when the Ctrl modifier is used.
2507 ++no_reduce_keys;
2508 c = may_adjust_key_for_ctrl(modifiers, c);
2509 --no_reduce_keys;
2510
2511 // remove the SHIFT modifier for keys where it's already included,
2512 // e.g., '(' and '*'
2513 modifiers = may_remove_shift_modifier(modifiers, c);
2514
Bram Moolenaar071d4272004-06-13 20:20:40 +00002515 if (typebuf_changed(tb_change_cnt))
2516 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002517 // "buf" may be invalid now if a client put something in the
2518 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519 typeaheadlen = 0;
2520 break;
2521 }
2522
2523 if (c == Ctrl_C && ctrl_c_interrupts)
2524 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002525# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002526 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002527# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002528 got_int = TRUE;
2529 }
2530
Bram Moolenaar071d4272004-06-13 20:20:40 +00002531 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002532 {
2533 int n = 1;
2534
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002535 if (ch2 == NUL)
2536 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002537 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002538 char_u *p;
2539 WCHAR ch[2];
2540
2541 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002542 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002543 {
2544 ch[1] = tgetch(&modifiers, &ch2);
2545 n++;
2546 }
2547 p = utf16_to_enc(ch, &n);
2548 if (p != NULL)
2549 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002550 for (i = 0, j = 0; i < n; i++)
2551 {
2552 typeahead[typeaheadlen + j++] = p[i];
2553# ifdef VIMDLL
2554 if (p[i] == CSI)
2555 {
2556 typeahead[typeaheadlen + j++] = KS_EXTRA;
2557 typeahead[typeaheadlen + j++] = KE_CSI;
2558 }
2559# endif
2560 }
2561 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002562 vim_free(p);
2563 }
2564 }
2565 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002566 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002567 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002568# ifdef VIMDLL
2569 if (c == CSI)
2570 {
2571 typeahead[typeaheadlen + 1] = KS_EXTRA;
2572 typeahead[typeaheadlen + 2] = KE_CSI;
2573 n = 3;
2574 }
2575# endif
2576 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002577 if (ch2 != NUL)
2578 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002579 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002580 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002581 switch (ch2)
2582 {
2583 case (WCHAR)'\324': // SHIFT+Insert
2584 case (WCHAR)'\325': // CTRL+Insert
2585 case (WCHAR)'\327': // SHIFT+Delete
2586 case (WCHAR)'\330': // CTRL+Delete
2587 typeahead[typeaheadlen + n] = (char_u)ch2;
2588 n++;
2589 break;
2590
2591 default:
2592 typeahead[typeaheadlen + n] = 3;
2593 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2594 n += 2;
2595 break;
2596 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002597 }
2598 else
2599 {
2600 typeahead[typeaheadlen + n] = 3;
2601 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2602 n += 2;
2603 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002604 }
2605
Bram Moolenaar0f873732019-12-05 20:28:46 +01002606 // Use the ALT key to set the 8th bit of the character
2607 // when it's one byte, the 8th bit isn't set yet and not
2608 // using a double-byte encoding (would become a lead
2609 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002610 if ((modifiers & MOD_MASK_ALT)
2611 && n == 1
2612 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002613 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002614 )
2615 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002616 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2617 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002618 modifiers &= ~MOD_MASK_ALT;
2619 }
2620
2621 if (modifiers != 0)
2622 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002623 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002624 mch_memmove(typeahead + typeaheadlen + 3,
2625 typeahead + typeaheadlen, n);
2626 typeahead[typeaheadlen++] = K_SPECIAL;
2627 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2628 typeahead[typeaheadlen++] = modifiers;
2629 }
2630
2631 typeaheadlen += n;
2632
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002633# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002634 if (fdDump)
2635 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002636# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002637 }
2638 }
2639 }
2640
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002641# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002642 if (fdDump)
2643 {
2644 fputs("]\n", fdDump);
2645 fflush(fdDump);
2646 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002647# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002648
Bram Moolenaar071d4272004-06-13 20:20:40 +00002649theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002650 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002651 len = 0;
2652 while (len < maxlen && typeaheadlen > 0)
2653 {
2654 buf[len++] = typeahead[0];
2655 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2656 }
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00002657# ifdef FEAT_EVAL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002658 if (len > 0)
2659 {
2660 buf[len] = NUL;
2661 ch_log(NULL, "raw key input: \"%s\"", buf);
2662 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002663# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002664 return len;
2665
Bram Moolenaar0f873732019-12-05 20:28:46 +01002666#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002667 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002668#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002669}
2670
Bram Moolenaar82881492012-11-20 16:53:39 +01002671#ifndef PROTO
2672# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002673# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002674# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002675#endif
2676
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002677/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002678 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002679 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2680 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002681 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002682 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002683 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002684executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002685{
LemonBoy40fd7e62022-05-05 20:18:16 +01002686 int attrs = win32_getattrs((char_u *)name);
2687
2688 // The file doesn't exist or is a folder.
2689 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2690 return FALSE;
2691 // Check if the file is an AppExecLink, a special alias used by Windows
2692 // Store for its apps.
2693 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002694 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002695 char_u *res = resolve_appexeclink((char_u *)name);
2696 if (res == NULL)
2697 return FALSE;
2698 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002699 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002700 *path = res;
2701 else
2702 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002703 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002704 else if (path != NULL)
2705 *path = FullName_save((char_u *)name, FALSE);
2706 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002707}
2708
2709/*
2710 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2711 * If "use_path" is FALSE: Return TRUE if "name" exists.
2712 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2713 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2714 * the allocated memory.
2715 */
2716 static int
2717executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2718{
2719 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2720 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2721 // UTF-8.
2722 char_u buf[_MAX_PATH * 3];
2723 size_t len = STRLEN(name);
2724 size_t tmplen;
2725 char_u *p, *e, *e2;
2726 char_u *pathbuf = NULL;
2727 char_u *pathext = NULL;
2728 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002729 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002730 int noext = FALSE;
2731 int retval = FALSE;
2732
2733 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002734 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002735
2736 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002737 shname = gettail(p_sh);
2738 if (strstr((char *)shname, "sh") != NULL &&
2739 !(strstr((char *)shname, "powershell") != NULL
2740 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002741 noext = TRUE;
2742
2743 if (use_pathext)
2744 {
2745 pathext = mch_getenv("PATHEXT");
2746 if (pathext == NULL)
2747 pathext = (char_u *)".com;.exe;.bat;.cmd";
2748
2749 if (noext == FALSE)
2750 {
2751 /*
2752 * Loop over all extensions in $PATHEXT.
2753 * Check "name" ends with extension.
2754 */
2755 p = pathext;
2756 while (*p)
2757 {
2758 if (p[0] == ';'
2759 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2760 {
2761 // Skip empty or single ".".
2762 ++p;
2763 continue;
2764 }
2765 e = vim_strchr(p, ';');
2766 if (e == NULL)
2767 e = p + STRLEN(p);
2768 tmplen = e - p;
2769
2770 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2771 {
2772 noext = TRUE;
2773 break;
2774 }
2775
2776 p = e;
2777 }
2778 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002779 }
2780
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002781 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002782 if (pathext == NULL)
2783 pathext = (char_u *)".";
2784 else if (noext == TRUE)
2785 {
2786 if (pathextbuf == NULL)
2787 pathextbuf = alloc(STRLEN(pathext) + 3);
2788 if (pathextbuf == NULL)
2789 {
2790 retval = FALSE;
2791 goto theend;
2792 }
2793 STRCPY(pathextbuf, ".;");
2794 STRCAT(pathextbuf, pathext);
2795 pathext = pathextbuf;
2796 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002797
Bram Moolenaar95da1362020-05-30 18:37:55 +02002798 // Use $PATH when "use_path" is TRUE and "name" is basename.
2799 if (use_path && gettail((char_u *)name) == (char_u *)name)
2800 {
2801 p = mch_getenv("PATH");
2802 if (p != NULL)
2803 {
2804 pathbuf = alloc(STRLEN(p) + 3);
2805 if (pathbuf == NULL)
2806 {
2807 retval = FALSE;
2808 goto theend;
2809 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002810
2811 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2812 STRCPY(pathbuf, ".;");
2813 else
2814 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002815 STRCAT(pathbuf, p);
2816 }
2817 }
2818
2819 /*
2820 * Walk through all entries in $PATH to check if "name" exists there and
2821 * is an executable file.
2822 */
2823 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2824 while (*p)
2825 {
2826 if (*p == ';') // Skip empty entry
2827 {
2828 ++p;
2829 continue;
2830 }
2831 e = vim_strchr(p, ';');
2832 if (e == NULL)
2833 e = p + STRLEN(p);
2834
2835 if (e - p + len + 2 > sizeof(buf))
2836 {
2837 retval = FALSE;
2838 goto theend;
2839 }
2840 // A single "." that means current dir.
2841 if (e - p == 1 && *p == '.')
2842 STRCPY(buf, name);
2843 else
2844 {
2845 vim_strncpy(buf, p, e - p);
2846 add_pathsep(buf);
2847 STRCAT(buf, name);
2848 }
2849 tmplen = STRLEN(buf);
2850
2851 /*
2852 * Loop over all extensions in $PATHEXT.
2853 * Check "name" with extension added.
2854 */
2855 p = pathext;
2856 while (*p)
2857 {
2858 if (*p == ';')
2859 {
2860 // Skip empty entry
2861 ++p;
2862 continue;
2863 }
2864 e2 = vim_strchr(p, (int)';');
2865 if (e2 == NULL)
2866 e2 = p + STRLEN(p);
2867
2868 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2869 {
2870 // Not a single "." that means no extension is added.
2871 if (e2 - p + tmplen + 1 > sizeof(buf))
2872 {
2873 retval = FALSE;
2874 goto theend;
2875 }
2876 vim_strncpy(buf + tmplen, p, e2 - p);
2877 }
2878 if (executable_file((char *)buf, path))
2879 {
2880 retval = TRUE;
2881 goto theend;
2882 }
2883
2884 p = e2;
2885 }
2886
2887 p = e;
2888 }
2889
2890theend:
2891 free(pathextbuf);
2892 free(pathbuf);
2893 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002894}
2895
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002896#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2897 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002898/*
2899 * Bad parameter handler.
2900 *
2901 * Certain MS CRT functions will intentionally crash when passed invalid
2902 * parameters to highlight possible security holes. Setting this function as
2903 * the bad parameter handler will prevent the crash.
2904 *
2905 * In debug builds the parameters contain CRT information that might help track
2906 * down the source of a problem, but in non-debug builds the arguments are all
2907 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2908 * worth allowing these to make debugging of issues easier.
2909 */
2910 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002911bad_param_handler(const wchar_t *expression UNUSED,
2912 const wchar_t *function UNUSED,
2913 const wchar_t *file UNUSED,
2914 unsigned int line UNUSED,
2915 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002916{
2917}
2918
2919# define SET_INVALID_PARAM_HANDLER \
2920 ((void)_set_invalid_parameter_handler(bad_param_handler))
2921#else
2922# define SET_INVALID_PARAM_HANDLER
2923#endif
2924
Bram Moolenaar4f974752019-02-17 17:44:42 +01002925#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002926
2927/*
2928 * GUI version of mch_init().
2929 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002930 static void
2931mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002932{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002933# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002934 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002935# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002936
Bram Moolenaar0f873732019-12-05 20:28:46 +01002937 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002938 SET_INVALID_PARAM_HANDLER;
2939
Bram Moolenaar0f873732019-12-05 20:28:46 +01002940 // Let critical errors result in a failure, not in a dialog box. Required
2941 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002942 SetErrorMode(SEM_FAILCRITICALERRORS);
2943
Bram Moolenaar0f873732019-12-05 20:28:46 +01002944 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002945
Bram Moolenaar0f873732019-12-05 20:28:46 +01002946 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002947 Rows = 25;
2948 Columns = 80;
2949
Bram Moolenaar0f873732019-12-05 20:28:46 +01002950 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002951 {
2952 char_u vimrun_location[_MAX_PATH + 4];
2953
Bram Moolenaar0f873732019-12-05 20:28:46 +01002954 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002955 STRCPY(vimrun_location, exe_name);
2956 STRCPY(gettail(vimrun_location), "vimrun.exe");
2957 if (mch_getperm(vimrun_location) >= 0)
2958 {
2959 if (*skiptowhite(vimrun_location) != NUL)
2960 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002961 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002962 mch_memmove(vimrun_location + 1, vimrun_location,
2963 STRLEN(vimrun_location) + 1);
2964 *vimrun_location = '"';
2965 STRCPY(gettail(vimrun_location), "vimrun\" ");
2966 }
2967 else
2968 STRCPY(gettail(vimrun_location), "vimrun ");
2969
2970 vimrun_path = (char *)vim_strsave(vimrun_location);
2971 s_dont_use_vimrun = FALSE;
2972 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002973 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002974 s_dont_use_vimrun = FALSE;
2975
Bram Moolenaar0f873732019-12-05 20:28:46 +01002976 // Don't give the warning for a missing vimrun.exe right now, but only
2977 // when vimrun was supposed to be used. Don't bother people that do
2978 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002979 if (s_dont_use_vimrun)
2980 need_vimrun_warning = TRUE;
2981 }
2982
2983 /*
2984 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2985 * Otherwise the default "findstr /n" is used.
2986 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002987 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01002988 set_option_value_give_err((char_u *)"grepprg",
2989 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002990
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002991# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002992 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002993# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002994
2995 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002996}
2997
2998
Bram Moolenaar0f873732019-12-05 20:28:46 +01002999#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003000
3001#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003002
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003003# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
3004# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003005
3006/*
3007 * ClearConsoleBuffer()
3008 * Description:
3009 * Clears the entire contents of the console screen buffer, using the
3010 * specified attribute.
3011 * Returns:
3012 * TRUE on success
3013 */
3014 static BOOL
3015ClearConsoleBuffer(WORD wAttribute)
3016{
3017 CONSOLE_SCREEN_BUFFER_INFO csbi;
3018 COORD coord;
3019 DWORD NumCells, dummy;
3020
3021 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3022 return FALSE;
3023
3024 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
3025 coord.X = 0;
3026 coord.Y = 0;
3027 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
3028 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003029 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003030 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
3031 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003032 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003033
3034 return TRUE;
3035}
3036
3037/*
3038 * FitConsoleWindow()
3039 * Description:
3040 * Checks if the console window will fit within given buffer dimensions.
3041 * Also, if requested, will shrink the window to fit.
3042 * Returns:
3043 * TRUE on success
3044 */
3045 static BOOL
3046FitConsoleWindow(
3047 COORD dwBufferSize,
3048 BOOL WantAdjust)
3049{
3050 CONSOLE_SCREEN_BUFFER_INFO csbi;
3051 COORD dwWindowSize;
3052 BOOL NeedAdjust = FALSE;
3053
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003054 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3055 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003056
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003057 /*
3058 * A buffer resize will fail if the current console window does
3059 * not lie completely within that buffer. To avoid this, we might
3060 * have to move and possibly shrink the window.
3061 */
3062 if (csbi.srWindow.Right >= dwBufferSize.X)
3063 {
3064 dwWindowSize.X = SRWIDTH(csbi.srWindow);
3065 if (dwWindowSize.X > dwBufferSize.X)
3066 dwWindowSize.X = dwBufferSize.X;
3067 csbi.srWindow.Right = dwBufferSize.X - 1;
3068 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
3069 NeedAdjust = TRUE;
3070 }
3071 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
3072 {
3073 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
3074 if (dwWindowSize.Y > dwBufferSize.Y)
3075 dwWindowSize.Y = dwBufferSize.Y;
3076 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
3077 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
3078 NeedAdjust = TRUE;
3079 }
3080 if (NeedAdjust && WantAdjust)
3081 {
3082 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
3083 return FALSE;
3084 }
3085 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003086}
3087
3088typedef struct ConsoleBufferStruct
3089{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003090 BOOL IsValid;
3091 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003092 PCHAR_INFO Buffer;
3093 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003094 PSMALL_RECT Regions;
3095 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003096} ConsoleBuffer;
3097
3098/*
3099 * SaveConsoleBuffer()
3100 * Description:
3101 * Saves important information about the console buffer, including the
3102 * actual buffer contents. The saved information is suitable for later
3103 * restoration by RestoreConsoleBuffer().
3104 * Returns:
3105 * TRUE if all information was saved; FALSE otherwise
3106 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
3107 */
3108 static BOOL
3109SaveConsoleBuffer(
3110 ConsoleBuffer *cb)
3111{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003112 DWORD NumCells;
3113 COORD BufferCoord;
3114 SMALL_RECT ReadRegion;
3115 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003116 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003117
Bram Moolenaar071d4272004-06-13 20:20:40 +00003118 if (cb == NULL)
3119 return FALSE;
3120
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003121 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003122 {
3123 cb->IsValid = FALSE;
3124 return FALSE;
3125 }
3126 cb->IsValid = TRUE;
3127
Christopher Plewright1140b512022-11-12 18:46:05 +00003128 // VTP uses alternate screen buffer.
3129 // No need to save buffer contents for restoration.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003130 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003131 return TRUE;
3132
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003133 /*
3134 * Allocate a buffer large enough to hold the entire console screen
3135 * buffer. If this ConsoleBuffer structure has already been initialized
3136 * with a buffer of the correct size, then just use that one.
3137 */
3138 if (!cb->IsValid || cb->Buffer == NULL ||
3139 cb->BufferSize.X != cb->Info.dwSize.X ||
3140 cb->BufferSize.Y != cb->Info.dwSize.Y)
3141 {
3142 cb->BufferSize.X = cb->Info.dwSize.X;
3143 cb->BufferSize.Y = cb->Info.dwSize.Y;
3144 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
3145 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003146 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003147 if (cb->Buffer == NULL)
3148 return FALSE;
3149 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003150
3151 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003152 * We will now copy the console screen buffer into our buffer.
3153 * ReadConsoleOutput() seems to be limited as far as how much you
3154 * can read at a time. Empirically, this number seems to be about
3155 * 12000 cells (rows * columns). Start at position (0, 0) and copy
3156 * in chunks until it is all copied. The chunks will all have the
3157 * same horizontal characteristics, so initialize them now. The
3158 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003159 */
Bram Moolenaar61594242015-09-01 20:23:37 +02003160 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003161 ReadRegion.Left = 0;
3162 ReadRegion.Right = cb->Info.dwSize.X - 1;
3163 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003164
3165 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
3166 if (cb->Regions == NULL || numregions != cb->NumRegions)
3167 {
3168 cb->NumRegions = numregions;
3169 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003170 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003171 if (cb->Regions == NULL)
3172 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003173 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003174 return FALSE;
3175 }
3176 }
3177
3178 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003179 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003180 /*
3181 * Read into position (0, Y) in our buffer.
3182 */
3183 BufferCoord.Y = Y;
3184 /*
3185 * Read the region whose top left corner is (0, Y) and whose bottom
3186 * right corner is (width - 1, Y + Y_incr - 1). This should define
3187 * a region of size width by Y_incr. Don't worry if this region is
3188 * too large for the remaining buffer; it will be cropped.
3189 */
3190 ReadRegion.Top = Y;
3191 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003192 if (!ReadConsoleOutputW(g_hConOut, // output handle
3193 cb->Buffer, // our buffer
3194 cb->BufferSize, // dimensions of our buffer
3195 BufferCoord, // offset in our buffer
3196 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003197 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003198 VIM_CLEAR(cb->Buffer);
3199 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003200 return FALSE;
3201 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02003202 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003203 }
3204
3205 return TRUE;
3206}
3207
3208/*
3209 * RestoreConsoleBuffer()
3210 * Description:
3211 * Restores important information about the console buffer, including the
3212 * actual buffer contents, if desired. The information to restore is in
3213 * the same format used by SaveConsoleBuffer().
3214 * Returns:
3215 * TRUE on success
3216 */
3217 static BOOL
3218RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003219 ConsoleBuffer *cb,
3220 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003221{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003222 COORD BufferCoord;
3223 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003224 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003225
Christopher Plewright1140b512022-11-12 18:46:05 +00003226 // VTP uses alternate screen buffer.
3227 // No need to restore buffer contents.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003228 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003229 return TRUE;
3230
Bram Moolenaar071d4272004-06-13 20:20:40 +00003231 if (cb == NULL || !cb->IsValid)
3232 return FALSE;
3233
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003234 /*
3235 * Before restoring the buffer contents, clear the current buffer, and
3236 * restore the cursor position and window information. Doing this now
3237 * prevents old buffer contents from "flashing" onto the screen.
3238 */
3239 if (RestoreScreen)
3240 ClearConsoleBuffer(cb->Info.wAttributes);
3241
3242 FitConsoleWindow(cb->Info.dwSize, TRUE);
3243 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
3244 return FALSE;
3245 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
3246 return FALSE;
3247
3248 if (!RestoreScreen)
3249 {
3250 /*
3251 * No need to restore the screen buffer contents, so we're done.
3252 */
3253 return TRUE;
3254 }
3255
3256 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
3257 return FALSE;
3258 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
3259 return FALSE;
3260
3261 /*
3262 * Restore the screen buffer contents.
3263 */
3264 if (cb->Buffer != NULL)
3265 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003266 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003267 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003268 BufferCoord.X = cb->Regions[i].Left;
3269 BufferCoord.Y = cb->Regions[i].Top;
3270 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01003271 if (!WriteConsoleOutputW(g_hConOut, // output handle
3272 cb->Buffer, // our buffer
3273 cb->BufferSize, // dimensions of our buffer
3274 BufferCoord, // offset in our buffer
3275 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02003276 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003277 }
3278 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003279
3280 return TRUE;
3281}
3282
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003283# define FEAT_RESTORE_ORIG_SCREEN
3284# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003285static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003286# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003287static ConsoleBuffer g_cbNonTermcap = { 0 };
3288static ConsoleBuffer g_cbTermcap = { 0 };
3289
Bram Moolenaar071d4272004-06-13 20:20:40 +00003290char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01003291HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00003292static HICON g_hOrigIconSmall = NULL;
3293static HICON g_hOrigIcon = NULL;
3294static HICON g_hVimIcon = NULL;
3295static BOOL g_fCanChangeIcon = FALSE;
3296
Bram Moolenaar071d4272004-06-13 20:20:40 +00003297/*
3298 * GetConsoleIcon()
3299 * Description:
3300 * Attempts to retrieve the small icon and/or the big icon currently in
3301 * use by a given window.
3302 * Returns:
3303 * TRUE on success
3304 */
3305 static BOOL
3306GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003307 HWND hWnd,
3308 HICON *phIconSmall,
3309 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003310{
3311 if (hWnd == NULL)
3312 return FALSE;
3313
3314 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003315 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
3316 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003317 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003318 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
3319 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003320 return TRUE;
3321}
3322
3323/*
3324 * SetConsoleIcon()
3325 * Description:
3326 * Attempts to change the small icon and/or the big icon currently in
3327 * use by a given window.
3328 * Returns:
3329 * TRUE on success
3330 */
3331 static BOOL
3332SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003333 HWND hWnd,
3334 HICON hIconSmall,
3335 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003336{
Bram Moolenaar071d4272004-06-13 20:20:40 +00003337 if (hWnd == NULL)
3338 return FALSE;
3339
3340 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003341 SendMessage(hWnd, WM_SETICON,
3342 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003343 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003344 SendMessage(hWnd, WM_SETICON,
3345 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003346 return TRUE;
3347}
3348
3349/*
3350 * SaveConsoleTitleAndIcon()
3351 * Description:
3352 * Saves the current console window title in g_szOrigTitle, for later
3353 * restoration. Also, attempts to obtain a handle to the console window,
3354 * and use it to save the small and big icons currently in use by the
3355 * console window. This is not always possible on some versions of Windows;
3356 * nor is it possible when running Vim remotely using Telnet (since the
3357 * console window the user sees is owned by a remote process).
3358 */
3359 static void
3360SaveConsoleTitleAndIcon(void)
3361{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003362 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003363 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
3364 return;
3365
3366 /*
3367 * Obtain a handle to the console window using GetConsoleWindow() from
3368 * KERNEL32.DLL; we need to handle in order to change the window icon.
3369 * This function only exists on NT-based Windows, starting with Windows
3370 * 2000. On older operating systems, we can't change the window icon
3371 * anyway.
3372 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003373 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003374 if (g_hWnd == NULL)
3375 return;
3376
Bram Moolenaar0f873732019-12-05 20:28:46 +01003377 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003378 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
3379 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
3380 return;
3381
Bram Moolenaar0f873732019-12-05 20:28:46 +01003382 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01003383 if (
3384# ifdef FEAT_LIBCALL
3385 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
3386# endif
3387 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003388 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003389 if (g_hVimIcon != NULL)
3390 g_fCanChangeIcon = TRUE;
3391}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003392
3393static int g_fWindInitCalled = FALSE;
3394static int g_fTermcapMode = FALSE;
3395static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003396
3397/*
3398 * non-GUI version of mch_init().
3399 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003400 static void
3401mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003402{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003403# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003404 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003405# endif
3406# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00003407 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003408# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003409
Bram Moolenaar0f873732019-12-05 20:28:46 +01003410 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02003411 SET_INVALID_PARAM_HANDLER;
3412
Bram Moolenaar0f873732019-12-05 20:28:46 +01003413 // Let critical errors result in a failure, not in a dialog box. Required
3414 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003415 SetErrorMode(SEM_FAILCRITICALERRORS);
3416
Bram Moolenaar0f873732019-12-05 20:28:46 +01003417 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00003418 out_flush();
3419
Bram Moolenaar0f873732019-12-05 20:28:46 +01003420 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00003421 if (read_cmd_fd == 0)
3422 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
3423 else
3424 create_conin();
3425 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
3426
Christopher Plewright38804d62022-11-09 23:55:52 +00003427 wt_init();
3428 vtp_flag_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003429# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01003430 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003431 SaveConsoleBuffer(&g_cbOrig);
3432 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003433# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01003434 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003435 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
3436 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003437# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003438 if (cterm_normal_fg_color == 0)
3439 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
3440 if (cterm_normal_bg_color == 0)
3441 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
3442
Bram Moolenaarbdace832019-03-02 10:13:42 +01003443 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02003444 g_color_index_fg = g_attrDefault & 0xf;
3445 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
3446
Bram Moolenaar0f873732019-12-05 20:28:46 +01003447 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00003448 update_tcap(g_attrCurrent);
3449
3450 GetConsoleCursorInfo(g_hConOut, &g_cci);
3451 GetConsoleMode(g_hConIn, &g_cmodein);
3452 GetConsoleMode(g_hConOut, &g_cmodeout);
3453
Bram Moolenaar071d4272004-06-13 20:20:40 +00003454 SaveConsoleTitleAndIcon();
3455 /*
3456 * Set both the small and big icons of the console window to Vim's icon.
3457 * Note that Vim presently only has one size of icon (32x32), but it
3458 * automatically gets scaled down to 16x16 when setting the small icon.
3459 */
3460 if (g_fCanChangeIcon)
3461 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003462
3463 ui_get_shellsize();
3464
Christopher Plewrightd343c602023-01-22 18:58:30 +00003465 vtp_init();
3466
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003467# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003468 fdDump = fopen("dump", "wt");
3469
3470 if (fdDump)
3471 {
3472 time_t t;
3473
3474 time(&t);
3475 fputs(ctime(&t), fdDump);
3476 fflush(fdDump);
3477 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003478# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003479
3480 g_fWindInitCalled = TRUE;
3481
Bram Moolenaar071d4272004-06-13 20:20:40 +00003482 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003483
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003484# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003485 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003486# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003487}
3488
3489/*
3490 * non-GUI version of mch_exit().
3491 * Shut down and exit with status `r'
3492 * Careful: mch_exit() may be called before mch_init()!
3493 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003494 static void
3495mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003496{
Bram Moolenaar955f1982017-02-05 15:10:51 +01003497 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003498
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003499 vtp_exit();
3500
Bram Moolenaar955f1982017-02-05 15:10:51 +01003501 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003502 if (g_fWindInitCalled)
3503 settmode(TMODE_COOK);
3504
Bram Moolenaar0f873732019-12-05 20:28:46 +01003505 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00003506
3507 if (g_fWindInitCalled)
3508 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02003509 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003510 /*
3511 * Restore both the small and big icons of the console window to
3512 * what they were at startup. Don't do this when the window is
3513 * closed, Vim would hang here.
3514 */
3515 if (g_fCanChangeIcon && !g_fForceExit)
3516 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003517
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003518# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003519 if (fdDump)
3520 {
3521 time_t t;
3522
3523 time(&t);
3524 fputs(ctime(&t), fdDump);
3525 fclose(fdDump);
3526 }
3527 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003528# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003529 }
3530
3531 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003532 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003533 SetConsoleMode(g_hConOut, g_cmodeout);
3534
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003535# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003536 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003537# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003538
3539 exit(r);
3540}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003541#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003542
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003543 void
3544mch_init(void)
3545{
3546#ifdef VIMDLL
3547 if (gui.starting)
3548 mch_init_g();
3549 else
3550 mch_init_c();
3551#elif defined(FEAT_GUI_MSWIN)
3552 mch_init_g();
3553#else
3554 mch_init_c();
3555#endif
3556}
3557
3558 void
3559mch_exit(int r)
3560{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003561#ifdef FEAT_NETBEANS_INTG
3562 netbeans_send_disconnect();
3563#endif
3564
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003565#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003566 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003567 mch_exit_g(r);
3568 else
3569 mch_exit_c(r);
3570#elif defined(FEAT_GUI_MSWIN)
3571 mch_exit_g(r);
3572#else
3573 mch_exit_c(r);
3574#endif
3575}
3576
Bram Moolenaar071d4272004-06-13 20:20:40 +00003577/*
3578 * Do we have an interactive window?
3579 */
3580 int
3581mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003582 int argc UNUSED,
3583 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003584{
3585 get_exe_name();
3586
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003587#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003588 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003589#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003590# ifdef VIMDLL
3591 if (gui.in_use)
3592 return OK;
3593# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003594 if (isatty(1))
3595 return OK;
3596 return FAIL;
3597#endif
3598}
3599
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003600/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003601 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003602 * When "len" is > 0, also expand short to long filenames.
3603 */
3604 void
3605fname_case(
3606 char_u *name,
3607 int len)
3608{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003609 int flen;
3610 WCHAR *p;
3611 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003612
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003613 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003614 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003615 return;
3616
3617 slash_adjust(name);
3618
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003619 p = enc_to_utf16(name, NULL);
3620 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003621 return;
3622
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003623 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003624 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003625 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003626
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003627 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003628 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003629 if (len > 0 || flen >= (int)STRLEN(q))
3630 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3631 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003632 }
3633 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003634 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003635}
3636
3637
3638/*
3639 * Insert user name in s[len].
3640 */
3641 int
3642mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003643 char_u *s,
3644 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003645{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003646 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003647 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003648
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003649 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003650 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003651 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003652
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003653 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003654 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003655 vim_strncpy(s, p, len - 1);
3656 vim_free(p);
3657 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003658 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003659 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003660 s[0] = NUL;
3661 return FAIL;
3662}
3663
3664
3665/*
3666 * Insert host name in s[len].
3667 */
3668 void
3669mch_get_host_name(
3670 char_u *s,
3671 int len)
3672{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003673 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003674 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003675
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003676 if (!GetComputerNameW(wszHostName, &wcch))
3677 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003678
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003679 char_u *p = utf16_to_enc(wszHostName, NULL);
3680 if (p == NULL)
3681 return;
3682
3683 vim_strncpy(s, p, len - 1);
3684 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003685}
3686
3687
3688/*
3689 * return process ID
3690 */
3691 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003692mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003693{
3694 return (long)GetCurrentProcessId();
3695}
3696
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003697/*
3698 * return TRUE if process "pid" is still running
3699 */
3700 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003701mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003702{
3703 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3704 DWORD status = 0;
3705 int ret = FALSE;
3706
3707 if (hProcess == NULL)
3708 return FALSE; // might not have access
3709 if (GetExitCodeProcess(hProcess, &status) )
3710 ret = status == STILL_ACTIVE;
3711 CloseHandle(hProcess);
3712 return ret;
3713}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003714
3715/*
3716 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3717 * Return OK for success, FAIL for failure.
3718 */
3719 int
3720mch_dirname(
3721 char_u *buf,
3722 int len)
3723{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003724 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003725
Bram Moolenaar071d4272004-06-13 20:20:40 +00003726 /*
3727 * Originally this was:
3728 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3729 * But the Win32s known bug list says that getcwd() doesn't work
3730 * so use the Win32 system call instead. <Negri>
3731 */
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003732 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) == 0)
3733 return FAIL;
3734
3735 WCHAR wcbuf[_MAX_PATH + 1];
3736 char_u *p = NULL;
3737
3738 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003739 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003740 p = utf16_to_enc(wcbuf, NULL);
3741 if (STRLEN(p) >= (size_t)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003742 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003743 // long path name is too long, fall back to short one
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003744 vim_free(p);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003745 p = NULL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003746 }
3747 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003748 if (p == NULL)
3749 p = utf16_to_enc(wbuf, NULL);
3750
3751 if (p == NULL)
3752 return FAIL;
3753
3754 vim_strncpy(buf, p, len - 1);
3755 vim_free(p);
3756 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003757}
3758
3759/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003760 * Get file permissions for "name".
3761 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003762 */
3763 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003764mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003765{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003766 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003767 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003768
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003769 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003770 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003771}
3772
3773
3774/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003775 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003776 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003777 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003778 */
3779 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003780mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003781{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003782 long n;
3783 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003784
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003785 p = enc_to_utf16(name, NULL);
3786 if (p == NULL)
3787 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003788
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003789 n = _wchmod(p, perm);
3790 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003791 if (n == -1)
3792 return FAIL;
3793
3794 win32_set_archive(name);
3795
3796 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003797}
3798
3799/*
3800 * Set hidden flag for "name".
3801 */
3802 void
3803mch_hide(char_u *name)
3804{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003805 int attrs = win32_getattrs(name);
3806 if (attrs == -1)
3807 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003808
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003809 attrs |= FILE_ATTRIBUTE_HIDDEN;
3810 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003811}
3812
3813/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003814 * Return TRUE if file "name" exists and is hidden.
3815 */
3816 int
3817mch_ishidden(char_u *name)
3818{
3819 int f = win32_getattrs(name);
3820
3821 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003822 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003823
3824 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3825}
3826
3827/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003828 * return TRUE if "name" is a directory
3829 * return FALSE if "name" is not a directory or upon error
3830 */
3831 int
3832mch_isdir(char_u *name)
3833{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003834 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003835
3836 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003837 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003838
3839 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3840}
3841
3842/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003843 * return TRUE if "name" is a directory, NOT a symlink to a directory
3844 * return FALSE if "name" is not a directory
3845 * return FALSE for error
3846 */
3847 int
3848mch_isrealdir(char_u *name)
3849{
3850 return mch_isdir(name) && !mch_is_symbolic_link(name);
3851}
3852
3853/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003854 * Create directory "name".
3855 * Return 0 on success, -1 on error.
3856 */
3857 int
3858mch_mkdir(char_u *name)
3859{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003860 WCHAR *p;
3861 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003862
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003863 p = enc_to_utf16(name, NULL);
3864 if (p == NULL)
3865 return -1;
3866 retval = _wmkdir(p);
3867 vim_free(p);
3868 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003869}
3870
3871/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003872 * Delete directory "name".
3873 * Return 0 on success, -1 on error.
3874 */
3875 int
3876mch_rmdir(char_u *name)
3877{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003878 WCHAR *p;
3879 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003880
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003881 p = enc_to_utf16(name, NULL);
3882 if (p == NULL)
3883 return -1;
3884 retval = _wrmdir(p);
3885 vim_free(p);
3886 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003887}
3888
3889/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003890 * Return TRUE if file "fname" has more than one link.
3891 */
3892 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003893mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003894{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003895 BY_HANDLE_FILE_INFORMATION info;
3896
3897 return win32_fileinfo(fname, &info) == FILEINFO_OK
3898 && info.nNumberOfLinks > 1;
3899}
3900
3901/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003902 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003903 */
3904 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003905mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003906{
3907 HANDLE hFind;
3908 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003909 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003910 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003911 WIN32_FIND_DATAW findDataW;
3912
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003913 wn = enc_to_utf16(name, NULL);
3914 if (wn == NULL)
3915 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003916
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003917 hFind = FindFirstFileW(wn, &findDataW);
3918 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003919 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003920 {
3921 fileFlags = findDataW.dwFileAttributes;
3922 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003923 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003924 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003925
3926 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003927 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3928 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003929 res = TRUE;
3930
3931 return res;
3932}
3933
3934/*
3935 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3936 * link.
3937 */
3938 int
3939mch_is_linked(char_u *fname)
3940{
3941 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3942 return TRUE;
3943 return FALSE;
3944}
3945
3946/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003947 * Get the by-handle-file-information for "fname".
3948 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003949 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003950 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3951 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3952 */
3953 int
3954win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3955{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003956 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003957 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003958 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003959
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003960 wn = enc_to_utf16(fname, NULL);
3961 if (wn == NULL)
3962 return FILEINFO_ENC_FAIL;
3963
3964 hFile = CreateFileW(wn, // file name
3965 GENERIC_READ, // access mode
3966 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3967 NULL, // security descriptor
3968 OPEN_EXISTING, // creation disposition
3969 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3970 NULL); // handle to template file
3971 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003972
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003973 if (hFile == INVALID_HANDLE_VALUE)
3974 return FILEINFO_READ_FAIL;
3975
3976 if (GetFileInformationByHandle(hFile, info) != 0)
3977 res = FILEINFO_OK;
3978 else
3979 res = FILEINFO_INFO_FAIL;
3980 CloseHandle(hFile);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003981
Bram Moolenaar03f48552006-02-28 23:52:23 +00003982 return res;
3983}
3984
3985/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003986 * get file attributes for `name'
3987 * -1 : error
3988 * else FILE_ATTRIBUTE_* defined in winnt.h
3989 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003990 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003991win32_getattrs(char_u *name)
3992{
3993 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003994 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003995
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003996 p = enc_to_utf16(name, NULL);
3997 if (p == NULL)
3998 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003999
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004000 attr = GetFileAttributesW(p);
4001 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004002
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004003 return attr;
4004}
4005
4006/*
4007 * set file attributes for `name' to `attrs'
4008 *
4009 * return -1 for failure, 0 otherwise
4010 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004011 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004012win32_setattrs(char_u *name, int attrs)
4013{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004014 int res;
4015 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004016
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004017 p = enc_to_utf16(name, NULL);
4018 if (p == NULL)
4019 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004020
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004021 res = SetFileAttributesW(p, attrs);
4022 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004023
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004024 return res ? 0 : -1;
4025}
4026
4027/*
4028 * Set archive flag for "name".
4029 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004030 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004031win32_set_archive(char_u *name)
4032{
4033 int attrs = win32_getattrs(name);
4034 if (attrs == -1)
4035 return -1;
4036
4037 attrs |= FILE_ATTRIBUTE_ARCHIVE;
4038 return win32_setattrs(name, attrs);
4039}
4040
4041/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004042 * Return TRUE if file or directory "name" is writable (not readonly).
4043 * Strange semantics of Win32: a readonly directory is writable, but you can't
4044 * delete a file. Let's say this means it is writable.
4045 */
4046 int
4047mch_writable(char_u *name)
4048{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004049 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004050
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004051 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
4052 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004053}
4054
Bram Moolenaar071d4272004-06-13 20:20:40 +00004055/*
Bram Moolenaar43663192017-03-05 14:29:12 +01004056 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01004057 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01004058 * When returning TRUE and "path" is not NULL save the path and set "*path" to
4059 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004060 */
4061 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01004062mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004063{
Bram Moolenaar95da1362020-05-30 18:37:55 +02004064 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004065}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004066
4067/*
4068 * Check what "name" is:
4069 * NODE_NORMAL: file or directory (or doesn't exist)
4070 * NODE_WRITABLE: writable device, socket, fifo, etc.
4071 * NODE_OTHER: non-writable things
4072 */
4073 int
4074mch_nodetype(char_u *name)
4075{
4076 HANDLE hFile;
4077 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004078 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004079
Bram Moolenaar0f873732019-12-05 20:28:46 +01004080 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
4081 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
4082 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00004083 if (STRNCMP(name, "\\\\.\\", 4) == 0)
4084 return NODE_WRITABLE;
4085
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004086 wn = enc_to_utf16(name, NULL);
4087 if (wn == NULL)
4088 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004089
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004090 hFile = CreateFileW(wn, // file name
4091 GENERIC_WRITE, // access mode
4092 0, // share mode
4093 NULL, // security descriptor
4094 OPEN_EXISTING, // creation disposition
4095 0, // file attributes
4096 NULL); // handle to template file
4097 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004098 if (hFile == INVALID_HANDLE_VALUE)
4099 return NODE_NORMAL;
4100
4101 type = GetFileType(hFile);
4102 CloseHandle(hFile);
4103 if (type == FILE_TYPE_CHAR)
4104 return NODE_WRITABLE;
4105 if (type == FILE_TYPE_DISK)
4106 return NODE_NORMAL;
4107 return NODE_OTHER;
4108}
4109
4110#ifdef HAVE_ACL
4111struct my_acl
4112{
4113 PSECURITY_DESCRIPTOR pSecurityDescriptor;
4114 PSID pSidOwner;
4115 PSID pSidGroup;
4116 PACL pDacl;
4117 PACL pSacl;
4118};
4119#endif
4120
4121/*
4122 * Return a pointer to the ACL of file "fname" in allocated memory.
4123 * Return NULL if the ACL is not available for whatever reason.
4124 */
4125 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004126mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004127{
4128#ifndef HAVE_ACL
4129 return (vim_acl_T)NULL;
4130#else
4131 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02004132 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004133
Bram Moolenaarc799fe22019-05-28 23:08:19 +02004134 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004135 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004136 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004137 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02004138
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004139 wn = enc_to_utf16(fname, NULL);
4140 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004141 {
4142 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004143 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004144 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004145
4146 // Try to retrieve the entire security descriptor.
4147 err = GetNamedSecurityInfoW(
4148 wn, // Abstract filename
4149 SE_FILE_OBJECT, // File Object
4150 OWNER_SECURITY_INFORMATION |
4151 GROUP_SECURITY_INFORMATION |
4152 DACL_SECURITY_INFORMATION |
4153 SACL_SECURITY_INFORMATION,
4154 &p->pSidOwner, // Ownership information.
4155 &p->pSidGroup, // Group membership.
4156 &p->pDacl, // Discretionary information.
4157 &p->pSacl, // For auditing purposes.
4158 &p->pSecurityDescriptor);
4159 if (err == ERROR_ACCESS_DENIED ||
4160 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004161 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004162 // Retrieve only DACL.
4163 (void)GetNamedSecurityInfoW(
4164 wn,
4165 SE_FILE_OBJECT,
4166 DACL_SECURITY_INFORMATION,
4167 NULL,
4168 NULL,
4169 &p->pDacl,
4170 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004171 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004172 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004173 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004174 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004175 mch_free_acl((vim_acl_T)p);
4176 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004177 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004178 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004179 }
4180
4181 return (vim_acl_T)p;
4182#endif
4183}
4184
Bram Moolenaar27515922013-06-29 15:36:26 +02004185#ifdef HAVE_ACL
4186/*
4187 * Check if "acl" contains inherited ACE.
4188 */
4189 static BOOL
4190is_acl_inherited(PACL acl)
4191{
4192 DWORD i;
4193 ACL_SIZE_INFORMATION acl_info;
4194 PACCESS_ALLOWED_ACE ace;
4195
4196 acl_info.AceCount = 0;
4197 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
4198 for (i = 0; i < acl_info.AceCount; i++)
4199 {
4200 GetAce(acl, i, (LPVOID *)&ace);
4201 if (ace->Header.AceFlags & INHERITED_ACE)
4202 return TRUE;
4203 }
4204 return FALSE;
4205}
4206#endif
4207
Bram Moolenaar071d4272004-06-13 20:20:40 +00004208/*
4209 * Set the ACL of file "fname" to "acl" (unless it's NULL).
4210 * Errors are ignored.
4211 * This must only be called with "acl" equal to what mch_get_acl() returned.
4212 */
4213 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004214mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004215{
4216#ifdef HAVE_ACL
4217 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02004218 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004219 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004220
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004221 if (p == NULL)
4222 return;
4223
4224 wn = enc_to_utf16(fname, NULL);
4225 if (wn == NULL)
4226 return;
4227
4228 // Set security flags
4229 if (p->pSidOwner)
4230 sec_info |= OWNER_SECURITY_INFORMATION;
4231 if (p->pSidGroup)
4232 sec_info |= GROUP_SECURITY_INFORMATION;
4233 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02004234 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004235 sec_info |= DACL_SECURITY_INFORMATION;
4236 // Do not inherit its parent's DACL.
4237 // If the DACL is inherited, Cygwin permissions would be changed.
4238 if (!is_acl_inherited(p->pDacl))
4239 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02004240 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004241 if (p->pSacl)
4242 sec_info |= SACL_SECURITY_INFORMATION;
4243
4244 (void)SetNamedSecurityInfoW(
4245 wn, // Abstract filename
4246 SE_FILE_OBJECT, // File Object
4247 sec_info,
4248 p->pSidOwner, // Ownership information.
4249 p->pSidGroup, // Group membership.
4250 p->pDacl, // Discretionary information.
4251 p->pSacl // For auditing purposes.
4252 );
4253 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004254#endif
4255}
4256
4257 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004258mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004259{
4260#ifdef HAVE_ACL
4261 struct my_acl *p = (struct my_acl *)acl;
4262
4263 if (p != NULL)
4264 {
4265 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
4266 vim_free(p);
4267 }
4268#endif
4269}
4270
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004271#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004272
4273/*
4274 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
4275 */
4276 static BOOL WINAPI
4277handler_routine(
4278 DWORD dwCtrlType)
4279{
Bram Moolenaar589b1102017-08-12 16:39:05 +02004280 INPUT_RECORD ir;
4281 DWORD out;
4282
Bram Moolenaar071d4272004-06-13 20:20:40 +00004283 switch (dwCtrlType)
4284 {
4285 case CTRL_C_EVENT:
4286 if (ctrl_c_interrupts)
4287 g_fCtrlCPressed = TRUE;
4288 return TRUE;
4289
4290 case CTRL_BREAK_EVENT:
4291 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02004292 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004293 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02004294 ir.EventType = KEY_EVENT;
4295 ir.Event.KeyEvent.bKeyDown = TRUE;
4296 ir.Event.KeyEvent.wRepeatCount = 1;
4297 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
4298 ir.Event.KeyEvent.wVirtualScanCode = 0;
4299 ir.Event.KeyEvent.dwControlKeyState = 0;
4300 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
4301 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004302 return TRUE;
4303
Bram Moolenaar0f873732019-12-05 20:28:46 +01004304 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00004305 case CTRL_CLOSE_EVENT:
4306 case CTRL_LOGOFF_EVENT:
4307 case CTRL_SHUTDOWN_EVENT:
4308 windgoto((int)Rows - 1, 0);
4309 g_fForceExit = TRUE;
4310
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004311 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004312 (dwCtrlType == CTRL_CLOSE_EVENT
4313 ? _("close")
4314 : dwCtrlType == CTRL_LOGOFF_EVENT
4315 ? _("logoff")
4316 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004317# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00004318 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004319# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004320
Bram Moolenaar0f873732019-12-05 20:28:46 +01004321 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00004322
Bram Moolenaar0f873732019-12-05 20:28:46 +01004323 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00004324
4325 default:
4326 return FALSE;
4327 }
4328}
4329
4330
4331/*
4332 * set the tty in (raw) ? "raw" : "cooked" mode
4333 */
4334 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02004335mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004336{
4337 DWORD cmodein;
4338 DWORD cmodeout;
4339 BOOL bEnableHandler;
4340
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004341# ifdef VIMDLL
4342 if (gui.in_use)
4343 return;
4344# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004345 GetConsoleMode(g_hConIn, &cmodein);
4346 GetConsoleMode(g_hConOut, &cmodeout);
4347 if (tmode == TMODE_RAW)
4348 {
4349 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4350 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004351 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004352 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004353 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004354 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
4355 }
4356 else
4357 {
4358 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
4359 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004360 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004361# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01004362 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
4363 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004364 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004365# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004366 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004367# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004368 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004369 bEnableHandler = TRUE;
4370 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004371 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00004372 {
4373 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4374 ENABLE_ECHO_INPUT);
4375 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
4376 bEnableHandler = FALSE;
4377 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004378 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004379 SetConsoleMode(g_hConOut, cmodeout);
4380 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
4381
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004382# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004383 if (fdDump)
4384 {
4385 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
4386 tmode == TMODE_RAW ? "raw" :
4387 tmode == TMODE_COOK ? "cooked" : "normal",
4388 cmodein, cmodeout);
4389 fflush(fdDump);
4390 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004391# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004392}
4393
4394
4395/*
4396 * Get the size of the current window in `Rows' and `Columns'
4397 * Return OK when size could be determined, FAIL otherwise.
4398 */
4399 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004400mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004401{
4402 CONSOLE_SCREEN_BUFFER_INFO csbi;
4403
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004404# ifdef VIMDLL
4405 if (gui.in_use)
4406 return OK;
4407# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004408 if (!g_fTermcapMode && g_cbTermcap.IsValid)
4409 {
4410 /*
4411 * For some reason, we are trying to get the screen dimensions
4412 * even though we are not in termcap mode. The 'Rows' and 'Columns'
4413 * variables are really intended to mean the size of Vim screen
4414 * while in termcap mode.
4415 */
4416 Rows = g_cbTermcap.Info.dwSize.Y;
4417 Columns = g_cbTermcap.Info.dwSize.X;
4418 }
4419 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4420 {
4421 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4422 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4423 }
4424 else
4425 {
4426 Rows = 25;
4427 Columns = 80;
4428 }
4429 return OK;
4430}
4431
4432/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004433 * Resize console buffer to 'COORD'
4434 */
4435 static void
4436ResizeConBuf(
4437 HANDLE hConsole,
4438 COORD coordScreen)
4439{
4440 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4441 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004442# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004443 if (fdDump)
4444 {
4445 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4446 GetLastError());
4447 fflush(fdDump);
4448 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004449# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004450 }
4451}
4452
4453/*
4454 * Resize console window size to 'srWindowRect'
4455 */
4456 static void
4457ResizeWindow(
4458 HANDLE hConsole,
4459 SMALL_RECT srWindowRect)
4460{
4461 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4462 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004463# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004464 if (fdDump)
4465 {
4466 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4467 GetLastError());
4468 fflush(fdDump);
4469 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004470# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004471 }
4472}
4473
4474/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004475 * Set a console window to `xSize' * `ySize'
4476 */
4477 static void
4478ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004479 HANDLE hConsole,
4480 int xSize,
4481 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004482{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004483 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
4484 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004485 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004486 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004487 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004488
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004489# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004490 if (fdDump)
4491 {
4492 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4493 fflush(fdDump);
4494 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004495# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004496
Bram Moolenaar0f873732019-12-05 20:28:46 +01004497 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00004498 coordScreen = GetLargestConsoleWindowSize(hConsole);
4499
Bram Moolenaar0f873732019-12-05 20:28:46 +01004500 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00004501 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4502 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4503 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4504
4505 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4506 {
4507 int sx, sy;
4508
4509 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4510 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4511 if (sy < ySize || sx < xSize)
4512 {
4513 /*
4514 * Increasing number of lines/columns, do buffer first.
4515 * Use the maximal size in x and y direction.
4516 */
4517 if (sy < ySize)
4518 coordScreen.Y = ySize;
4519 else
4520 coordScreen.Y = sy;
4521 if (sx < xSize)
4522 coordScreen.X = xSize;
4523 else
4524 coordScreen.X = sx;
4525 SetConsoleScreenBufferSize(hConsole, coordScreen);
4526 }
4527 }
4528
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004529 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004530 coordScreen.X = xSize;
4531 coordScreen.Y = ySize;
4532
Bram Moolenaar2551c032018-08-23 22:38:31 +02004533 // In the new console call API, only the first time in reverse order
4534 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004535 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004536 ResizeWindow(hConsole, srWindowRect);
4537 ResizeConBuf(hConsole, coordScreen);
4538 }
4539 else
4540 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004541 // Workaround for a Windows 10 bug
4542 cursor.X = srWindowRect.Left;
4543 cursor.Y = srWindowRect.Top;
4544 SetConsoleCursorPosition(hConsole, cursor);
4545
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004546 ResizeConBuf(hConsole, coordScreen);
4547 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004548 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004549 }
4550}
4551
4552
4553/*
4554 * Set the console window to `Rows' * `Columns'
4555 */
4556 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004557mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004558{
4559 COORD coordScreen;
4560
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004561# ifdef VIMDLL
4562 if (gui.in_use)
4563 return;
4564# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004565 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004566 if (suppress_winsize != 0)
4567 {
4568 suppress_winsize = 2;
4569 return;
4570 }
4571
4572 if (term_console)
4573 {
4574 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4575
Bram Moolenaar0f873732019-12-05 20:28:46 +01004576 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004577 if (Rows > coordScreen.Y)
4578 Rows = coordScreen.Y;
4579 if (Columns > coordScreen.X)
4580 Columns = coordScreen.X;
4581
4582 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4583 }
4584}
4585
4586/*
4587 * Rows and/or Columns has changed.
4588 */
4589 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004590mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004591{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004592# ifdef VIMDLL
4593 if (gui.in_use)
4594 return;
4595# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004596 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4597}
4598
4599
4600/*
4601 * Called when started up, to set the winsize that was delayed.
4602 */
4603 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004604mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004605{
4606 if (suppress_winsize == 2)
4607 {
4608 suppress_winsize = 0;
4609 mch_set_shellsize();
4610 shell_resized();
4611 }
4612 suppress_winsize = 0;
4613}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004614#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004615
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004616 static BOOL
4617vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004618 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004619 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004620 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004621 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004622 PROCESS_INFORMATION *pi,
4623 LPVOID *env,
4624 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004625{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004626 BOOL ret = FALSE;
4627 WCHAR *wcmd, *wcwd = NULL;
4628
4629 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4630 if (wcmd == NULL)
4631 return FALSE;
4632 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004633 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004634 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4635 if (wcwd == NULL)
4636 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004637 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004638
4639 ret = CreateProcessW(
4640 NULL, // Executable name
4641 wcmd, // Command to execute
4642 NULL, // Process security attributes
4643 NULL, // Thread security attributes
4644 inherit_handles, // Inherit handles
4645 flags, // Creation flags
4646 env, // Environment
4647 wcwd, // Current directory
4648 (LPSTARTUPINFOW)si, // Startup information
4649 pi); // Process information
4650theend:
4651 vim_free(wcmd);
4652 vim_free(wcwd);
4653 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004654}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004655
4656
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004657 static HINSTANCE
4658vim_shell_execute(
4659 char *cmd,
4660 INT n_show_cmd)
4661{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004662 HINSTANCE ret;
4663 WCHAR *wcmd;
4664
4665 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4666 if (wcmd == NULL)
4667 return (HINSTANCE) 0;
4668
4669 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4670 vim_free(wcmd);
4671 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004672}
4673
4674
Bram Moolenaar4f974752019-02-17 17:44:42 +01004675#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004676
4677/*
4678 * Specialised version of system() for Win32 GUI mode.
4679 * This version proceeds as follows:
4680 * 1. Create a console window for use by the subprocess
4681 * 2. Run the subprocess (it gets the allocated console by default)
4682 * 3. Wait for the subprocess to terminate and get its exit code
4683 * 4. Prompt the user to press a key to close the console window
4684 */
4685 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004686mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004687{
4688 STARTUPINFO si;
4689 PROCESS_INFORMATION pi;
4690 DWORD ret = 0;
4691 HWND hwnd = GetFocus();
4692
4693 si.cb = sizeof(si);
4694 si.lpReserved = NULL;
4695 si.lpDesktop = NULL;
4696 si.lpTitle = NULL;
4697 si.dwFlags = STARTF_USESHOWWINDOW;
4698 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004699 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004700 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004701 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004702 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004703 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004704 else
4705 si.wShowWindow = SW_SHOWNORMAL;
4706 si.cbReserved2 = 0;
4707 si.lpReserved2 = NULL;
4708
Bram Moolenaar0f873732019-12-05 20:28:46 +01004709 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004710 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004711 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4712 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004713
Bram Moolenaar0f873732019-12-05 20:28:46 +01004714 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004715 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004716# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004717 int delay = 1;
4718
Bram Moolenaar0f873732019-12-05 20:28:46 +01004719 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004720 for (;;)
4721 {
4722 MSG msg;
4723
K.Takatab7057bd2022-01-21 11:37:07 +00004724 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004725 {
4726 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004727 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004728 delay = 1;
4729 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004730 }
4731 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4732 break;
4733
Bram Moolenaar0f873732019-12-05 20:28:46 +01004734 // We start waiting for a very short time and then increase it, so
4735 // that we respond quickly when the process is quick, and don't
4736 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004737 if (delay < 50)
4738 delay += 10;
4739 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004740# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004741 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004742# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004743
Bram Moolenaar0f873732019-12-05 20:28:46 +01004744 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004745 GetExitCodeProcess(pi.hProcess, &ret);
4746 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004747
Bram Moolenaar0f873732019-12-05 20:28:46 +01004748 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004749 CloseHandle(pi.hThread);
4750 CloseHandle(pi.hProcess);
4751
Bram Moolenaar0f873732019-12-05 20:28:46 +01004752 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004753 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4754
4755 return ret;
4756}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004757
4758/*
4759 * Thread launched by the gui to send the current buffer data to the
4760 * process. This way avoid to hang up vim totally if the children
4761 * process take a long time to process the lines.
4762 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004763 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004764sub_process_writer(LPVOID param)
4765{
4766 HANDLE g_hChildStd_IN_Wr = param;
4767 linenr_T lnum = curbuf->b_op_start.lnum;
4768 DWORD len = 0;
4769 DWORD l;
4770 char_u *lp = ml_get(lnum);
4771 char_u *s;
4772 int written = 0;
4773
4774 for (;;)
4775 {
4776 l = (DWORD)STRLEN(lp + written);
4777 if (l == 0)
4778 len = 0;
4779 else if (lp[written] == NL)
4780 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004781 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004782 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4783 }
4784 else
4785 {
4786 s = vim_strchr(lp + written, NL);
4787 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4788 s == NULL ? l : (DWORD)(s - (lp + written)),
4789 &len, NULL);
4790 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004791 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004792 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004793 // Finished a line, add a NL, unless this line should not have
4794 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004795 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004796 || (!curbuf->b_p_bin
4797 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004798 || (lnum != curbuf->b_no_eol_lnum
4799 && (lnum != curbuf->b_ml.ml_line_count
4800 || curbuf->b_p_eol)))
4801 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004802 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4803 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004804 }
4805
4806 ++lnum;
4807 if (lnum > curbuf->b_op_end.lnum)
4808 break;
4809
4810 lp = ml_get(lnum);
4811 written = 0;
4812 }
4813 else if (len > 0)
4814 written += len;
4815 }
4816
Bram Moolenaar0f873732019-12-05 20:28:46 +01004817 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004818 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004819 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004820}
4821
4822
Bram Moolenaar0f873732019-12-05 20:28:46 +01004823# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004824
4825/*
4826 * This function read from the children's stdout and write the
4827 * data on screen or in the buffer accordingly.
4828 */
4829 static void
4830dump_pipe(int options,
4831 HANDLE g_hChildStd_OUT_Rd,
4832 garray_T *ga,
4833 char_u buffer[],
4834 DWORD *buffer_off)
4835{
4836 DWORD availableBytes = 0;
4837 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004838 int ret;
4839 DWORD len;
4840 DWORD toRead;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004841
Bram Moolenaar0f873732019-12-05 20:28:46 +01004842 // we query the pipe to see if there is any data to read
4843 // to avoid to perform a blocking read
4844 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4845 NULL, // optional buffer
4846 0, // buffer size
4847 NULL, // number of read bytes
4848 &availableBytes, // available bytes total
4849 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004850
Bram Moolenaar0f873732019-12-05 20:28:46 +01004851 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004852 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004853 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01004854 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004855 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004856 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004857
Bram Moolenaar0f873732019-12-05 20:28:46 +01004858 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004859 if (len == 0)
4860 break;
4861
4862 availableBytes -= len;
4863
4864 if (options & SHELL_READ)
4865 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004866 // Do NUL -> NL translation, append NL separated
4867 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004868 for (i = 0; i < len; ++i)
4869 {
4870 if (buffer[i] == NL)
4871 append_ga_line(ga);
4872 else if (buffer[i] == NUL)
4873 ga_append(ga, NL);
4874 else
4875 ga_append(ga, buffer[i]);
4876 }
4877 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004878 else if (has_mbyte)
4879 {
4880 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004881 int c;
4882 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004883
4884 len += *buffer_off;
4885 buffer[len] = NUL;
4886
Bram Moolenaar0f873732019-12-05 20:28:46 +01004887 // Check if the last character in buffer[] is
4888 // incomplete, keep these bytes for the next
4889 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004890 for (p = buffer; p < buffer + len; p += l)
4891 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004892 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004893 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004894 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004895 else if (MB_BYTE2LEN(*p) != l)
4896 break;
4897 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004898 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004899 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004900 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004901 if (len >= 12)
4902 ++p;
4903 else
4904 {
4905 *buffer_off = len;
4906 return;
4907 }
4908 }
4909 c = *p;
4910 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004911 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004912 if (p < buffer + len)
4913 {
4914 *p = c;
4915 *buffer_off = (DWORD)((buffer + len) - p);
4916 mch_memmove(buffer, p, *buffer_off);
4917 return;
4918 }
4919 *buffer_off = 0;
4920 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004921 else
4922 {
4923 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004924 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004925 }
4926
4927 windgoto(msg_row, msg_col);
4928 cursor_on();
4929 out_flush();
4930 }
4931}
4932
4933/*
4934 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4935 * for communication and doesn't open any new window.
4936 */
4937 static int
4938mch_system_piped(char *cmd, int options)
4939{
4940 STARTUPINFO si;
4941 PROCESS_INFORMATION pi;
4942 DWORD ret = 0;
4943
4944 HANDLE g_hChildStd_IN_Rd = NULL;
4945 HANDLE g_hChildStd_IN_Wr = NULL;
4946 HANDLE g_hChildStd_OUT_Rd = NULL;
4947 HANDLE g_hChildStd_OUT_Wr = NULL;
4948
Bram Moolenaar0f873732019-12-05 20:28:46 +01004949 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004950 DWORD len;
4951
Bram Moolenaar0f873732019-12-05 20:28:46 +01004952 // buffer used to receive keys
4953 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4954 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004955
4956 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004957 int noread_cnt = 0;
4958 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004959 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004960 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004961 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004962
4963 SECURITY_ATTRIBUTES saAttr;
4964
Bram Moolenaar0f873732019-12-05 20:28:46 +01004965 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004966 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4967 saAttr.bInheritHandle = TRUE;
4968 saAttr.lpSecurityDescriptor = NULL;
4969
4970 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004971 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004972 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004973 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004974 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004975 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004976 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004977 {
4978 CloseHandle(g_hChildStd_IN_Rd);
4979 CloseHandle(g_hChildStd_IN_Wr);
4980 CloseHandle(g_hChildStd_OUT_Rd);
4981 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004982 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004983 }
4984
4985 si.cb = sizeof(si);
4986 si.lpReserved = NULL;
4987 si.lpDesktop = NULL;
4988 si.lpTitle = NULL;
4989 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4990
Bram Moolenaar0f873732019-12-05 20:28:46 +01004991 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004992 si.hStdError = g_hChildStd_OUT_Wr;
4993 si.hStdOutput = g_hChildStd_OUT_Wr;
4994 si.hStdInput = g_hChildStd_IN_Rd;
4995 si.wShowWindow = SW_HIDE;
4996 si.cbReserved2 = 0;
4997 si.lpReserved2 = NULL;
4998
4999 if (options & SHELL_READ)
5000 ga_init2(&ga, 1, BUFLEN);
5001
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005002 if (cmd != NULL)
5003 {
5004 p = (char *)vim_strsave((char_u *)cmd);
5005 if (p != NULL)
5006 unescape_shellxquote((char_u *)p, p_sxe);
5007 else
5008 p = cmd;
5009 }
5010
Bram Moolenaar0f873732019-12-05 20:28:46 +01005011 // Now, run the command.
5012 // About "Inherit handles" being TRUE: this command can be litigious,
5013 // handle inheritance was deactivated for pending temp file, but, if we
5014 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005015 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
5016 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005017
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005018 if (p != cmd)
5019 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005020
Bram Moolenaar0f873732019-12-05 20:28:46 +01005021 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005022 CloseHandle(g_hChildStd_IN_Rd);
5023 CloseHandle(g_hChildStd_OUT_Wr);
5024
5025 if (options & SHELL_WRITE)
5026 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02005027 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005028 _beginthreadex(NULL, // security attributes
5029 0, // default stack size
5030 sub_process_writer, // function to be executed
5031 g_hChildStd_IN_Wr, // parameter
5032 0, // creation flag, start immediately
5033 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005034 CloseHandle(thread);
5035 g_hChildStd_IN_Wr = NULL;
5036 }
5037
Bram Moolenaar0f873732019-12-05 20:28:46 +01005038 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005039 for (;;)
5040 {
5041 MSG msg;
5042
K.Takatab7057bd2022-01-21 11:37:07 +00005043 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005044 {
5045 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00005046 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005047 }
5048
Bram Moolenaar0f873732019-12-05 20:28:46 +01005049 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005050 if ((options & (SHELL_READ|SHELL_WRITE))
5051# ifdef FEAT_GUI
5052 || gui.in_use
5053# endif
5054 )
5055 {
5056 len = 0;
5057 if (!(options & SHELL_EXPAND)
5058 && ((options &
5059 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
5060 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
5061# ifdef FEAT_GUI
5062 || gui.in_use
5063# endif
5064 )
5065 && (ta_len > 0 || noread_cnt > 4))
5066 {
5067 if (ta_len == 0)
5068 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005069 // Get extra characters when we don't have any. Reset the
5070 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005071 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005072 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
5073 }
5074 if (ta_len > 0 || len > 0)
5075 {
5076 /*
5077 * For pipes: Check for CTRL-C: send interrupt signal to
5078 * child. Check for CTRL-D: EOF, close pipe to child.
5079 */
5080 if (len == 1 && cmd != NULL)
5081 {
5082 if (ta_buf[ta_len] == Ctrl_C)
5083 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005084 // Learn what exit code is expected, for
5085 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005086 TerminateProcess(pi.hProcess, 9);
5087 }
5088 if (ta_buf[ta_len] == Ctrl_D)
5089 {
5090 CloseHandle(g_hChildStd_IN_Wr);
5091 g_hChildStd_IN_Wr = NULL;
5092 }
5093 }
5094
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01005095 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005096
5097 /*
5098 * For pipes: echo the typed characters. For a pty this
5099 * does not seem to work.
5100 */
5101 for (i = ta_len; i < ta_len + len; ++i)
5102 {
5103 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
5104 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005105 else if (has_mbyte)
5106 {
5107 int l = (*mb_ptr2len)(ta_buf + i);
5108
5109 msg_outtrans_len(ta_buf + i, l);
5110 i += l - 1;
5111 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005112 else
5113 msg_outtrans_len(ta_buf + i, 1);
5114 }
5115 windgoto(msg_row, msg_col);
5116 out_flush();
5117
5118 ta_len += len;
5119
5120 /*
5121 * Write the characters to the child, unless EOF has been
5122 * typed for pipes. Write one character at a time, to
5123 * avoid losing too much typeahead. When writing buffer
5124 * lines, drop the typed characters (only check for
5125 * CTRL-C).
5126 */
5127 if (options & SHELL_WRITE)
5128 ta_len = 0;
5129 else if (g_hChildStd_IN_Wr != NULL)
5130 {
5131 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
5132 1, &len, NULL);
5133 // if we are typing in, we want to keep things reactive
5134 delay = 1;
5135 if (len > 0)
5136 {
5137 ta_len -= len;
5138 mch_memmove(ta_buf, ta_buf + len, ta_len);
5139 }
5140 }
5141 }
5142 }
5143 }
5144
5145 if (ta_len)
5146 ui_inchar_undo(ta_buf, ta_len);
5147
5148 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
5149 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005150 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005151 break;
5152 }
5153
5154 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005155 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005156
Bram Moolenaar0f873732019-12-05 20:28:46 +01005157 // We start waiting for a very short time and then increase it, so
5158 // that we respond quickly when the process is quick, and don't
5159 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005160 if (delay < 50)
5161 delay += 10;
5162 }
5163
Bram Moolenaar0f873732019-12-05 20:28:46 +01005164 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005165 CloseHandle(g_hChildStd_OUT_Rd);
5166 if (g_hChildStd_IN_Wr != NULL)
5167 CloseHandle(g_hChildStd_IN_Wr);
5168
5169 WaitForSingleObject(pi.hProcess, INFINITE);
5170
Bram Moolenaar0f873732019-12-05 20:28:46 +01005171 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005172 GetExitCodeProcess(pi.hProcess, &ret);
5173
5174 if (options & SHELL_READ)
5175 {
5176 if (ga.ga_len > 0)
5177 {
5178 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01005179 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005180 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
5181 }
5182 else
5183 curbuf->b_no_eol_lnum = 0;
5184 ga_clear(&ga);
5185 }
5186
Bram Moolenaar0f873732019-12-05 20:28:46 +01005187 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005188 CloseHandle(pi.hThread);
5189 CloseHandle(pi.hProcess);
5190
5191 return ret;
5192}
5193
5194 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005195mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005196{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005197 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005198 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005199 return mch_system_piped(cmd, options);
5200 else
5201 return mch_system_classic(cmd, options);
5202}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005203#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005204
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005205#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005206 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02005207mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005208{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005209 int ret;
5210 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005211 char_u *buf;
5212 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005213
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005214 // If the command starts and ends with double quotes, enclose the command
5215 // in parentheses.
5216 len = STRLEN(cmd);
5217 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
5218 {
5219 len += 3;
5220 buf = alloc(len);
5221 if (buf == NULL)
5222 return -1;
5223 vim_snprintf((char *)buf, len, "(%s)", cmd);
5224 wcmd = enc_to_utf16(buf, NULL);
5225 free(buf);
5226 }
5227 else
5228 wcmd = enc_to_utf16((char_u *)cmd, NULL);
5229
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005230 if (wcmd == NULL)
5231 return -1;
5232
5233 ret = _wsystem(wcmd);
5234 vim_free(wcmd);
5235 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005236}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005237
5238#endif
5239
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005240 static int
5241mch_system(char *cmd, int options)
5242{
5243#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005244 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005245 return mch_system_g(cmd, options);
5246 else
5247 return mch_system_c(cmd, options);
5248#elif defined(FEAT_GUI_MSWIN)
5249 return mch_system_g(cmd, options);
5250#else
5251 return mch_system_c(cmd, options);
5252#endif
5253}
5254
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005255#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
5256/*
5257 * Use a terminal window to run a shell command in.
5258 */
5259 static int
5260mch_call_shell_terminal(
5261 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005262 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005263{
5264 jobopt_T opt;
5265 char_u *newcmd = NULL;
5266 typval_T argvar[2];
5267 long_u cmdlen;
5268 int retval = -1;
5269 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005270 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005271 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005272 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005273
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005274 if (cmd == NULL)
5275 cmdlen = STRLEN(p_sh) + 1;
5276 else
5277 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005278 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005279 if (newcmd == NULL)
5280 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005281 if (cmd == NULL)
5282 {
5283 STRCPY(newcmd, p_sh);
5284 ch_log(NULL, "starting terminal to run a shell");
5285 }
5286 else
5287 {
5288 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
5289 ch_log(NULL, "starting terminal for system command '%s'", cmd);
5290 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005291
5292 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005293
5294 argvar[0].v_type = VAR_STRING;
5295 argvar[0].vval.v_string = newcmd;
5296 argvar[1].v_type = VAR_UNKNOWN;
5297 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005298 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01005299 {
5300 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005301 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01005302 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005303
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005304 job = term_getjob(buf->b_term);
5305 ++job->jv_refcount;
5306
Bram Moolenaar0f873732019-12-05 20:28:46 +01005307 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005308 aucmd_prepbuf(&aco, buf);
Bram Moolenaare76062c2022-11-28 18:51:43 +00005309 if (curbuf == buf)
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005310 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005311 // Only do this when a window was found for "buf".
5312 clear_oparg(&oa);
5313 while (term_use_loop())
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005314 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005315 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
5316 {
5317 // If terminal_loop() returns OK we got a key that is handled
5318 // in Normal model. We don't do redrawing anyway.
5319 if (terminal_loop(TRUE) == OK)
5320 normal_cmd(&oa, TRUE);
5321 }
5322 else
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005323 normal_cmd(&oa, TRUE);
5324 }
Bram Moolenaare76062c2022-11-28 18:51:43 +00005325 retval = job->jv_exitval;
5326 ch_log(NULL, "system command finished");
5327
5328 job_unref(job);
5329
5330 // restore curwin/curbuf and a few other things
5331 aucmd_restbuf(&aco);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005332 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005333
5334 wait_return(TRUE);
5335 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
5336
5337 vim_free(newcmd);
5338 return retval;
5339}
5340#endif
5341
Bram Moolenaar071d4272004-06-13 20:20:40 +00005342/*
5343 * Either execute a command by calling the shell or start a new shell
5344 */
5345 int
5346mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005347 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005348 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00005349{
5350 int x = 0;
5351 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005352 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02005353
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00005354#ifdef FEAT_EVAL
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01005355 ch_log(NULL, "executing shell command: %s", cmd);
5356#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01005357 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02005358 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005359 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005360 if (cmd == NULL)
5361 wcscat(szShellTitle, L" :sh");
5362 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005363 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005364 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005365
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005366 if (wn != NULL)
5367 {
5368 wcscat(szShellTitle, L" - !");
5369 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02005370 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005371 wcscat(szShellTitle, wn);
5372 SetConsoleTitleW(szShellTitle);
5373 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005374 }
5375 }
5376 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005377
5378 out_flush();
5379
5380#ifdef MCH_WRITE_DUMP
5381 if (fdDump)
5382 {
5383 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
5384 fflush(fdDump);
5385 }
5386#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005387#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005388 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005389 if (
5390# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005391 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005392# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005393 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005394 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
5395 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005396 char_u *cmdbase = cmd;
5397
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02005398 if (cmdbase != NULL)
5399 // Skip a leading quote and (.
5400 while (*cmdbase == '"' || *cmdbase == '(')
5401 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005402
5403 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01005404 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
5405 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005406 {
5407 // Use a terminal window to run the command in.
5408 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005409 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005410 return x;
5411 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005412 }
5413#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005414
5415 /*
5416 * Catch all deadly signals while running the external command, because a
5417 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5418 */
5419 signal(SIGINT, SIG_IGN);
5420#if defined(__GNUC__) && !defined(__MINGW32__)
5421 signal(SIGKILL, SIG_IGN);
5422#else
5423 signal(SIGBREAK, SIG_IGN);
5424#endif
5425 signal(SIGILL, SIG_IGN);
5426 signal(SIGFPE, SIG_IGN);
5427 signal(SIGSEGV, SIG_IGN);
5428 signal(SIGTERM, SIG_IGN);
5429 signal(SIGABRT, SIG_IGN);
5430
5431 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005432 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00005433
5434 if (cmd == NULL)
5435 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005436 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005437 }
5438 else
5439 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005440 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005441 char_u *newcmd = NULL;
5442 char_u *cmdbase = cmd;
5443 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005444
Bram Moolenaar0f873732019-12-05 20:28:46 +01005445 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005446 if (*cmdbase == '"' )
5447 ++cmdbase;
5448 if (*cmdbase == '(')
5449 ++cmdbase;
5450
Bram Moolenaar1c465442017-03-12 20:10:05 +01005451 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005452 {
5453 STARTUPINFO si;
5454 PROCESS_INFORMATION pi;
5455 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005456 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005457 char_u *p;
5458
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005459 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005460 si.cb = sizeof(si);
5461 si.lpReserved = NULL;
5462 si.lpDesktop = NULL;
5463 si.lpTitle = NULL;
5464 si.dwFlags = 0;
5465 si.cbReserved2 = 0;
5466 si.lpReserved2 = NULL;
5467
5468 cmdbase = skipwhite(cmdbase + 5);
5469 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005470 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005471 {
5472 cmdbase = skipwhite(cmdbase + 4);
5473 si.dwFlags = STARTF_USESHOWWINDOW;
5474 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005475 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005476 }
5477 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005478 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005479 {
5480 cmdbase = skipwhite(cmdbase + 2);
5481 flags = CREATE_NO_WINDOW;
5482 si.dwFlags = STARTF_USESTDHANDLES;
5483 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005484 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005485 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005486 NULL, // Security att.
5487 OPEN_EXISTING, // Open flags
5488 FILE_ATTRIBUTE_NORMAL, // File att.
5489 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005490 si.hStdOutput = si.hStdInput;
5491 si.hStdError = si.hStdInput;
5492 }
5493
Bram Moolenaar0f873732019-12-05 20:28:46 +01005494 // Remove a trailing ", ) and )" if they have a match
5495 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005496 if (cmdbase > cmd)
5497 {
5498 p = cmdbase + STRLEN(cmdbase);
5499 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5500 *--p = NUL;
5501 if (p > cmdbase && p[-1] == ')'
5502 && (*cmd =='(' || cmd[1] == '('))
5503 *--p = NUL;
5504 }
5505
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005506 newcmd = cmdbase;
5507 unescape_shellxquote(cmdbase, p_sxe);
5508
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005509 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005510 * If creating new console, arguments are passed to the
5511 * 'cmd.exe' as-is. If it's not, arguments are not treated
5512 * correctly for current 'cmd.exe'. So unescape characters in
5513 * shellxescape except '|' for avoiding to be treated as
5514 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005515 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005516 if (flags != CREATE_NEW_CONSOLE)
5517 {
5518 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005519 char_u *cmd_shell = mch_getenv("COMSPEC");
5520
5521 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005522 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005523
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005524 subcmd = vim_strsave_escaped_ext(cmdbase,
5525 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005526 if (subcmd != NULL)
5527 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005528 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005529 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005530 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005531 if (newcmd != NULL)
5532 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005533 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005534 else
5535 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005536 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005537 }
5538 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005539
5540 /*
5541 * Now, start the command as a process, so that it doesn't
5542 * inherit our handles which causes unpleasant dangling swap
5543 * files if we exit before the spawned process
5544 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005545 if (vim_create_process((char *)newcmd, FALSE, flags,
5546 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005547 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005548 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5549 > (HINSTANCE)32)
5550 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005551 else
5552 {
5553 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005554#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005555# ifdef VIMDLL
5556 if (gui.in_use)
5557# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005558 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005559#endif
5560 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005561
5562 if (newcmd != cmdbase)
5563 vim_free(newcmd);
5564
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005565 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005566 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005567 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005568 CloseHandle(si.hStdInput);
5569 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005570 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005571 CloseHandle(pi.hThread);
5572 CloseHandle(pi.hProcess);
5573 }
5574 else
5575 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005576 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005577#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005578 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005579 (!s_dont_use_vimrun && p_stmp ?
5580 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5581 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005582#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005583 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005584
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005585 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005586 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005587 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005588#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005589 if (
5590# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005591 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005592# endif
5593 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005594 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005595 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5596 "External commands will not pause after completion.\n"
5597 "See :help win32-vimrun for more information.");
5598 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005599 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5600 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005601
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005602 if (wmsg != NULL && wtitle != NULL)
5603 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5604 vim_free(wmsg);
5605 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005606 need_vimrun_warning = FALSE;
5607 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005608 if (
5609# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005610 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005611# endif
5612 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005613 // Use vimrun to execute the command. It opens a console
5614 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005615 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005616 vimrun_path,
5617 (msg_silent != 0 || (options & SHELL_DOOUT))
5618 ? "-s " : "",
5619 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005620 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005621# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005622 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005623# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005624 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005625 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005626 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5627 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005628 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005629#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005630 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005631 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005632 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005633 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005634 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005635 }
5636 }
5637
5638 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005639 {
5640 // The shell may have messed with the mode, always set it.
5641 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005642 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005643 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005644
Bram Moolenaar0f873732019-12-05 20:28:46 +01005645 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005646 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005647#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005648 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005649 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005650#endif
5651 )
5652 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005653 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005654 msg_putchar('\n');
5655 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005656 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005657
5658 signal(SIGINT, SIG_DFL);
5659#if defined(__GNUC__) && !defined(__MINGW32__)
5660 signal(SIGKILL, SIG_DFL);
5661#else
5662 signal(SIGBREAK, SIG_DFL);
5663#endif
5664 signal(SIGILL, SIG_DFL);
5665 signal(SIGFPE, SIG_DFL);
5666 signal(SIGSEGV, SIG_DFL);
5667 signal(SIGTERM, SIG_DFL);
5668 signal(SIGABRT, SIG_DFL);
5669
5670 return x;
5671}
5672
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005673#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005674 static HANDLE
5675job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005676 char_u *fname,
5677 DWORD dwDesiredAccess,
5678 DWORD dwShareMode,
5679 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5680 DWORD dwCreationDisposition,
5681 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005682{
5683 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005684 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005685
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005686 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005687 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005688 return INVALID_HANDLE_VALUE;
5689
5690 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5691 lpSecurityAttributes, dwCreationDisposition,
5692 dwFlagsAndAttributes, NULL);
5693 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005694 return h;
5695}
5696
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005697/*
5698 * Turn the dictionary "env" into a NUL separated list that can be used as the
5699 * environment argument of vim_create_process().
5700 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005701 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005702win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005703{
5704 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005705 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005706 LPVOID base = GetEnvironmentStringsW();
5707
Bram Moolenaar0f873732019-12-05 20:28:46 +01005708 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005709 if (ga_grow(gap, 1) == FAIL)
5710 return;
5711
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005712 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005713 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005714 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005715 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005716 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005717 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005718 typval_T *item = &dict_lookup(hi)->di_tv;
5719 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005720 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005721 --todo;
5722 if (wkey != NULL && wval != NULL)
5723 {
5724 size_t n;
5725 size_t lkey = wcslen(wkey);
5726 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005727
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005728 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5729 continue;
5730 for (n = 0; n < lkey; n++)
5731 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5732 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5733 for (n = 0; n < lval; n++)
5734 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5735 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5736 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005737 vim_free(wkey);
5738 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005739 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005740 }
5741 }
5742
Bram Moolenaar355757a2020-02-10 22:06:32 +01005743 if (base)
5744 {
5745 WCHAR *p = (WCHAR*) base;
5746
5747 // for last \0
5748 if (ga_grow(gap, 1) == FAIL)
5749 return;
5750
5751 while (*p != 0 || *(p + 1) != 0)
5752 {
5753 if (ga_grow(gap, 1) == OK)
5754 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5755 p++;
5756 }
5757 FreeEnvironmentStrings(base);
5758 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5759 }
5760
Bram Moolenaar493359e2018-06-12 20:25:52 +02005761# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005762 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005763# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005764 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005765 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005766# endif
5767# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005768 char_u *version = get_vim_var_str(VV_VERSION);
5769 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005770# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005771 // size of "VIM_SERVERNAME=" and value,
5772 // plus "VIM_TERMINAL=" and value,
5773 // plus two terminating NULs
5774 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005775# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005776 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005777# endif
5778# ifdef FEAT_TERMINAL
5779 + 13 + version_len + 2
5780# endif
5781 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005782
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005783 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005784 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005785# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005786 for (n = 0; n < 15; n++)
5787 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5788 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005789 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005790 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5791 (WCHAR)servername[n];
5792 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005793# endif
5794# ifdef FEAT_TERMINAL
5795 if (is_terminal)
5796 {
5797 for (n = 0; n < 13; n++)
5798 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5799 (WCHAR)"VIM_TERMINAL="[n];
5800 for (n = 0; n < version_len; n++)
5801 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5802 (WCHAR)version[n];
5803 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5804 }
5805# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005806 }
5807 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005808# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005809}
5810
Bram Moolenaarb091f302019-01-19 14:37:00 +01005811/*
5812 * Create a pair of pipes.
5813 * Return TRUE for success, FALSE for failure.
5814 */
5815 static BOOL
5816create_pipe_pair(HANDLE handles[2])
5817{
5818 static LONG s;
5819 char name[64];
5820 SECURITY_ATTRIBUTES sa;
5821
5822 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5823 GetCurrentProcessId(),
5824 InterlockedIncrement(&s));
5825
5826 // Create named pipe. Max size of named pipe is 65535.
5827 handles[1] = CreateNamedPipe(
5828 name,
5829 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5830 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005831 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005832
5833 if (handles[1] == INVALID_HANDLE_VALUE)
5834 return FALSE;
5835
5836 sa.nLength = sizeof(sa);
5837 sa.bInheritHandle = TRUE;
5838 sa.lpSecurityDescriptor = NULL;
5839
5840 handles[0] = CreateFile(name,
5841 FILE_GENERIC_READ,
5842 FILE_SHARE_READ, &sa,
5843 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5844
5845 if (handles[0] == INVALID_HANDLE_VALUE)
5846 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005847 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005848 return FALSE;
5849 }
5850
5851 return TRUE;
5852}
5853
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005854 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005855mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005856{
5857 STARTUPINFO si;
5858 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005859 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005860 SECURITY_ATTRIBUTES saAttr;
5861 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005862 HANDLE ifd[2];
5863 HANDLE ofd[2];
5864 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005865 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005866
5867 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5868 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5869 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5870 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5871 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5872 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5873 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5874
5875 if (use_out_for_err && use_null_for_out)
5876 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005877
5878 ifd[0] = INVALID_HANDLE_VALUE;
5879 ifd[1] = INVALID_HANDLE_VALUE;
5880 ofd[0] = INVALID_HANDLE_VALUE;
5881 ofd[1] = INVALID_HANDLE_VALUE;
5882 efd[0] = INVALID_HANDLE_VALUE;
5883 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005884 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005885
Bram Moolenaar14207f42016-10-27 21:13:10 +02005886 jo = CreateJobObject(NULL, NULL);
5887 if (jo == NULL)
5888 {
5889 job->jv_status = JOB_FAILED;
5890 goto failed;
5891 }
5892
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005893 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005894 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005895
Bram Moolenaar76467df2016-02-12 19:30:26 +01005896 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005897 ZeroMemory(&si, sizeof(si));
5898 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005899 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005900 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005901
Bram Moolenaard8070362016-02-15 21:56:54 +01005902 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5903 saAttr.bInheritHandle = TRUE;
5904 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005905
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005906 if (use_file_for_in)
5907 {
5908 char_u *fname = options->jo_io_name[PART_IN];
5909
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005910 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5911 FILE_SHARE_READ | FILE_SHARE_WRITE,
5912 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5913 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005914 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005915 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005916 goto failed;
5917 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005918 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005919 else if (!use_null_for_in
5920 && (!create_pipe_pair(ifd)
5921 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005922 goto failed;
5923
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005924 if (use_file_for_out)
5925 {
5926 char_u *fname = options->jo_io_name[PART_OUT];
5927
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005928 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5929 FILE_SHARE_READ | FILE_SHARE_WRITE,
5930 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5931 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005932 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005933 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005934 goto failed;
5935 }
5936 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005937 else if (!use_null_for_out &&
5938 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005939 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005940 goto failed;
5941
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005942 if (use_file_for_err)
5943 {
5944 char_u *fname = options->jo_io_name[PART_ERR];
5945
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005946 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5947 FILE_SHARE_READ | FILE_SHARE_WRITE,
5948 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5949 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005950 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005951 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005952 goto failed;
5953 }
5954 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005955 else if (!use_out_for_err && !use_null_for_err &&
5956 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005957 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005958 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005959
Bram Moolenaard8070362016-02-15 21:56:54 +01005960 si.dwFlags |= STARTF_USESTDHANDLES;
5961 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005962 si.hStdOutput = ofd[1];
5963 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5964
5965 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5966 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005967 if (options->jo_set & JO_CHANNEL)
5968 {
5969 channel = options->jo_channel;
5970 if (channel != NULL)
5971 ++channel->ch_refcount;
5972 }
5973 else
5974 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005975 if (channel == NULL)
5976 goto failed;
5977 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005978
5979 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005980 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005981 CREATE_DEFAULT_ERROR_MODE |
5982 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005983 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005984 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005985 &si, &pi,
5986 ga.ga_data,
5987 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005988 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005989 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005990 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005991 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005992 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005993
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005994 ga_clear(&ga);
5995
Bram Moolenaar14207f42016-10-27 21:13:10 +02005996 if (!AssignProcessToJobObject(jo, pi.hProcess))
5997 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005998 // if failing, switch the way to terminate
5999 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02006000 CloseHandle(jo);
6001 jo = NULL;
6002 }
6003 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01006004 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006005 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02006006 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006007 job->jv_status = JOB_STARTED;
6008
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02006009 CloseHandle(ifd[0]);
6010 CloseHandle(ofd[1]);
6011 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01006012 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01006013
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006014 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006015 if (channel != NULL)
6016 {
6017 channel_set_pipes(channel,
6018 use_file_for_in || use_null_for_in
6019 ? INVALID_FD : (sock_T)ifd[1],
6020 use_file_for_out || use_null_for_out
6021 ? INVALID_FD : (sock_T)ofd[0],
6022 use_out_for_err || use_file_for_err || use_null_for_err
6023 ? INVALID_FD : (sock_T)efd[0]);
6024 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006025 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006026 return;
6027
6028failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01006029 CloseHandle(ifd[0]);
6030 CloseHandle(ofd[0]);
6031 CloseHandle(efd[0]);
6032 CloseHandle(ifd[1]);
6033 CloseHandle(ofd[1]);
6034 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01006035 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006036 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006037}
6038
6039 char *
6040mch_job_status(job_T *job)
6041{
6042 DWORD dwExitCode = 0;
6043
Bram Moolenaar76467df2016-02-12 19:30:26 +01006044 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
6045 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006046 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01006047 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01006048 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02006049 {
6050 ch_log(job->jv_channel, "Job ended");
6051 job->jv_status = JOB_ENDED;
6052 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006053 return "dead";
6054 }
6055 return "run";
6056}
6057
Bram Moolenaar97792de2016-10-15 18:36:49 +02006058 job_T *
6059mch_detect_ended_job(job_T *job_list)
6060{
6061 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
6062 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
6063 job_T *job = job_list;
6064
6065 while (job != NULL)
6066 {
6067 DWORD n;
6068 DWORD result;
6069
6070 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
6071 && job != NULL; job = job->jv_next)
6072 {
6073 if (job->jv_status == JOB_STARTED)
6074 {
6075 jobHandles[n] = job->jv_proc_info.hProcess;
6076 jobArray[n] = job;
6077 ++n;
6078 }
6079 }
6080 if (n == 0)
6081 continue;
6082 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
6083 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
6084 {
6085 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
6086
6087 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
6088 return wait_job;
6089 }
6090 }
6091 return NULL;
6092}
6093
Bram Moolenaarfb630902016-10-29 14:55:00 +02006094 static BOOL
6095terminate_all(HANDLE process, int code)
6096{
6097 PROCESSENTRY32 pe;
6098 HANDLE h = INVALID_HANDLE_VALUE;
6099 DWORD pid = GetProcessId(process);
6100
6101 if (pid != 0)
6102 {
6103 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
6104 if (h != INVALID_HANDLE_VALUE)
6105 {
6106 pe.dwSize = sizeof(PROCESSENTRY32);
6107 if (!Process32First(h, &pe))
6108 goto theend;
6109
6110 do
6111 {
6112 if (pe.th32ParentProcessID == pid)
6113 {
6114 HANDLE ph = OpenProcess(
6115 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
6116 if (ph != NULL)
6117 {
6118 terminate_all(ph, code);
6119 CloseHandle(ph);
6120 }
6121 }
6122 } while (Process32Next(h, &pe));
6123
6124 CloseHandle(h);
6125 }
6126 }
6127
6128theend:
6129 return TerminateProcess(process, code);
6130}
6131
6132/*
6133 * Send a (deadly) signal to "job".
6134 * Return FAIL if it didn't work.
6135 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006136 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02006137mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006138{
Bram Moolenaar923d9262016-02-25 20:56:01 +01006139 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006140
Bram Moolenaar923d9262016-02-25 20:56:01 +01006141 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01006142 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006143 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02006144 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006145 {
6146 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
6147 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00006148 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006149 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01006150 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006151 }
6152
6153 if (!AttachConsole(job->jv_proc_info.dwProcessId))
6154 return FAIL;
6155 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01006156 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
6157 job->jv_proc_info.dwProcessId)
6158 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006159 FreeConsole();
6160 return ret;
6161}
6162
6163/*
6164 * Clear the data related to "job".
6165 */
6166 void
6167mch_clear_job(job_T *job)
6168{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00006169 if (job->jv_status == JOB_FAILED)
6170 return;
6171
6172 if (job->jv_job_object != NULL)
6173 CloseHandle(job->jv_job_object);
6174 CloseHandle(job->jv_proc_info.hProcess);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006175}
6176#endif
6177
Bram Moolenaar071d4272004-06-13 20:20:40 +00006178
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006179#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006180
6181/*
6182 * Start termcap mode
6183 */
6184 static void
6185termcap_mode_start(void)
6186{
6187 DWORD cmodein;
6188
6189 if (g_fTermcapMode)
6190 return;
6191
Christopher Plewright1140b512022-11-12 18:46:05 +00006192 // VTP uses alternate screen buffer.
6193 // Switch to a new alternate screen buffer.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00006194 // But, not if running in a nested terminal
6195 if (use_alternate_screen_buffer)
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006196 vtp_printf("\033[?1049h");
6197
Bram Moolenaar071d4272004-06-13 20:20:40 +00006198 SaveConsoleBuffer(&g_cbNonTermcap);
6199
6200 if (g_cbTermcap.IsValid)
6201 {
6202 /*
6203 * We've been in termcap mode before. Restore certain screen
6204 * characteristics, including the buffer size and the window
6205 * size. Since we will be redrawing the screen, we don't need
6206 * to restore the actual contents of the buffer.
6207 */
6208 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006209 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006210 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
6211 Rows = g_cbTermcap.Info.dwSize.Y;
6212 Columns = g_cbTermcap.Info.dwSize.X;
6213 }
6214 else
6215 {
6216 /*
6217 * This is our first time entering termcap mode. Clear the console
6218 * screen buffer, and resize the buffer to match the current window
6219 * size. We will use this as the size of our editing environment.
6220 */
6221 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006222 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006223 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
6224 }
6225
Bram Moolenaar071d4272004-06-13 20:20:40 +00006226 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006227
6228 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006229 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006230 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006231 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006232 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
6233 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006234 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006235 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006236 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006237 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6238 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006239 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006240 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006241
6242 redraw_later_clear();
6243 g_fTermcapMode = TRUE;
6244}
6245
6246
6247/*
6248 * End termcap mode
6249 */
6250 static void
6251termcap_mode_end(void)
6252{
6253 DWORD cmodein;
6254 ConsoleBuffer *cb;
6255 COORD coord;
6256 DWORD dwDummy;
6257
6258 if (!g_fTermcapMode)
6259 return;
6260
6261 SaveConsoleBuffer(&g_cbTermcap);
6262
6263 GetConsoleMode(g_hConIn, &cmodein);
6264 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006265 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6266 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006267
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006268# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01006269 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006270# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006271 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006272# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006273 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01006274 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006275
Christopher Plewright1140b512022-11-12 18:46:05 +00006276 // VTP uses alternate screen buffer.
6277 // Switch back to main screen buffer.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00006278 if (exiting && use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00006279 vtp_printf("\033[?1049l");
6280
6281 if (!USE_WT && (p_rs || exiting))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006282 {
6283 /*
6284 * Clear anything that happens to be on the current line.
6285 */
6286 coord.X = 0;
6287 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
Christopher Plewright1140b512022-11-12 18:46:05 +00006288 if (!vtp_working)
6289 FillConsoleOutputCharacter(g_hConOut, ' ',
6290 cb->Info.dwSize.X, coord, &dwDummy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006291 /*
6292 * The following is just for aesthetics. If we are exiting without
6293 * restoring the screen, then we want to have a prompt string
6294 * appear at the bottom line. However, the command interpreter
6295 * seems to always advance the cursor one line before displaying
6296 * the prompt string, which causes the screen to scroll. To
6297 * counter this, move the cursor up one line before exiting.
6298 */
6299 if (exiting && !p_rs)
6300 coord.Y--;
6301 /*
6302 * Position the cursor at the leftmost column of the desired row.
6303 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006304 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006305 }
Christopher Plewright1140b512022-11-12 18:46:05 +00006306 SetConsoleCursorInfo(g_hConOut, &g_cci);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006307 g_fTermcapMode = FALSE;
6308}
Christopher Plewright38804d62022-11-09 23:55:52 +00006309#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006310
6311
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006312#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006313 void
6314mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01006315 char_u *s UNUSED,
6316 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006317{
Bram Moolenaar0f873732019-12-05 20:28:46 +01006318 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00006319}
6320
6321#else
6322
6323/*
6324 * clear `n' chars, starting from `coord'
6325 */
6326 static void
6327clear_chars(
6328 COORD coord,
6329 DWORD n)
6330{
Christopher Plewright38804d62022-11-09 23:55:52 +00006331 if (!vtp_working)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006332 {
6333 DWORD dwDummy;
6334
6335 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
6336 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
6337 &dwDummy);
6338 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006339 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02006340 {
6341 set_console_color_rgb();
6342 gotoxy(coord.X + 1, coord.Y + 1);
6343 vtp_printf("\033[%dX", n);
6344 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006345}
6346
6347
6348/*
6349 * Clear the screen
6350 */
6351 static void
6352clear_screen(void)
6353{
6354 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006355
Christopher Plewright38804d62022-11-09 23:55:52 +00006356 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006357 clear_chars(g_coord, Rows * Columns);
6358 else
6359 {
6360 set_console_color_rgb();
6361 gotoxy(1, 1);
6362 vtp_printf("\033[2J");
6363 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006364}
6365
6366
6367/*
6368 * Clear to end of display
6369 */
6370 static void
6371clear_to_end_of_display(void)
6372{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006373 COORD save = g_coord;
6374
Christopher Plewright38804d62022-11-09 23:55:52 +00006375 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006376 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006377 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006378 else
6379 {
6380 set_console_color_rgb();
6381 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6382 vtp_printf("\033[0J");
6383
6384 gotoxy(save.X + 1, save.Y + 1);
6385 g_coord = save;
6386 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006387}
6388
6389
6390/*
6391 * Clear to end of line
6392 */
6393 static void
6394clear_to_end_of_line(void)
6395{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006396 COORD save = g_coord;
6397
Christopher Plewright38804d62022-11-09 23:55:52 +00006398 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006399 clear_chars(g_coord, Columns - g_coord.X);
6400 else
6401 {
6402 set_console_color_rgb();
6403 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6404 vtp_printf("\033[0K");
6405
6406 gotoxy(save.X + 1, save.Y + 1);
6407 g_coord = save;
6408 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006409}
6410
6411
6412/*
6413 * Scroll the scroll region up by `cLines' lines
6414 */
6415 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006416scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006417{
6418 COORD oldcoord = g_coord;
6419
6420 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6421 delete_lines(cLines);
6422
6423 g_coord = oldcoord;
6424}
6425
6426
6427/*
6428 * Set the scroll region
6429 */
6430 static void
6431set_scroll_region(
6432 unsigned left,
6433 unsigned top,
6434 unsigned right,
6435 unsigned bottom)
6436{
6437 if (left >= right
6438 || top >= bottom
6439 || right > (unsigned) Columns - 1
6440 || bottom > (unsigned) Rows - 1)
6441 return;
6442
6443 g_srScrollRegion.Left = left;
6444 g_srScrollRegion.Top = top;
6445 g_srScrollRegion.Right = right;
6446 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006447}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006448
Bram Moolenaar6982f422019-02-16 16:48:01 +01006449 static void
6450set_scroll_region_tb(
6451 unsigned top,
6452 unsigned bottom)
6453{
6454 if (top >= bottom || bottom > (unsigned)Rows - 1)
6455 return;
6456
6457 g_srScrollRegion.Top = top;
6458 g_srScrollRegion.Bottom = bottom;
6459}
6460
6461 static void
6462set_scroll_region_lr(
6463 unsigned left,
6464 unsigned right)
6465{
6466 if (left >= right || right > (unsigned)Columns - 1)
6467 return;
6468
6469 g_srScrollRegion.Left = left;
6470 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006471}
6472
6473
6474/*
6475 * Insert `cLines' lines at the current cursor position
6476 */
6477 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006478insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006479{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006480 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006481 COORD dest;
6482 CHAR_INFO fill;
6483
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006484 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6485
Bram Moolenaar6982f422019-02-16 16:48:01 +01006486 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006487 dest.Y = g_coord.Y + cLines;
6488
Bram Moolenaar6982f422019-02-16 16:48:01 +01006489 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006490 source.Top = g_coord.Y;
6491 source.Right = g_srScrollRegion.Right;
6492 source.Bottom = g_srScrollRegion.Bottom - cLines;
6493
Bram Moolenaar6982f422019-02-16 16:48:01 +01006494 clip.Left = g_srScrollRegion.Left;
6495 clip.Top = g_coord.Y;
6496 clip.Right = g_srScrollRegion.Right;
6497 clip.Bottom = g_srScrollRegion.Bottom;
6498
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006499 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006500 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006501# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006502 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006503# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006504 ))
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006505 fill.Attributes = g_attrCurrent;
6506 else
6507 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006508
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006509 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006510
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006511 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6512
Bram Moolenaar6982f422019-02-16 16:48:01 +01006513 // Here we have to deal with a win32 console flake: If the scroll
6514 // region looks like abc and we scroll c to a and fill with d we get
6515 // cbd... if we scroll block c one line at a time to a, we get cdd...
6516 // vim expects cdd consistently... So we have to deal with that
6517 // here... (this also occurs scrolling the same way in the other
6518 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006519
6520 if (source.Bottom < dest.Y)
6521 {
6522 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006523 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006524
Bram Moolenaar6982f422019-02-16 16:48:01 +01006525 coord.X = source.Left;
6526 for (i = clip.Top; i < dest.Y; ++i)
6527 {
6528 coord.Y = i;
6529 clear_chars(coord, source.Right - source.Left + 1);
6530 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006531 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006532
Christopher Plewright38804d62022-11-09 23:55:52 +00006533 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006534 {
6535 COORD coord;
6536 int i;
6537
6538 coord.X = source.Left;
6539 for (i = source.Top; i < dest.Y; ++i)
6540 {
6541 coord.Y = i;
6542 clear_chars(coord, source.Right - source.Left + 1);
6543 }
6544 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006545}
6546
6547
6548/*
6549 * Delete `cLines' lines at the current cursor position
6550 */
6551 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006552delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006553{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006554 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006555 COORD dest;
6556 CHAR_INFO fill;
6557 int nb;
6558
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006559 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6560
Bram Moolenaar6982f422019-02-16 16:48:01 +01006561 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006562 dest.Y = g_coord.Y;
6563
Bram Moolenaar6982f422019-02-16 16:48:01 +01006564 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006565 source.Top = g_coord.Y + cLines;
6566 source.Right = g_srScrollRegion.Right;
6567 source.Bottom = g_srScrollRegion.Bottom;
6568
Bram Moolenaar6982f422019-02-16 16:48:01 +01006569 clip.Left = g_srScrollRegion.Left;
6570 clip.Top = g_coord.Y;
6571 clip.Right = g_srScrollRegion.Right;
6572 clip.Bottom = g_srScrollRegion.Bottom;
6573
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006574 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006575 if (!vtp_working)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006576 fill.Attributes = g_attrCurrent;
6577 else
6578 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006579
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006580 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006581
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006582 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6583
Bram Moolenaar6982f422019-02-16 16:48:01 +01006584 // Here we have to deal with a win32 console flake; See insert_lines()
6585 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006586
6587 nb = dest.Y + (source.Bottom - source.Top) + 1;
6588
6589 if (nb < source.Top)
6590 {
6591 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006592 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006593
Bram Moolenaar6982f422019-02-16 16:48:01 +01006594 coord.X = source.Left;
6595 for (i = nb; i < clip.Bottom; ++i)
6596 {
6597 coord.Y = i;
6598 clear_chars(coord, source.Right - source.Left + 1);
6599 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006600 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006601
Christopher Plewright38804d62022-11-09 23:55:52 +00006602 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006603 {
6604 COORD coord;
6605 int i;
6606
6607 coord.X = source.Left;
6608 for (i = nb; i <= source.Bottom; ++i)
6609 {
6610 coord.Y = i;
6611 clear_chars(coord, source.Right - source.Left + 1);
6612 }
6613 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006614}
6615
6616
6617/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006618 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006619 */
6620 static void
6621gotoxy(
6622 unsigned x,
6623 unsigned y)
6624{
6625 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6626 return;
6627
Christopher Plewright38804d62022-11-09 23:55:52 +00006628 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006629# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006630 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006631# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006632 ))
Bram Moolenaar2313b612019-09-27 14:14:32 +02006633 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006634 // There are reports of double-width characters not displayed
6635 // correctly. This workaround should fix it, similar to how it's done
6636 // for VTP.
6637 g_coord.X = 0;
6638 SetConsoleCursorPosition(g_hConOut, g_coord);
6639
Bram Moolenaar2313b612019-09-27 14:14:32 +02006640 // external cursor coords are 1-based; internal are 0-based
6641 g_coord.X = x - 1;
6642 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006643 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006644 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006645 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006646 {
6647 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006648 // destruction. Insider build bug. Always enabled because it's cheap
6649 // and avoids mistakes with recognizing the build.
6650 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006651
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006652 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006653
6654 g_coord.X = x - 1;
6655 g_coord.Y = y - 1;
6656 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006657}
6658
6659
6660/*
6661 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006662 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006663 */
6664 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006665textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006666{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006667 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006668
6669 SetConsoleTextAttribute(g_hConOut, wAttr);
6670}
6671
6672
6673 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006674textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006675{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006676 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006677
Christopher Plewright38804d62022-11-09 23:55:52 +00006678 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006679 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6680 else
6681 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006682}
6683
6684
6685 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006686textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006687{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006688 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006689
Christopher Plewright38804d62022-11-09 23:55:52 +00006690 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006691 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6692 else
6693 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006694}
6695
6696
6697/*
6698 * restore the default text attribute (whatever we started with)
6699 */
6700 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006701normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006702{
Christopher Plewright38804d62022-11-09 23:55:52 +00006703 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006704 textattr(g_attrDefault);
6705 else
6706 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006707}
6708
6709
6710static WORD g_attrPreStandout = 0;
6711
6712/*
6713 * Make the text standout, by brightening it
6714 */
6715 static void
6716standout(void)
6717{
6718 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006719
Bram Moolenaar071d4272004-06-13 20:20:40 +00006720 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6721}
6722
6723
6724/*
6725 * Turn off standout mode
6726 */
6727 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006728standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006729{
6730 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006731 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006732
6733 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006734}
6735
6736
6737/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006738 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006739 */
6740 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006741mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006742{
6743 char_u *p;
6744 int n;
6745
6746 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6747 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006748 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006749# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006750 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006751# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006752 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006753 {
6754 p = T_ME + 2;
6755 n = getdigits(&p);
6756 if (*p == 'm' && n > 0)
6757 {
6758 cterm_normal_fg_color = (n & 0xf) + 1;
6759 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6760 }
6761 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006762# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006763 cterm_normal_fg_gui_color = INVALCOLOR;
6764 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006765# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006766}
6767
6768
6769/*
6770 * visual bell: flash the screen
6771 */
6772 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006773visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006774{
6775 COORD coordOrigin = {0, 0};
6776 WORD attrFlash = ~g_attrCurrent & 0xff;
6777
6778 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006779 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006780
6781 if (oldattrs == NULL)
6782 return;
6783 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6784 coordOrigin, &dwDummy);
6785 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6786 coordOrigin, &dwDummy);
6787
Bram Moolenaar0f873732019-12-05 20:28:46 +01006788 Sleep(15); // wait for 15 msec
Christopher Plewright38804d62022-11-09 23:55:52 +00006789 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006790 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006791 coordOrigin, &dwDummy);
6792 vim_free(oldattrs);
6793}
6794
6795
6796/*
6797 * Make the cursor visible or invisible
6798 */
6799 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006800cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006801{
6802 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006803
Christopher Plewright38804d62022-11-09 23:55:52 +00006804 if (vtp_working)
Bram Moolenaar2695de62020-04-17 21:13:01 +02006805 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6806
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006807# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006808 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006809# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006810}
6811
6812
6813/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006814 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006815 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006816 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006817 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006818write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006819 char_u *pchBuf,
6820 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006821{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006822 COORD coord = g_coord;
6823 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006824 DWORD n, cchwritten;
6825 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006826 static WCHAR *unicodebuf = NULL;
6827 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006828 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006829 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006830 static WCHAR *utf8spbuf = NULL;
6831 static int utf8splength;
6832 static DWORD utf8spcells;
6833 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006834
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006835 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006836 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006837 utf8usingbuf = &unicodebuf;
6838 do
6839 {
6840 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6841 unicodebuf, unibuflen);
6842 if (length && length <= unibuflen)
6843 break;
6844 vim_free(unicodebuf);
6845 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6846 unibuflen = unibuflen ? 0 : length;
6847 } while(1);
6848 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006849 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006850 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6851 {
6852 if (utf8usingbuf != &utf8spbuf)
6853 {
6854 if (utf8spbuf == NULL)
6855 {
6856 cells = mb_string2cells((char_u *)" ", 1);
6857 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6858 utf8spbuf = LALLOC_MULT(WCHAR, length);
6859 if (utf8spbuf != NULL)
6860 {
6861 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6862 utf8usingbuf = &utf8spbuf;
6863 utf8splength = length;
6864 utf8spcells = cells;
6865 }
6866 }
6867 else
6868 {
6869 utf8usingbuf = &utf8spbuf;
6870 length = utf8splength;
6871 cells = utf8spcells;
6872 }
6873 }
6874 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006875
Christopher Plewright38804d62022-11-09 23:55:52 +00006876 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006877# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006878 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006879# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006880 ))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006881 {
6882 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6883 coord, &written);
6884 // When writing fails or didn't write a single character, pretend one
6885 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006886 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006887 coord, &cchwritten) == 0
6888 || cchwritten == 0 || cchwritten == (DWORD)-1)
6889 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006890 }
6891 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006892 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006893 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006894 NULL) == 0 || cchwritten == 0)
6895 cchwritten = 1;
6896 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006897
K.Takata135e1522022-01-29 15:27:58 +00006898 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006899 {
6900 written = cbToWrite;
6901 g_coord.X += (SHORT)cells;
6902 }
6903 else
6904 {
6905 char_u *p = pchBuf;
6906 for (n = 0; n < cchwritten; n++)
6907 MB_CPTR_ADV(p);
6908 written = p - pchBuf;
6909 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006910 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006911
6912 while (g_coord.X > g_srScrollRegion.Right)
6913 {
6914 g_coord.X -= (SHORT) Columns;
6915 if (g_coord.Y < g_srScrollRegion.Bottom)
6916 g_coord.Y++;
6917 }
6918
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006919 // Cursor under VTP is always in the correct position, no need to reset.
Christopher Plewright38804d62022-11-09 23:55:52 +00006920 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006921# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006922 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006923# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006924 ))
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006925 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006926
6927 return written;
6928}
6929
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006930 static char_u *
6931get_seq(
6932 int *args,
6933 int *count,
6934 char_u *head)
6935{
6936 int argc;
6937 char_u *p;
6938
6939 if (head == NULL || *head != '\033')
6940 return NULL;
6941
6942 argc = 0;
6943 p = head;
6944 ++p;
6945 do
6946 {
6947 ++p;
6948 args[argc] = getdigits(&p);
6949 argc += (argc < 15) ? 1 : 0;
6950 } while (*p == ';');
6951 *count = argc;
6952
6953 return p;
6954}
6955
6956 static char_u *
6957get_sgr(
6958 int *args,
6959 int *count,
6960 char_u *head)
6961{
6962 char_u *p = get_seq(args, count, head);
6963
6964 return (p && *p == 'm') ? ++p : NULL;
6965}
6966
6967/*
6968 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6969 */
6970 static char_u *
6971sgrn2(
6972 char_u *head,
6973 int n)
6974{
6975 int argc;
6976 int args[16];
6977 char_u *p = get_sgr(args, &argc, head);
6978
6979 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6980}
6981
6982/*
6983 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6984 */
6985 static char_u *
6986sgrnc(
6987 char_u *head,
6988 int n)
6989{
6990 int argc;
6991 int args[16];
6992 char_u *p = get_sgr(args, &argc, head);
6993
6994 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6995 ? p : NULL;
6996}
6997
6998 static char_u *
6999skipblank(char_u *q)
7000{
7001 char_u *p = q;
7002
7003 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
7004 ++p;
7005 return p;
7006}
7007
7008/*
7009 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
7010 * NULL.
7011 */
7012 static char_u *
7013sgrn2c(
7014 char_u *head,
7015 int n)
7016{
7017 char_u *p = sgrn2(head, n);
7018
7019 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
7020}
7021
7022/*
7023 * If there is only a newline between the sequence immediately following it,
7024 * a pointer to the character following the newline is returned.
7025 * Otherwise NULL.
7026 */
7027 static char_u *
7028sgrn2cn(
7029 char_u *head,
7030 int n)
7031{
7032 char_u *p = sgrn2(head, n);
7033
7034 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
7035}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007036
7037/*
7038 * mch_write(): write the output buffer to the screen, translating ESC
7039 * sequences into calls to console output routines.
7040 */
7041 void
7042mch_write(
7043 char_u *s,
7044 int len)
7045{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007046 char_u *end = s + len;
7047
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007048# ifdef VIMDLL
7049 if (gui.in_use)
7050 return;
7051# endif
7052
Bram Moolenaar071d4272004-06-13 20:20:40 +00007053 if (!term_console)
7054 {
7055 write(1, s, (unsigned)len);
7056 return;
7057 }
7058
Bram Moolenaar0f873732019-12-05 20:28:46 +01007059 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00007060 while (len--)
7061 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007062 int prefix = -1;
7063 char_u ch;
7064
7065 // While processing a sequence, on rare occasions it seems that another
7066 // sequence may be inserted asynchronously.
7067 if (len < 0)
7068 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01007069 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007070 return;
7071 }
7072
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007073 while (s + ++prefix < end)
7074 {
7075 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007076 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
7077 && ch != '\a' && ch != '\033'))
7078 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007079 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007080
7081 if (p_wd)
7082 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007083 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007084 if (prefix != 0)
7085 prefix = 1;
7086 }
7087
7088 if (prefix != 0)
7089 {
7090 DWORD nWritten;
7091
7092 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007093# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007094 if (fdDump)
7095 {
7096 fputc('>', fdDump);
7097 fwrite(s, sizeof(char_u), nWritten, fdDump);
7098 fputs("<\n", fdDump);
7099 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007100# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007101 len -= (nWritten - 1);
7102 s += nWritten;
7103 }
7104 else if (s[0] == '\n')
7105 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007106 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00007107 if (g_coord.Y == g_srScrollRegion.Bottom)
7108 {
7109 scroll(1);
7110 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
7111 }
7112 else
7113 {
7114 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
7115 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007116# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007117 if (fdDump)
7118 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007119# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007120 s++;
7121 }
7122 else if (s[0] == '\r')
7123 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007124 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00007125 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007126# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007127 if (fdDump)
7128 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007129# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007130 s++;
7131 }
7132 else if (s[0] == '\b')
7133 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007134 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00007135 if (g_coord.X > g_srScrollRegion.Left)
7136 g_coord.X--;
7137 else if (g_coord.Y > g_srScrollRegion.Top)
7138 {
7139 g_coord.X = g_srScrollRegion.Right;
7140 g_coord.Y--;
7141 }
7142 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007143# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007144 if (fdDump)
7145 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007146# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007147 s++;
7148 }
7149 else if (s[0] == '\a')
7150 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007151 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00007152 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007153# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007154 if (fdDump)
7155 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007156# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007157 s++;
7158 }
7159 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
7160 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007161# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007162 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007163# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007164 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007165 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007166 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007167
7168 switch (s[2])
7169 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007170 case '0': case '1': case '2': case '3': case '4':
7171 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007172 if (*(p = get_seq(args, &argc, s)) != 'm')
7173 goto notsgr;
7174
7175 p = s;
7176
7177 // Handling frequent optional sequences. Output to the screen
7178 // takes too long, so do not output as much as possible.
7179
7180 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
7181 // resetFG,FG,BG are omitted.
7182 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007183 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007184 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
7185 len = len + 1 - (int)(p - s);
7186 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007187 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007188 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007189
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007190 // If FG,BG,BG,FG of SGR are connected, the first FG can be
7191 // omitted.
7192 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
7193 p = sp;
7194
7195 // If FG,BG,FG,BG of SGR are connected, the first FG can be
7196 // omitted.
7197 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
7198 p = sp;
7199
7200 // If BG,BG of SGR are connected, the first BG can be omitted.
7201 if (sgrn2((sp = sgrn2(p, 48)), 48))
7202 p = sp;
7203
7204 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007205 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007206 if (sgrn2((sp = sgrnc(p, 39)), 38))
7207 p = sp;
7208
7209 p = get_seq(args, &argc, p);
7210
7211notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007212 arg1 = args[0];
7213 arg2 = args[1];
7214 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007215 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007216 if (argc == 1 && args[0] == 0)
7217 normvideo();
7218 else if (argc == 1)
7219 {
Christopher Plewright38804d62022-11-09 23:55:52 +00007220 if (vtp_working
7221# ifdef FEAT_TERMGUICOLORS
7222 && (p_tgc || t_colors >= 256)
7223# endif
7224 )
7225 textcolor((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007226 else
Christopher Plewright38804d62022-11-09 23:55:52 +00007227 textattr((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007228 }
Christopher Plewright38804d62022-11-09 23:55:52 +00007229 else if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007230 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007231 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007232 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007233 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007234 gotoxy(arg2, arg1);
7235 }
7236 else if (argc == 2 && *p == 'r')
7237 {
7238 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
7239 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01007240 else if (argc == 2 && *p == 'R')
7241 {
7242 set_scroll_region_tb(arg1, arg2);
7243 }
7244 else if (argc == 2 && *p == 'V')
7245 {
7246 set_scroll_region_lr(arg1, arg2);
7247 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007248 else if (argc == 1 && *p == 'A')
7249 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007250 gotoxy(g_coord.X + 1,
7251 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
7252 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007253 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007254 {
7255 textbackground((WORD) arg1);
7256 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007257 else if (argc == 1 && *p == 'C')
7258 {
7259 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
7260 g_coord.Y + 1);
7261 }
7262 else if (argc == 1 && *p == 'f')
7263 {
7264 textcolor((WORD) arg1);
7265 }
7266 else if (argc == 1 && *p == 'H')
7267 {
7268 gotoxy(1, arg1);
7269 }
7270 else if (argc == 1 && *p == 'L')
7271 {
7272 insert_lines(arg1);
7273 }
7274 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007275 {
7276 delete_lines(arg1);
7277 }
7278
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007279 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007280 s = p + 1;
7281 break;
7282
Bram Moolenaar071d4272004-06-13 20:20:40 +00007283 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007284 gotoxy(g_coord.X + 1,
7285 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
7286 goto got3;
7287
7288 case 'B':
7289 visual_bell();
7290 goto got3;
7291
7292 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007293 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
7294 g_coord.Y + 1);
7295 goto got3;
7296
7297 case 'E':
7298 termcap_mode_end();
7299 goto got3;
7300
7301 case 'F':
7302 standout();
7303 goto got3;
7304
7305 case 'f':
7306 standend();
7307 goto got3;
7308
7309 case 'H':
7310 gotoxy(1, 1);
7311 goto got3;
7312
7313 case 'j':
7314 clear_to_end_of_display();
7315 goto got3;
7316
7317 case 'J':
7318 clear_screen();
7319 goto got3;
7320
7321 case 'K':
7322 clear_to_end_of_line();
7323 goto got3;
7324
7325 case 'L':
7326 insert_lines(1);
7327 goto got3;
7328
7329 case 'M':
7330 delete_lines(1);
7331 goto got3;
7332
7333 case 'S':
7334 termcap_mode_start();
7335 goto got3;
7336
7337 case 'V':
7338 cursor_visible(TRUE);
7339 goto got3;
7340
7341 case 'v':
7342 cursor_visible(FALSE);
7343 goto got3;
7344
7345 got3:
7346 s += 3;
7347 len -= 2;
7348 }
7349
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007350# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007351 if (fdDump)
7352 {
7353 fputs("ESC | ", fdDump);
7354 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
7355 fputc('\n', fdDump);
7356 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007357# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007358 }
K.Takatadf5320c2022-09-01 13:20:16 +01007359 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
7360 {
7361 int l = 2;
7362
7363 if (isdigit(s[l]))
7364 l++;
7365 if (s[l] == ' ' && s[l + 1] == 'q')
7366 {
7367 // DECSCUSR (cursor style) sequences
Christopher Plewright38804d62022-11-09 23:55:52 +00007368 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01007369 vtp_printf("%.*s", l + 2, s); // Pass through
7370 s += l + 2;
7371 len -= l + 1;
7372 }
7373 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007374 else
7375 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007376 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00007377 DWORD nWritten;
7378
7379 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007380# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007381 if (fdDump)
7382 {
7383 fputc('>', fdDump);
7384 fwrite(s, sizeof(char_u), nWritten, fdDump);
7385 fputs("<\n", fdDump);
7386 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007387# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007388
7389 len -= (nWritten - 1);
7390 s += nWritten;
7391 }
7392 }
7393
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007394# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007395 if (fdDump)
7396 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007397# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007398}
7399
Bram Moolenaar0f873732019-12-05 20:28:46 +01007400#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00007401
7402
7403/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01007404 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007405 */
7406 void
7407mch_delay(
7408 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02007409 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007410{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007411#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007412 Sleep((int)msec); // never wait for input
7413#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007414# ifdef VIMDLL
7415 if (gui.in_use)
7416 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007417 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007418 return;
7419 }
7420# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02007421 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007422# ifdef FEAT_MZSCHEME
7423 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
7424 {
7425 int towait = p_mzq;
7426
Bram Moolenaar0f873732019-12-05 20:28:46 +01007427 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007428 while (msec > 0)
7429 {
7430 mzvim_check_threads();
7431 if (msec < towait)
7432 towait = msec;
7433 Sleep(towait);
7434 msec -= towait;
7435 }
7436 }
7437 else
7438# endif
7439 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007440 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007441 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007442#endif
7443}
7444
7445
7446/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01007447 * This version of remove is not scared by a readonly (backup) file.
7448 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007449 * Return 0 for success, -1 for failure.
7450 */
7451 int
7452mch_remove(char_u *name)
7453{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007454 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007455 int n;
7456
Bram Moolenaar203258c2016-01-17 22:15:16 +01007457 /*
7458 * On Windows, deleting a directory's symbolic link is done by
7459 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
7460 */
7461 if (mch_isdir(name) && mch_is_symbolic_link(name))
7462 return mch_rmdir(name);
7463
Bram Moolenaar12b559e2013-06-12 22:41:37 +02007464 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
7465
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007466 wn = enc_to_utf16(name, NULL);
7467 if (wn == NULL)
7468 return -1;
7469
7470 n = DeleteFileW(wn) ? 0 : -1;
7471 vim_free(wn);
7472 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007473}
7474
7475
7476/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007477 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007478 */
7479 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007480mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007481{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007482#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7483# ifdef VIMDLL
7484 if (!gui.in_use)
7485# endif
7486 if (g_fCtrlCPressed || g_fCBrkPressed)
7487 {
7488 ctrl_break_was_pressed = g_fCBrkPressed;
7489 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7490 got_int = TRUE;
7491 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007492#endif
7493}
7494
Bram Moolenaar0f873732019-12-05 20:28:46 +01007495// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007496#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007497
7498/*
7499 * How much main memory in KiB that can be used by VIM.
7500 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007501 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007502mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007503{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007504 MEMORYSTATUSEX ms;
7505
Bram Moolenaar0f873732019-12-05 20:28:46 +01007506 // Need to use GlobalMemoryStatusEx() when there is more memory than
7507 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007508 ms.dwLength = sizeof(MEMORYSTATUSEX);
7509 GlobalMemoryStatusEx(&ms);
7510 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007511 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007512 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007513 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007514 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007515 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007516 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007517 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007518 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007519 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007520 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007521 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007522}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007523
Bram Moolenaar071d4272004-06-13 20:20:40 +00007524/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007525 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00007526 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
7527 * file whose short file name is "FOO.BAR" (its long file name will
7528 * be correct: "foo.bar~"). Because a file can be accessed by
7529 * either its SFN or its LFN, "foo.bar" has effectively been
7530 * renamed to "foo.bar", which is not at all what was wanted. This
7531 * seems to happen only when renaming files with three-character
7532 * extensions by appending a suffix that does not include ".".
7533 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
7534 *
7535 * There is another problem, which isn't really a bug but isn't right either:
7536 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
7537 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
7538 * service pack 6. Doesn't seem to happen on Windows 98.
7539 *
7540 * Like rename(), returns 0 upon success, non-zero upon failure.
7541 * Should probably set errno appropriately when errors occur.
7542 */
7543 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007544mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007545{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007546 WCHAR *p;
7547 int i;
7548 WCHAR szTempFile[_MAX_PATH + 1];
7549 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007550 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007551
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007552 // No need to play tricks unless the file name contains a "~" as the
7553 // seventh character.
7554 p = wold;
7555 for (i = 0; wold[i] != NUL; ++i)
7556 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
7557 && wold[i + 1] != 0)
7558 p = wold + i + 1;
7559 if ((int)(wold + i - p) < 8 || p[6] != '~')
7560 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007561
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007562 // Get base path of new file name. Undocumented feature: If pszNewFile is
7563 // a directory, no error is returned and pszFilePart will be NULL.
7564 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007565 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007566 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007567
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007568 // Get (and create) a unique temporary file name in directory of new file
7569 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007570 return -2;
7571
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007572 // blow the temp file away
7573 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007574 return -3;
7575
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007576 // rename old file to the temp file
7577 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007578 return -4;
7579
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007580 // now create an empty file called pszOldFile; this prevents the operating
7581 // system using pszOldFile as an alias (SFN) if we're renaming within the
7582 // same directory. For example, we're editing a file called
7583 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7584 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7585 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7586 // cause all sorts of problems later in buf_write(). So, we create an
7587 // empty file called filena~1.txt and the system will have to find some
7588 // other SFN for filena~1.txt~, such as filena~2.txt
7589 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007590 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7591 return -5;
7592 if (!CloseHandle(hf))
7593 return -6;
7594
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007595 // rename the temp file to the new file
7596 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007597 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007598 // Renaming failed. Rename the file back to its old name, so that it
7599 // looks like nothing happened.
7600 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007601 return -7;
7602 }
7603
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007604 // Seems to be left around on Novell filesystems
7605 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007606
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007607 // finally, remove the empty old file
7608 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007609 return -8;
7610
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007611 return 0;
7612}
7613
7614
7615/*
7616 * Converts the filenames to UTF-16, then call mch_wrename().
7617 * Like rename(), returns 0 upon success, non-zero upon failure.
7618 */
7619 int
7620mch_rename(
7621 const char *pszOldFile,
7622 const char *pszNewFile)
7623{
7624 WCHAR *wold = NULL;
7625 WCHAR *wnew = NULL;
7626 int retval = -1;
7627
7628 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7629 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7630 if (wold != NULL && wnew != NULL)
7631 retval = mch_wrename(wold, wnew);
7632 vim_free(wold);
7633 vim_free(wnew);
7634 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007635}
7636
7637/*
7638 * Get the default shell for the current hardware platform
7639 */
7640 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007641default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007642{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007643 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007644}
7645
7646/*
7647 * mch_access() extends access() to do more detailed check on network drives.
7648 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7649 */
7650 int
7651mch_access(char *n, int p)
7652{
7653 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007654 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007655 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007656
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007657 wn = enc_to_utf16((char_u *)n, NULL);
7658 if (wn == NULL)
7659 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007660
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007661 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007662 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007663 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007664
7665 if (p & R_OK)
7666 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007667 // Read check is performed by seeing if we can do a find file on
7668 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007669 int i;
7670 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007671
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007672 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7673 TempNameW[i] = wn[i];
7674 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7675 TempNameW[i++] = '\\';
7676 TempNameW[i++] = '*';
7677 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007678
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007679 hFile = FindFirstFileW(TempNameW, &d);
7680 if (hFile == INVALID_HANDLE_VALUE)
7681 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007682 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007683 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007684 }
7685
7686 if (p & W_OK)
7687 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007688 // Trying to create a temporary file in the directory should catch
7689 // directories on read-only network shares. However, in
7690 // directories whose ACL allows writes but denies deletes will end
7691 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007692 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7693 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007694 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007695 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007696 }
7697 }
7698 else
7699 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007700 // Don't consider a file read-only if another process has opened it.
7701 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7702
Bram Moolenaar0f873732019-12-05 20:28:46 +01007703 // Trying to open the file for the required access does ACL, read-only
7704 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007705 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7706 | ((p & R_OK) ? GENERIC_READ : 0);
7707
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007708 hFile = CreateFileW(wn, access_mode, share_mode,
7709 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007710 if (hFile == INVALID_HANDLE_VALUE)
7711 goto getout;
7712 CloseHandle(hFile);
7713 }
7714
Bram Moolenaar0f873732019-12-05 20:28:46 +01007715 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007716getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007717 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007718 return retval;
7719}
7720
Bram Moolenaar071d4272004-06-13 20:20:40 +00007721/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007722 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007723 */
7724 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007725mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007726{
7727 WCHAR *wn;
7728 int f;
7729
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007730 wn = enc_to_utf16((char_u *)name, NULL);
7731 if (wn == NULL)
7732 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007733
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007734 f = _wopen(wn, flags, mode);
7735 vim_free(wn);
7736 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007737}
7738
7739/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007740 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007741 */
7742 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007743mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007744{
7745 WCHAR *wn, *wm;
7746 FILE *f = NULL;
7747
Bram Moolenaara12a1612019-01-24 16:39:02 +01007748#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007749 // Work around an annoying assertion in the Microsoft debug CRT
7750 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007751 char newMode = mode[strlen(mode) - 1];
7752 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007753
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007754 _get_fmode(&oldMode);
7755 if (newMode == 't')
7756 _set_fmode(_O_TEXT);
7757 else if (newMode == 'b')
7758 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007759#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007760 wn = enc_to_utf16((char_u *)name, NULL);
7761 wm = enc_to_utf16((char_u *)mode, NULL);
7762 if (wn != NULL && wm != NULL)
7763 f = _wfopen(wn, wm);
7764 vim_free(wn);
7765 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007766
Bram Moolenaara12a1612019-01-24 16:39:02 +01007767#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007768 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007769#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007770 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007771}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007772
Bram Moolenaar071d4272004-06-13 20:20:40 +00007773/*
7774 * SUB STREAM (aka info stream) handling:
7775 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007776 * NTFS can have sub streams for each file. The normal contents of a file is
7777 * stored in the main stream, and extra contents (author information, title and
7778 * so on) can be stored in a sub stream. After Windows 2000, the user can
7779 * access and store this information in sub streams via an explorer's property
7780 * menu item in the right click menu. This information in sub streams was lost
7781 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007782 *
7783 * Incomplete explanation:
7784 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7785 * More useful info and an example:
7786 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7787 */
7788
7789/*
7790 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7791 * and write to stream "substream" of file "to".
7792 * Errors are ignored.
7793 */
7794 static void
7795copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7796{
7797 HANDLE hTo;
7798 WCHAR *to_name;
7799
7800 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7801 wcscpy(to_name, to);
7802 wcscat(to_name, substream);
7803
7804 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7805 FILE_ATTRIBUTE_NORMAL, NULL);
7806 if (hTo != INVALID_HANDLE_VALUE)
7807 {
7808 long done;
7809 DWORD todo;
7810 DWORD readcnt, written;
7811 char buf[4096];
7812
Bram Moolenaar0f873732019-12-05 20:28:46 +01007813 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007814 for (done = 0; done < len; done += written)
7815 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007816 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007817 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7818 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007819 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7820 FALSE, FALSE, context)
7821 || readcnt != todo
7822 || !WriteFile(hTo, buf, todo, &written, NULL)
7823 || written != todo)
7824 break;
7825 }
7826 CloseHandle(hTo);
7827 }
7828
7829 free(to_name);
7830}
7831
7832/*
7833 * Copy info streams from file "from" to file "to".
7834 */
7835 static void
7836copy_infostreams(char_u *from, char_u *to)
7837{
7838 WCHAR *fromw;
7839 WCHAR *tow;
7840 HANDLE sh;
7841 WIN32_STREAM_ID sid;
7842 int headersize;
7843 WCHAR streamname[_MAX_PATH];
7844 DWORD readcount;
7845 void *context = NULL;
7846 DWORD lo, hi;
7847 int len;
7848
Bram Moolenaar0f873732019-12-05 20:28:46 +01007849 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007850 fromw = enc_to_utf16(from, NULL);
7851 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007852 if (fromw != NULL && tow != NULL)
7853 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007854 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007855 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7856 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7857 if (sh != INVALID_HANDLE_VALUE)
7858 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007859 // Use BackupRead() to find the info streams. Repeat until we
7860 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007861 for (;;)
7862 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007863 // Get the header to find the length of the stream name. If
7864 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007865 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007866 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007867 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7868 &readcount, FALSE, FALSE, &context)
7869 || readcount == 0)
7870 break;
7871
Bram Moolenaar0f873732019-12-05 20:28:46 +01007872 // We only deal with streams that have a name. The normal
7873 // file data appears to be without a name, even though docs
7874 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007875 if (sid.dwStreamNameSize > 0)
7876 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007877 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007878 if (!BackupRead(sh, (LPBYTE)streamname,
7879 sid.dwStreamNameSize,
7880 &readcount, FALSE, FALSE, &context))
7881 break;
7882
Bram Moolenaar0f873732019-12-05 20:28:46 +01007883 // Copy an info stream with a name ":anything:$DATA".
7884 // Skip "::$DATA", it has no stream name (examples suggest
7885 // it might be used for the normal file contents).
7886 // Note that BackupRead() counts bytes, but the name is in
7887 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007888 len = readcount / sizeof(WCHAR);
7889 streamname[len] = 0;
7890 if (len > 7 && wcsicmp(streamname + len - 6,
7891 L":$DATA") == 0)
7892 {
7893 streamname[len - 6] = 0;
7894 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007895 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007896 }
7897 }
7898
Bram Moolenaar0f873732019-12-05 20:28:46 +01007899 // Advance to the next stream. We might try seeking too far,
7900 // but BackupSeek() doesn't skip over stream borders, thus
7901 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007902 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007903 &lo, &hi, &context);
7904 }
7905
Bram Moolenaar0f873732019-12-05 20:28:46 +01007906 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007907 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7908
7909 CloseHandle(sh);
7910 }
7911 }
7912 vim_free(fromw);
7913 vim_free(tow);
7914}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007915
7916/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007917 * ntdll.dll definitions
7918 */
7919#define FileEaInformation 7
7920#ifndef STATUS_SUCCESS
7921# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7922#endif
7923
7924typedef struct _FILE_FULL_EA_INFORMATION_ {
7925 ULONG NextEntryOffset;
7926 UCHAR Flags;
7927 UCHAR EaNameLength;
7928 USHORT EaValueLength;
7929 CHAR EaName[1];
7930} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7931
7932typedef struct _FILE_EA_INFORMATION_ {
7933 ULONG EaSize;
7934} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7935
Paul Ollis65745772022-06-05 16:55:54 +01007936#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007937typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7938 PHANDLE FileHandle,
7939 ACCESS_MASK DesiredAccess,
7940 POBJECT_ATTRIBUTES ObjectAttributes,
7941 PIO_STATUS_BLOCK IoStatusBlock,
7942 ULONG ShareAccess,
7943 ULONG OpenOptions);
7944typedef NTSTATUS (NTAPI *PfnNtClose)(
7945 HANDLE Handle);
7946typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007947 HANDLE FileHandle,
7948 PIO_STATUS_BLOCK IoStatusBlock,
7949 PVOID Buffer,
7950 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007951typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7952 HANDLE FileHandle,
7953 PIO_STATUS_BLOCK IoStatusBlock,
7954 PVOID Buffer,
7955 ULONG Length,
7956 BOOLEAN ReturnSingleEntry,
7957 PVOID EaList,
7958 ULONG EaListLength,
7959 PULONG EaIndex,
7960 BOOLEAN RestartScan);
7961typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007962 HANDLE FileHandle,
7963 PIO_STATUS_BLOCK IoStatusBlock,
7964 PVOID FileInformation,
7965 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007966 FILE_INFORMATION_CLASS FileInformationClass);
7967typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7968 PUNICODE_STRING DestinationString,
7969 PCWSTR SourceString);
7970
7971PfnNtOpenFile pNtOpenFile = NULL;
7972PfnNtClose pNtClose = NULL;
7973PfnNtSetEaFile pNtSetEaFile = NULL;
7974PfnNtQueryEaFile pNtQueryEaFile = NULL;
7975PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7976PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01007977#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007978
7979/*
7980 * Load ntdll.dll functions.
7981 */
7982 static BOOL
7983load_ntdll(void)
7984{
7985 static int loaded = -1;
7986
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00007987 if (loaded != -1)
7988 return (BOOL) loaded;
7989
7990 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7991 if (hNtdll != NULL)
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007992 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00007993 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7994 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7995 pNtSetEaFile = (PfnNtSetEaFile)
7996 GetProcAddress(hNtdll, "NtSetEaFile");
7997 pNtQueryEaFile = (PfnNtQueryEaFile)
7998 GetProcAddress(hNtdll, "NtQueryEaFile");
7999 pNtQueryInformationFile = (PfnNtQueryInformationFile)
8000 GetProcAddress(hNtdll, "NtQueryInformationFile");
8001 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
8002 GetProcAddress(hNtdll, "RtlInitUnicodeString");
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008003 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008004 if (pNtOpenFile == NULL
8005 || pNtClose == NULL
8006 || pNtSetEaFile == NULL
8007 || pNtQueryEaFile == NULL
8008 || pNtQueryInformationFile == NULL
8009 || pRtlInitUnicodeString == NULL)
8010 loaded = FALSE;
8011 else
8012 loaded = TRUE;
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008013 return (BOOL) loaded;
8014}
8015
8016/*
8017 * Copy extended attributes (EA) from file "from" to file "to".
8018 */
8019 static void
8020copy_extattr(char_u *from, char_u *to)
8021{
8022 char_u *fromf = NULL;
8023 char_u *tof = NULL;
8024 WCHAR *fromw = NULL;
8025 WCHAR *tow = NULL;
8026 UNICODE_STRING u;
8027 HANDLE h;
8028 OBJECT_ATTRIBUTES oa;
8029 IO_STATUS_BLOCK iosb;
8030 FILE_EA_INFORMATION_ eainfo = {0};
8031 void *ea = NULL;
8032
8033 if (!load_ntdll())
8034 return;
8035
8036 // Convert the file names to the fully qualified object names.
8037 fromf = alloc(STRLEN(from) + 5);
8038 tof = alloc(STRLEN(to) + 5);
8039 if (fromf == NULL || tof == NULL)
8040 goto theend;
8041 STRCPY(fromf, "\\??\\");
8042 STRCAT(fromf, from);
8043 STRCPY(tof, "\\??\\");
8044 STRCAT(tof, to);
8045
8046 // Convert the names to wide characters.
8047 fromw = enc_to_utf16(fromf, NULL);
8048 tow = enc_to_utf16(tof, NULL);
8049 if (fromw == NULL || tow == NULL)
8050 goto theend;
8051
8052 // Get the EA.
8053 pRtlInitUnicodeString(&u, fromw);
8054 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8055 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
8056 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8057 goto theend;
8058 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
8059 FileEaInformation);
8060 if (eainfo.EaSize != 0)
8061 {
8062 ea = alloc(eainfo.EaSize);
8063 if (ea != NULL)
8064 {
8065 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
8066 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
8067 {
8068 vim_free(ea);
8069 ea = NULL;
8070 }
8071 }
8072 }
8073 pNtClose(h);
8074
8075 // Set the EA.
8076 if (ea != NULL)
8077 {
8078 pRtlInitUnicodeString(&u, tow);
8079 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8080 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
8081 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8082 goto theend;
8083
8084 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
8085 pNtClose(h);
8086 }
8087
8088theend:
8089 vim_free(fromf);
8090 vim_free(tof);
8091 vim_free(fromw);
8092 vim_free(tow);
8093 vim_free(ea);
8094}
8095
8096/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008097 * Copy file attributes from file "from" to file "to".
8098 * For Windows NT and later we copy info streams.
8099 * Always returns zero, errors are ignored.
8100 */
8101 int
8102mch_copy_file_attribute(char_u *from, char_u *to)
8103{
Bram Moolenaar0f873732019-12-05 20:28:46 +01008104 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02008105 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008106 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008107 return 0;
8108}
8109
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008110
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008111/*
K.Takatadc73b4b2021-06-08 18:32:36 +02008112 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008113 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008114static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008115static LPWSTR *ArglistW = NULL;
8116static int global_argc = 0;
8117static char **global_argv;
8118
Bram Moolenaar0f873732019-12-05 20:28:46 +01008119static int used_file_argc = 0; // last argument in global_argv[] used
8120 // for the argument list.
8121static int *used_file_indexes = NULL; // indexes in global_argv[] for
8122 // command line arguments added to
8123 // the argument list
8124static int used_file_count = 0; // nr of entries in used_file_indexes
8125static int used_file_literal = FALSE; // take file names literally
8126static int used_file_full_path = FALSE; // file name was full path
8127static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008128static int used_alist_count = 0;
8129
8130
8131/*
8132 * Get the command line arguments. Unicode version.
8133 * Returns argc. Zero when something fails.
8134 */
8135 int
8136get_cmd_argsW(char ***argvp)
8137{
8138 char **argv = NULL;
8139 int argc = 0;
8140 int i;
8141
Bram Moolenaar14993322014-09-09 12:25:33 +02008142 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008143 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
8144 if (ArglistW != NULL)
8145 {
8146 argv = malloc((nArgsW + 1) * sizeof(char *));
8147 if (argv != NULL)
8148 {
8149 argc = nArgsW;
8150 argv[argc] = NULL;
8151 for (i = 0; i < argc; ++i)
8152 {
8153 int len;
8154
K.Takatadc73b4b2021-06-08 18:32:36 +02008155 // Convert each Unicode argument to UTF-8.
8156 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008157 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008158 (LPSTR *)&argv[i], &len, 0, 0);
8159 if (argv[i] == NULL)
8160 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008161 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008162 while (i > 0)
8163 free(argv[--i]);
8164 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01008165 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008166 argc = 0;
8167 }
8168 }
8169 }
8170 }
8171
8172 global_argc = argc;
8173 global_argv = argv;
8174 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02008175 {
8176 if (used_file_indexes != NULL)
8177 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008178 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02008179 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008180
8181 if (argvp != NULL)
8182 *argvp = argv;
8183 return argc;
8184}
8185
8186 void
8187free_cmd_argsW(void)
8188{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008189 if (ArglistW == NULL)
8190 return;
8191
8192 GlobalFree(ArglistW);
8193 ArglistW = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008194}
8195
8196/*
8197 * Remember "name" is an argument that was added to the argument list.
8198 * This avoids that we have to re-parse the argument list when fix_arg_enc()
8199 * is called.
8200 */
8201 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008202used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008203{
8204 int i;
8205
8206 if (used_file_indexes == NULL)
8207 return;
8208 for (i = used_file_argc + 1; i < global_argc; ++i)
8209 if (STRCMP(global_argv[i], name) == 0)
8210 {
8211 used_file_argc = i;
8212 used_file_indexes[used_file_count++] = i;
8213 break;
8214 }
8215 used_file_literal = literal;
8216 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008217 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008218}
8219
8220/*
8221 * Remember the length of the argument list as it was. If it changes then we
8222 * leave it alone when 'encoding' is set.
8223 */
8224 void
8225set_alist_count(void)
8226{
8227 used_alist_count = GARGCOUNT;
8228}
8229
8230/*
8231 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02008232 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008233 * and convert them to 'encoding'.
8234 */
8235 void
8236fix_arg_enc(void)
8237{
8238 int i;
8239 int idx;
8240 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00008241 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008242
Bram Moolenaar0f873732019-12-05 20:28:46 +01008243 // Safety checks:
8244 // - if argument count differs between the wide and non-wide argument
8245 // list, something must be wrong.
8246 // - the file name arguments must have been located.
8247 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008248 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008249 || ArglistW == NULL
8250 || used_file_indexes == NULL
8251 || used_file_count == 0
8252 || used_alist_count != GARGCOUNT)
8253 return;
8254
Bram Moolenaar0f873732019-12-05 20:28:46 +01008255 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02008256 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008257 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008258 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00008259 for (i = 0; i < GARGCOUNT; ++i)
8260 fnum_list[i] = GARGLIST[i].ae_fnum;
8261
Bram Moolenaar0f873732019-12-05 20:28:46 +01008262 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008263 alist_clear(&global_alist);
8264 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008265 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008266
8267 for (i = 0; i < used_file_count; ++i)
8268 {
8269 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008270 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008271 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00008272 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008273 int literal = used_file_literal;
8274
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008275#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01008276 // When using diff mode may need to concatenate file name to
8277 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008278 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
8279 && !mch_isdir(alist_name(&GARGLIST[0])))
8280 {
8281 char_u *r;
8282
8283 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
8284 if (r != NULL)
8285 {
8286 vim_free(str);
8287 str = r;
8288 }
8289 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008290#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01008291 // Re-use the old buffer by renaming it. When not using literal
8292 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00008293 if (used_file_literal)
8294 buf_set_name(fnum_list[i], str);
8295
Bram Moolenaar0f873732019-12-05 20:28:46 +01008296 // Check backtick literal. backtick literal is already expanded in
8297 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008298 if (literal == FALSE)
8299 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02008300 size_t len = STRLEN(str);
8301
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008302 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
8303 literal = TRUE;
8304 }
8305 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008306 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008307 }
8308
8309 if (!used_file_literal)
8310 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008311 // Now expand wildcards in the arguments.
8312 // Temporarily add '(' and ')' to 'isfname'. These are valid
8313 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00008314 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01008315 // Also, unset wildignore to not be influenced by this option.
8316 // The arguments specified in command-line should be kept even if
8317 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00008318 // Use :legacy so that it also works when in Vim9 script.
8319 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
8320 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00008321 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00008322 do_cmdline_cmd(
8323 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
8324 do_cmdline_cmd(
8325 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008326 }
8327
Bram Moolenaar0f873732019-12-05 20:28:46 +01008328 // If wildcard expansion failed, we are editing the first file of the
8329 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008330 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
8331 {
8332 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00008333 if (GARGCOUNT == 1 && used_file_full_path
8334 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
8335 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008336 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00008337
8338 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008339}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008340
8341 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02008342mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008343{
8344 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008345 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008346
Bram Moolenaar964b3742019-05-24 18:54:09 +02008347 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008348 if (envbuf == NULL)
8349 return -1;
8350
8351 sprintf((char *)envbuf, "%s=%s", var, value);
8352
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008353 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008354
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008355 vim_free(envbuf);
8356 if (p == NULL)
8357 return -1;
8358 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008359#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008360 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008361#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008362 // Unlike Un*x systems, we can free the string for _wputenv().
8363 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008364
8365 return 0;
8366}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008367
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008368/*
8369 * Support for 256 colors and 24-bit colors was added in Windows 10
8370 * version 1703 (Creators update).
8371 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008372#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
8373
8374/*
8375 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02008376 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008377 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008378#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008379
8380/*
8381 * ConPTY differences between versions, need different logic.
8382 * version 1903 (May 2019 update).
8383 */
8384#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
8385
8386/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008387 * version 1909 (November 2019 update).
8388 */
8389#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
8390
8391/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008392 * Stay ahead of the next update, and when it's done, fix this.
8393 * version ? (2020 update, temporarily use the build number of insider preview)
8394 */
8395#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
8396
8397/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02008398 * Confirm until this version. Also the logic changes.
8399 * insider preview.
8400 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02008401#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008402
8403/*
8404 * Not stable now.
8405 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008406#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Christopher Plewright1140b512022-11-12 18:46:05 +00008407// Notes:
8408// Win 10 22H2 Final is build 19045, it's conpty is widely used.
8409// Strangely, 19045 is newer but is a lower build number than the 2020 insider
8410// preview which had a build 19587. And, not sure how stable that was?
8411// Win Server 2022 (May 10, 2022) is build 20348, its conpty is widely used.
8412// Win 11 starts from build 22000, even though the major version says 10!
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008413
8414 static void
8415vtp_flag_init(void)
8416{
8417 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008418#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008419 DWORD mode;
8420 HANDLE out;
8421
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008422# ifdef VIMDLL
8423 if (!gui.in_use)
8424# endif
8425 {
8426 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008427
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008428 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
8429 GetConsoleMode(out, &mode);
8430 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
8431 if (SetConsoleMode(out, mode) == 0)
8432 vtp_working = 0;
8433 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008434#endif
8435
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008436 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008437 conpty_working = 1;
8438 if (ver >= CONPTY_STABLE_BUILD)
8439 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008440
Bram Moolenaar57da6982019-09-13 22:30:11 +02008441 if (ver <= CONPTY_INSIDER_BUILD)
8442 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008443 if (ver <= CONPTY_1909_BUILD)
8444 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02008445 if (ver <= CONPTY_1903_BUILD)
8446 conpty_type = 2;
8447 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
8448 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008449
8450 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
8451 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008452}
8453
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008454#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008455
8456 static void
8457vtp_init(void)
8458{
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008459# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightd343c602023-01-22 18:58:30 +00008460 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8461 csbi.cbSize = sizeof(csbi);
8462 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8463 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
8464 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
8465 store_console_bg_rgb = save_console_bg_rgb;
8466 store_console_fg_rgb = save_console_fg_rgb;
Christopher Plewright38804d62022-11-09 23:55:52 +00008467
Christopher Plewrightd343c602023-01-22 18:58:30 +00008468 COLORREF bg;
8469 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
8470 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8471 default_console_color_bg = bg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008472
Christopher Plewrightd343c602023-01-22 18:58:30 +00008473 COLORREF fg;
8474 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
8475 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8476 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008477# endif
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00008478 use_alternate_screen_buffer = win10_22H2_or_later && p_rs && vtp_working
Bram Moolenaar9fca1332022-12-22 21:06:41 +00008479 && !mch_getenv("VIM_TERMINAL");
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008480 set_console_color_rgb();
8481}
8482
8483 static void
8484vtp_exit(void)
8485{
Bram Moolenaardf543822020-01-30 11:53:59 +01008486 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008487}
8488
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008489 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008490vtp_printf(
8491 char *format,
8492 ...)
8493{
8494 char_u buf[100];
8495 va_list list;
8496 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008497 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008498
8499 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008500 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008501 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008502 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008503 return (int)result;
8504}
8505
8506 static void
8507vtp_sgr_bulk(
8508 int arg)
8509{
8510 int args[1];
8511
8512 args[0] = arg;
8513 vtp_sgr_bulks(1, args);
8514}
8515
K.Takata6e1d31e2022-02-03 13:05:32 +00008516# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008517 if ((*p-- = "0123456789"[(n = x % 10)]) \
8518 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8519 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8520
K.Takata6e1d31e2022-02-03 13:05:32 +00008521# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008522 case x: \
8523 FAST256(newargs[x - 1]);
8524
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008525 static void
8526vtp_sgr_bulks(
8527 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008528 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008529{
K.Takata6e1d31e2022-02-03 13:05:32 +00008530# define MAXSGR 16
8531# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008532 char_u buf[SGRBUFSIZE];
8533 char_u *p;
8534 int in, out;
8535 int newargs[16];
8536 static int sgrfgr = -1, sgrfgg, sgrfgb;
8537 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008538
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008539 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008540 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008541 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008542 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008543 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008544 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008545
8546 in = out = 0;
8547 while (in < argc)
8548 {
8549 int s = args[in];
8550 int copylen = 1;
8551
8552 if (s == 38)
8553 {
8554 if (argc - in >= 5 && args[in + 1] == 2)
8555 {
8556 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8557 && sgrfgb == args[in + 4])
8558 {
8559 in += 5;
8560 copylen = 0;
8561 }
8562 else
8563 {
8564 sgrfgr = args[in + 2];
8565 sgrfgg = args[in + 3];
8566 sgrfgb = args[in + 4];
8567 copylen = 5;
8568 }
8569 }
8570 else if (argc - in >= 3 && args[in + 1] == 5)
8571 {
8572 sgrfgr = -1;
8573 copylen = 3;
8574 }
8575 }
8576 else if (s == 48)
8577 {
8578 if (argc - in >= 5 && args[in + 1] == 2)
8579 {
8580 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8581 && sgrbgb == args[in + 4])
8582 {
8583 in += 5;
8584 copylen = 0;
8585 }
8586 else
8587 {
8588 sgrbgr = args[in + 2];
8589 sgrbgg = args[in + 3];
8590 sgrbgb = args[in + 4];
8591 copylen = 5;
8592 }
8593 }
8594 else if (argc - in >= 3 && args[in + 1] == 5)
8595 {
8596 sgrbgr = -1;
8597 copylen = 3;
8598 }
8599 }
8600 else if (30 <= s && s <= 39)
8601 sgrfgr = -1;
8602 else if (90 <= s && s <= 97)
8603 sgrfgr = -1;
8604 else if (40 <= s && s <= 49)
8605 sgrbgr = -1;
8606 else if (100 <= s && s <= 107)
8607 sgrbgr = -1;
8608 else if (s == 0)
8609 sgrfgr = sgrbgr = -1;
8610
8611 while (copylen--)
8612 newargs[out++] = args[in++];
8613 }
8614
8615 p = &buf[sizeof(buf) - 1];
8616 *p-- = 'm';
8617
8618 switch (out)
8619 {
8620 int n, m;
8621 DWORD r;
8622
8623 FAST256CASE(16);
8624 *p-- = ';';
8625 FAST256CASE(15);
8626 *p-- = ';';
8627 FAST256CASE(14);
8628 *p-- = ';';
8629 FAST256CASE(13);
8630 *p-- = ';';
8631 FAST256CASE(12);
8632 *p-- = ';';
8633 FAST256CASE(11);
8634 *p-- = ';';
8635 FAST256CASE(10);
8636 *p-- = ';';
8637 FAST256CASE(9);
8638 *p-- = ';';
8639 FAST256CASE(8);
8640 *p-- = ';';
8641 FAST256CASE(7);
8642 *p-- = ';';
8643 FAST256CASE(6);
8644 *p-- = ';';
8645 FAST256CASE(5);
8646 *p-- = ';';
8647 FAST256CASE(4);
8648 *p-- = ';';
8649 FAST256CASE(3);
8650 *p-- = ';';
8651 FAST256CASE(2);
8652 *p-- = ';';
8653 FAST256CASE(1);
8654 *p-- = '[';
8655 *p = '\033';
8656 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8657 default:
8658 break;
8659 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008660}
8661
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008662 static void
8663wt_init(void)
8664{
Christopher Plewright1140b512022-11-12 18:46:05 +00008665 wt_working = mch_getenv("WT_SESSION") != NULL;
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008666}
8667
Christopher Plewrightd343c602023-01-22 18:58:30 +00008668 int
8669use_wt(void)
8670{
8671 return USE_WT;
8672}
8673
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008674# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008675 static int
8676ctermtoxterm(
8677 int cterm)
8678{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008679 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008680
8681 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8682 return (((int)r << 16) | ((int)g << 8) | (int)b);
8683}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008684# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008685
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008686 static void
8687set_console_color_rgb(void)
8688{
8689# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008690 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008691 guicolor_T fg, bg;
8692 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008693
Christopher Plewright38804d62022-11-09 23:55:52 +00008694 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008695 return;
8696
Bram Moolenaara050b942019-12-02 21:35:31 +01008697 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8698
Christopher Plewright38804d62022-11-09 23:55:52 +00008699 if (p_tgc || t_colors >= 256)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008700 {
8701 term_fg_rgb_color(fg);
8702 term_bg_rgb_color(bg);
8703 return;
8704 }
8705
Christopher Plewrightd343c602023-01-22 18:58:30 +00008706 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8707 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008708
Christopher Plewrightd343c602023-01-22 18:58:30 +00008709 csbi.cbSize = sizeof(csbi);
8710 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008711
Christopher Plewrightd343c602023-01-22 18:58:30 +00008712 csbi.cbSize = sizeof(csbi);
8713 csbi.srWindow.Right += 1;
8714 csbi.srWindow.Bottom += 1;
8715 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8716 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
8717 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8718 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
8719 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008720# endif
8721}
8722
Bram Moolenaara050b942019-12-02 21:35:31 +01008723# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8724 void
8725get_default_console_color(
8726 int *cterm_fg,
8727 int *cterm_bg,
8728 guicolor_T *gui_fg,
8729 guicolor_T *gui_bg)
8730{
8731 int id;
8732 guicolor_T guifg = INVALCOLOR;
8733 guicolor_T guibg = INVALCOLOR;
8734 int ctermfg = 0;
8735 int ctermbg = 0;
Christopher Plewright38804d62022-11-09 23:55:52 +00008736 int dummynull = 0;
Bram Moolenaara050b942019-12-02 21:35:31 +01008737
8738 id = syn_name2id((char_u *)"Normal");
8739 if (id > 0 && p_tgc)
8740 syn_id2colors(id, &guifg, &guibg);
8741 if (guifg == INVALCOLOR)
8742 {
8743 ctermfg = -1;
8744 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008745 syn_id2cterm_bg(id, &ctermfg, &dummynull);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008746 if (ctermfg != -1)
8747 guifg = ctermtoxterm(ctermfg);
Christopher Plewright38804d62022-11-09 23:55:52 +00008748 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008749 guifg = USE_WT ? INVALCOLOR : default_console_color_fg;
8750 cterm_normal_fg_gui_color = guifg;
8751 ctermfg = ctermfg < 0 ? 0 : ctermfg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008752 }
8753 if (guibg == INVALCOLOR)
8754 {
8755 ctermbg = -1;
8756 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008757 syn_id2cterm_bg(id, &dummynull, &ctermbg);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008758 if (ctermbg != -1)
8759 guibg = ctermtoxterm(ctermbg);
K.Takatae53a0d42022-09-05 21:45:11 +01008760 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008761 guibg = USE_WT ? INVALCOLOR : default_console_color_bg;
8762 cterm_normal_bg_gui_color = guibg;
8763 ctermbg = ctermbg < 0 ? 0 : ctermbg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008764 }
8765
8766 *cterm_fg = ctermfg;
8767 *cterm_bg = ctermbg;
8768 *gui_fg = guifg;
8769 *gui_bg = guibg;
8770}
8771# endif
8772
Bram Moolenaardf543822020-01-30 11:53:59 +01008773/*
8774 * Set the console colors to the original colors or the last set colors.
8775 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008776 static void
8777reset_console_color_rgb(void)
8778{
8779# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008780
Christopher Plewright38804d62022-11-09 23:55:52 +00008781 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8782
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008783 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008784 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008785
8786 csbi.cbSize = sizeof(csbi);
8787 csbi.srWindow.Right += 1;
8788 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008789 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8790 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008791 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008792# endif
8793}
8794
8795/*
8796 * Set the console colors to the original colors.
8797 */
8798 static void
8799restore_console_color_rgb(void)
8800{
8801# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00008802
K.Takata27b53be2022-09-18 12:25:49 +01008803 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008804
8805 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008806 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008807
8808 csbi.cbSize = sizeof(csbi);
8809 csbi.srWindow.Right += 1;
8810 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008811 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8812 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008813 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008814# endif
8815}
8816
8817 void
8818control_console_color_rgb(void)
8819{
Christopher Plewright38804d62022-11-09 23:55:52 +00008820 if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008821 set_console_color_rgb();
8822 else
8823 reset_console_color_rgb();
8824}
8825
8826 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008827use_vtp(void)
8828{
8829 return USE_VTP;
8830}
8831
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008832 int
8833is_term_win32(void)
8834{
8835 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8836}
8837
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008838 int
8839has_vtp_working(void)
8840{
8841 return vtp_working;
8842}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008843
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008844#endif
8845
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008846 int
8847has_conpty_working(void)
8848{
8849 return conpty_working;
8850}
8851
8852 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008853get_conpty_type(void)
8854{
8855 return conpty_type;
8856}
8857
8858 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008859is_conpty_stable(void)
8860{
8861 return conpty_stable;
8862}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008863
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008864 int
8865get_conpty_fix_type(void)
8866{
8867 return conpty_fix_type;
8868}
8869
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008870#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008871 void
8872resize_console_buf(void)
8873{
8874 CONSOLE_SCREEN_BUFFER_INFO csbi;
8875 COORD coord;
8876 SMALL_RECT newsize;
8877
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008878 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8879 return;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008880
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008881 coord.X = SRWIDTH(csbi.srWindow);
8882 coord.Y = SRHEIGHT(csbi.srWindow);
8883 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008884
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008885 newsize.Left = 0;
8886 newsize.Top = 0;
8887 newsize.Right = coord.X - 1;
8888 newsize.Bottom = coord.Y - 1;
8889 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8890
8891 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008892}
8893#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008894
8895 char *
8896GetWin32Error(void)
8897{
K.Takatad68b2fc2022-02-12 11:18:37 +00008898 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008899 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008900
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008901 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8902 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008903 if (oldmsg != NULL)
8904 LocalFree(oldmsg);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008905 if (msg == NULL)
8906 return NULL;
8907
8908 // remove trailing \r\n
8909 char *pcrlf = strstr(msg, "\r\n");
8910 if (pcrlf != NULL)
8911 *pcrlf = '\0';
8912 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008913 return msg;
8914}
Paul Ollis65745772022-06-05 16:55:54 +01008915
8916#if defined(FEAT_RELTIME) || defined(PROTO)
8917static HANDLE timer_handle;
8918static int timer_active = FALSE;
8919
8920/*
8921 * Calls to start_timeout alternate the return value pointer between the two
8922 * entries in timeout_flags. If the previously active timeout is very close to
8923 * expiring when start_timeout() is called then a race condition means that the
8924 * set_flag() function may still be invoked after the previous timer is
8925 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8926 * timeouts.
8927 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008928static sig_atomic_t timeout_flags[2];
8929static int timeout_flag_idx = 0;
8930static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01008931
8932
8933 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01008934set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01008935{
8936 int *timeout_flag = (int *)param;
8937
8938 *timeout_flag = TRUE;
8939}
8940
8941/*
8942 * Stop any active timeout.
8943 */
8944 void
8945stop_timeout(void)
8946{
8947 if (timer_active)
8948 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01008949 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01008950 timer_active = FALSE;
8951 if (!ret && GetLastError() != ERROR_IO_PENDING)
8952 {
8953 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
8954 }
8955 }
8956 *timeout_flag = FALSE;
8957}
8958
8959/*
8960 * Start the timeout timer.
8961 *
8962 * The period is defined in milliseconds.
8963 *
8964 * The return value is a pointer to a flag that is initialised to 0. If the
8965 * timeout expires, the flag is set to 1. This will only return pointers to
8966 * static memory; i.e. any pointer returned by this function may always be
8967 * safely dereferenced.
8968 *
8969 * This function is not expected to fail, but if it does it still returns a
8970 * valid flag pointer; the flag will remain stuck at zero.
8971 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008972 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01008973start_timeout(long msec)
8974{
Paul Ollis65745772022-06-05 16:55:54 +01008975 BOOL ret;
8976
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008977 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01008978
8979 stop_timeout();
8980 ret = CreateTimerQueueTimer(
8981 &timer_handle, NULL, set_flag, timeout_flag,
8982 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
8983 if (!ret)
8984 {
8985 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
8986 }
8987 else
8988 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008989 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01008990 timer_active = TRUE;
8991 *timeout_flag = FALSE;
8992 }
8993 return timeout_flag;
8994}
8995#endif