blob: 8a254f8a1a5b445c78dbd79fd77e3a4beca9c008 [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();
3429 vtp_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003430# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01003431 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003432 SaveConsoleBuffer(&g_cbOrig);
3433 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003434# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01003435 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003436 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
3437 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003438# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003439 if (cterm_normal_fg_color == 0)
3440 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
3441 if (cterm_normal_bg_color == 0)
3442 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
3443
Bram Moolenaarbdace832019-03-02 10:13:42 +01003444 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02003445 g_color_index_fg = g_attrDefault & 0xf;
3446 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
3447
Bram Moolenaar0f873732019-12-05 20:28:46 +01003448 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00003449 update_tcap(g_attrCurrent);
3450
3451 GetConsoleCursorInfo(g_hConOut, &g_cci);
3452 GetConsoleMode(g_hConIn, &g_cmodein);
3453 GetConsoleMode(g_hConOut, &g_cmodeout);
3454
Bram Moolenaar071d4272004-06-13 20:20:40 +00003455 SaveConsoleTitleAndIcon();
3456 /*
3457 * Set both the small and big icons of the console window to Vim's icon.
3458 * Note that Vim presently only has one size of icon (32x32), but it
3459 * automatically gets scaled down to 16x16 when setting the small icon.
3460 */
3461 if (g_fCanChangeIcon)
3462 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003463
3464 ui_get_shellsize();
3465
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003466# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003467 fdDump = fopen("dump", "wt");
3468
3469 if (fdDump)
3470 {
3471 time_t t;
3472
3473 time(&t);
3474 fputs(ctime(&t), fdDump);
3475 fflush(fdDump);
3476 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003477# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003478
3479 g_fWindInitCalled = TRUE;
3480
Bram Moolenaar071d4272004-06-13 20:20:40 +00003481 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003482
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003483# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003484 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003485# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003486}
3487
3488/*
3489 * non-GUI version of mch_exit().
3490 * Shut down and exit with status `r'
3491 * Careful: mch_exit() may be called before mch_init()!
3492 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003493 static void
3494mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003495{
Bram Moolenaar955f1982017-02-05 15:10:51 +01003496 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003497
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003498 vtp_exit();
3499
Bram Moolenaar955f1982017-02-05 15:10:51 +01003500 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003501 if (g_fWindInitCalled)
3502 settmode(TMODE_COOK);
3503
Bram Moolenaar0f873732019-12-05 20:28:46 +01003504 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00003505
3506 if (g_fWindInitCalled)
3507 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02003508 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003509 /*
3510 * Restore both the small and big icons of the console window to
3511 * what they were at startup. Don't do this when the window is
3512 * closed, Vim would hang here.
3513 */
3514 if (g_fCanChangeIcon && !g_fForceExit)
3515 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003516
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003517# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003518 if (fdDump)
3519 {
3520 time_t t;
3521
3522 time(&t);
3523 fputs(ctime(&t), fdDump);
3524 fclose(fdDump);
3525 }
3526 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003527# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003528 }
3529
3530 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003531 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003532 SetConsoleMode(g_hConOut, g_cmodeout);
3533
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003534# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003535 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003536# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003537
3538 exit(r);
3539}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003540#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003541
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003542 void
3543mch_init(void)
3544{
3545#ifdef VIMDLL
3546 if (gui.starting)
3547 mch_init_g();
3548 else
3549 mch_init_c();
3550#elif defined(FEAT_GUI_MSWIN)
3551 mch_init_g();
3552#else
3553 mch_init_c();
3554#endif
3555}
3556
3557 void
3558mch_exit(int r)
3559{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003560#ifdef FEAT_NETBEANS_INTG
3561 netbeans_send_disconnect();
3562#endif
3563
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003564#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003565 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003566 mch_exit_g(r);
3567 else
3568 mch_exit_c(r);
3569#elif defined(FEAT_GUI_MSWIN)
3570 mch_exit_g(r);
3571#else
3572 mch_exit_c(r);
3573#endif
3574}
3575
Bram Moolenaar071d4272004-06-13 20:20:40 +00003576/*
3577 * Do we have an interactive window?
3578 */
3579 int
3580mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003581 int argc UNUSED,
3582 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003583{
3584 get_exe_name();
3585
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003586#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003587 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003588#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003589# ifdef VIMDLL
3590 if (gui.in_use)
3591 return OK;
3592# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003593 if (isatty(1))
3594 return OK;
3595 return FAIL;
3596#endif
3597}
3598
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003599/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003600 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003601 * When "len" is > 0, also expand short to long filenames.
3602 */
3603 void
3604fname_case(
3605 char_u *name,
3606 int len)
3607{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003608 int flen;
3609 WCHAR *p;
3610 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003611
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003612 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003613 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003614 return;
3615
3616 slash_adjust(name);
3617
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003618 p = enc_to_utf16(name, NULL);
3619 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003620 return;
3621
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003622 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003623 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003624 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003625
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003626 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003627 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003628 if (len > 0 || flen >= (int)STRLEN(q))
3629 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3630 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003631 }
3632 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003633 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003634}
3635
3636
3637/*
3638 * Insert user name in s[len].
3639 */
3640 int
3641mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003642 char_u *s,
3643 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003644{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003645 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003646 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003647
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003648 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003649 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003650 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003651
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003652 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003653 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003654 vim_strncpy(s, p, len - 1);
3655 vim_free(p);
3656 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003657 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003658 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003659 s[0] = NUL;
3660 return FAIL;
3661}
3662
3663
3664/*
3665 * Insert host name in s[len].
3666 */
3667 void
3668mch_get_host_name(
3669 char_u *s,
3670 int len)
3671{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003672 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003673 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003674
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003675 if (!GetComputerNameW(wszHostName, &wcch))
3676 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003677
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003678 char_u *p = utf16_to_enc(wszHostName, NULL);
3679 if (p == NULL)
3680 return;
3681
3682 vim_strncpy(s, p, len - 1);
3683 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003684}
3685
3686
3687/*
3688 * return process ID
3689 */
3690 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003691mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003692{
3693 return (long)GetCurrentProcessId();
3694}
3695
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003696/*
3697 * return TRUE if process "pid" is still running
3698 */
3699 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003700mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003701{
3702 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3703 DWORD status = 0;
3704 int ret = FALSE;
3705
3706 if (hProcess == NULL)
3707 return FALSE; // might not have access
3708 if (GetExitCodeProcess(hProcess, &status) )
3709 ret = status == STILL_ACTIVE;
3710 CloseHandle(hProcess);
3711 return ret;
3712}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003713
3714/*
3715 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3716 * Return OK for success, FAIL for failure.
3717 */
3718 int
3719mch_dirname(
3720 char_u *buf,
3721 int len)
3722{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003723 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003724
Bram Moolenaar071d4272004-06-13 20:20:40 +00003725 /*
3726 * Originally this was:
3727 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3728 * But the Win32s known bug list says that getcwd() doesn't work
3729 * so use the Win32 system call instead. <Negri>
3730 */
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003731 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) == 0)
3732 return FAIL;
3733
3734 WCHAR wcbuf[_MAX_PATH + 1];
3735 char_u *p = NULL;
3736
3737 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003738 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003739 p = utf16_to_enc(wcbuf, NULL);
3740 if (STRLEN(p) >= (size_t)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003741 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003742 // long path name is too long, fall back to short one
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003743 vim_free(p);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003744 p = NULL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003745 }
3746 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003747 if (p == NULL)
3748 p = utf16_to_enc(wbuf, NULL);
3749
3750 if (p == NULL)
3751 return FAIL;
3752
3753 vim_strncpy(buf, p, len - 1);
3754 vim_free(p);
3755 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003756}
3757
3758/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003759 * Get file permissions for "name".
3760 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003761 */
3762 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003763mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003764{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003765 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003766 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003767
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003768 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003769 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003770}
3771
3772
3773/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003774 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003775 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003776 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003777 */
3778 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003779mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003780{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003781 long n;
3782 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003783
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003784 p = enc_to_utf16(name, NULL);
3785 if (p == NULL)
3786 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003787
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003788 n = _wchmod(p, perm);
3789 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003790 if (n == -1)
3791 return FAIL;
3792
3793 win32_set_archive(name);
3794
3795 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003796}
3797
3798/*
3799 * Set hidden flag for "name".
3800 */
3801 void
3802mch_hide(char_u *name)
3803{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003804 int attrs = win32_getattrs(name);
3805 if (attrs == -1)
3806 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003807
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003808 attrs |= FILE_ATTRIBUTE_HIDDEN;
3809 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003810}
3811
3812/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003813 * Return TRUE if file "name" exists and is hidden.
3814 */
3815 int
3816mch_ishidden(char_u *name)
3817{
3818 int f = win32_getattrs(name);
3819
3820 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003821 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003822
3823 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3824}
3825
3826/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003827 * return TRUE if "name" is a directory
3828 * return FALSE if "name" is not a directory or upon error
3829 */
3830 int
3831mch_isdir(char_u *name)
3832{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003833 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003834
3835 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003836 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003837
3838 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3839}
3840
3841/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003842 * return TRUE if "name" is a directory, NOT a symlink to a directory
3843 * return FALSE if "name" is not a directory
3844 * return FALSE for error
3845 */
3846 int
3847mch_isrealdir(char_u *name)
3848{
3849 return mch_isdir(name) && !mch_is_symbolic_link(name);
3850}
3851
3852/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003853 * Create directory "name".
3854 * Return 0 on success, -1 on error.
3855 */
3856 int
3857mch_mkdir(char_u *name)
3858{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003859 WCHAR *p;
3860 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003861
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003862 p = enc_to_utf16(name, NULL);
3863 if (p == NULL)
3864 return -1;
3865 retval = _wmkdir(p);
3866 vim_free(p);
3867 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003868}
3869
3870/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003871 * Delete directory "name".
3872 * Return 0 on success, -1 on error.
3873 */
3874 int
3875mch_rmdir(char_u *name)
3876{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003877 WCHAR *p;
3878 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003879
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003880 p = enc_to_utf16(name, NULL);
3881 if (p == NULL)
3882 return -1;
3883 retval = _wrmdir(p);
3884 vim_free(p);
3885 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003886}
3887
3888/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003889 * Return TRUE if file "fname" has more than one link.
3890 */
3891 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003892mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003893{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003894 BY_HANDLE_FILE_INFORMATION info;
3895
3896 return win32_fileinfo(fname, &info) == FILEINFO_OK
3897 && info.nNumberOfLinks > 1;
3898}
3899
3900/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003901 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003902 */
3903 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003904mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003905{
3906 HANDLE hFind;
3907 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003908 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003909 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003910 WIN32_FIND_DATAW findDataW;
3911
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003912 wn = enc_to_utf16(name, NULL);
3913 if (wn == NULL)
3914 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003915
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003916 hFind = FindFirstFileW(wn, &findDataW);
3917 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003918 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003919 {
3920 fileFlags = findDataW.dwFileAttributes;
3921 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003922 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003923 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003924
3925 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003926 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3927 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003928 res = TRUE;
3929
3930 return res;
3931}
3932
3933/*
3934 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3935 * link.
3936 */
3937 int
3938mch_is_linked(char_u *fname)
3939{
3940 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3941 return TRUE;
3942 return FALSE;
3943}
3944
3945/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003946 * Get the by-handle-file-information for "fname".
3947 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003948 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003949 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3950 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3951 */
3952 int
3953win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3954{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003955 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003956 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003957 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003958
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003959 wn = enc_to_utf16(fname, NULL);
3960 if (wn == NULL)
3961 return FILEINFO_ENC_FAIL;
3962
3963 hFile = CreateFileW(wn, // file name
3964 GENERIC_READ, // access mode
3965 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3966 NULL, // security descriptor
3967 OPEN_EXISTING, // creation disposition
3968 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3969 NULL); // handle to template file
3970 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003971
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003972 if (hFile == INVALID_HANDLE_VALUE)
3973 return FILEINFO_READ_FAIL;
3974
3975 if (GetFileInformationByHandle(hFile, info) != 0)
3976 res = FILEINFO_OK;
3977 else
3978 res = FILEINFO_INFO_FAIL;
3979 CloseHandle(hFile);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003980
Bram Moolenaar03f48552006-02-28 23:52:23 +00003981 return res;
3982}
3983
3984/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003985 * get file attributes for `name'
3986 * -1 : error
3987 * else FILE_ATTRIBUTE_* defined in winnt.h
3988 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003989 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003990win32_getattrs(char_u *name)
3991{
3992 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003993 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003994
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003995 p = enc_to_utf16(name, NULL);
3996 if (p == NULL)
3997 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003998
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003999 attr = GetFileAttributesW(p);
4000 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004001
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004002 return attr;
4003}
4004
4005/*
4006 * set file attributes for `name' to `attrs'
4007 *
4008 * return -1 for failure, 0 otherwise
4009 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004010 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004011win32_setattrs(char_u *name, int attrs)
4012{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004013 int res;
4014 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004015
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004016 p = enc_to_utf16(name, NULL);
4017 if (p == NULL)
4018 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004019
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004020 res = SetFileAttributesW(p, attrs);
4021 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004022
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004023 return res ? 0 : -1;
4024}
4025
4026/*
4027 * Set archive flag for "name".
4028 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004029 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004030win32_set_archive(char_u *name)
4031{
4032 int attrs = win32_getattrs(name);
4033 if (attrs == -1)
4034 return -1;
4035
4036 attrs |= FILE_ATTRIBUTE_ARCHIVE;
4037 return win32_setattrs(name, attrs);
4038}
4039
4040/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004041 * Return TRUE if file or directory "name" is writable (not readonly).
4042 * Strange semantics of Win32: a readonly directory is writable, but you can't
4043 * delete a file. Let's say this means it is writable.
4044 */
4045 int
4046mch_writable(char_u *name)
4047{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004048 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004049
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004050 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
4051 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004052}
4053
Bram Moolenaar071d4272004-06-13 20:20:40 +00004054/*
Bram Moolenaar43663192017-03-05 14:29:12 +01004055 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01004056 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01004057 * When returning TRUE and "path" is not NULL save the path and set "*path" to
4058 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004059 */
4060 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01004061mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004062{
Bram Moolenaar95da1362020-05-30 18:37:55 +02004063 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004064}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004065
4066/*
4067 * Check what "name" is:
4068 * NODE_NORMAL: file or directory (or doesn't exist)
4069 * NODE_WRITABLE: writable device, socket, fifo, etc.
4070 * NODE_OTHER: non-writable things
4071 */
4072 int
4073mch_nodetype(char_u *name)
4074{
4075 HANDLE hFile;
4076 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004077 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004078
Bram Moolenaar0f873732019-12-05 20:28:46 +01004079 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
4080 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
4081 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00004082 if (STRNCMP(name, "\\\\.\\", 4) == 0)
4083 return NODE_WRITABLE;
4084
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004085 wn = enc_to_utf16(name, NULL);
4086 if (wn == NULL)
4087 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004088
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004089 hFile = CreateFileW(wn, // file name
4090 GENERIC_WRITE, // access mode
4091 0, // share mode
4092 NULL, // security descriptor
4093 OPEN_EXISTING, // creation disposition
4094 0, // file attributes
4095 NULL); // handle to template file
4096 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004097 if (hFile == INVALID_HANDLE_VALUE)
4098 return NODE_NORMAL;
4099
4100 type = GetFileType(hFile);
4101 CloseHandle(hFile);
4102 if (type == FILE_TYPE_CHAR)
4103 return NODE_WRITABLE;
4104 if (type == FILE_TYPE_DISK)
4105 return NODE_NORMAL;
4106 return NODE_OTHER;
4107}
4108
4109#ifdef HAVE_ACL
4110struct my_acl
4111{
4112 PSECURITY_DESCRIPTOR pSecurityDescriptor;
4113 PSID pSidOwner;
4114 PSID pSidGroup;
4115 PACL pDacl;
4116 PACL pSacl;
4117};
4118#endif
4119
4120/*
4121 * Return a pointer to the ACL of file "fname" in allocated memory.
4122 * Return NULL if the ACL is not available for whatever reason.
4123 */
4124 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004125mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004126{
4127#ifndef HAVE_ACL
4128 return (vim_acl_T)NULL;
4129#else
4130 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02004131 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004132
Bram Moolenaarc799fe22019-05-28 23:08:19 +02004133 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004134 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004135 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004136 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02004137
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004138 wn = enc_to_utf16(fname, NULL);
4139 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004140 {
4141 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004142 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004143 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004144
4145 // Try to retrieve the entire security descriptor.
4146 err = GetNamedSecurityInfoW(
4147 wn, // Abstract filename
4148 SE_FILE_OBJECT, // File Object
4149 OWNER_SECURITY_INFORMATION |
4150 GROUP_SECURITY_INFORMATION |
4151 DACL_SECURITY_INFORMATION |
4152 SACL_SECURITY_INFORMATION,
4153 &p->pSidOwner, // Ownership information.
4154 &p->pSidGroup, // Group membership.
4155 &p->pDacl, // Discretionary information.
4156 &p->pSacl, // For auditing purposes.
4157 &p->pSecurityDescriptor);
4158 if (err == ERROR_ACCESS_DENIED ||
4159 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004160 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004161 // Retrieve only DACL.
4162 (void)GetNamedSecurityInfoW(
4163 wn,
4164 SE_FILE_OBJECT,
4165 DACL_SECURITY_INFORMATION,
4166 NULL,
4167 NULL,
4168 &p->pDacl,
4169 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004170 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004171 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004172 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004173 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004174 mch_free_acl((vim_acl_T)p);
4175 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004176 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004177 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004178 }
4179
4180 return (vim_acl_T)p;
4181#endif
4182}
4183
Bram Moolenaar27515922013-06-29 15:36:26 +02004184#ifdef HAVE_ACL
4185/*
4186 * Check if "acl" contains inherited ACE.
4187 */
4188 static BOOL
4189is_acl_inherited(PACL acl)
4190{
4191 DWORD i;
4192 ACL_SIZE_INFORMATION acl_info;
4193 PACCESS_ALLOWED_ACE ace;
4194
4195 acl_info.AceCount = 0;
4196 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
4197 for (i = 0; i < acl_info.AceCount; i++)
4198 {
4199 GetAce(acl, i, (LPVOID *)&ace);
4200 if (ace->Header.AceFlags & INHERITED_ACE)
4201 return TRUE;
4202 }
4203 return FALSE;
4204}
4205#endif
4206
Bram Moolenaar071d4272004-06-13 20:20:40 +00004207/*
4208 * Set the ACL of file "fname" to "acl" (unless it's NULL).
4209 * Errors are ignored.
4210 * This must only be called with "acl" equal to what mch_get_acl() returned.
4211 */
4212 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004213mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004214{
4215#ifdef HAVE_ACL
4216 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02004217 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004218 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004219
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004220 if (p == NULL)
4221 return;
4222
4223 wn = enc_to_utf16(fname, NULL);
4224 if (wn == NULL)
4225 return;
4226
4227 // Set security flags
4228 if (p->pSidOwner)
4229 sec_info |= OWNER_SECURITY_INFORMATION;
4230 if (p->pSidGroup)
4231 sec_info |= GROUP_SECURITY_INFORMATION;
4232 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02004233 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004234 sec_info |= DACL_SECURITY_INFORMATION;
4235 // Do not inherit its parent's DACL.
4236 // If the DACL is inherited, Cygwin permissions would be changed.
4237 if (!is_acl_inherited(p->pDacl))
4238 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02004239 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004240 if (p->pSacl)
4241 sec_info |= SACL_SECURITY_INFORMATION;
4242
4243 (void)SetNamedSecurityInfoW(
4244 wn, // Abstract filename
4245 SE_FILE_OBJECT, // File Object
4246 sec_info,
4247 p->pSidOwner, // Ownership information.
4248 p->pSidGroup, // Group membership.
4249 p->pDacl, // Discretionary information.
4250 p->pSacl // For auditing purposes.
4251 );
4252 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004253#endif
4254}
4255
4256 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004257mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004258{
4259#ifdef HAVE_ACL
4260 struct my_acl *p = (struct my_acl *)acl;
4261
4262 if (p != NULL)
4263 {
4264 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
4265 vim_free(p);
4266 }
4267#endif
4268}
4269
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004270#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004271
4272/*
4273 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
4274 */
4275 static BOOL WINAPI
4276handler_routine(
4277 DWORD dwCtrlType)
4278{
Bram Moolenaar589b1102017-08-12 16:39:05 +02004279 INPUT_RECORD ir;
4280 DWORD out;
4281
Bram Moolenaar071d4272004-06-13 20:20:40 +00004282 switch (dwCtrlType)
4283 {
4284 case CTRL_C_EVENT:
4285 if (ctrl_c_interrupts)
4286 g_fCtrlCPressed = TRUE;
4287 return TRUE;
4288
4289 case CTRL_BREAK_EVENT:
4290 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02004291 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004292 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02004293 ir.EventType = KEY_EVENT;
4294 ir.Event.KeyEvent.bKeyDown = TRUE;
4295 ir.Event.KeyEvent.wRepeatCount = 1;
4296 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
4297 ir.Event.KeyEvent.wVirtualScanCode = 0;
4298 ir.Event.KeyEvent.dwControlKeyState = 0;
4299 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
4300 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004301 return TRUE;
4302
Bram Moolenaar0f873732019-12-05 20:28:46 +01004303 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00004304 case CTRL_CLOSE_EVENT:
4305 case CTRL_LOGOFF_EVENT:
4306 case CTRL_SHUTDOWN_EVENT:
4307 windgoto((int)Rows - 1, 0);
4308 g_fForceExit = TRUE;
4309
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004310 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004311 (dwCtrlType == CTRL_CLOSE_EVENT
4312 ? _("close")
4313 : dwCtrlType == CTRL_LOGOFF_EVENT
4314 ? _("logoff")
4315 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004316# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00004317 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004318# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004319
Bram Moolenaar0f873732019-12-05 20:28:46 +01004320 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00004321
Bram Moolenaar0f873732019-12-05 20:28:46 +01004322 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00004323
4324 default:
4325 return FALSE;
4326 }
4327}
4328
4329
4330/*
4331 * set the tty in (raw) ? "raw" : "cooked" mode
4332 */
4333 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02004334mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004335{
4336 DWORD cmodein;
4337 DWORD cmodeout;
4338 BOOL bEnableHandler;
4339
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004340# ifdef VIMDLL
4341 if (gui.in_use)
4342 return;
4343# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004344 GetConsoleMode(g_hConIn, &cmodein);
4345 GetConsoleMode(g_hConOut, &cmodeout);
4346 if (tmode == TMODE_RAW)
4347 {
4348 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4349 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004350 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004351 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004352 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004353 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
4354 }
4355 else
4356 {
4357 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
4358 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004359 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004360# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01004361 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
4362 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004363 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004364# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004365 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004366# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004367 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004368 bEnableHandler = TRUE;
4369 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004370 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00004371 {
4372 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4373 ENABLE_ECHO_INPUT);
4374 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
4375 bEnableHandler = FALSE;
4376 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004377 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004378 SetConsoleMode(g_hConOut, cmodeout);
4379 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
4380
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004381# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004382 if (fdDump)
4383 {
4384 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
4385 tmode == TMODE_RAW ? "raw" :
4386 tmode == TMODE_COOK ? "cooked" : "normal",
4387 cmodein, cmodeout);
4388 fflush(fdDump);
4389 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004390# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004391}
4392
4393
4394/*
4395 * Get the size of the current window in `Rows' and `Columns'
4396 * Return OK when size could be determined, FAIL otherwise.
4397 */
4398 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004399mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004400{
4401 CONSOLE_SCREEN_BUFFER_INFO csbi;
4402
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004403# ifdef VIMDLL
4404 if (gui.in_use)
4405 return OK;
4406# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004407 if (!g_fTermcapMode && g_cbTermcap.IsValid)
4408 {
4409 /*
4410 * For some reason, we are trying to get the screen dimensions
4411 * even though we are not in termcap mode. The 'Rows' and 'Columns'
4412 * variables are really intended to mean the size of Vim screen
4413 * while in termcap mode.
4414 */
4415 Rows = g_cbTermcap.Info.dwSize.Y;
4416 Columns = g_cbTermcap.Info.dwSize.X;
4417 }
4418 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4419 {
4420 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4421 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4422 }
4423 else
4424 {
4425 Rows = 25;
4426 Columns = 80;
4427 }
4428 return OK;
4429}
4430
4431/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004432 * Resize console buffer to 'COORD'
4433 */
4434 static void
4435ResizeConBuf(
4436 HANDLE hConsole,
4437 COORD coordScreen)
4438{
4439 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4440 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004441# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004442 if (fdDump)
4443 {
4444 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4445 GetLastError());
4446 fflush(fdDump);
4447 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004448# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004449 }
4450}
4451
4452/*
4453 * Resize console window size to 'srWindowRect'
4454 */
4455 static void
4456ResizeWindow(
4457 HANDLE hConsole,
4458 SMALL_RECT srWindowRect)
4459{
4460 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4461 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004462# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004463 if (fdDump)
4464 {
4465 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4466 GetLastError());
4467 fflush(fdDump);
4468 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004469# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004470 }
4471}
4472
4473/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004474 * Set a console window to `xSize' * `ySize'
4475 */
4476 static void
4477ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004478 HANDLE hConsole,
4479 int xSize,
4480 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004481{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004482 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
4483 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004484 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004485 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004486 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004487
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004488# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004489 if (fdDump)
4490 {
4491 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4492 fflush(fdDump);
4493 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004494# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004495
Bram Moolenaar0f873732019-12-05 20:28:46 +01004496 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00004497 coordScreen = GetLargestConsoleWindowSize(hConsole);
4498
Bram Moolenaar0f873732019-12-05 20:28:46 +01004499 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00004500 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4501 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4502 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4503
4504 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4505 {
4506 int sx, sy;
4507
4508 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4509 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4510 if (sy < ySize || sx < xSize)
4511 {
4512 /*
4513 * Increasing number of lines/columns, do buffer first.
4514 * Use the maximal size in x and y direction.
4515 */
4516 if (sy < ySize)
4517 coordScreen.Y = ySize;
4518 else
4519 coordScreen.Y = sy;
4520 if (sx < xSize)
4521 coordScreen.X = xSize;
4522 else
4523 coordScreen.X = sx;
4524 SetConsoleScreenBufferSize(hConsole, coordScreen);
4525 }
4526 }
4527
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004528 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004529 coordScreen.X = xSize;
4530 coordScreen.Y = ySize;
4531
Bram Moolenaar2551c032018-08-23 22:38:31 +02004532 // In the new console call API, only the first time in reverse order
4533 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004534 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004535 ResizeWindow(hConsole, srWindowRect);
4536 ResizeConBuf(hConsole, coordScreen);
4537 }
4538 else
4539 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004540 // Workaround for a Windows 10 bug
4541 cursor.X = srWindowRect.Left;
4542 cursor.Y = srWindowRect.Top;
4543 SetConsoleCursorPosition(hConsole, cursor);
4544
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004545 ResizeConBuf(hConsole, coordScreen);
4546 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004547 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004548 }
4549}
4550
4551
4552/*
4553 * Set the console window to `Rows' * `Columns'
4554 */
4555 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004556mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004557{
4558 COORD coordScreen;
4559
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004560# ifdef VIMDLL
4561 if (gui.in_use)
4562 return;
4563# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004564 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004565 if (suppress_winsize != 0)
4566 {
4567 suppress_winsize = 2;
4568 return;
4569 }
4570
4571 if (term_console)
4572 {
4573 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4574
Bram Moolenaar0f873732019-12-05 20:28:46 +01004575 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004576 if (Rows > coordScreen.Y)
4577 Rows = coordScreen.Y;
4578 if (Columns > coordScreen.X)
4579 Columns = coordScreen.X;
4580
4581 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4582 }
4583}
4584
4585/*
4586 * Rows and/or Columns has changed.
4587 */
4588 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004589mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004590{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004591# ifdef VIMDLL
4592 if (gui.in_use)
4593 return;
4594# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004595 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4596}
4597
4598
4599/*
4600 * Called when started up, to set the winsize that was delayed.
4601 */
4602 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004603mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004604{
4605 if (suppress_winsize == 2)
4606 {
4607 suppress_winsize = 0;
4608 mch_set_shellsize();
4609 shell_resized();
4610 }
4611 suppress_winsize = 0;
4612}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004613#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004614
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004615 static BOOL
4616vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004617 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004618 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004619 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004620 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004621 PROCESS_INFORMATION *pi,
4622 LPVOID *env,
4623 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004624{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004625 BOOL ret = FALSE;
4626 WCHAR *wcmd, *wcwd = NULL;
4627
4628 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4629 if (wcmd == NULL)
4630 return FALSE;
4631 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004632 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004633 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4634 if (wcwd == NULL)
4635 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004636 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004637
4638 ret = CreateProcessW(
4639 NULL, // Executable name
4640 wcmd, // Command to execute
4641 NULL, // Process security attributes
4642 NULL, // Thread security attributes
4643 inherit_handles, // Inherit handles
4644 flags, // Creation flags
4645 env, // Environment
4646 wcwd, // Current directory
4647 (LPSTARTUPINFOW)si, // Startup information
4648 pi); // Process information
4649theend:
4650 vim_free(wcmd);
4651 vim_free(wcwd);
4652 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004653}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004654
4655
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004656 static HINSTANCE
4657vim_shell_execute(
4658 char *cmd,
4659 INT n_show_cmd)
4660{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004661 HINSTANCE ret;
4662 WCHAR *wcmd;
4663
4664 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4665 if (wcmd == NULL)
4666 return (HINSTANCE) 0;
4667
4668 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4669 vim_free(wcmd);
4670 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004671}
4672
4673
Bram Moolenaar4f974752019-02-17 17:44:42 +01004674#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004675
4676/*
4677 * Specialised version of system() for Win32 GUI mode.
4678 * This version proceeds as follows:
4679 * 1. Create a console window for use by the subprocess
4680 * 2. Run the subprocess (it gets the allocated console by default)
4681 * 3. Wait for the subprocess to terminate and get its exit code
4682 * 4. Prompt the user to press a key to close the console window
4683 */
4684 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004685mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004686{
4687 STARTUPINFO si;
4688 PROCESS_INFORMATION pi;
4689 DWORD ret = 0;
4690 HWND hwnd = GetFocus();
4691
4692 si.cb = sizeof(si);
4693 si.lpReserved = NULL;
4694 si.lpDesktop = NULL;
4695 si.lpTitle = NULL;
4696 si.dwFlags = STARTF_USESHOWWINDOW;
4697 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004698 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004699 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004700 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004701 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004702 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004703 else
4704 si.wShowWindow = SW_SHOWNORMAL;
4705 si.cbReserved2 = 0;
4706 si.lpReserved2 = NULL;
4707
Bram Moolenaar0f873732019-12-05 20:28:46 +01004708 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004709 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004710 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4711 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004712
Bram Moolenaar0f873732019-12-05 20:28:46 +01004713 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004714 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004715# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004716 int delay = 1;
4717
Bram Moolenaar0f873732019-12-05 20:28:46 +01004718 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004719 for (;;)
4720 {
4721 MSG msg;
4722
K.Takatab7057bd2022-01-21 11:37:07 +00004723 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004724 {
4725 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004726 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004727 delay = 1;
4728 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004729 }
4730 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4731 break;
4732
Bram Moolenaar0f873732019-12-05 20:28:46 +01004733 // We start waiting for a very short time and then increase it, so
4734 // that we respond quickly when the process is quick, and don't
4735 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004736 if (delay < 50)
4737 delay += 10;
4738 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004739# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004740 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004741# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004742
Bram Moolenaar0f873732019-12-05 20:28:46 +01004743 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004744 GetExitCodeProcess(pi.hProcess, &ret);
4745 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004746
Bram Moolenaar0f873732019-12-05 20:28:46 +01004747 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004748 CloseHandle(pi.hThread);
4749 CloseHandle(pi.hProcess);
4750
Bram Moolenaar0f873732019-12-05 20:28:46 +01004751 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004752 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4753
4754 return ret;
4755}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004756
4757/*
4758 * Thread launched by the gui to send the current buffer data to the
4759 * process. This way avoid to hang up vim totally if the children
4760 * process take a long time to process the lines.
4761 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004762 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004763sub_process_writer(LPVOID param)
4764{
4765 HANDLE g_hChildStd_IN_Wr = param;
4766 linenr_T lnum = curbuf->b_op_start.lnum;
4767 DWORD len = 0;
4768 DWORD l;
4769 char_u *lp = ml_get(lnum);
4770 char_u *s;
4771 int written = 0;
4772
4773 for (;;)
4774 {
4775 l = (DWORD)STRLEN(lp + written);
4776 if (l == 0)
4777 len = 0;
4778 else if (lp[written] == NL)
4779 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004780 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004781 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4782 }
4783 else
4784 {
4785 s = vim_strchr(lp + written, NL);
4786 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4787 s == NULL ? l : (DWORD)(s - (lp + written)),
4788 &len, NULL);
4789 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004790 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004791 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004792 // Finished a line, add a NL, unless this line should not have
4793 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004794 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004795 || (!curbuf->b_p_bin
4796 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004797 || (lnum != curbuf->b_no_eol_lnum
4798 && (lnum != curbuf->b_ml.ml_line_count
4799 || curbuf->b_p_eol)))
4800 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004801 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4802 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004803 }
4804
4805 ++lnum;
4806 if (lnum > curbuf->b_op_end.lnum)
4807 break;
4808
4809 lp = ml_get(lnum);
4810 written = 0;
4811 }
4812 else if (len > 0)
4813 written += len;
4814 }
4815
Bram Moolenaar0f873732019-12-05 20:28:46 +01004816 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004817 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004818 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004819}
4820
4821
Bram Moolenaar0f873732019-12-05 20:28:46 +01004822# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004823
4824/*
4825 * This function read from the children's stdout and write the
4826 * data on screen or in the buffer accordingly.
4827 */
4828 static void
4829dump_pipe(int options,
4830 HANDLE g_hChildStd_OUT_Rd,
4831 garray_T *ga,
4832 char_u buffer[],
4833 DWORD *buffer_off)
4834{
4835 DWORD availableBytes = 0;
4836 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004837 int ret;
4838 DWORD len;
4839 DWORD toRead;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004840
Bram Moolenaar0f873732019-12-05 20:28:46 +01004841 // we query the pipe to see if there is any data to read
4842 // to avoid to perform a blocking read
4843 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4844 NULL, // optional buffer
4845 0, // buffer size
4846 NULL, // number of read bytes
4847 &availableBytes, // available bytes total
4848 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004849
Bram Moolenaar0f873732019-12-05 20:28:46 +01004850 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004851 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004852 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01004853 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004854 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004855 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004856
Bram Moolenaar0f873732019-12-05 20:28:46 +01004857 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004858 if (len == 0)
4859 break;
4860
4861 availableBytes -= len;
4862
4863 if (options & SHELL_READ)
4864 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004865 // Do NUL -> NL translation, append NL separated
4866 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004867 for (i = 0; i < len; ++i)
4868 {
4869 if (buffer[i] == NL)
4870 append_ga_line(ga);
4871 else if (buffer[i] == NUL)
4872 ga_append(ga, NL);
4873 else
4874 ga_append(ga, buffer[i]);
4875 }
4876 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004877 else if (has_mbyte)
4878 {
4879 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004880 int c;
4881 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004882
4883 len += *buffer_off;
4884 buffer[len] = NUL;
4885
Bram Moolenaar0f873732019-12-05 20:28:46 +01004886 // Check if the last character in buffer[] is
4887 // incomplete, keep these bytes for the next
4888 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004889 for (p = buffer; p < buffer + len; p += l)
4890 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004891 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004892 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004893 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004894 else if (MB_BYTE2LEN(*p) != l)
4895 break;
4896 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004897 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004898 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004899 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004900 if (len >= 12)
4901 ++p;
4902 else
4903 {
4904 *buffer_off = len;
4905 return;
4906 }
4907 }
4908 c = *p;
4909 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004910 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004911 if (p < buffer + len)
4912 {
4913 *p = c;
4914 *buffer_off = (DWORD)((buffer + len) - p);
4915 mch_memmove(buffer, p, *buffer_off);
4916 return;
4917 }
4918 *buffer_off = 0;
4919 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004920 else
4921 {
4922 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004923 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004924 }
4925
4926 windgoto(msg_row, msg_col);
4927 cursor_on();
4928 out_flush();
4929 }
4930}
4931
4932/*
4933 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4934 * for communication and doesn't open any new window.
4935 */
4936 static int
4937mch_system_piped(char *cmd, int options)
4938{
4939 STARTUPINFO si;
4940 PROCESS_INFORMATION pi;
4941 DWORD ret = 0;
4942
4943 HANDLE g_hChildStd_IN_Rd = NULL;
4944 HANDLE g_hChildStd_IN_Wr = NULL;
4945 HANDLE g_hChildStd_OUT_Rd = NULL;
4946 HANDLE g_hChildStd_OUT_Wr = NULL;
4947
Bram Moolenaar0f873732019-12-05 20:28:46 +01004948 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004949 DWORD len;
4950
Bram Moolenaar0f873732019-12-05 20:28:46 +01004951 // buffer used to receive keys
4952 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4953 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004954
4955 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004956 int noread_cnt = 0;
4957 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004958 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004959 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004960 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004961
4962 SECURITY_ATTRIBUTES saAttr;
4963
Bram Moolenaar0f873732019-12-05 20:28:46 +01004964 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004965 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4966 saAttr.bInheritHandle = TRUE;
4967 saAttr.lpSecurityDescriptor = NULL;
4968
4969 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004970 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004971 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004972 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004973 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004974 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004975 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004976 {
4977 CloseHandle(g_hChildStd_IN_Rd);
4978 CloseHandle(g_hChildStd_IN_Wr);
4979 CloseHandle(g_hChildStd_OUT_Rd);
4980 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004981 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004982 }
4983
4984 si.cb = sizeof(si);
4985 si.lpReserved = NULL;
4986 si.lpDesktop = NULL;
4987 si.lpTitle = NULL;
4988 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4989
Bram Moolenaar0f873732019-12-05 20:28:46 +01004990 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004991 si.hStdError = g_hChildStd_OUT_Wr;
4992 si.hStdOutput = g_hChildStd_OUT_Wr;
4993 si.hStdInput = g_hChildStd_IN_Rd;
4994 si.wShowWindow = SW_HIDE;
4995 si.cbReserved2 = 0;
4996 si.lpReserved2 = NULL;
4997
4998 if (options & SHELL_READ)
4999 ga_init2(&ga, 1, BUFLEN);
5000
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005001 if (cmd != NULL)
5002 {
5003 p = (char *)vim_strsave((char_u *)cmd);
5004 if (p != NULL)
5005 unescape_shellxquote((char_u *)p, p_sxe);
5006 else
5007 p = cmd;
5008 }
5009
Bram Moolenaar0f873732019-12-05 20:28:46 +01005010 // Now, run the command.
5011 // About "Inherit handles" being TRUE: this command can be litigious,
5012 // handle inheritance was deactivated for pending temp file, but, if we
5013 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005014 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
5015 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005016
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005017 if (p != cmd)
5018 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005019
Bram Moolenaar0f873732019-12-05 20:28:46 +01005020 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005021 CloseHandle(g_hChildStd_IN_Rd);
5022 CloseHandle(g_hChildStd_OUT_Wr);
5023
5024 if (options & SHELL_WRITE)
5025 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02005026 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005027 _beginthreadex(NULL, // security attributes
5028 0, // default stack size
5029 sub_process_writer, // function to be executed
5030 g_hChildStd_IN_Wr, // parameter
5031 0, // creation flag, start immediately
5032 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005033 CloseHandle(thread);
5034 g_hChildStd_IN_Wr = NULL;
5035 }
5036
Bram Moolenaar0f873732019-12-05 20:28:46 +01005037 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005038 for (;;)
5039 {
5040 MSG msg;
5041
K.Takatab7057bd2022-01-21 11:37:07 +00005042 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005043 {
5044 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00005045 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005046 }
5047
Bram Moolenaar0f873732019-12-05 20:28:46 +01005048 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005049 if ((options & (SHELL_READ|SHELL_WRITE))
5050# ifdef FEAT_GUI
5051 || gui.in_use
5052# endif
5053 )
5054 {
5055 len = 0;
5056 if (!(options & SHELL_EXPAND)
5057 && ((options &
5058 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
5059 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
5060# ifdef FEAT_GUI
5061 || gui.in_use
5062# endif
5063 )
5064 && (ta_len > 0 || noread_cnt > 4))
5065 {
5066 if (ta_len == 0)
5067 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005068 // Get extra characters when we don't have any. Reset the
5069 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005070 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005071 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
5072 }
5073 if (ta_len > 0 || len > 0)
5074 {
5075 /*
5076 * For pipes: Check for CTRL-C: send interrupt signal to
5077 * child. Check for CTRL-D: EOF, close pipe to child.
5078 */
5079 if (len == 1 && cmd != NULL)
5080 {
5081 if (ta_buf[ta_len] == Ctrl_C)
5082 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005083 // Learn what exit code is expected, for
5084 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005085 TerminateProcess(pi.hProcess, 9);
5086 }
5087 if (ta_buf[ta_len] == Ctrl_D)
5088 {
5089 CloseHandle(g_hChildStd_IN_Wr);
5090 g_hChildStd_IN_Wr = NULL;
5091 }
5092 }
5093
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01005094 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005095
5096 /*
5097 * For pipes: echo the typed characters. For a pty this
5098 * does not seem to work.
5099 */
5100 for (i = ta_len; i < ta_len + len; ++i)
5101 {
5102 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
5103 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005104 else if (has_mbyte)
5105 {
5106 int l = (*mb_ptr2len)(ta_buf + i);
5107
5108 msg_outtrans_len(ta_buf + i, l);
5109 i += l - 1;
5110 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005111 else
5112 msg_outtrans_len(ta_buf + i, 1);
5113 }
5114 windgoto(msg_row, msg_col);
5115 out_flush();
5116
5117 ta_len += len;
5118
5119 /*
5120 * Write the characters to the child, unless EOF has been
5121 * typed for pipes. Write one character at a time, to
5122 * avoid losing too much typeahead. When writing buffer
5123 * lines, drop the typed characters (only check for
5124 * CTRL-C).
5125 */
5126 if (options & SHELL_WRITE)
5127 ta_len = 0;
5128 else if (g_hChildStd_IN_Wr != NULL)
5129 {
5130 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
5131 1, &len, NULL);
5132 // if we are typing in, we want to keep things reactive
5133 delay = 1;
5134 if (len > 0)
5135 {
5136 ta_len -= len;
5137 mch_memmove(ta_buf, ta_buf + len, ta_len);
5138 }
5139 }
5140 }
5141 }
5142 }
5143
5144 if (ta_len)
5145 ui_inchar_undo(ta_buf, ta_len);
5146
5147 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
5148 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005149 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005150 break;
5151 }
5152
5153 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005154 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005155
Bram Moolenaar0f873732019-12-05 20:28:46 +01005156 // We start waiting for a very short time and then increase it, so
5157 // that we respond quickly when the process is quick, and don't
5158 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005159 if (delay < 50)
5160 delay += 10;
5161 }
5162
Bram Moolenaar0f873732019-12-05 20:28:46 +01005163 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005164 CloseHandle(g_hChildStd_OUT_Rd);
5165 if (g_hChildStd_IN_Wr != NULL)
5166 CloseHandle(g_hChildStd_IN_Wr);
5167
5168 WaitForSingleObject(pi.hProcess, INFINITE);
5169
Bram Moolenaar0f873732019-12-05 20:28:46 +01005170 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005171 GetExitCodeProcess(pi.hProcess, &ret);
5172
5173 if (options & SHELL_READ)
5174 {
5175 if (ga.ga_len > 0)
5176 {
5177 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01005178 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005179 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
5180 }
5181 else
5182 curbuf->b_no_eol_lnum = 0;
5183 ga_clear(&ga);
5184 }
5185
Bram Moolenaar0f873732019-12-05 20:28:46 +01005186 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005187 CloseHandle(pi.hThread);
5188 CloseHandle(pi.hProcess);
5189
5190 return ret;
5191}
5192
5193 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005194mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005195{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005196 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005197 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005198 return mch_system_piped(cmd, options);
5199 else
5200 return mch_system_classic(cmd, options);
5201}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005202#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005203
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005204#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005205 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02005206mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005207{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005208 int ret;
5209 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005210 char_u *buf;
5211 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005212
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005213 // If the command starts and ends with double quotes, enclose the command
5214 // in parentheses.
5215 len = STRLEN(cmd);
5216 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
5217 {
5218 len += 3;
5219 buf = alloc(len);
5220 if (buf == NULL)
5221 return -1;
5222 vim_snprintf((char *)buf, len, "(%s)", cmd);
5223 wcmd = enc_to_utf16(buf, NULL);
5224 free(buf);
5225 }
5226 else
5227 wcmd = enc_to_utf16((char_u *)cmd, NULL);
5228
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005229 if (wcmd == NULL)
5230 return -1;
5231
5232 ret = _wsystem(wcmd);
5233 vim_free(wcmd);
5234 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005235}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005236
5237#endif
5238
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005239 static int
5240mch_system(char *cmd, int options)
5241{
5242#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005243 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005244 return mch_system_g(cmd, options);
5245 else
5246 return mch_system_c(cmd, options);
5247#elif defined(FEAT_GUI_MSWIN)
5248 return mch_system_g(cmd, options);
5249#else
5250 return mch_system_c(cmd, options);
5251#endif
5252}
5253
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005254#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
5255/*
5256 * Use a terminal window to run a shell command in.
5257 */
5258 static int
5259mch_call_shell_terminal(
5260 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005261 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005262{
5263 jobopt_T opt;
5264 char_u *newcmd = NULL;
5265 typval_T argvar[2];
5266 long_u cmdlen;
5267 int retval = -1;
5268 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005269 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005270 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005271 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005272
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005273 if (cmd == NULL)
5274 cmdlen = STRLEN(p_sh) + 1;
5275 else
5276 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005277 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005278 if (newcmd == NULL)
5279 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005280 if (cmd == NULL)
5281 {
5282 STRCPY(newcmd, p_sh);
5283 ch_log(NULL, "starting terminal to run a shell");
5284 }
5285 else
5286 {
5287 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
5288 ch_log(NULL, "starting terminal for system command '%s'", cmd);
5289 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005290
5291 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005292
5293 argvar[0].v_type = VAR_STRING;
5294 argvar[0].vval.v_string = newcmd;
5295 argvar[1].v_type = VAR_UNKNOWN;
5296 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005297 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01005298 {
5299 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005300 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01005301 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005302
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005303 job = term_getjob(buf->b_term);
5304 ++job->jv_refcount;
5305
Bram Moolenaar0f873732019-12-05 20:28:46 +01005306 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005307 aucmd_prepbuf(&aco, buf);
Bram Moolenaare76062c2022-11-28 18:51:43 +00005308 if (curbuf == buf)
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005309 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005310 // Only do this when a window was found for "buf".
5311 clear_oparg(&oa);
5312 while (term_use_loop())
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005313 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005314 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
5315 {
5316 // If terminal_loop() returns OK we got a key that is handled
5317 // in Normal model. We don't do redrawing anyway.
5318 if (terminal_loop(TRUE) == OK)
5319 normal_cmd(&oa, TRUE);
5320 }
5321 else
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005322 normal_cmd(&oa, TRUE);
5323 }
Bram Moolenaare76062c2022-11-28 18:51:43 +00005324 retval = job->jv_exitval;
5325 ch_log(NULL, "system command finished");
5326
5327 job_unref(job);
5328
5329 // restore curwin/curbuf and a few other things
5330 aucmd_restbuf(&aco);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005331 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005332
5333 wait_return(TRUE);
5334 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
5335
5336 vim_free(newcmd);
5337 return retval;
5338}
5339#endif
5340
Bram Moolenaar071d4272004-06-13 20:20:40 +00005341/*
5342 * Either execute a command by calling the shell or start a new shell
5343 */
5344 int
5345mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005346 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005347 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00005348{
5349 int x = 0;
5350 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005351 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02005352
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00005353#ifdef FEAT_EVAL
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01005354 ch_log(NULL, "executing shell command: %s", cmd);
5355#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01005356 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02005357 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005358 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005359 if (cmd == NULL)
5360 wcscat(szShellTitle, L" :sh");
5361 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005362 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005363 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005364
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005365 if (wn != NULL)
5366 {
5367 wcscat(szShellTitle, L" - !");
5368 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02005369 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005370 wcscat(szShellTitle, wn);
5371 SetConsoleTitleW(szShellTitle);
5372 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005373 }
5374 }
5375 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005376
5377 out_flush();
5378
5379#ifdef MCH_WRITE_DUMP
5380 if (fdDump)
5381 {
5382 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
5383 fflush(fdDump);
5384 }
5385#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005386#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005387 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005388 if (
5389# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005390 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005391# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005392 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005393 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
5394 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005395 char_u *cmdbase = cmd;
5396
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02005397 if (cmdbase != NULL)
5398 // Skip a leading quote and (.
5399 while (*cmdbase == '"' || *cmdbase == '(')
5400 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005401
5402 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01005403 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
5404 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005405 {
5406 // Use a terminal window to run the command in.
5407 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005408 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005409 return x;
5410 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005411 }
5412#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005413
5414 /*
5415 * Catch all deadly signals while running the external command, because a
5416 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5417 */
5418 signal(SIGINT, SIG_IGN);
5419#if defined(__GNUC__) && !defined(__MINGW32__)
5420 signal(SIGKILL, SIG_IGN);
5421#else
5422 signal(SIGBREAK, SIG_IGN);
5423#endif
5424 signal(SIGILL, SIG_IGN);
5425 signal(SIGFPE, SIG_IGN);
5426 signal(SIGSEGV, SIG_IGN);
5427 signal(SIGTERM, SIG_IGN);
5428 signal(SIGABRT, SIG_IGN);
5429
5430 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005431 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00005432
5433 if (cmd == NULL)
5434 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005435 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005436 }
5437 else
5438 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005439 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005440 char_u *newcmd = NULL;
5441 char_u *cmdbase = cmd;
5442 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005443
Bram Moolenaar0f873732019-12-05 20:28:46 +01005444 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005445 if (*cmdbase == '"' )
5446 ++cmdbase;
5447 if (*cmdbase == '(')
5448 ++cmdbase;
5449
Bram Moolenaar1c465442017-03-12 20:10:05 +01005450 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005451 {
5452 STARTUPINFO si;
5453 PROCESS_INFORMATION pi;
5454 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005455 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005456 char_u *p;
5457
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005458 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005459 si.cb = sizeof(si);
5460 si.lpReserved = NULL;
5461 si.lpDesktop = NULL;
5462 si.lpTitle = NULL;
5463 si.dwFlags = 0;
5464 si.cbReserved2 = 0;
5465 si.lpReserved2 = NULL;
5466
5467 cmdbase = skipwhite(cmdbase + 5);
5468 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005469 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005470 {
5471 cmdbase = skipwhite(cmdbase + 4);
5472 si.dwFlags = STARTF_USESHOWWINDOW;
5473 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005474 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005475 }
5476 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005477 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005478 {
5479 cmdbase = skipwhite(cmdbase + 2);
5480 flags = CREATE_NO_WINDOW;
5481 si.dwFlags = STARTF_USESTDHANDLES;
5482 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005483 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005484 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005485 NULL, // Security att.
5486 OPEN_EXISTING, // Open flags
5487 FILE_ATTRIBUTE_NORMAL, // File att.
5488 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005489 si.hStdOutput = si.hStdInput;
5490 si.hStdError = si.hStdInput;
5491 }
5492
Bram Moolenaar0f873732019-12-05 20:28:46 +01005493 // Remove a trailing ", ) and )" if they have a match
5494 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005495 if (cmdbase > cmd)
5496 {
5497 p = cmdbase + STRLEN(cmdbase);
5498 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5499 *--p = NUL;
5500 if (p > cmdbase && p[-1] == ')'
5501 && (*cmd =='(' || cmd[1] == '('))
5502 *--p = NUL;
5503 }
5504
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005505 newcmd = cmdbase;
5506 unescape_shellxquote(cmdbase, p_sxe);
5507
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005508 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005509 * If creating new console, arguments are passed to the
5510 * 'cmd.exe' as-is. If it's not, arguments are not treated
5511 * correctly for current 'cmd.exe'. So unescape characters in
5512 * shellxescape except '|' for avoiding to be treated as
5513 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005514 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005515 if (flags != CREATE_NEW_CONSOLE)
5516 {
5517 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005518 char_u *cmd_shell = mch_getenv("COMSPEC");
5519
5520 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005521 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005522
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005523 subcmd = vim_strsave_escaped_ext(cmdbase,
5524 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005525 if (subcmd != NULL)
5526 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005527 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005528 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005529 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005530 if (newcmd != NULL)
5531 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005532 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005533 else
5534 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005535 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005536 }
5537 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005538
5539 /*
5540 * Now, start the command as a process, so that it doesn't
5541 * inherit our handles which causes unpleasant dangling swap
5542 * files if we exit before the spawned process
5543 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005544 if (vim_create_process((char *)newcmd, FALSE, flags,
5545 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005546 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005547 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5548 > (HINSTANCE)32)
5549 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005550 else
5551 {
5552 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005553#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005554# ifdef VIMDLL
5555 if (gui.in_use)
5556# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005557 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005558#endif
5559 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005560
5561 if (newcmd != cmdbase)
5562 vim_free(newcmd);
5563
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005564 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005565 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005566 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005567 CloseHandle(si.hStdInput);
5568 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005569 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005570 CloseHandle(pi.hThread);
5571 CloseHandle(pi.hProcess);
5572 }
5573 else
5574 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005575 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005576#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005577 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005578 (!s_dont_use_vimrun && p_stmp ?
5579 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5580 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005581#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005582 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005583
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005584 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005585 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005586 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005587#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005588 if (
5589# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005590 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005591# endif
5592 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005593 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005594 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5595 "External commands will not pause after completion.\n"
5596 "See :help win32-vimrun for more information.");
5597 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005598 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5599 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005600
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005601 if (wmsg != NULL && wtitle != NULL)
5602 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5603 vim_free(wmsg);
5604 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005605 need_vimrun_warning = FALSE;
5606 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005607 if (
5608# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005609 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005610# endif
5611 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005612 // Use vimrun to execute the command. It opens a console
5613 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005614 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005615 vimrun_path,
5616 (msg_silent != 0 || (options & SHELL_DOOUT))
5617 ? "-s " : "",
5618 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005619 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005620# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005621 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005622# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005623 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005624 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005625 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5626 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005627 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005628#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005629 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005630 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005631 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005632 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005633 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005634 }
5635 }
5636
5637 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005638 {
5639 // The shell may have messed with the mode, always set it.
5640 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005641 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005642 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005643
Bram Moolenaar0f873732019-12-05 20:28:46 +01005644 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005645 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005646#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005647 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005648 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005649#endif
5650 )
5651 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005652 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005653 msg_putchar('\n');
5654 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005655 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005656
5657 signal(SIGINT, SIG_DFL);
5658#if defined(__GNUC__) && !defined(__MINGW32__)
5659 signal(SIGKILL, SIG_DFL);
5660#else
5661 signal(SIGBREAK, SIG_DFL);
5662#endif
5663 signal(SIGILL, SIG_DFL);
5664 signal(SIGFPE, SIG_DFL);
5665 signal(SIGSEGV, SIG_DFL);
5666 signal(SIGTERM, SIG_DFL);
5667 signal(SIGABRT, SIG_DFL);
5668
5669 return x;
5670}
5671
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005672#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005673 static HANDLE
5674job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005675 char_u *fname,
5676 DWORD dwDesiredAccess,
5677 DWORD dwShareMode,
5678 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5679 DWORD dwCreationDisposition,
5680 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005681{
5682 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005683 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005684
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005685 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005686 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005687 return INVALID_HANDLE_VALUE;
5688
5689 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5690 lpSecurityAttributes, dwCreationDisposition,
5691 dwFlagsAndAttributes, NULL);
5692 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005693 return h;
5694}
5695
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005696/*
5697 * Turn the dictionary "env" into a NUL separated list that can be used as the
5698 * environment argument of vim_create_process().
5699 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005700 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005701win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005702{
5703 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005704 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005705 LPVOID base = GetEnvironmentStringsW();
5706
Bram Moolenaar0f873732019-12-05 20:28:46 +01005707 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005708 if (ga_grow(gap, 1) == FAIL)
5709 return;
5710
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005711 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005712 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005713 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005714 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005715 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005716 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005717 typval_T *item = &dict_lookup(hi)->di_tv;
5718 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005719 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005720 --todo;
5721 if (wkey != NULL && wval != NULL)
5722 {
5723 size_t n;
5724 size_t lkey = wcslen(wkey);
5725 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005726
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005727 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5728 continue;
5729 for (n = 0; n < lkey; n++)
5730 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5731 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5732 for (n = 0; n < lval; n++)
5733 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5734 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5735 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005736 vim_free(wkey);
5737 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005738 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005739 }
5740 }
5741
Bram Moolenaar355757a2020-02-10 22:06:32 +01005742 if (base)
5743 {
5744 WCHAR *p = (WCHAR*) base;
5745
5746 // for last \0
5747 if (ga_grow(gap, 1) == FAIL)
5748 return;
5749
5750 while (*p != 0 || *(p + 1) != 0)
5751 {
5752 if (ga_grow(gap, 1) == OK)
5753 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5754 p++;
5755 }
5756 FreeEnvironmentStrings(base);
5757 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5758 }
5759
Bram Moolenaar493359e2018-06-12 20:25:52 +02005760# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005761 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005762# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005763 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005764 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005765# endif
5766# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005767 char_u *version = get_vim_var_str(VV_VERSION);
5768 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005769# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005770 // size of "VIM_SERVERNAME=" and value,
5771 // plus "VIM_TERMINAL=" and value,
5772 // plus two terminating NULs
5773 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005774# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005775 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005776# endif
5777# ifdef FEAT_TERMINAL
5778 + 13 + version_len + 2
5779# endif
5780 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005781
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005782 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005783 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005784# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005785 for (n = 0; n < 15; n++)
5786 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5787 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005788 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005789 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5790 (WCHAR)servername[n];
5791 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005792# endif
5793# ifdef FEAT_TERMINAL
5794 if (is_terminal)
5795 {
5796 for (n = 0; n < 13; n++)
5797 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5798 (WCHAR)"VIM_TERMINAL="[n];
5799 for (n = 0; n < version_len; n++)
5800 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5801 (WCHAR)version[n];
5802 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5803 }
5804# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005805 }
5806 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005807# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005808}
5809
Bram Moolenaarb091f302019-01-19 14:37:00 +01005810/*
5811 * Create a pair of pipes.
5812 * Return TRUE for success, FALSE for failure.
5813 */
5814 static BOOL
5815create_pipe_pair(HANDLE handles[2])
5816{
5817 static LONG s;
5818 char name[64];
5819 SECURITY_ATTRIBUTES sa;
5820
5821 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5822 GetCurrentProcessId(),
5823 InterlockedIncrement(&s));
5824
5825 // Create named pipe. Max size of named pipe is 65535.
5826 handles[1] = CreateNamedPipe(
5827 name,
5828 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5829 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005830 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005831
5832 if (handles[1] == INVALID_HANDLE_VALUE)
5833 return FALSE;
5834
5835 sa.nLength = sizeof(sa);
5836 sa.bInheritHandle = TRUE;
5837 sa.lpSecurityDescriptor = NULL;
5838
5839 handles[0] = CreateFile(name,
5840 FILE_GENERIC_READ,
5841 FILE_SHARE_READ, &sa,
5842 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5843
5844 if (handles[0] == INVALID_HANDLE_VALUE)
5845 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005846 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005847 return FALSE;
5848 }
5849
5850 return TRUE;
5851}
5852
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005853 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005854mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005855{
5856 STARTUPINFO si;
5857 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005858 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005859 SECURITY_ATTRIBUTES saAttr;
5860 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005861 HANDLE ifd[2];
5862 HANDLE ofd[2];
5863 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005864 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005865
5866 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5867 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5868 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5869 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5870 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5871 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5872 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5873
5874 if (use_out_for_err && use_null_for_out)
5875 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005876
5877 ifd[0] = INVALID_HANDLE_VALUE;
5878 ifd[1] = INVALID_HANDLE_VALUE;
5879 ofd[0] = INVALID_HANDLE_VALUE;
5880 ofd[1] = INVALID_HANDLE_VALUE;
5881 efd[0] = INVALID_HANDLE_VALUE;
5882 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005883 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005884
Bram Moolenaar14207f42016-10-27 21:13:10 +02005885 jo = CreateJobObject(NULL, NULL);
5886 if (jo == NULL)
5887 {
5888 job->jv_status = JOB_FAILED;
5889 goto failed;
5890 }
5891
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005892 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005893 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005894
Bram Moolenaar76467df2016-02-12 19:30:26 +01005895 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005896 ZeroMemory(&si, sizeof(si));
5897 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005898 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005899 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005900
Bram Moolenaard8070362016-02-15 21:56:54 +01005901 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5902 saAttr.bInheritHandle = TRUE;
5903 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005904
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005905 if (use_file_for_in)
5906 {
5907 char_u *fname = options->jo_io_name[PART_IN];
5908
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005909 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5910 FILE_SHARE_READ | FILE_SHARE_WRITE,
5911 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5912 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005913 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005914 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005915 goto failed;
5916 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005917 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005918 else if (!use_null_for_in
5919 && (!create_pipe_pair(ifd)
5920 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005921 goto failed;
5922
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005923 if (use_file_for_out)
5924 {
5925 char_u *fname = options->jo_io_name[PART_OUT];
5926
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005927 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5928 FILE_SHARE_READ | FILE_SHARE_WRITE,
5929 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5930 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005931 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005932 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005933 goto failed;
5934 }
5935 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005936 else if (!use_null_for_out &&
5937 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005938 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005939 goto failed;
5940
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005941 if (use_file_for_err)
5942 {
5943 char_u *fname = options->jo_io_name[PART_ERR];
5944
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005945 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5946 FILE_SHARE_READ | FILE_SHARE_WRITE,
5947 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5948 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005949 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005950 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005951 goto failed;
5952 }
5953 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005954 else if (!use_out_for_err && !use_null_for_err &&
5955 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005956 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005957 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005958
Bram Moolenaard8070362016-02-15 21:56:54 +01005959 si.dwFlags |= STARTF_USESTDHANDLES;
5960 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005961 si.hStdOutput = ofd[1];
5962 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5963
5964 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5965 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005966 if (options->jo_set & JO_CHANNEL)
5967 {
5968 channel = options->jo_channel;
5969 if (channel != NULL)
5970 ++channel->ch_refcount;
5971 }
5972 else
5973 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005974 if (channel == NULL)
5975 goto failed;
5976 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005977
5978 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005979 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005980 CREATE_DEFAULT_ERROR_MODE |
5981 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005982 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005983 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005984 &si, &pi,
5985 ga.ga_data,
5986 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005987 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005988 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005989 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005990 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005991 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005992
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005993 ga_clear(&ga);
5994
Bram Moolenaar14207f42016-10-27 21:13:10 +02005995 if (!AssignProcessToJobObject(jo, pi.hProcess))
5996 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005997 // if failing, switch the way to terminate
5998 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005999 CloseHandle(jo);
6000 jo = NULL;
6001 }
6002 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01006003 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006004 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02006005 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006006 job->jv_status = JOB_STARTED;
6007
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02006008 CloseHandle(ifd[0]);
6009 CloseHandle(ofd[1]);
6010 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01006011 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01006012
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006013 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006014 if (channel != NULL)
6015 {
6016 channel_set_pipes(channel,
6017 use_file_for_in || use_null_for_in
6018 ? INVALID_FD : (sock_T)ifd[1],
6019 use_file_for_out || use_null_for_out
6020 ? INVALID_FD : (sock_T)ofd[0],
6021 use_out_for_err || use_file_for_err || use_null_for_err
6022 ? INVALID_FD : (sock_T)efd[0]);
6023 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006024 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006025 return;
6026
6027failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01006028 CloseHandle(ifd[0]);
6029 CloseHandle(ofd[0]);
6030 CloseHandle(efd[0]);
6031 CloseHandle(ifd[1]);
6032 CloseHandle(ofd[1]);
6033 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01006034 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006035 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006036}
6037
6038 char *
6039mch_job_status(job_T *job)
6040{
6041 DWORD dwExitCode = 0;
6042
Bram Moolenaar76467df2016-02-12 19:30:26 +01006043 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
6044 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006045 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01006046 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01006047 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02006048 {
6049 ch_log(job->jv_channel, "Job ended");
6050 job->jv_status = JOB_ENDED;
6051 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006052 return "dead";
6053 }
6054 return "run";
6055}
6056
Bram Moolenaar97792de2016-10-15 18:36:49 +02006057 job_T *
6058mch_detect_ended_job(job_T *job_list)
6059{
6060 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
6061 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
6062 job_T *job = job_list;
6063
6064 while (job != NULL)
6065 {
6066 DWORD n;
6067 DWORD result;
6068
6069 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
6070 && job != NULL; job = job->jv_next)
6071 {
6072 if (job->jv_status == JOB_STARTED)
6073 {
6074 jobHandles[n] = job->jv_proc_info.hProcess;
6075 jobArray[n] = job;
6076 ++n;
6077 }
6078 }
6079 if (n == 0)
6080 continue;
6081 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
6082 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
6083 {
6084 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
6085
6086 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
6087 return wait_job;
6088 }
6089 }
6090 return NULL;
6091}
6092
Bram Moolenaarfb630902016-10-29 14:55:00 +02006093 static BOOL
6094terminate_all(HANDLE process, int code)
6095{
6096 PROCESSENTRY32 pe;
6097 HANDLE h = INVALID_HANDLE_VALUE;
6098 DWORD pid = GetProcessId(process);
6099
6100 if (pid != 0)
6101 {
6102 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
6103 if (h != INVALID_HANDLE_VALUE)
6104 {
6105 pe.dwSize = sizeof(PROCESSENTRY32);
6106 if (!Process32First(h, &pe))
6107 goto theend;
6108
6109 do
6110 {
6111 if (pe.th32ParentProcessID == pid)
6112 {
6113 HANDLE ph = OpenProcess(
6114 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
6115 if (ph != NULL)
6116 {
6117 terminate_all(ph, code);
6118 CloseHandle(ph);
6119 }
6120 }
6121 } while (Process32Next(h, &pe));
6122
6123 CloseHandle(h);
6124 }
6125 }
6126
6127theend:
6128 return TerminateProcess(process, code);
6129}
6130
6131/*
6132 * Send a (deadly) signal to "job".
6133 * Return FAIL if it didn't work.
6134 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006135 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02006136mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006137{
Bram Moolenaar923d9262016-02-25 20:56:01 +01006138 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006139
Bram Moolenaar923d9262016-02-25 20:56:01 +01006140 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01006141 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006142 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02006143 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006144 {
6145 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
6146 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00006147 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006148 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01006149 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006150 }
6151
6152 if (!AttachConsole(job->jv_proc_info.dwProcessId))
6153 return FAIL;
6154 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01006155 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
6156 job->jv_proc_info.dwProcessId)
6157 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006158 FreeConsole();
6159 return ret;
6160}
6161
6162/*
6163 * Clear the data related to "job".
6164 */
6165 void
6166mch_clear_job(job_T *job)
6167{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00006168 if (job->jv_status == JOB_FAILED)
6169 return;
6170
6171 if (job->jv_job_object != NULL)
6172 CloseHandle(job->jv_job_object);
6173 CloseHandle(job->jv_proc_info.hProcess);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006174}
6175#endif
6176
Bram Moolenaar071d4272004-06-13 20:20:40 +00006177
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006178#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006179
6180/*
6181 * Start termcap mode
6182 */
6183 static void
6184termcap_mode_start(void)
6185{
6186 DWORD cmodein;
6187
6188 if (g_fTermcapMode)
6189 return;
6190
Christopher Plewright1140b512022-11-12 18:46:05 +00006191 // VTP uses alternate screen buffer.
6192 // Switch to a new alternate screen buffer.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00006193 // But, not if running in a nested terminal
6194 if (use_alternate_screen_buffer)
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006195 vtp_printf("\033[?1049h");
6196
Bram Moolenaar071d4272004-06-13 20:20:40 +00006197 SaveConsoleBuffer(&g_cbNonTermcap);
6198
6199 if (g_cbTermcap.IsValid)
6200 {
6201 /*
6202 * We've been in termcap mode before. Restore certain screen
6203 * characteristics, including the buffer size and the window
6204 * size. Since we will be redrawing the screen, we don't need
6205 * to restore the actual contents of the buffer.
6206 */
6207 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006208 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006209 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
6210 Rows = g_cbTermcap.Info.dwSize.Y;
6211 Columns = g_cbTermcap.Info.dwSize.X;
6212 }
6213 else
6214 {
6215 /*
6216 * This is our first time entering termcap mode. Clear the console
6217 * screen buffer, and resize the buffer to match the current window
6218 * size. We will use this as the size of our editing environment.
6219 */
6220 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006221 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006222 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
6223 }
6224
Bram Moolenaar071d4272004-06-13 20:20:40 +00006225 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006226
6227 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006228 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006229 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006230 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006231 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
6232 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006233 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006234 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006235 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006236 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6237 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006238 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006239 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006240
6241 redraw_later_clear();
6242 g_fTermcapMode = TRUE;
6243}
6244
6245
6246/*
6247 * End termcap mode
6248 */
6249 static void
6250termcap_mode_end(void)
6251{
6252 DWORD cmodein;
6253 ConsoleBuffer *cb;
6254 COORD coord;
6255 DWORD dwDummy;
6256
6257 if (!g_fTermcapMode)
6258 return;
6259
6260 SaveConsoleBuffer(&g_cbTermcap);
6261
6262 GetConsoleMode(g_hConIn, &cmodein);
6263 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006264 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6265 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006266
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006267# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01006268 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006269# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006270 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006271# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006272 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01006273 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006274
Christopher Plewright1140b512022-11-12 18:46:05 +00006275 // VTP uses alternate screen buffer.
6276 // Switch back to main screen buffer.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00006277 if (exiting && use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00006278 vtp_printf("\033[?1049l");
6279
6280 if (!USE_WT && (p_rs || exiting))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006281 {
6282 /*
6283 * Clear anything that happens to be on the current line.
6284 */
6285 coord.X = 0;
6286 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
Christopher Plewright1140b512022-11-12 18:46:05 +00006287 if (!vtp_working)
6288 FillConsoleOutputCharacter(g_hConOut, ' ',
6289 cb->Info.dwSize.X, coord, &dwDummy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006290 /*
6291 * The following is just for aesthetics. If we are exiting without
6292 * restoring the screen, then we want to have a prompt string
6293 * appear at the bottom line. However, the command interpreter
6294 * seems to always advance the cursor one line before displaying
6295 * the prompt string, which causes the screen to scroll. To
6296 * counter this, move the cursor up one line before exiting.
6297 */
6298 if (exiting && !p_rs)
6299 coord.Y--;
6300 /*
6301 * Position the cursor at the leftmost column of the desired row.
6302 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006303 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006304 }
Christopher Plewright1140b512022-11-12 18:46:05 +00006305 SetConsoleCursorInfo(g_hConOut, &g_cci);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006306 g_fTermcapMode = FALSE;
6307}
Christopher Plewright38804d62022-11-09 23:55:52 +00006308#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006309
6310
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006311#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006312 void
6313mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01006314 char_u *s UNUSED,
6315 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006316{
Bram Moolenaar0f873732019-12-05 20:28:46 +01006317 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00006318}
6319
6320#else
6321
6322/*
6323 * clear `n' chars, starting from `coord'
6324 */
6325 static void
6326clear_chars(
6327 COORD coord,
6328 DWORD n)
6329{
Christopher Plewright38804d62022-11-09 23:55:52 +00006330 if (!vtp_working)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006331 {
6332 DWORD dwDummy;
6333
6334 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
6335 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
6336 &dwDummy);
6337 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006338 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02006339 {
6340 set_console_color_rgb();
6341 gotoxy(coord.X + 1, coord.Y + 1);
6342 vtp_printf("\033[%dX", n);
6343 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006344}
6345
6346
6347/*
6348 * Clear the screen
6349 */
6350 static void
6351clear_screen(void)
6352{
6353 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006354
Christopher Plewright38804d62022-11-09 23:55:52 +00006355 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006356 clear_chars(g_coord, Rows * Columns);
6357 else
6358 {
6359 set_console_color_rgb();
6360 gotoxy(1, 1);
6361 vtp_printf("\033[2J");
6362 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006363}
6364
6365
6366/*
6367 * Clear to end of display
6368 */
6369 static void
6370clear_to_end_of_display(void)
6371{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006372 COORD save = g_coord;
6373
Christopher Plewright38804d62022-11-09 23:55:52 +00006374 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006375 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006376 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006377 else
6378 {
6379 set_console_color_rgb();
6380 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6381 vtp_printf("\033[0J");
6382
6383 gotoxy(save.X + 1, save.Y + 1);
6384 g_coord = save;
6385 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006386}
6387
6388
6389/*
6390 * Clear to end of line
6391 */
6392 static void
6393clear_to_end_of_line(void)
6394{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006395 COORD save = g_coord;
6396
Christopher Plewright38804d62022-11-09 23:55:52 +00006397 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006398 clear_chars(g_coord, Columns - g_coord.X);
6399 else
6400 {
6401 set_console_color_rgb();
6402 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6403 vtp_printf("\033[0K");
6404
6405 gotoxy(save.X + 1, save.Y + 1);
6406 g_coord = save;
6407 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006408}
6409
6410
6411/*
6412 * Scroll the scroll region up by `cLines' lines
6413 */
6414 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006415scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006416{
6417 COORD oldcoord = g_coord;
6418
6419 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6420 delete_lines(cLines);
6421
6422 g_coord = oldcoord;
6423}
6424
6425
6426/*
6427 * Set the scroll region
6428 */
6429 static void
6430set_scroll_region(
6431 unsigned left,
6432 unsigned top,
6433 unsigned right,
6434 unsigned bottom)
6435{
6436 if (left >= right
6437 || top >= bottom
6438 || right > (unsigned) Columns - 1
6439 || bottom > (unsigned) Rows - 1)
6440 return;
6441
6442 g_srScrollRegion.Left = left;
6443 g_srScrollRegion.Top = top;
6444 g_srScrollRegion.Right = right;
6445 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006446}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006447
Bram Moolenaar6982f422019-02-16 16:48:01 +01006448 static void
6449set_scroll_region_tb(
6450 unsigned top,
6451 unsigned bottom)
6452{
6453 if (top >= bottom || bottom > (unsigned)Rows - 1)
6454 return;
6455
6456 g_srScrollRegion.Top = top;
6457 g_srScrollRegion.Bottom = bottom;
6458}
6459
6460 static void
6461set_scroll_region_lr(
6462 unsigned left,
6463 unsigned right)
6464{
6465 if (left >= right || right > (unsigned)Columns - 1)
6466 return;
6467
6468 g_srScrollRegion.Left = left;
6469 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006470}
6471
6472
6473/*
6474 * Insert `cLines' lines at the current cursor position
6475 */
6476 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006477insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006478{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006479 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006480 COORD dest;
6481 CHAR_INFO fill;
6482
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006483 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6484
Bram Moolenaar6982f422019-02-16 16:48:01 +01006485 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006486 dest.Y = g_coord.Y + cLines;
6487
Bram Moolenaar6982f422019-02-16 16:48:01 +01006488 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006489 source.Top = g_coord.Y;
6490 source.Right = g_srScrollRegion.Right;
6491 source.Bottom = g_srScrollRegion.Bottom - cLines;
6492
Bram Moolenaar6982f422019-02-16 16:48:01 +01006493 clip.Left = g_srScrollRegion.Left;
6494 clip.Top = g_coord.Y;
6495 clip.Right = g_srScrollRegion.Right;
6496 clip.Bottom = g_srScrollRegion.Bottom;
6497
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006498 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006499 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006500# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006501 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006502# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006503 ))
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006504 fill.Attributes = g_attrCurrent;
6505 else
6506 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006507
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006508 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006509
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006510 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6511
Bram Moolenaar6982f422019-02-16 16:48:01 +01006512 // Here we have to deal with a win32 console flake: If the scroll
6513 // region looks like abc and we scroll c to a and fill with d we get
6514 // cbd... if we scroll block c one line at a time to a, we get cdd...
6515 // vim expects cdd consistently... So we have to deal with that
6516 // here... (this also occurs scrolling the same way in the other
6517 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006518
6519 if (source.Bottom < dest.Y)
6520 {
6521 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006522 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006523
Bram Moolenaar6982f422019-02-16 16:48:01 +01006524 coord.X = source.Left;
6525 for (i = clip.Top; i < dest.Y; ++i)
6526 {
6527 coord.Y = i;
6528 clear_chars(coord, source.Right - source.Left + 1);
6529 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006530 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006531
Christopher Plewright38804d62022-11-09 23:55:52 +00006532 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006533 {
6534 COORD coord;
6535 int i;
6536
6537 coord.X = source.Left;
6538 for (i = source.Top; i < dest.Y; ++i)
6539 {
6540 coord.Y = i;
6541 clear_chars(coord, source.Right - source.Left + 1);
6542 }
6543 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006544}
6545
6546
6547/*
6548 * Delete `cLines' lines at the current cursor position
6549 */
6550 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006551delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006552{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006553 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006554 COORD dest;
6555 CHAR_INFO fill;
6556 int nb;
6557
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006558 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6559
Bram Moolenaar6982f422019-02-16 16:48:01 +01006560 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006561 dest.Y = g_coord.Y;
6562
Bram Moolenaar6982f422019-02-16 16:48:01 +01006563 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006564 source.Top = g_coord.Y + cLines;
6565 source.Right = g_srScrollRegion.Right;
6566 source.Bottom = g_srScrollRegion.Bottom;
6567
Bram Moolenaar6982f422019-02-16 16:48:01 +01006568 clip.Left = g_srScrollRegion.Left;
6569 clip.Top = g_coord.Y;
6570 clip.Right = g_srScrollRegion.Right;
6571 clip.Bottom = g_srScrollRegion.Bottom;
6572
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006573 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006574 if (!vtp_working)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006575 fill.Attributes = g_attrCurrent;
6576 else
6577 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006578
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006579 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006580
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006581 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6582
Bram Moolenaar6982f422019-02-16 16:48:01 +01006583 // Here we have to deal with a win32 console flake; See insert_lines()
6584 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006585
6586 nb = dest.Y + (source.Bottom - source.Top) + 1;
6587
6588 if (nb < source.Top)
6589 {
6590 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006591 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006592
Bram Moolenaar6982f422019-02-16 16:48:01 +01006593 coord.X = source.Left;
6594 for (i = nb; i < clip.Bottom; ++i)
6595 {
6596 coord.Y = i;
6597 clear_chars(coord, source.Right - source.Left + 1);
6598 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006599 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006600
Christopher Plewright38804d62022-11-09 23:55:52 +00006601 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006602 {
6603 COORD coord;
6604 int i;
6605
6606 coord.X = source.Left;
6607 for (i = nb; i <= source.Bottom; ++i)
6608 {
6609 coord.Y = i;
6610 clear_chars(coord, source.Right - source.Left + 1);
6611 }
6612 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006613}
6614
6615
6616/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006617 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006618 */
6619 static void
6620gotoxy(
6621 unsigned x,
6622 unsigned y)
6623{
6624 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6625 return;
6626
Christopher Plewright38804d62022-11-09 23:55:52 +00006627 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006628# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006629 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006630# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006631 ))
Bram Moolenaar2313b612019-09-27 14:14:32 +02006632 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006633 // There are reports of double-width characters not displayed
6634 // correctly. This workaround should fix it, similar to how it's done
6635 // for VTP.
6636 g_coord.X = 0;
6637 SetConsoleCursorPosition(g_hConOut, g_coord);
6638
Bram Moolenaar2313b612019-09-27 14:14:32 +02006639 // external cursor coords are 1-based; internal are 0-based
6640 g_coord.X = x - 1;
6641 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006642 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006643 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006644 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006645 {
6646 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006647 // destruction. Insider build bug. Always enabled because it's cheap
6648 // and avoids mistakes with recognizing the build.
6649 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006650
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006651 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006652
6653 g_coord.X = x - 1;
6654 g_coord.Y = y - 1;
6655 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006656}
6657
6658
6659/*
6660 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006661 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006662 */
6663 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006664textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006665{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006666 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006667
6668 SetConsoleTextAttribute(g_hConOut, wAttr);
6669}
6670
6671
6672 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006673textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006674{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006675 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006676
Christopher Plewright38804d62022-11-09 23:55:52 +00006677 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006678 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6679 else
6680 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006681}
6682
6683
6684 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006685textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006686{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006687 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006688
Christopher Plewright38804d62022-11-09 23:55:52 +00006689 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006690 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6691 else
6692 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006693}
6694
6695
6696/*
6697 * restore the default text attribute (whatever we started with)
6698 */
6699 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006700normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006701{
Christopher Plewright38804d62022-11-09 23:55:52 +00006702 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006703 textattr(g_attrDefault);
6704 else
6705 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006706}
6707
6708
6709static WORD g_attrPreStandout = 0;
6710
6711/*
6712 * Make the text standout, by brightening it
6713 */
6714 static void
6715standout(void)
6716{
6717 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006718
Bram Moolenaar071d4272004-06-13 20:20:40 +00006719 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6720}
6721
6722
6723/*
6724 * Turn off standout mode
6725 */
6726 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006727standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006728{
6729 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006730 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006731
6732 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006733}
6734
6735
6736/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006737 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006738 */
6739 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006740mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006741{
6742 char_u *p;
6743 int n;
6744
6745 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6746 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006747 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006748# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006749 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006750# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006751 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006752 {
6753 p = T_ME + 2;
6754 n = getdigits(&p);
6755 if (*p == 'm' && n > 0)
6756 {
6757 cterm_normal_fg_color = (n & 0xf) + 1;
6758 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6759 }
6760 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006761# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006762 cterm_normal_fg_gui_color = INVALCOLOR;
6763 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006764# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006765}
6766
6767
6768/*
6769 * visual bell: flash the screen
6770 */
6771 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006772visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006773{
6774 COORD coordOrigin = {0, 0};
6775 WORD attrFlash = ~g_attrCurrent & 0xff;
6776
6777 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006778 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006779
6780 if (oldattrs == NULL)
6781 return;
6782 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6783 coordOrigin, &dwDummy);
6784 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6785 coordOrigin, &dwDummy);
6786
Bram Moolenaar0f873732019-12-05 20:28:46 +01006787 Sleep(15); // wait for 15 msec
Christopher Plewright38804d62022-11-09 23:55:52 +00006788 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006789 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006790 coordOrigin, &dwDummy);
6791 vim_free(oldattrs);
6792}
6793
6794
6795/*
6796 * Make the cursor visible or invisible
6797 */
6798 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006799cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006800{
6801 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006802
Christopher Plewright38804d62022-11-09 23:55:52 +00006803 if (vtp_working)
Bram Moolenaar2695de62020-04-17 21:13:01 +02006804 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6805
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006806# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006807 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006808# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006809}
6810
6811
6812/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006813 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006814 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006815 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006816 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006817write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006818 char_u *pchBuf,
6819 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006820{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006821 COORD coord = g_coord;
6822 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006823 DWORD n, cchwritten;
6824 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006825 static WCHAR *unicodebuf = NULL;
6826 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006827 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006828 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006829 static WCHAR *utf8spbuf = NULL;
6830 static int utf8splength;
6831 static DWORD utf8spcells;
6832 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006833
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006834 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006835 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006836 utf8usingbuf = &unicodebuf;
6837 do
6838 {
6839 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6840 unicodebuf, unibuflen);
6841 if (length && length <= unibuflen)
6842 break;
6843 vim_free(unicodebuf);
6844 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6845 unibuflen = unibuflen ? 0 : length;
6846 } while(1);
6847 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006848 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006849 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6850 {
6851 if (utf8usingbuf != &utf8spbuf)
6852 {
6853 if (utf8spbuf == NULL)
6854 {
6855 cells = mb_string2cells((char_u *)" ", 1);
6856 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6857 utf8spbuf = LALLOC_MULT(WCHAR, length);
6858 if (utf8spbuf != NULL)
6859 {
6860 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6861 utf8usingbuf = &utf8spbuf;
6862 utf8splength = length;
6863 utf8spcells = cells;
6864 }
6865 }
6866 else
6867 {
6868 utf8usingbuf = &utf8spbuf;
6869 length = utf8splength;
6870 cells = utf8spcells;
6871 }
6872 }
6873 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006874
Christopher Plewright38804d62022-11-09 23:55:52 +00006875 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006876# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006877 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006878# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006879 ))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006880 {
6881 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6882 coord, &written);
6883 // When writing fails or didn't write a single character, pretend one
6884 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006885 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006886 coord, &cchwritten) == 0
6887 || cchwritten == 0 || cchwritten == (DWORD)-1)
6888 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006889 }
6890 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006891 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006892 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006893 NULL) == 0 || cchwritten == 0)
6894 cchwritten = 1;
6895 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006896
K.Takata135e1522022-01-29 15:27:58 +00006897 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006898 {
6899 written = cbToWrite;
6900 g_coord.X += (SHORT)cells;
6901 }
6902 else
6903 {
6904 char_u *p = pchBuf;
6905 for (n = 0; n < cchwritten; n++)
6906 MB_CPTR_ADV(p);
6907 written = p - pchBuf;
6908 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006909 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006910
6911 while (g_coord.X > g_srScrollRegion.Right)
6912 {
6913 g_coord.X -= (SHORT) Columns;
6914 if (g_coord.Y < g_srScrollRegion.Bottom)
6915 g_coord.Y++;
6916 }
6917
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006918 // Cursor under VTP is always in the correct position, no need to reset.
Christopher Plewright38804d62022-11-09 23:55:52 +00006919 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006920# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006921 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006922# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006923 ))
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006924 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006925
6926 return written;
6927}
6928
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006929 static char_u *
6930get_seq(
6931 int *args,
6932 int *count,
6933 char_u *head)
6934{
6935 int argc;
6936 char_u *p;
6937
6938 if (head == NULL || *head != '\033')
6939 return NULL;
6940
6941 argc = 0;
6942 p = head;
6943 ++p;
6944 do
6945 {
6946 ++p;
6947 args[argc] = getdigits(&p);
6948 argc += (argc < 15) ? 1 : 0;
6949 } while (*p == ';');
6950 *count = argc;
6951
6952 return p;
6953}
6954
6955 static char_u *
6956get_sgr(
6957 int *args,
6958 int *count,
6959 char_u *head)
6960{
6961 char_u *p = get_seq(args, count, head);
6962
6963 return (p && *p == 'm') ? ++p : NULL;
6964}
6965
6966/*
6967 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6968 */
6969 static char_u *
6970sgrn2(
6971 char_u *head,
6972 int n)
6973{
6974 int argc;
6975 int args[16];
6976 char_u *p = get_sgr(args, &argc, head);
6977
6978 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6979}
6980
6981/*
6982 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6983 */
6984 static char_u *
6985sgrnc(
6986 char_u *head,
6987 int n)
6988{
6989 int argc;
6990 int args[16];
6991 char_u *p = get_sgr(args, &argc, head);
6992
6993 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6994 ? p : NULL;
6995}
6996
6997 static char_u *
6998skipblank(char_u *q)
6999{
7000 char_u *p = q;
7001
7002 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
7003 ++p;
7004 return p;
7005}
7006
7007/*
7008 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
7009 * NULL.
7010 */
7011 static char_u *
7012sgrn2c(
7013 char_u *head,
7014 int n)
7015{
7016 char_u *p = sgrn2(head, n);
7017
7018 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
7019}
7020
7021/*
7022 * If there is only a newline between the sequence immediately following it,
7023 * a pointer to the character following the newline is returned.
7024 * Otherwise NULL.
7025 */
7026 static char_u *
7027sgrn2cn(
7028 char_u *head,
7029 int n)
7030{
7031 char_u *p = sgrn2(head, n);
7032
7033 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
7034}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007035
7036/*
7037 * mch_write(): write the output buffer to the screen, translating ESC
7038 * sequences into calls to console output routines.
7039 */
7040 void
7041mch_write(
7042 char_u *s,
7043 int len)
7044{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007045 char_u *end = s + len;
7046
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007047# ifdef VIMDLL
7048 if (gui.in_use)
7049 return;
7050# endif
7051
Bram Moolenaar071d4272004-06-13 20:20:40 +00007052 if (!term_console)
7053 {
7054 write(1, s, (unsigned)len);
7055 return;
7056 }
7057
Bram Moolenaar0f873732019-12-05 20:28:46 +01007058 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00007059 while (len--)
7060 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007061 int prefix = -1;
7062 char_u ch;
7063
7064 // While processing a sequence, on rare occasions it seems that another
7065 // sequence may be inserted asynchronously.
7066 if (len < 0)
7067 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01007068 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007069 return;
7070 }
7071
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007072 while (s + ++prefix < end)
7073 {
7074 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007075 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
7076 && ch != '\a' && ch != '\033'))
7077 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007078 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007079
7080 if (p_wd)
7081 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007082 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007083 if (prefix != 0)
7084 prefix = 1;
7085 }
7086
7087 if (prefix != 0)
7088 {
7089 DWORD nWritten;
7090
7091 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007092# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007093 if (fdDump)
7094 {
7095 fputc('>', fdDump);
7096 fwrite(s, sizeof(char_u), nWritten, fdDump);
7097 fputs("<\n", fdDump);
7098 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007099# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007100 len -= (nWritten - 1);
7101 s += nWritten;
7102 }
7103 else if (s[0] == '\n')
7104 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007105 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00007106 if (g_coord.Y == g_srScrollRegion.Bottom)
7107 {
7108 scroll(1);
7109 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
7110 }
7111 else
7112 {
7113 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
7114 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007115# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007116 if (fdDump)
7117 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007118# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007119 s++;
7120 }
7121 else if (s[0] == '\r')
7122 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007123 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00007124 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007125# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007126 if (fdDump)
7127 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007128# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007129 s++;
7130 }
7131 else if (s[0] == '\b')
7132 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007133 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00007134 if (g_coord.X > g_srScrollRegion.Left)
7135 g_coord.X--;
7136 else if (g_coord.Y > g_srScrollRegion.Top)
7137 {
7138 g_coord.X = g_srScrollRegion.Right;
7139 g_coord.Y--;
7140 }
7141 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007142# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007143 if (fdDump)
7144 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007145# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007146 s++;
7147 }
7148 else if (s[0] == '\a')
7149 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007150 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00007151 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007152# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007153 if (fdDump)
7154 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007155# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007156 s++;
7157 }
7158 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
7159 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007160# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007161 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007162# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007163 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007164 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007165 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007166
7167 switch (s[2])
7168 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007169 case '0': case '1': case '2': case '3': case '4':
7170 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007171 if (*(p = get_seq(args, &argc, s)) != 'm')
7172 goto notsgr;
7173
7174 p = s;
7175
7176 // Handling frequent optional sequences. Output to the screen
7177 // takes too long, so do not output as much as possible.
7178
7179 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
7180 // resetFG,FG,BG are omitted.
7181 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007182 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007183 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
7184 len = len + 1 - (int)(p - s);
7185 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007186 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007187 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007188
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007189 // If FG,BG,BG,FG of SGR are connected, the first FG can be
7190 // omitted.
7191 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
7192 p = sp;
7193
7194 // If FG,BG,FG,BG of SGR are connected, the first FG can be
7195 // omitted.
7196 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
7197 p = sp;
7198
7199 // If BG,BG of SGR are connected, the first BG can be omitted.
7200 if (sgrn2((sp = sgrn2(p, 48)), 48))
7201 p = sp;
7202
7203 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007204 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007205 if (sgrn2((sp = sgrnc(p, 39)), 38))
7206 p = sp;
7207
7208 p = get_seq(args, &argc, p);
7209
7210notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007211 arg1 = args[0];
7212 arg2 = args[1];
7213 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007214 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007215 if (argc == 1 && args[0] == 0)
7216 normvideo();
7217 else if (argc == 1)
7218 {
Christopher Plewright38804d62022-11-09 23:55:52 +00007219 if (vtp_working
7220# ifdef FEAT_TERMGUICOLORS
7221 && (p_tgc || t_colors >= 256)
7222# endif
7223 )
7224 textcolor((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007225 else
Christopher Plewright38804d62022-11-09 23:55:52 +00007226 textattr((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007227 }
Christopher Plewright38804d62022-11-09 23:55:52 +00007228 else if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007229 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007230 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007231 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007232 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007233 gotoxy(arg2, arg1);
7234 }
7235 else if (argc == 2 && *p == 'r')
7236 {
7237 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
7238 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01007239 else if (argc == 2 && *p == 'R')
7240 {
7241 set_scroll_region_tb(arg1, arg2);
7242 }
7243 else if (argc == 2 && *p == 'V')
7244 {
7245 set_scroll_region_lr(arg1, arg2);
7246 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007247 else if (argc == 1 && *p == 'A')
7248 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007249 gotoxy(g_coord.X + 1,
7250 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
7251 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007252 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007253 {
7254 textbackground((WORD) arg1);
7255 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007256 else if (argc == 1 && *p == 'C')
7257 {
7258 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
7259 g_coord.Y + 1);
7260 }
7261 else if (argc == 1 && *p == 'f')
7262 {
7263 textcolor((WORD) arg1);
7264 }
7265 else if (argc == 1 && *p == 'H')
7266 {
7267 gotoxy(1, arg1);
7268 }
7269 else if (argc == 1 && *p == 'L')
7270 {
7271 insert_lines(arg1);
7272 }
7273 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007274 {
7275 delete_lines(arg1);
7276 }
7277
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007278 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007279 s = p + 1;
7280 break;
7281
Bram Moolenaar071d4272004-06-13 20:20:40 +00007282 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007283 gotoxy(g_coord.X + 1,
7284 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
7285 goto got3;
7286
7287 case 'B':
7288 visual_bell();
7289 goto got3;
7290
7291 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007292 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
7293 g_coord.Y + 1);
7294 goto got3;
7295
7296 case 'E':
7297 termcap_mode_end();
7298 goto got3;
7299
7300 case 'F':
7301 standout();
7302 goto got3;
7303
7304 case 'f':
7305 standend();
7306 goto got3;
7307
7308 case 'H':
7309 gotoxy(1, 1);
7310 goto got3;
7311
7312 case 'j':
7313 clear_to_end_of_display();
7314 goto got3;
7315
7316 case 'J':
7317 clear_screen();
7318 goto got3;
7319
7320 case 'K':
7321 clear_to_end_of_line();
7322 goto got3;
7323
7324 case 'L':
7325 insert_lines(1);
7326 goto got3;
7327
7328 case 'M':
7329 delete_lines(1);
7330 goto got3;
7331
7332 case 'S':
7333 termcap_mode_start();
7334 goto got3;
7335
7336 case 'V':
7337 cursor_visible(TRUE);
7338 goto got3;
7339
7340 case 'v':
7341 cursor_visible(FALSE);
7342 goto got3;
7343
7344 got3:
7345 s += 3;
7346 len -= 2;
7347 }
7348
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007349# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007350 if (fdDump)
7351 {
7352 fputs("ESC | ", fdDump);
7353 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
7354 fputc('\n', fdDump);
7355 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007356# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007357 }
K.Takatadf5320c2022-09-01 13:20:16 +01007358 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
7359 {
7360 int l = 2;
7361
7362 if (isdigit(s[l]))
7363 l++;
7364 if (s[l] == ' ' && s[l + 1] == 'q')
7365 {
7366 // DECSCUSR (cursor style) sequences
Christopher Plewright38804d62022-11-09 23:55:52 +00007367 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01007368 vtp_printf("%.*s", l + 2, s); // Pass through
7369 s += l + 2;
7370 len -= l + 1;
7371 }
7372 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007373 else
7374 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007375 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00007376 DWORD nWritten;
7377
7378 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007379# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007380 if (fdDump)
7381 {
7382 fputc('>', fdDump);
7383 fwrite(s, sizeof(char_u), nWritten, fdDump);
7384 fputs("<\n", fdDump);
7385 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007386# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007387
7388 len -= (nWritten - 1);
7389 s += nWritten;
7390 }
7391 }
7392
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007393# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007394 if (fdDump)
7395 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007396# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007397}
7398
Bram Moolenaar0f873732019-12-05 20:28:46 +01007399#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00007400
7401
7402/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01007403 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007404 */
7405 void
7406mch_delay(
7407 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02007408 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007409{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007410#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007411 Sleep((int)msec); // never wait for input
7412#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007413# ifdef VIMDLL
7414 if (gui.in_use)
7415 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007416 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007417 return;
7418 }
7419# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02007420 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007421# ifdef FEAT_MZSCHEME
7422 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
7423 {
7424 int towait = p_mzq;
7425
Bram Moolenaar0f873732019-12-05 20:28:46 +01007426 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007427 while (msec > 0)
7428 {
7429 mzvim_check_threads();
7430 if (msec < towait)
7431 towait = msec;
7432 Sleep(towait);
7433 msec -= towait;
7434 }
7435 }
7436 else
7437# endif
7438 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007439 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007440 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007441#endif
7442}
7443
7444
7445/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01007446 * This version of remove is not scared by a readonly (backup) file.
7447 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007448 * Return 0 for success, -1 for failure.
7449 */
7450 int
7451mch_remove(char_u *name)
7452{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007453 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007454 int n;
7455
Bram Moolenaar203258c2016-01-17 22:15:16 +01007456 /*
7457 * On Windows, deleting a directory's symbolic link is done by
7458 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
7459 */
7460 if (mch_isdir(name) && mch_is_symbolic_link(name))
7461 return mch_rmdir(name);
7462
Bram Moolenaar12b559e2013-06-12 22:41:37 +02007463 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
7464
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007465 wn = enc_to_utf16(name, NULL);
7466 if (wn == NULL)
7467 return -1;
7468
7469 n = DeleteFileW(wn) ? 0 : -1;
7470 vim_free(wn);
7471 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007472}
7473
7474
7475/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007476 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007477 */
7478 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007479mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007480{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007481#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7482# ifdef VIMDLL
7483 if (!gui.in_use)
7484# endif
7485 if (g_fCtrlCPressed || g_fCBrkPressed)
7486 {
7487 ctrl_break_was_pressed = g_fCBrkPressed;
7488 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7489 got_int = TRUE;
7490 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007491#endif
7492}
7493
Bram Moolenaar0f873732019-12-05 20:28:46 +01007494// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007495#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007496
7497/*
7498 * How much main memory in KiB that can be used by VIM.
7499 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007500 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007501mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007502{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007503 MEMORYSTATUSEX ms;
7504
Bram Moolenaar0f873732019-12-05 20:28:46 +01007505 // Need to use GlobalMemoryStatusEx() when there is more memory than
7506 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007507 ms.dwLength = sizeof(MEMORYSTATUSEX);
7508 GlobalMemoryStatusEx(&ms);
7509 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007510 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007511 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007512 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007513 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007514 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007515 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007516 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007517 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007518 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007519 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007520 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007521}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007522
Bram Moolenaar071d4272004-06-13 20:20:40 +00007523/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007524 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00007525 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
7526 * file whose short file name is "FOO.BAR" (its long file name will
7527 * be correct: "foo.bar~"). Because a file can be accessed by
7528 * either its SFN or its LFN, "foo.bar" has effectively been
7529 * renamed to "foo.bar", which is not at all what was wanted. This
7530 * seems to happen only when renaming files with three-character
7531 * extensions by appending a suffix that does not include ".".
7532 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
7533 *
7534 * There is another problem, which isn't really a bug but isn't right either:
7535 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
7536 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
7537 * service pack 6. Doesn't seem to happen on Windows 98.
7538 *
7539 * Like rename(), returns 0 upon success, non-zero upon failure.
7540 * Should probably set errno appropriately when errors occur.
7541 */
7542 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007543mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007544{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007545 WCHAR *p;
7546 int i;
7547 WCHAR szTempFile[_MAX_PATH + 1];
7548 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007549 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007550
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007551 // No need to play tricks unless the file name contains a "~" as the
7552 // seventh character.
7553 p = wold;
7554 for (i = 0; wold[i] != NUL; ++i)
7555 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
7556 && wold[i + 1] != 0)
7557 p = wold + i + 1;
7558 if ((int)(wold + i - p) < 8 || p[6] != '~')
7559 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007560
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007561 // Get base path of new file name. Undocumented feature: If pszNewFile is
7562 // a directory, no error is returned and pszFilePart will be NULL.
7563 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007564 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007565 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007566
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007567 // Get (and create) a unique temporary file name in directory of new file
7568 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007569 return -2;
7570
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007571 // blow the temp file away
7572 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007573 return -3;
7574
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007575 // rename old file to the temp file
7576 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007577 return -4;
7578
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007579 // now create an empty file called pszOldFile; this prevents the operating
7580 // system using pszOldFile as an alias (SFN) if we're renaming within the
7581 // same directory. For example, we're editing a file called
7582 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7583 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7584 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7585 // cause all sorts of problems later in buf_write(). So, we create an
7586 // empty file called filena~1.txt and the system will have to find some
7587 // other SFN for filena~1.txt~, such as filena~2.txt
7588 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007589 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7590 return -5;
7591 if (!CloseHandle(hf))
7592 return -6;
7593
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007594 // rename the temp file to the new file
7595 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007596 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007597 // Renaming failed. Rename the file back to its old name, so that it
7598 // looks like nothing happened.
7599 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007600 return -7;
7601 }
7602
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007603 // Seems to be left around on Novell filesystems
7604 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007605
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007606 // finally, remove the empty old file
7607 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007608 return -8;
7609
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007610 return 0;
7611}
7612
7613
7614/*
7615 * Converts the filenames to UTF-16, then call mch_wrename().
7616 * Like rename(), returns 0 upon success, non-zero upon failure.
7617 */
7618 int
7619mch_rename(
7620 const char *pszOldFile,
7621 const char *pszNewFile)
7622{
7623 WCHAR *wold = NULL;
7624 WCHAR *wnew = NULL;
7625 int retval = -1;
7626
7627 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7628 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7629 if (wold != NULL && wnew != NULL)
7630 retval = mch_wrename(wold, wnew);
7631 vim_free(wold);
7632 vim_free(wnew);
7633 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007634}
7635
7636/*
7637 * Get the default shell for the current hardware platform
7638 */
7639 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007640default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007641{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007642 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007643}
7644
7645/*
7646 * mch_access() extends access() to do more detailed check on network drives.
7647 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7648 */
7649 int
7650mch_access(char *n, int p)
7651{
7652 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007653 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007654 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007655
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007656 wn = enc_to_utf16((char_u *)n, NULL);
7657 if (wn == NULL)
7658 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007659
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007660 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007661 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007662 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007663
7664 if (p & R_OK)
7665 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007666 // Read check is performed by seeing if we can do a find file on
7667 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007668 int i;
7669 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007670
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007671 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7672 TempNameW[i] = wn[i];
7673 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7674 TempNameW[i++] = '\\';
7675 TempNameW[i++] = '*';
7676 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007677
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007678 hFile = FindFirstFileW(TempNameW, &d);
7679 if (hFile == INVALID_HANDLE_VALUE)
7680 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007681 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007682 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007683 }
7684
7685 if (p & W_OK)
7686 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007687 // Trying to create a temporary file in the directory should catch
7688 // directories on read-only network shares. However, in
7689 // directories whose ACL allows writes but denies deletes will end
7690 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007691 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7692 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007693 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007694 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007695 }
7696 }
7697 else
7698 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007699 // Don't consider a file read-only if another process has opened it.
7700 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7701
Bram Moolenaar0f873732019-12-05 20:28:46 +01007702 // Trying to open the file for the required access does ACL, read-only
7703 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007704 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7705 | ((p & R_OK) ? GENERIC_READ : 0);
7706
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007707 hFile = CreateFileW(wn, access_mode, share_mode,
7708 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007709 if (hFile == INVALID_HANDLE_VALUE)
7710 goto getout;
7711 CloseHandle(hFile);
7712 }
7713
Bram Moolenaar0f873732019-12-05 20:28:46 +01007714 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007715getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007716 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007717 return retval;
7718}
7719
Bram Moolenaar071d4272004-06-13 20:20:40 +00007720/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007721 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007722 */
7723 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007724mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007725{
7726 WCHAR *wn;
7727 int f;
7728
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007729 wn = enc_to_utf16((char_u *)name, NULL);
7730 if (wn == NULL)
7731 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007732
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007733 f = _wopen(wn, flags, mode);
7734 vim_free(wn);
7735 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007736}
7737
7738/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007739 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007740 */
7741 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007742mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007743{
7744 WCHAR *wn, *wm;
7745 FILE *f = NULL;
7746
Bram Moolenaara12a1612019-01-24 16:39:02 +01007747#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007748 // Work around an annoying assertion in the Microsoft debug CRT
7749 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007750 char newMode = mode[strlen(mode) - 1];
7751 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007752
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007753 _get_fmode(&oldMode);
7754 if (newMode == 't')
7755 _set_fmode(_O_TEXT);
7756 else if (newMode == 'b')
7757 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007758#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007759 wn = enc_to_utf16((char_u *)name, NULL);
7760 wm = enc_to_utf16((char_u *)mode, NULL);
7761 if (wn != NULL && wm != NULL)
7762 f = _wfopen(wn, wm);
7763 vim_free(wn);
7764 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007765
Bram Moolenaara12a1612019-01-24 16:39:02 +01007766#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007767 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007768#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007769 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007770}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007771
Bram Moolenaar071d4272004-06-13 20:20:40 +00007772/*
7773 * SUB STREAM (aka info stream) handling:
7774 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007775 * NTFS can have sub streams for each file. The normal contents of a file is
7776 * stored in the main stream, and extra contents (author information, title and
7777 * so on) can be stored in a sub stream. After Windows 2000, the user can
7778 * access and store this information in sub streams via an explorer's property
7779 * menu item in the right click menu. This information in sub streams was lost
7780 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007781 *
7782 * Incomplete explanation:
7783 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7784 * More useful info and an example:
7785 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7786 */
7787
7788/*
7789 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7790 * and write to stream "substream" of file "to".
7791 * Errors are ignored.
7792 */
7793 static void
7794copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7795{
7796 HANDLE hTo;
7797 WCHAR *to_name;
7798
7799 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7800 wcscpy(to_name, to);
7801 wcscat(to_name, substream);
7802
7803 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7804 FILE_ATTRIBUTE_NORMAL, NULL);
7805 if (hTo != INVALID_HANDLE_VALUE)
7806 {
7807 long done;
7808 DWORD todo;
7809 DWORD readcnt, written;
7810 char buf[4096];
7811
Bram Moolenaar0f873732019-12-05 20:28:46 +01007812 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007813 for (done = 0; done < len; done += written)
7814 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007815 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007816 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7817 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007818 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7819 FALSE, FALSE, context)
7820 || readcnt != todo
7821 || !WriteFile(hTo, buf, todo, &written, NULL)
7822 || written != todo)
7823 break;
7824 }
7825 CloseHandle(hTo);
7826 }
7827
7828 free(to_name);
7829}
7830
7831/*
7832 * Copy info streams from file "from" to file "to".
7833 */
7834 static void
7835copy_infostreams(char_u *from, char_u *to)
7836{
7837 WCHAR *fromw;
7838 WCHAR *tow;
7839 HANDLE sh;
7840 WIN32_STREAM_ID sid;
7841 int headersize;
7842 WCHAR streamname[_MAX_PATH];
7843 DWORD readcount;
7844 void *context = NULL;
7845 DWORD lo, hi;
7846 int len;
7847
Bram Moolenaar0f873732019-12-05 20:28:46 +01007848 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007849 fromw = enc_to_utf16(from, NULL);
7850 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007851 if (fromw != NULL && tow != NULL)
7852 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007853 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007854 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7855 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7856 if (sh != INVALID_HANDLE_VALUE)
7857 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007858 // Use BackupRead() to find the info streams. Repeat until we
7859 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007860 for (;;)
7861 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007862 // Get the header to find the length of the stream name. If
7863 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007864 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007865 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007866 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7867 &readcount, FALSE, FALSE, &context)
7868 || readcount == 0)
7869 break;
7870
Bram Moolenaar0f873732019-12-05 20:28:46 +01007871 // We only deal with streams that have a name. The normal
7872 // file data appears to be without a name, even though docs
7873 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007874 if (sid.dwStreamNameSize > 0)
7875 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007876 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007877 if (!BackupRead(sh, (LPBYTE)streamname,
7878 sid.dwStreamNameSize,
7879 &readcount, FALSE, FALSE, &context))
7880 break;
7881
Bram Moolenaar0f873732019-12-05 20:28:46 +01007882 // Copy an info stream with a name ":anything:$DATA".
7883 // Skip "::$DATA", it has no stream name (examples suggest
7884 // it might be used for the normal file contents).
7885 // Note that BackupRead() counts bytes, but the name is in
7886 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007887 len = readcount / sizeof(WCHAR);
7888 streamname[len] = 0;
7889 if (len > 7 && wcsicmp(streamname + len - 6,
7890 L":$DATA") == 0)
7891 {
7892 streamname[len - 6] = 0;
7893 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007894 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007895 }
7896 }
7897
Bram Moolenaar0f873732019-12-05 20:28:46 +01007898 // Advance to the next stream. We might try seeking too far,
7899 // but BackupSeek() doesn't skip over stream borders, thus
7900 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007901 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007902 &lo, &hi, &context);
7903 }
7904
Bram Moolenaar0f873732019-12-05 20:28:46 +01007905 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007906 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7907
7908 CloseHandle(sh);
7909 }
7910 }
7911 vim_free(fromw);
7912 vim_free(tow);
7913}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007914
7915/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007916 * ntdll.dll definitions
7917 */
7918#define FileEaInformation 7
7919#ifndef STATUS_SUCCESS
7920# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7921#endif
7922
7923typedef struct _FILE_FULL_EA_INFORMATION_ {
7924 ULONG NextEntryOffset;
7925 UCHAR Flags;
7926 UCHAR EaNameLength;
7927 USHORT EaValueLength;
7928 CHAR EaName[1];
7929} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7930
7931typedef struct _FILE_EA_INFORMATION_ {
7932 ULONG EaSize;
7933} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7934
Paul Ollis65745772022-06-05 16:55:54 +01007935#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007936typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7937 PHANDLE FileHandle,
7938 ACCESS_MASK DesiredAccess,
7939 POBJECT_ATTRIBUTES ObjectAttributes,
7940 PIO_STATUS_BLOCK IoStatusBlock,
7941 ULONG ShareAccess,
7942 ULONG OpenOptions);
7943typedef NTSTATUS (NTAPI *PfnNtClose)(
7944 HANDLE Handle);
7945typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007946 HANDLE FileHandle,
7947 PIO_STATUS_BLOCK IoStatusBlock,
7948 PVOID Buffer,
7949 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007950typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7951 HANDLE FileHandle,
7952 PIO_STATUS_BLOCK IoStatusBlock,
7953 PVOID Buffer,
7954 ULONG Length,
7955 BOOLEAN ReturnSingleEntry,
7956 PVOID EaList,
7957 ULONG EaListLength,
7958 PULONG EaIndex,
7959 BOOLEAN RestartScan);
7960typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007961 HANDLE FileHandle,
7962 PIO_STATUS_BLOCK IoStatusBlock,
7963 PVOID FileInformation,
7964 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007965 FILE_INFORMATION_CLASS FileInformationClass);
7966typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7967 PUNICODE_STRING DestinationString,
7968 PCWSTR SourceString);
7969
7970PfnNtOpenFile pNtOpenFile = NULL;
7971PfnNtClose pNtClose = NULL;
7972PfnNtSetEaFile pNtSetEaFile = NULL;
7973PfnNtQueryEaFile pNtQueryEaFile = NULL;
7974PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7975PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01007976#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007977
7978/*
7979 * Load ntdll.dll functions.
7980 */
7981 static BOOL
7982load_ntdll(void)
7983{
7984 static int loaded = -1;
7985
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00007986 if (loaded != -1)
7987 return (BOOL) loaded;
7988
7989 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7990 if (hNtdll != NULL)
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007991 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00007992 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7993 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7994 pNtSetEaFile = (PfnNtSetEaFile)
7995 GetProcAddress(hNtdll, "NtSetEaFile");
7996 pNtQueryEaFile = (PfnNtQueryEaFile)
7997 GetProcAddress(hNtdll, "NtQueryEaFile");
7998 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7999 GetProcAddress(hNtdll, "NtQueryInformationFile");
8000 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
8001 GetProcAddress(hNtdll, "RtlInitUnicodeString");
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008002 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008003 if (pNtOpenFile == NULL
8004 || pNtClose == NULL
8005 || pNtSetEaFile == NULL
8006 || pNtQueryEaFile == NULL
8007 || pNtQueryInformationFile == NULL
8008 || pRtlInitUnicodeString == NULL)
8009 loaded = FALSE;
8010 else
8011 loaded = TRUE;
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008012 return (BOOL) loaded;
8013}
8014
8015/*
8016 * Copy extended attributes (EA) from file "from" to file "to".
8017 */
8018 static void
8019copy_extattr(char_u *from, char_u *to)
8020{
8021 char_u *fromf = NULL;
8022 char_u *tof = NULL;
8023 WCHAR *fromw = NULL;
8024 WCHAR *tow = NULL;
8025 UNICODE_STRING u;
8026 HANDLE h;
8027 OBJECT_ATTRIBUTES oa;
8028 IO_STATUS_BLOCK iosb;
8029 FILE_EA_INFORMATION_ eainfo = {0};
8030 void *ea = NULL;
8031
8032 if (!load_ntdll())
8033 return;
8034
8035 // Convert the file names to the fully qualified object names.
8036 fromf = alloc(STRLEN(from) + 5);
8037 tof = alloc(STRLEN(to) + 5);
8038 if (fromf == NULL || tof == NULL)
8039 goto theend;
8040 STRCPY(fromf, "\\??\\");
8041 STRCAT(fromf, from);
8042 STRCPY(tof, "\\??\\");
8043 STRCAT(tof, to);
8044
8045 // Convert the names to wide characters.
8046 fromw = enc_to_utf16(fromf, NULL);
8047 tow = enc_to_utf16(tof, NULL);
8048 if (fromw == NULL || tow == NULL)
8049 goto theend;
8050
8051 // Get the EA.
8052 pRtlInitUnicodeString(&u, fromw);
8053 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8054 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
8055 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8056 goto theend;
8057 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
8058 FileEaInformation);
8059 if (eainfo.EaSize != 0)
8060 {
8061 ea = alloc(eainfo.EaSize);
8062 if (ea != NULL)
8063 {
8064 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
8065 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
8066 {
8067 vim_free(ea);
8068 ea = NULL;
8069 }
8070 }
8071 }
8072 pNtClose(h);
8073
8074 // Set the EA.
8075 if (ea != NULL)
8076 {
8077 pRtlInitUnicodeString(&u, tow);
8078 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8079 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
8080 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8081 goto theend;
8082
8083 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
8084 pNtClose(h);
8085 }
8086
8087theend:
8088 vim_free(fromf);
8089 vim_free(tof);
8090 vim_free(fromw);
8091 vim_free(tow);
8092 vim_free(ea);
8093}
8094
8095/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008096 * Copy file attributes from file "from" to file "to".
8097 * For Windows NT and later we copy info streams.
8098 * Always returns zero, errors are ignored.
8099 */
8100 int
8101mch_copy_file_attribute(char_u *from, char_u *to)
8102{
Bram Moolenaar0f873732019-12-05 20:28:46 +01008103 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02008104 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008105 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008106 return 0;
8107}
8108
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008109
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008110/*
K.Takatadc73b4b2021-06-08 18:32:36 +02008111 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008112 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008113static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008114static LPWSTR *ArglistW = NULL;
8115static int global_argc = 0;
8116static char **global_argv;
8117
Bram Moolenaar0f873732019-12-05 20:28:46 +01008118static int used_file_argc = 0; // last argument in global_argv[] used
8119 // for the argument list.
8120static int *used_file_indexes = NULL; // indexes in global_argv[] for
8121 // command line arguments added to
8122 // the argument list
8123static int used_file_count = 0; // nr of entries in used_file_indexes
8124static int used_file_literal = FALSE; // take file names literally
8125static int used_file_full_path = FALSE; // file name was full path
8126static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008127static int used_alist_count = 0;
8128
8129
8130/*
8131 * Get the command line arguments. Unicode version.
8132 * Returns argc. Zero when something fails.
8133 */
8134 int
8135get_cmd_argsW(char ***argvp)
8136{
8137 char **argv = NULL;
8138 int argc = 0;
8139 int i;
8140
Bram Moolenaar14993322014-09-09 12:25:33 +02008141 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008142 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
8143 if (ArglistW != NULL)
8144 {
8145 argv = malloc((nArgsW + 1) * sizeof(char *));
8146 if (argv != NULL)
8147 {
8148 argc = nArgsW;
8149 argv[argc] = NULL;
8150 for (i = 0; i < argc; ++i)
8151 {
8152 int len;
8153
K.Takatadc73b4b2021-06-08 18:32:36 +02008154 // Convert each Unicode argument to UTF-8.
8155 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008156 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008157 (LPSTR *)&argv[i], &len, 0, 0);
8158 if (argv[i] == NULL)
8159 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008160 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008161 while (i > 0)
8162 free(argv[--i]);
8163 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01008164 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008165 argc = 0;
8166 }
8167 }
8168 }
8169 }
8170
8171 global_argc = argc;
8172 global_argv = argv;
8173 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02008174 {
8175 if (used_file_indexes != NULL)
8176 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008177 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02008178 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008179
8180 if (argvp != NULL)
8181 *argvp = argv;
8182 return argc;
8183}
8184
8185 void
8186free_cmd_argsW(void)
8187{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008188 if (ArglistW == NULL)
8189 return;
8190
8191 GlobalFree(ArglistW);
8192 ArglistW = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008193}
8194
8195/*
8196 * Remember "name" is an argument that was added to the argument list.
8197 * This avoids that we have to re-parse the argument list when fix_arg_enc()
8198 * is called.
8199 */
8200 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008201used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008202{
8203 int i;
8204
8205 if (used_file_indexes == NULL)
8206 return;
8207 for (i = used_file_argc + 1; i < global_argc; ++i)
8208 if (STRCMP(global_argv[i], name) == 0)
8209 {
8210 used_file_argc = i;
8211 used_file_indexes[used_file_count++] = i;
8212 break;
8213 }
8214 used_file_literal = literal;
8215 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008216 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008217}
8218
8219/*
8220 * Remember the length of the argument list as it was. If it changes then we
8221 * leave it alone when 'encoding' is set.
8222 */
8223 void
8224set_alist_count(void)
8225{
8226 used_alist_count = GARGCOUNT;
8227}
8228
8229/*
8230 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02008231 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008232 * and convert them to 'encoding'.
8233 */
8234 void
8235fix_arg_enc(void)
8236{
8237 int i;
8238 int idx;
8239 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00008240 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008241
Bram Moolenaar0f873732019-12-05 20:28:46 +01008242 // Safety checks:
8243 // - if argument count differs between the wide and non-wide argument
8244 // list, something must be wrong.
8245 // - the file name arguments must have been located.
8246 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008247 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008248 || ArglistW == NULL
8249 || used_file_indexes == NULL
8250 || used_file_count == 0
8251 || used_alist_count != GARGCOUNT)
8252 return;
8253
Bram Moolenaar0f873732019-12-05 20:28:46 +01008254 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02008255 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008256 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008257 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00008258 for (i = 0; i < GARGCOUNT; ++i)
8259 fnum_list[i] = GARGLIST[i].ae_fnum;
8260
Bram Moolenaar0f873732019-12-05 20:28:46 +01008261 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008262 alist_clear(&global_alist);
8263 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008264 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008265
8266 for (i = 0; i < used_file_count; ++i)
8267 {
8268 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008269 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008270 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00008271 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008272 int literal = used_file_literal;
8273
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008274#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01008275 // When using diff mode may need to concatenate file name to
8276 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008277 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
8278 && !mch_isdir(alist_name(&GARGLIST[0])))
8279 {
8280 char_u *r;
8281
8282 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
8283 if (r != NULL)
8284 {
8285 vim_free(str);
8286 str = r;
8287 }
8288 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008289#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01008290 // Re-use the old buffer by renaming it. When not using literal
8291 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00008292 if (used_file_literal)
8293 buf_set_name(fnum_list[i], str);
8294
Bram Moolenaar0f873732019-12-05 20:28:46 +01008295 // Check backtick literal. backtick literal is already expanded in
8296 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008297 if (literal == FALSE)
8298 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02008299 size_t len = STRLEN(str);
8300
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008301 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
8302 literal = TRUE;
8303 }
8304 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008305 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008306 }
8307
8308 if (!used_file_literal)
8309 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008310 // Now expand wildcards in the arguments.
8311 // Temporarily add '(' and ')' to 'isfname'. These are valid
8312 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00008313 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01008314 // Also, unset wildignore to not be influenced by this option.
8315 // The arguments specified in command-line should be kept even if
8316 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00008317 // Use :legacy so that it also works when in Vim9 script.
8318 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
8319 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00008320 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00008321 do_cmdline_cmd(
8322 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
8323 do_cmdline_cmd(
8324 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008325 }
8326
Bram Moolenaar0f873732019-12-05 20:28:46 +01008327 // If wildcard expansion failed, we are editing the first file of the
8328 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008329 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
8330 {
8331 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00008332 if (GARGCOUNT == 1 && used_file_full_path
8333 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
8334 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008335 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00008336
8337 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008338}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008339
8340 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02008341mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008342{
8343 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008344 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008345
Bram Moolenaar964b3742019-05-24 18:54:09 +02008346 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008347 if (envbuf == NULL)
8348 return -1;
8349
8350 sprintf((char *)envbuf, "%s=%s", var, value);
8351
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008352 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008353
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008354 vim_free(envbuf);
8355 if (p == NULL)
8356 return -1;
8357 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008358#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008359 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008360#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008361 // Unlike Un*x systems, we can free the string for _wputenv().
8362 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008363
8364 return 0;
8365}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008366
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008367/*
8368 * Support for 256 colors and 24-bit colors was added in Windows 10
8369 * version 1703 (Creators update).
8370 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008371#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
8372
8373/*
8374 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02008375 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008376 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008377#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008378
8379/*
8380 * ConPTY differences between versions, need different logic.
8381 * version 1903 (May 2019 update).
8382 */
8383#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
8384
8385/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008386 * version 1909 (November 2019 update).
8387 */
8388#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
8389
8390/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008391 * Stay ahead of the next update, and when it's done, fix this.
8392 * version ? (2020 update, temporarily use the build number of insider preview)
8393 */
8394#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
8395
8396/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02008397 * Confirm until this version. Also the logic changes.
8398 * insider preview.
8399 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02008400#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008401
8402/*
8403 * Not stable now.
8404 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008405#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Christopher Plewright1140b512022-11-12 18:46:05 +00008406// Notes:
8407// Win 10 22H2 Final is build 19045, it's conpty is widely used.
8408// Strangely, 19045 is newer but is a lower build number than the 2020 insider
8409// preview which had a build 19587. And, not sure how stable that was?
8410// Win Server 2022 (May 10, 2022) is build 20348, its conpty is widely used.
8411// Win 11 starts from build 22000, even though the major version says 10!
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008412
8413 static void
8414vtp_flag_init(void)
8415{
8416 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008417#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008418 DWORD mode;
8419 HANDLE out;
8420
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008421# ifdef VIMDLL
8422 if (!gui.in_use)
8423# endif
8424 {
8425 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008426
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008427 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
8428 GetConsoleMode(out, &mode);
8429 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
8430 if (SetConsoleMode(out, mode) == 0)
8431 vtp_working = 0;
8432 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008433#endif
8434
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008435 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008436 conpty_working = 1;
8437 if (ver >= CONPTY_STABLE_BUILD)
8438 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008439
Bram Moolenaar57da6982019-09-13 22:30:11 +02008440 if (ver <= CONPTY_INSIDER_BUILD)
8441 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008442 if (ver <= CONPTY_1909_BUILD)
8443 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02008444 if (ver <= CONPTY_1903_BUILD)
8445 conpty_type = 2;
8446 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
8447 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008448
8449 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
8450 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008451}
8452
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008453#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008454
8455 static void
8456vtp_init(void)
8457{
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008458# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00008459 if (!vtp_working)
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008460 {
Christopher Plewright38804d62022-11-09 23:55:52 +00008461 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8462 csbi.cbSize = sizeof(csbi);
8463 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8464 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
8465 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
8466 store_console_bg_rgb = save_console_bg_rgb;
8467 store_console_fg_rgb = save_console_fg_rgb;
8468
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008469 COLORREF bg;
8470 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
8471 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8472 default_console_color_bg = bg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008473
8474 COLORREF fg;
8475 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
8476 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8477 default_console_color_fg = fg;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008478 }
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008479# endif
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00008480 use_alternate_screen_buffer = win10_22H2_or_later && p_rs && vtp_working
Bram Moolenaar9fca1332022-12-22 21:06:41 +00008481 && !mch_getenv("VIM_TERMINAL");
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008482 set_console_color_rgb();
8483}
8484
8485 static void
8486vtp_exit(void)
8487{
Bram Moolenaardf543822020-01-30 11:53:59 +01008488 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008489}
8490
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008491 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008492vtp_printf(
8493 char *format,
8494 ...)
8495{
8496 char_u buf[100];
8497 va_list list;
8498 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008499 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008500
8501 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008502 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008503 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008504 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008505 return (int)result;
8506}
8507
8508 static void
8509vtp_sgr_bulk(
8510 int arg)
8511{
8512 int args[1];
8513
8514 args[0] = arg;
8515 vtp_sgr_bulks(1, args);
8516}
8517
K.Takata6e1d31e2022-02-03 13:05:32 +00008518# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008519 if ((*p-- = "0123456789"[(n = x % 10)]) \
8520 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8521 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8522
K.Takata6e1d31e2022-02-03 13:05:32 +00008523# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008524 case x: \
8525 FAST256(newargs[x - 1]);
8526
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008527 static void
8528vtp_sgr_bulks(
8529 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008530 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008531{
K.Takata6e1d31e2022-02-03 13:05:32 +00008532# define MAXSGR 16
8533# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008534 char_u buf[SGRBUFSIZE];
8535 char_u *p;
8536 int in, out;
8537 int newargs[16];
8538 static int sgrfgr = -1, sgrfgg, sgrfgb;
8539 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008540
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008541 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008542 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008543 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008544 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008545 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008546 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008547
8548 in = out = 0;
8549 while (in < argc)
8550 {
8551 int s = args[in];
8552 int copylen = 1;
8553
8554 if (s == 38)
8555 {
8556 if (argc - in >= 5 && args[in + 1] == 2)
8557 {
8558 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8559 && sgrfgb == args[in + 4])
8560 {
8561 in += 5;
8562 copylen = 0;
8563 }
8564 else
8565 {
8566 sgrfgr = args[in + 2];
8567 sgrfgg = args[in + 3];
8568 sgrfgb = args[in + 4];
8569 copylen = 5;
8570 }
8571 }
8572 else if (argc - in >= 3 && args[in + 1] == 5)
8573 {
8574 sgrfgr = -1;
8575 copylen = 3;
8576 }
8577 }
8578 else if (s == 48)
8579 {
8580 if (argc - in >= 5 && args[in + 1] == 2)
8581 {
8582 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8583 && sgrbgb == args[in + 4])
8584 {
8585 in += 5;
8586 copylen = 0;
8587 }
8588 else
8589 {
8590 sgrbgr = args[in + 2];
8591 sgrbgg = args[in + 3];
8592 sgrbgb = args[in + 4];
8593 copylen = 5;
8594 }
8595 }
8596 else if (argc - in >= 3 && args[in + 1] == 5)
8597 {
8598 sgrbgr = -1;
8599 copylen = 3;
8600 }
8601 }
8602 else if (30 <= s && s <= 39)
8603 sgrfgr = -1;
8604 else if (90 <= s && s <= 97)
8605 sgrfgr = -1;
8606 else if (40 <= s && s <= 49)
8607 sgrbgr = -1;
8608 else if (100 <= s && s <= 107)
8609 sgrbgr = -1;
8610 else if (s == 0)
8611 sgrfgr = sgrbgr = -1;
8612
8613 while (copylen--)
8614 newargs[out++] = args[in++];
8615 }
8616
8617 p = &buf[sizeof(buf) - 1];
8618 *p-- = 'm';
8619
8620 switch (out)
8621 {
8622 int n, m;
8623 DWORD r;
8624
8625 FAST256CASE(16);
8626 *p-- = ';';
8627 FAST256CASE(15);
8628 *p-- = ';';
8629 FAST256CASE(14);
8630 *p-- = ';';
8631 FAST256CASE(13);
8632 *p-- = ';';
8633 FAST256CASE(12);
8634 *p-- = ';';
8635 FAST256CASE(11);
8636 *p-- = ';';
8637 FAST256CASE(10);
8638 *p-- = ';';
8639 FAST256CASE(9);
8640 *p-- = ';';
8641 FAST256CASE(8);
8642 *p-- = ';';
8643 FAST256CASE(7);
8644 *p-- = ';';
8645 FAST256CASE(6);
8646 *p-- = ';';
8647 FAST256CASE(5);
8648 *p-- = ';';
8649 FAST256CASE(4);
8650 *p-- = ';';
8651 FAST256CASE(3);
8652 *p-- = ';';
8653 FAST256CASE(2);
8654 *p-- = ';';
8655 FAST256CASE(1);
8656 *p-- = '[';
8657 *p = '\033';
8658 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8659 default:
8660 break;
8661 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008662}
8663
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008664 static void
8665wt_init(void)
8666{
Christopher Plewright1140b512022-11-12 18:46:05 +00008667 wt_working = mch_getenv("WT_SESSION") != NULL;
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008668}
8669
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008670# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008671 static int
8672ctermtoxterm(
8673 int cterm)
8674{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008675 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008676
8677 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8678 return (((int)r << 16) | ((int)g << 8) | (int)b);
8679}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008680# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008681
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008682 static void
8683set_console_color_rgb(void)
8684{
8685# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008686 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008687 guicolor_T fg, bg;
8688 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008689
Christopher Plewright38804d62022-11-09 23:55:52 +00008690 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008691 return;
8692
Bram Moolenaara050b942019-12-02 21:35:31 +01008693 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8694
Christopher Plewright38804d62022-11-09 23:55:52 +00008695 if (p_tgc || t_colors >= 256)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008696 {
8697 term_fg_rgb_color(fg);
8698 term_bg_rgb_color(bg);
8699 return;
8700 }
8701
Christopher Plewright38804d62022-11-09 23:55:52 +00008702 if (!conpty_working)
8703 {
8704 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8705 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008706
Christopher Plewright38804d62022-11-09 23:55:52 +00008707 csbi.cbSize = sizeof(csbi);
8708 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008709
Christopher Plewright38804d62022-11-09 23:55:52 +00008710 csbi.cbSize = sizeof(csbi);
8711 csbi.srWindow.Right += 1;
8712 csbi.srWindow.Bottom += 1;
8713 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8714 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
8715 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8716 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
8717 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8718 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008719# endif
8720}
8721
Bram Moolenaara050b942019-12-02 21:35:31 +01008722# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8723 void
8724get_default_console_color(
8725 int *cterm_fg,
8726 int *cterm_bg,
8727 guicolor_T *gui_fg,
8728 guicolor_T *gui_bg)
8729{
8730 int id;
8731 guicolor_T guifg = INVALCOLOR;
8732 guicolor_T guibg = INVALCOLOR;
8733 int ctermfg = 0;
8734 int ctermbg = 0;
Christopher Plewright38804d62022-11-09 23:55:52 +00008735 int dummynull = 0;
Bram Moolenaara050b942019-12-02 21:35:31 +01008736
8737 id = syn_name2id((char_u *)"Normal");
8738 if (id > 0 && p_tgc)
8739 syn_id2colors(id, &guifg, &guibg);
8740 if (guifg == INVALCOLOR)
8741 {
8742 ctermfg = -1;
8743 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008744 syn_id2cterm_bg(id, &ctermfg, &dummynull);
8745 if (vtp_working)
8746 {
8747 cterm_normal_fg_gui_color = guifg =
8748 ctermfg != -1 ? ctermtoxterm(ctermfg) : INVALCOLOR;
8749 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8750 }
8751 else
8752 {
8753 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
Bram Moolenaara050b942019-12-02 21:35:31 +01008754 : default_console_color_fg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008755 cterm_normal_fg_gui_color = guifg;
8756 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8757 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008758 }
8759 if (guibg == INVALCOLOR)
8760 {
8761 ctermbg = -1;
8762 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008763 syn_id2cterm_bg(id, &dummynull, &ctermbg);
8764 if (vtp_working)
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008765 {
8766 cterm_normal_bg_gui_color = guibg =
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01008767 ctermbg != -1 ? ctermtoxterm(ctermbg) : INVALCOLOR;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008768 if (ctermbg < 0)
8769 ctermbg = 0;
8770 }
K.Takatae53a0d42022-09-05 21:45:11 +01008771 else
8772 {
8773 guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8774 : default_console_color_bg;
8775 cterm_normal_bg_gui_color = guibg;
8776 ctermbg = ctermbg < 0 ? 0 : ctermbg;
8777 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008778 }
8779
8780 *cterm_fg = ctermfg;
8781 *cterm_bg = ctermbg;
8782 *gui_fg = guifg;
8783 *gui_bg = guibg;
8784}
8785# endif
8786
Bram Moolenaardf543822020-01-30 11:53:59 +01008787/*
8788 * Set the console colors to the original colors or the last set colors.
8789 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008790 static void
8791reset_console_color_rgb(void)
8792{
8793# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008794
Christopher Plewright38804d62022-11-09 23:55:52 +00008795 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008796 return;
8797
Christopher Plewright38804d62022-11-09 23:55:52 +00008798 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8799
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008800 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008801 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008802
8803 csbi.cbSize = sizeof(csbi);
8804 csbi.srWindow.Right += 1;
8805 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008806 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8807 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008808 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008809# endif
8810}
8811
8812/*
8813 * Set the console colors to the original colors.
8814 */
8815 static void
8816restore_console_color_rgb(void)
8817{
8818# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00008819 if (vtp_working)
8820 return;
8821
K.Takata27b53be2022-09-18 12:25:49 +01008822 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008823
8824 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008825 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008826
8827 csbi.cbSize = sizeof(csbi);
8828 csbi.srWindow.Right += 1;
8829 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008830 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8831 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008832 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008833# endif
8834}
8835
8836 void
8837control_console_color_rgb(void)
8838{
Christopher Plewright38804d62022-11-09 23:55:52 +00008839 if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008840 set_console_color_rgb();
8841 else
8842 reset_console_color_rgb();
8843}
8844
8845 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008846use_vtp(void)
8847{
8848 return USE_VTP;
8849}
8850
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008851 int
8852is_term_win32(void)
8853{
8854 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8855}
8856
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008857 int
8858has_vtp_working(void)
8859{
8860 return vtp_working;
8861}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008862
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008863#endif
8864
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008865 int
8866has_conpty_working(void)
8867{
8868 return conpty_working;
8869}
8870
8871 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008872get_conpty_type(void)
8873{
8874 return conpty_type;
8875}
8876
8877 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008878is_conpty_stable(void)
8879{
8880 return conpty_stable;
8881}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008882
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008883 int
8884get_conpty_fix_type(void)
8885{
8886 return conpty_fix_type;
8887}
8888
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008889#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008890 void
8891resize_console_buf(void)
8892{
8893 CONSOLE_SCREEN_BUFFER_INFO csbi;
8894 COORD coord;
8895 SMALL_RECT newsize;
8896
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008897 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8898 return;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008899
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008900 coord.X = SRWIDTH(csbi.srWindow);
8901 coord.Y = SRHEIGHT(csbi.srWindow);
8902 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008903
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008904 newsize.Left = 0;
8905 newsize.Top = 0;
8906 newsize.Right = coord.X - 1;
8907 newsize.Bottom = coord.Y - 1;
8908 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8909
8910 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008911}
8912#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008913
8914 char *
8915GetWin32Error(void)
8916{
K.Takatad68b2fc2022-02-12 11:18:37 +00008917 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008918 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008919
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008920 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8921 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008922 if (oldmsg != NULL)
8923 LocalFree(oldmsg);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008924 if (msg == NULL)
8925 return NULL;
8926
8927 // remove trailing \r\n
8928 char *pcrlf = strstr(msg, "\r\n");
8929 if (pcrlf != NULL)
8930 *pcrlf = '\0';
8931 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008932 return msg;
8933}
Paul Ollis65745772022-06-05 16:55:54 +01008934
8935#if defined(FEAT_RELTIME) || defined(PROTO)
8936static HANDLE timer_handle;
8937static int timer_active = FALSE;
8938
8939/*
8940 * Calls to start_timeout alternate the return value pointer between the two
8941 * entries in timeout_flags. If the previously active timeout is very close to
8942 * expiring when start_timeout() is called then a race condition means that the
8943 * set_flag() function may still be invoked after the previous timer is
8944 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8945 * timeouts.
8946 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008947static sig_atomic_t timeout_flags[2];
8948static int timeout_flag_idx = 0;
8949static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01008950
8951
8952 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01008953set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01008954{
8955 int *timeout_flag = (int *)param;
8956
8957 *timeout_flag = TRUE;
8958}
8959
8960/*
8961 * Stop any active timeout.
8962 */
8963 void
8964stop_timeout(void)
8965{
8966 if (timer_active)
8967 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01008968 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01008969 timer_active = FALSE;
8970 if (!ret && GetLastError() != ERROR_IO_PENDING)
8971 {
8972 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
8973 }
8974 }
8975 *timeout_flag = FALSE;
8976}
8977
8978/*
8979 * Start the timeout timer.
8980 *
8981 * The period is defined in milliseconds.
8982 *
8983 * The return value is a pointer to a flag that is initialised to 0. If the
8984 * timeout expires, the flag is set to 1. This will only return pointers to
8985 * static memory; i.e. any pointer returned by this function may always be
8986 * safely dereferenced.
8987 *
8988 * This function is not expected to fail, but if it does it still returns a
8989 * valid flag pointer; the flag will remain stuck at zero.
8990 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008991 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01008992start_timeout(long msec)
8993{
Paul Ollis65745772022-06-05 16:55:54 +01008994 BOOL ret;
8995
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008996 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01008997
8998 stop_timeout();
8999 ret = CreateTimerQueueTimer(
9000 &timer_handle, NULL, set_flag, timeout_flag,
9001 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
9002 if (!ret)
9003 {
9004 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
9005 }
9006 else
9007 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01009008 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01009009 timer_active = TRUE;
9010 *timeout_flag = FALSE;
9011 }
9012 return timeout_flag;
9013}
9014#endif