blob: 5c845c638eccdfe332d9fb3e4dc4d3ef78b2f5b0 [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;
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200180#endif
181#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000182static int s_dont_use_vimrun = TRUE;
183static int need_vimrun_warning = FALSE;
184static char *vimrun_path = "vimrun ";
185#endif
186
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200187static int win32_getattrs(char_u *name);
188static int win32_setattrs(char_u *name, int attrs);
189static int win32_set_archive(char_u *name);
190
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100191static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200192static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100193static int conpty_stable = 0;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +0200194static int conpty_fix_type = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100195static void vtp_flag_init();
196
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200197#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100198static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100199static void vtp_init();
200static void vtp_exit();
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100201static void vtp_sgr_bulk(int arg);
202static void vtp_sgr_bulks(int argc, int *argv);
203
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200204static int wt_working = 0;
205static void wt_init();
206
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100207static guicolor_T save_console_bg_rgb;
208static guicolor_T save_console_fg_rgb;
Bram Moolenaardf543822020-01-30 11:53:59 +0100209static guicolor_T store_console_bg_rgb;
210static guicolor_T store_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100211
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200212static int g_color_index_bg = 0;
213static int g_color_index_fg = 7;
214
215# ifdef FEAT_TERMGUICOLORS
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +0100216static int default_console_color_bg = 0x000000; // black
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200217static int default_console_color_fg = 0xc0c0c0; // white
218# endif
219
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100220# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200221# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200222# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100223# else
224# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200225# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100226# endif
227
228static void set_console_color_rgb(void);
229static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100230static void restore_console_color_rgb(void);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100231#endif
232
Bram Moolenaar0f873732019-12-05 20:28:46 +0100233// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100234#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
235# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
236#endif
237
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200238#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100239static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000240#endif
241
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200242static char_u *exe_path = NULL;
243
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100244static BOOL win8_or_later = FALSE;
245
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100246/*
247 * Get version number including build number
248 */
249typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100250#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100251 (((major) << 24) | ((minor) << 16) | (build))
252
253 static DWORD
254get_build_number(void)
255{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100256 OSVERSIONINFOW osver;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100257 HMODULE hNtdll;
258 PfnRtlGetVersion pRtlGetVersion;
259 DWORD ver = MAKE_VER(0, 0, 0);
260
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100261 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100262 hNtdll = GetModuleHandle("ntdll.dll");
263 if (hNtdll != NULL)
264 {
265 pRtlGetVersion =
266 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
267 pRtlGetVersion(&osver);
268 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
269 min(osver.dwMinorVersion, 255),
270 min(osver.dwBuildNumber, 32767));
271 }
272 return ver;
273}
274
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200275#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200276 static BOOL
277is_ambiwidth_event(
278 INPUT_RECORD *ir)
279{
280 return ir->EventType == KEY_EVENT
281 && ir->Event.KeyEvent.bKeyDown
282 && ir->Event.KeyEvent.wRepeatCount == 1
283 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
284 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000285 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200286 && ir->Event.KeyEvent.dwControlKeyState == 2;
287}
288
289 static void
290make_ambiwidth_event(
291 INPUT_RECORD *down,
292 INPUT_RECORD *up)
293{
294 down->Event.KeyEvent.wVirtualKeyCode = 0;
295 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000296 down->Event.KeyEvent.uChar.UnicodeChar
297 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200298 down->Event.KeyEvent.dwControlKeyState = 0;
299}
300
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100301/*
302 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100303 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100304 */
305 static BOOL
306read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100307 HANDLE hInput,
308 INPUT_RECORD *lpBuffer,
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100309 int nLength,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100310 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100311{
312 enum
313 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100314 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100315 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100316 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100317 static DWORD s_dwIndex = 0;
318 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100319 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100320 int head;
321 int tail;
322 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200323 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100324
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200325 if (nLength == -2)
326 return (s_dwMax > 0) ? TRUE : FALSE;
327
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100328 if (!win8_or_later)
329 {
330 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200331 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
332 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100333 }
334
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100335 if (s_dwMax == 0)
336 {
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200337 if (!USE_WT && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200338 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200339 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
340 if (dwEvents == 0 && nLength == -1)
341 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
342 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100343 s_dwIndex = 0;
344 s_dwMax = dwEvents;
345 if (dwEvents == 0)
346 {
347 *lpEvents = 0;
348 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100349 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100350
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200351 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
352 if (is_ambiwidth_event(&s_irCache[i]))
353 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
354
Bram Moolenaardd415a62014-02-05 14:02:27 +0100355 if (s_dwMax > 1)
356 {
357 head = 0;
358 tail = s_dwMax - 1;
359 while (head != tail)
360 {
361 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
362 && s_irCache[head + 1].EventType
363 == WINDOW_BUFFER_SIZE_EVENT)
364 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100365 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100366 for (i = head; i < tail; ++i)
367 s_irCache[i] = s_irCache[i + 1];
368 --tail;
369 continue;
370 }
371 head++;
372 }
373 s_dwMax = tail + 1;
374 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100375 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100376
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200377 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
378 {
379 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
380 {
381 s_irPseudo = s_irCache[s_dwIndex];
382 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
383 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
384 *lpBuffer = s_irPseudo;
385 *lpEvents = 1;
386 return TRUE;
387 }
388 }
389
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100390 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200391 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100392 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100393 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100394 return TRUE;
395}
396
397/*
398 * Version of PeekConsoleInput() that works with IME.
399 */
400 static BOOL
401peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100402 HANDLE hInput,
403 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200404 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100405 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100406{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100407 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100408}
409
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100410# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200411 static DWORD
412msg_wait_for_multiple_objects(
413 DWORD nCount,
414 LPHANDLE pHandles,
415 BOOL fWaitAll,
416 DWORD dwMilliseconds,
417 DWORD dwWakeMask)
418{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100419 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200420 return WAIT_OBJECT_0;
421 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
422 dwMilliseconds, dwWakeMask);
423}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100424# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200425
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100426# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200427 static DWORD
428wait_for_single_object(
429 HANDLE hHandle,
430 DWORD dwMilliseconds)
431{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100432 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200433 return WAIT_OBJECT_0;
434 return WaitForSingleObject(hHandle, dwMilliseconds);
435}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100436# endif
437#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200438
Bram Moolenaar071d4272004-06-13 20:20:40 +0000439 static void
440get_exe_name(void)
441{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100442 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
443 // as the maximum length that works (plus a NUL byte).
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100444#define MAX_ENV_PATH_LEN 8192
445 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200446 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000447
448 if (exe_name == NULL)
449 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100450 // store the name of the executable, may be used for $VIM
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100451 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000452 if (*temp != NUL)
453 exe_name = FullName_save((char_u *)temp, FALSE);
454 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000455
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200456 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000457 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200458 exe_path = vim_strnsave(exe_name, gettail_sep(exe_name) - exe_name);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200459 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000460 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100461 // Append our starting directory to $PATH, so that when doing
462 // "!xxd" it's found in our starting directory. Needed because
463 // SearchPath() also looks there.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200464 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100465 if (p == NULL
466 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200467 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100468 if (p == NULL || *p == NUL)
469 temp[0] = NUL;
470 else
471 {
472 STRCPY(temp, p);
473 STRCAT(temp, ";");
474 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200475 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100476 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200477 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000478 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000479 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000480}
481
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200482/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100483 * Unescape characters in "p" that appear in "escaped".
484 */
485 static void
486unescape_shellxquote(char_u *p, char_u *escaped)
487{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100488 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100489 int n;
490
491 while (*p != NUL)
492 {
493 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
494 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100495 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100496 p += n;
497 l -= n;
498 }
499}
500
501/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200502 * Load library "name".
503 */
504 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000505vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200506{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200507 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200508
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200509 // No need to load any library when registering OLE.
510 if (found_register_arg)
511 return dll;
512
Bram Moolenaar0f873732019-12-05 20:28:46 +0100513 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
514 // vimLoadLib() recursively, which causes a stack overflow.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200515 if (exe_path == NULL)
516 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200517 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200518 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200519 WCHAR old_dirw[MAXPATHL];
520
521 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
522 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100523 // Change directory to where the executable is, both to make
524 // sure we find a .dll there and to avoid looking for a .dll
525 // in the current directory.
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100526 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200527 dll = LoadLibrary(name);
528 SetCurrentDirectoryW(old_dirw);
529 return dll;
530 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200531 }
532 return dll;
533}
534
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200535#if defined(VIMDLL) || defined(PROTO)
536/*
537 * Check if the current executable file is for the GUI subsystem.
538 */
539 int
540mch_is_gui_executable(void)
541{
542 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
543 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
544 PIMAGE_NT_HEADERS pPE;
545
546 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
547 return FALSE;
548 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
549 if (pPE->Signature != IMAGE_NT_SIGNATURE)
550 return FALSE;
551 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
552 return TRUE;
553 return FALSE;
554}
555#endif
556
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000557#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
558 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100559/*
560 * Get related information about 'funcname' which is imported by 'hInst'.
561 * If 'info' is 0, return the function address.
562 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000563 * If 'info' is 2, hook the function with 'ptr', and return the original
564 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100565 */
566 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000567get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
568 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100569{
570 PBYTE pImage = (PBYTE)hInst;
571 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
572 PIMAGE_NT_HEADERS pPE;
573 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100574 PIMAGE_THUNK_DATA pIAT; // Import Address Table
575 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100576 PIMAGE_IMPORT_BY_NAME pImpName;
577
578 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
579 return NULL;
580 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
581 if (pPE->Signature != IMAGE_NT_SIGNATURE)
582 return NULL;
583 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
584 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
585 .VirtualAddress);
586 for (; pImpDesc->FirstThunk; ++pImpDesc)
587 {
588 if (!pImpDesc->OriginalFirstThunk)
589 continue;
590 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
591 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
592 for (; pIAT->u1.Function; ++pIAT, ++pINT)
593 {
594 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
595 continue;
596 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
597 + (UINT_PTR)(pINT->u1.AddressOfData));
598 if (strcmp((char *)pImpName->Name, funcname) == 0)
599 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000600 void *original;
601 DWORD old, new = PAGE_READWRITE;
602
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100603 switch (info)
604 {
605 case 0:
606 return (void *)pIAT->u1.Function;
607 case 1:
608 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000609 case 2:
610 original = (void *)pIAT->u1.Function;
611 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
612 new, &old);
613 pIAT->u1.Function = (UINT_PTR)ptr;
614 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
615 old, &new);
616 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100617 default:
618 return NULL;
619 }
620 }
621 }
622 }
623 return NULL;
624}
625
626/*
627 * Get the module handle which 'funcname' in 'hInst' is imported from.
628 */
629 HINSTANCE
630find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
631{
632 char *modulename;
633
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000634 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100635 if (modulename != NULL)
636 return GetModuleHandleA(modulename);
637 return NULL;
638}
639
640/*
641 * Get the address of 'funcname' which is imported by 'hInst' DLL.
642 */
643 void *
644get_dll_import_func(HINSTANCE hInst, const char *funcname)
645{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000646 return get_imported_func_info(hInst, funcname, 0, NULL);
647}
648
649/*
650 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
651 * and return the original function address.
652 */
653 void *
654hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
655{
656 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100657}
658#endif
659
Bram Moolenaar071d4272004-06-13 20:20:40 +0000660#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
661# ifndef GETTEXT_DLL
662# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200663# define GETTEXT_DLL_ALT1 "libintl-8.dll"
664# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000665# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100666// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000667static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200668static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000669static char *null_libintl_textdomain(const char *);
670static char *null_libintl_bindtextdomain(const char *, const char *);
671static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100672static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000673
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200674static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000675char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200676char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
677 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000678char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
679char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000680 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000681char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
682 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100683int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000684
685 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100686dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000687{
688 int i;
689 static struct
690 {
691 char *name;
692 FARPROC *ptr;
693 } libintl_entry[] =
694 {
695 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200696 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000697 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
698 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
699 {NULL, NULL}
700 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100701 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000702
Bram Moolenaar7554c542018-10-06 15:03:15 +0200703 // No need to initialize twice.
704 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000705 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200706 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100707 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100708# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100709 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200710 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100711# endif
712# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200713 if (!hLibintlDLL)
714 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100715# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100716 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000717 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200718 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000719 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200720 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000721 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200722 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000723 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200724 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000725 }
726 for (i = 0; libintl_entry[i].name != NULL
727 && libintl_entry[i].ptr != NULL; ++i)
728 {
K.Takata54119102022-02-03 13:33:03 +0000729 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000730 libintl_entry[i].name)) == NULL)
731 {
732 dyn_libintl_end();
733 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000734 {
735 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000736 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000737 verbose_leave();
738 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000739 return 0;
740 }
741 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000742
Bram Moolenaar0f873732019-12-05 20:28:46 +0100743 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100744 dyn_libintl_bind_textdomain_codeset = (char *(*)(const char *, const char *))
745 GetProcAddress(hLibintlDLL, "bind_textdomain_codeset");
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000746 if (dyn_libintl_bind_textdomain_codeset == NULL)
747 dyn_libintl_bind_textdomain_codeset =
748 null_libintl_bind_textdomain_codeset;
749
Bram Moolenaar0f873732019-12-05 20:28:46 +0100750 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100751 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
752 if (hmsvcrt != NULL)
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100753 dyn_libintl_wputenv = (int (*)(const wchar_t *))
754 GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100755 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
756 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100757
Bram Moolenaar071d4272004-06-13 20:20:40 +0000758 return 1;
759}
760
761 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100762dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000763{
764 if (hLibintlDLL)
765 FreeLibrary(hLibintlDLL);
766 hLibintlDLL = NULL;
767 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200768 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000769 dyn_libintl_textdomain = null_libintl_textdomain;
770 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000771 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100772 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000773}
774
775 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000776null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000777{
778 return (char*)msgid;
779}
780
781 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200782null_libintl_ngettext(
783 const char *msgid,
784 const char *msgid_plural,
785 unsigned long n)
786{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200787 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200788}
789
Bram Moolenaaree695f72016-08-03 22:08:45 +0200790 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100791null_libintl_bindtextdomain(
792 const char *domainname UNUSED,
793 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000794{
795 return NULL;
796}
797
798 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100799null_libintl_bind_textdomain_codeset(
800 const char *domainname UNUSED,
801 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000802{
803 return NULL;
804}
805
806 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100807null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000808{
809 return NULL;
810}
811
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200812 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100813null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100814{
815 return 0;
816}
817
Bram Moolenaar0f873732019-12-05 20:28:46 +0100818#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000819
Bram Moolenaar0f873732019-12-05 20:28:46 +0100820// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000821
822#ifndef VER_PLATFORM_WIN32_WINDOWS
823# define VER_PLATFORM_WIN32_WINDOWS 1
824#endif
825
Bram Moolenaar071d4272004-06-13 20:20:40 +0000826#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100827# ifndef PROTO
828# include <aclapi.h>
829# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200830# ifndef PROTECTED_DACL_SECURITY_INFORMATION
831# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
832# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000833#endif
834
Bram Moolenaar27515922013-06-29 15:36:26 +0200835#ifdef HAVE_ACL
836/*
837 * Enables or disables the specified privilege.
838 */
839 static BOOL
840win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
841{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100842 BOOL bResult;
843 LUID luid;
844 HANDLE hToken;
845 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200846
847 if (!OpenProcessToken(GetCurrentProcess(),
848 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
849 return FALSE;
850
851 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
852 {
853 CloseHandle(hToken);
854 return FALSE;
855 }
856
Bram Moolenaar45500912014-07-09 20:51:07 +0200857 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200858 tokenPrivileges.Privileges[0].Luid = luid;
859 tokenPrivileges.Privileges[0].Attributes = bEnable ?
860 SE_PRIVILEGE_ENABLED : 0;
861
862 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
863 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
864
865 CloseHandle(hToken);
866
867 return bResult && GetLastError() == ERROR_SUCCESS;
868}
869#endif
870
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100871#ifdef _MSC_VER
872// Suppress the deprecation warning for using GetVersionEx().
873// It is needed for implementing "windowsversion()".
874# pragma warning(push)
875# pragma warning(disable: 4996)
876#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000877/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200878 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000879 */
880 void
881PlatformId(void)
882{
883 static int done = FALSE;
884
885 if (!done)
886 {
887 OSVERSIONINFO ovi;
888
889 ovi.dwOSVersionInfoSize = sizeof(ovi);
890 GetVersionEx(&ovi);
891
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200892#ifdef FEAT_EVAL
Bram Moolenaar0c1e3742019-12-27 13:49:24 +0100893 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
894 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200895#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100896 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
897 || ovi.dwMajorVersion > 6)
898 win8_or_later = TRUE;
899
Bram Moolenaar071d4272004-06-13 20:20:40 +0000900#ifdef HAVE_ACL
Bram Moolenaar0f873732019-12-05 20:28:46 +0100901 // Enable privilege for getting or setting SACLs.
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200902 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000903#endif
904 done = TRUE;
905 }
906}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100907#ifdef _MSC_VER
908# pragma warning(pop)
909#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000910
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200911#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000912
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100913# define SHIFT (SHIFT_PRESSED)
914# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
915# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
916# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000917
918
Bram Moolenaar0f873732019-12-05 20:28:46 +0100919// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
920// We map function keys to their ANSI terminal equivalents, as produced
921// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
922// ANSI key with a value >= '\300' is nonstandard, but provided anyway
923// so that the user can have access to all SHIFT-, CTRL-, and ALT-
924// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000925
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000926static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000927{
928 WORD wVirtKey;
929 BOOL fAnsiKey;
930 int chAlone;
931 int chShift;
932 int chCtrl;
933 int chAlt;
934} VirtKeyMap[] =
935{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200936// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000937 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
938
939 { VK_F1, TRUE, ';', 'T', '^', 'h', },
940 { VK_F2, TRUE, '<', 'U', '_', 'i', },
941 { VK_F3, TRUE, '=', 'V', '`', 'j', },
942 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
943 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
944 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
945 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
946 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
947 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
948 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200949 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
950 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000951
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200952 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
953 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
954 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
955 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
956 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
957 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
958 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
959 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
960 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
961 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100962 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000963
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200964 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000965
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100966# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200967 // Most people don't have F13-F20, but what the hell...
968 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
969 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
970 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
971 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
972 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
973 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
974 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
975 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100976# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200977 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
978 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
979 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
980 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000981
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200982 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
983 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
984 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
985 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
986 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
987 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
988 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
989 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
990 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
991 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100992 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000993};
994
995
Bram Moolenaar0f873732019-12-05 20:28:46 +0100996/*
997 * The return code indicates key code size.
998 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000999 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001000win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001001 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001002{
1003 UINT uMods = pker->dwControlKeyState;
1004 static int s_iIsDead = 0;
1005 static WORD awAnsiCode[2];
1006 static BYTE abKeystate[256];
1007
1008
1009 if (s_iIsDead == 2)
1010 {
K.Takata972db232022-02-04 10:45:38 +00001011 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001012 s_iIsDead = 0;
1013 return 1;
1014 }
1015
K.Takata972db232022-02-04 10:45:38 +00001016 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001017 return 1;
1018
Bram Moolenaara80faa82020-04-12 19:37:17 +02001019 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001020
Bram Moolenaar0f873732019-12-05 20:28:46 +01001021 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001022 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001023
1024 if (uMods & SHIFT_PRESSED)
1025 abKeystate[VK_SHIFT] = 0x80;
1026 if (uMods & CAPSLOCK_ON)
1027 abKeystate[VK_CAPITAL] = 1;
1028
1029 if ((uMods & ALT_GR) == ALT_GR)
1030 {
1031 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1032 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1033 }
1034
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001035 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1036 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001037
1038 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001039 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001040
1041 return s_iIsDead;
1042}
1043
Bram Moolenaar071d4272004-06-13 20:20:40 +00001044static BOOL g_fJustGotFocus = FALSE;
1045
1046/*
1047 * Decode a KEY_EVENT into one or two keystrokes
1048 */
1049 static BOOL
1050decode_key_event(
1051 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001052 WCHAR *pch,
1053 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001054 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001055 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001056{
1057 int i;
1058 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1059
1060 *pch = *pch2 = NUL;
1061 g_fJustGotFocus = FALSE;
1062
Bram Moolenaar0f873732019-12-05 20:28:46 +01001063 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001064 if (!pker->bKeyDown)
1065 return FALSE;
1066
Bram Moolenaar0f873732019-12-05 20:28:46 +01001067 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001068 switch (pker->wVirtualKeyCode)
1069 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001070 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001071 case VK_SHIFT:
1072 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001073 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001074 return FALSE;
1075
1076 default:
1077 break;
1078 }
1079
Bram Moolenaar0f873732019-12-05 20:28:46 +01001080 // special cases
K.Takata972db232022-02-04 10:45:38 +00001081 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0
1082 && pker->uChar.UnicodeChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001083 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001084 // Ctrl-6 is Ctrl-^
Bram Moolenaar071d4272004-06-13 20:20:40 +00001085 if (pker->wVirtualKeyCode == '6')
1086 {
1087 *pch = Ctrl_HAT;
1088 return TRUE;
1089 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001090 // Ctrl-2 is Ctrl-@
Bram Moolenaar071d4272004-06-13 20:20:40 +00001091 else if (pker->wVirtualKeyCode == '2')
1092 {
1093 *pch = NUL;
1094 return TRUE;
1095 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001096 // Ctrl-- is Ctrl-_
Bram Moolenaar071d4272004-06-13 20:20:40 +00001097 else if (pker->wVirtualKeyCode == 0xBD)
1098 {
1099 *pch = Ctrl__;
1100 return TRUE;
1101 }
1102 }
1103
Bram Moolenaar0f873732019-12-05 20:28:46 +01001104 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001105 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1106 {
1107 *pch = K_NUL;
1108 *pch2 = '\017';
1109 return TRUE;
1110 }
1111
K.Takataeeec2542021-06-02 13:28:16 +02001112 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001113 {
1114 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1115 {
1116 if (nModifs == 0)
1117 *pch = VirtKeyMap[i].chAlone;
1118 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1119 *pch = VirtKeyMap[i].chShift;
1120 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1121 *pch = VirtKeyMap[i].chCtrl;
1122 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1123 *pch = VirtKeyMap[i].chAlt;
1124
1125 if (*pch != 0)
1126 {
1127 if (VirtKeyMap[i].fAnsiKey)
1128 {
1129 *pch2 = *pch;
1130 *pch = K_NUL;
1131 }
1132
1133 return TRUE;
1134 }
1135 }
1136 }
1137
1138 i = win32_kbd_patch_key(pker);
1139
1140 if (i < 0)
1141 *pch = NUL;
1142 else
1143 {
K.Takata972db232022-02-04 10:45:38 +00001144 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001145
1146 if (pmodifiers != NULL)
1147 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001148 // Pass on the ALT key as a modifier, but only when not combined
1149 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001150 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1151 *pmodifiers |= MOD_MASK_ALT;
1152
Bram Moolenaar0f873732019-12-05 20:28:46 +01001153 // Pass on SHIFT only for special keys, because we don't know when
1154 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001155 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1156 *pmodifiers |= MOD_MASK_SHIFT;
1157
Bram Moolenaar0f873732019-12-05 20:28:46 +01001158 // Pass on CTRL only for non-special keys, because we don't know
1159 // when it's already included with the character. And not when
1160 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001161 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1162 && *pch >= 0x20 && *pch < 0x80)
1163 *pmodifiers |= MOD_MASK_CTRL;
1164 }
1165 }
1166
1167 return (*pch != NUL);
1168}
1169
Bram Moolenaar0f873732019-12-05 20:28:46 +01001170#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001171
1172
Bram Moolenaar071d4272004-06-13 20:20:40 +00001173/*
1174 * For the GUI the mouse handling is in gui_w32.c.
1175 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001176#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001177 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001178mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001179{
1180}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001181#else
Bram Moolenaar0f873732019-12-05 20:28:46 +01001182static int g_fMouseAvail = FALSE; // mouse present
1183static int g_fMouseActive = FALSE; // mouse enabled
1184static int g_nMouseClick = -1; // mouse status
1185static int g_xMouse; // mouse x coordinate
1186static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001187static DWORD g_cmodein = 0; // Original console input mode
1188static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001189
1190/*
1191 * Enable or disable mouse input
1192 */
1193 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001194mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001195{
1196 DWORD cmodein;
1197
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001198# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001199 if (gui.in_use)
1200 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001201# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001202 if (!g_fMouseAvail)
1203 return;
1204
1205 g_fMouseActive = on;
1206 GetConsoleMode(g_hConIn, &cmodein);
1207
1208 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001209 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001210 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001211 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1212 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001213 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001214 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001215 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001216 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1217 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001218
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001219 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001220}
1221
Bram Moolenaar157d8132018-03-06 17:09:20 +01001222
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001223# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001224/*
1225 * Called when 'balloonevalterm' changed.
1226 */
1227 void
1228mch_bevalterm_changed(void)
1229{
1230 mch_setmouse(g_fMouseActive);
1231}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001232# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001233
Bram Moolenaarbf72e0c2022-10-18 21:48:14 +01001234#ifdef VIMDLL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001235/*
1236 * Win32 console mouse scroll event handler.
1237 * Loosely based on the _OnMouseWheel() function in gui_w32.c
1238 *
1239 * This encodes the mouse scroll direction and keyboard modifiers into
1240 * g_nMouseClick, and the mouse position into g_xMouse and g_yMouse
1241 *
1242 * The direction of the scroll is decoded from two fields of the win32 console
1243 * mouse event record;
1244 * 1. The axis - vertical or horizontal flag - from dwEventFlags, and
1245 * 2. The sign - positive or negative (aka delta flag) - from dwButtonState
1246 *
1247 * When scroll axis is HORIZONTAL
1248 * - If the high word of the dwButtonState member contains a positive
1249 * value, the wheel was rotated to the right.
1250 * - Otherwise, the wheel was rotated to the left.
1251 * When scroll axis is VERTICAL
1252 * - If the high word of the dwButtonState member contains a positive value,
1253 * the wheel was rotated forward, away from the user.
1254 * - Otherwise, the wheel was rotated backward, toward the user.
1255 */
1256 static void
1257decode_mouse_wheel(MOUSE_EVENT_RECORD *pmer)
1258{
1259 win_T *wp;
1260 int horizontal = (pmer->dwEventFlags == MOUSE_HWHEELED);
1261 int zDelta = pmer->dwButtonState;
1262
1263 g_xMouse = pmer->dwMousePosition.X;
1264 g_yMouse = pmer->dwMousePosition.Y;
1265
1266#ifdef FEAT_PROP_POPUP
1267 int lcol;
1268 int lrow;
1269 lcol = g_xMouse;
1270 lrow = g_yMouse;
1271 wp = mouse_find_win(&lrow, &lcol, FAIL_POPUP);
1272 if (wp != NULL && popup_is_popup(wp))
1273 {
1274 g_nMouseClick = -1;
1275 cmdarg_T cap;
1276 oparg_T oa;
1277 CLEAR_FIELD(cap);
1278 clear_oparg(&oa);
1279 cap.oap = &oa;
1280 if (horizontal)
1281 {
1282 cap.arg = zDelta < 0 ? MSCR_LEFT : MSCR_RIGHT;
1283 cap.cmdchar = zDelta < 0 ? K_MOUSELEFT : K_MOUSERIGHT;
1284 }
1285 else
1286 {
1287 cap.cmdchar = zDelta < 0 ? K_MOUSEUP : K_MOUSEDOWN;
1288 cap.arg = zDelta < 0 ? MSCR_UP : MSCR_DOWN;
1289 }
1290
1291 // Mouse hovers over popup window, scroll it if possible.
1292 mouse_row = wp->w_winrow;
1293 mouse_col = wp->w_wincol;
1294 nv_mousescroll(&cap);
1295 update_screen(0);
1296 setcursor();
1297 out_flush();
1298 return;
1299 }
1300#endif
1301 mouse_col = g_xMouse;
1302 mouse_row = g_yMouse;
1303
1304 char_u modifiers = 0;
1305 char_u direction = 0;
1306
1307 // Decode the direction into an event that Vim can process
1308 if (horizontal)
1309 direction = zDelta >= 0 ? KE_MOUSELEFT : KE_MOUSERIGHT;
1310 else
1311 direction = zDelta >= 0 ? KE_MOUSEDOWN : KE_MOUSEUP;
1312
1313 // Decode the win32 console key modifers into Vim mouse modifers.
1314 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1315 modifiers |= MOD_MASK_SHIFT; //MOUSE_SHIFT;
1316 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1317 modifiers |= MOD_MASK_CTRL; //MOUSE_CTRL;
1318 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1319 modifiers |= MOD_MASK_ALT; // MOUSE_ALT;
1320
1321 // add (bitwise or) the scroll direction and the key modifier chars
1322 // together.
1323 g_nMouseClick = ((direction << 8) | modifiers);
1324
1325 return;
1326}
Bram Moolenaarbf72e0c2022-10-18 21:48:14 +01001327#endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01001328
Bram Moolenaar071d4272004-06-13 20:20:40 +00001329/*
1330 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1331 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1332 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1333 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1334 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1335 * and we return the mouse position in g_xMouse and g_yMouse.
1336 *
1337 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1338 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1339 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1340 *
1341 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1342 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1343 *
1344 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1345 * moves, even if it stays within the same character cell. We ignore
1346 * all MOUSE_MOVED messages if the position hasn't really changed, and
1347 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1348 * we're only interested in MOUSE_DRAG).
1349 *
1350 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1351 * 2-button mouses by pressing the left & right buttons simultaneously.
1352 * In practice, it's almost impossible to click both at the same time,
1353 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1354 * in such cases, if the user is clicking quickly.
1355 */
1356 static BOOL
1357decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001358 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001359{
1360 static int s_nOldButton = -1;
1361 static int s_nOldMouseClick = -1;
1362 static int s_xOldMouse = -1;
1363 static int s_yOldMouse = -1;
1364 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001365# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001366 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001367# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001368 static int s_cClicks = 1;
1369 static BOOL s_fReleased = TRUE;
1370 static DWORD s_dwLastClickTime = 0;
1371 static BOOL s_fNextIsMiddle = FALSE;
1372
Bram Moolenaar0f873732019-12-05 20:28:46 +01001373 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001374
1375 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1376 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1377 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1378 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1379
1380 int nButton;
1381
1382 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1383 cButtons = 2;
1384
1385 if (!g_fMouseAvail || !g_fMouseActive)
1386 {
1387 g_nMouseClick = -1;
1388 return FALSE;
1389 }
1390
Bram Moolenaar0f873732019-12-05 20:28:46 +01001391 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001392 if (g_fJustGotFocus)
1393 {
1394 g_fJustGotFocus = FALSE;
1395 return FALSE;
1396 }
1397
Bram Moolenaar0f873732019-12-05 20:28:46 +01001398 // unprocessed mouse click?
Bram Moolenaar071d4272004-06-13 20:20:40 +00001399 if (g_nMouseClick != -1)
1400 return TRUE;
Christopher Plewright9298a992022-10-18 13:33:26 +01001401#ifdef VIMDLL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001402 if (pmer->dwEventFlags == MOUSE_WHEELED
1403 || pmer->dwEventFlags == MOUSE_HWHEELED)
1404 {
1405 decode_mouse_wheel(pmer);
1406 return TRUE; // we now should have a mouse scroll in g_nMouseClick
1407 }
Christopher Plewright9298a992022-10-18 13:33:26 +01001408#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001409 nButton = -1;
1410 g_xMouse = pmer->dwMousePosition.X;
1411 g_yMouse = pmer->dwMousePosition.Y;
1412
1413 if (pmer->dwEventFlags == MOUSE_MOVED)
1414 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001415 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1416 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001417 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1418 return FALSE;
1419 }
1420
Bram Moolenaar0f873732019-12-05 20:28:46 +01001421 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001422 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1423 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001424 nButton = MOUSE_RELEASE;
1425
Bram Moolenaar0f873732019-12-05 20:28:46 +01001426 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001427 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001428 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001429# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001430 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001431 if (p_bevalterm)
1432 nButton = MOUSE_DRAG;
1433 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001434# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001435 return FALSE;
1436 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001437
Bram Moolenaar071d4272004-06-13 20:20:40 +00001438 s_fReleased = TRUE;
1439 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001440 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001441 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001442 // on a 2-button mouse, hold down left and right buttons
1443 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001444
1445 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1446 {
1447 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1448
Bram Moolenaar0f873732019-12-05 20:28:46 +01001449 // if either left or right button only is pressed, see if the
1450 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001451 if (dwLR == LEFT || dwLR == RIGHT)
1452 {
1453 for (;;)
1454 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001455 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001456 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1457 != WAIT_OBJECT_0)
1458 break;
1459 else
1460 {
1461 DWORD cRecords = 0;
1462 INPUT_RECORD ir;
1463 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1464
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001465 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001466
1467 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1468 || !(pmer2->dwButtonState & LEFT_RIGHT))
1469 break;
1470 else
1471 {
1472 if (pmer2->dwEventFlags != MOUSE_MOVED)
1473 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001474 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001475
1476 return decode_mouse_event(pmer2);
1477 }
1478 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1479 s_yOldMouse == pmer2->dwMousePosition.Y)
1480 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001481 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001482 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001483
Bram Moolenaar0f873732019-12-05 20:28:46 +01001484 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001485 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001486
1487 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1488 break;
1489 }
1490 else
1491 break;
1492 }
1493 }
1494 }
1495 }
1496 }
1497
1498 if (s_fNextIsMiddle)
1499 {
1500 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1501 ? MOUSE_DRAG : MOUSE_MIDDLE;
1502 s_fNextIsMiddle = FALSE;
1503 }
1504 else if (cButtons == 2 &&
1505 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1506 {
1507 nButton = MOUSE_MIDDLE;
1508
1509 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1510 {
1511 s_fNextIsMiddle = TRUE;
1512 nButton = MOUSE_RELEASE;
1513 }
1514 }
1515 else if ((pmer->dwButtonState & LEFT) == LEFT)
1516 nButton = MOUSE_LEFT;
1517 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1518 nButton = MOUSE_MIDDLE;
1519 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1520 nButton = MOUSE_RIGHT;
1521
1522 if (! s_fReleased && ! s_fNextIsMiddle
1523 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1524 return FALSE;
1525
1526 s_fReleased = s_fNextIsMiddle;
1527 }
1528
1529 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1530 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001531 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001532 if (nButton != -1 && nButton != MOUSE_RELEASE)
1533 {
1534 DWORD dwCurrentTime = GetTickCount();
1535
1536 if (s_xOldMouse != g_xMouse
1537 || s_yOldMouse != g_yMouse
1538 || s_nOldButton != nButton
1539 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001540# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001541 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001542# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001543 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1544 {
1545 s_cClicks = 1;
1546 }
1547 else if (++s_cClicks > 4)
1548 {
1549 s_cClicks = 1;
1550 }
1551
1552 s_dwLastClickTime = dwCurrentTime;
1553 }
1554 }
1555 else if (pmer->dwEventFlags == MOUSE_MOVED)
1556 {
1557 if (nButton != -1 && nButton != MOUSE_RELEASE)
1558 nButton = MOUSE_DRAG;
1559
1560 s_cClicks = 1;
1561 }
1562
1563 if (nButton == -1)
1564 return FALSE;
1565
1566 if (nButton != MOUSE_RELEASE)
1567 s_nOldButton = nButton;
1568
1569 g_nMouseClick = nButton;
1570
1571 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1572 g_nMouseClick |= MOUSE_SHIFT;
1573 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1574 g_nMouseClick |= MOUSE_CTRL;
1575 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1576 g_nMouseClick |= MOUSE_ALT;
1577
1578 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1579 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1580
Bram Moolenaar0f873732019-12-05 20:28:46 +01001581 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001582 if (s_xOldMouse == g_xMouse
1583 && s_yOldMouse == g_yMouse
1584 && s_nOldMouseClick == g_nMouseClick)
1585 {
1586 g_nMouseClick = -1;
1587 return FALSE;
1588 }
1589
1590 s_xOldMouse = g_xMouse;
1591 s_yOldMouse = g_yMouse;
1592 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001593# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001594 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001595# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001596 s_nOldMouseClick = g_nMouseClick;
1597
1598 return TRUE;
1599}
1600
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001601#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001602
1603
1604#ifdef MCH_CURSOR_SHAPE
1605/*
1606 * Set the shape of the cursor.
1607 * 'thickness' can be from 1 (thin) to 99 (block)
1608 */
1609 static void
1610mch_set_cursor_shape(int thickness)
1611{
K.Takatadf5320c2022-09-01 13:20:16 +01001612 if (USE_VTP || USE_WT)
1613 {
1614 if (*T_CSI == NUL)
1615 {
1616 // If 't_SI' is not set, use the default cursor styles.
1617 if (thickness < 50)
1618 vtp_printf("\033[3 q"); // underline
1619 else
1620 vtp_printf("\033[0 q"); // default
1621 }
1622 }
1623 else
1624 {
1625 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1626 ConsoleCursorInfo.dwSize = thickness;
1627 ConsoleCursorInfo.bVisible = s_cursor_visible;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001628
K.Takatadf5320c2022-09-01 13:20:16 +01001629 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1630 if (s_cursor_visible)
1631 SetConsoleCursorPosition(g_hConOut, g_coord);
1632 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001633}
1634
1635 void
1636mch_update_cursor(void)
1637{
1638 int idx;
1639 int thickness;
1640
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001641# ifdef VIMDLL
1642 if (gui.in_use)
1643 return;
1644# endif
1645
Bram Moolenaar071d4272004-06-13 20:20:40 +00001646 /*
1647 * How the cursor is drawn depends on the current mode.
1648 */
1649 idx = get_shape_idx(FALSE);
1650
1651 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001652 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00001653 else
1654 thickness = shape_table[idx].percentage;
1655 mch_set_cursor_shape(thickness);
1656}
1657#endif
1658
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001659#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001660/*
1661 * Handle FOCUS_EVENT.
1662 */
1663 static void
1664handle_focus_event(INPUT_RECORD ir)
1665{
1666 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1667 ui_focus_change((int)g_fJustGotFocus);
1668}
1669
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001670static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1671
Bram Moolenaar071d4272004-06-13 20:20:40 +00001672/*
1673 * Wait until console input from keyboard or mouse is available,
1674 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001675 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001676 * Return TRUE if something is available FALSE if not.
1677 */
1678 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001679WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001680{
1681 DWORD dwNow = 0, dwEndTime = 0;
1682 INPUT_RECORD ir;
1683 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001684 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001685# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001686 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001687# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001688
1689 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001690 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001691 dwEndTime = GetTickCount() + msec;
1692 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001693 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001694 dwEndTime = INFINITE;
1695
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001696 // We need to loop until the end of the time period, because
1697 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001698 for (;;)
1699 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001700 // Only process messages when waiting.
1701 if (msec != 0)
1702 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001703# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001704 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001705# endif
1706# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001707 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001708# endif
1709# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001710 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001711# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001712 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001713
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001714 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001715# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001716 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001717# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001718 )
1719 return TRUE;
1720
1721 if (msec > 0)
1722 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001723 // If the specified wait time has passed, return. Beware that
1724 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001725 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001726 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001727 break;
1728 }
1729 if (msec != 0)
1730 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001731 DWORD dwWaitTime = dwEndTime - dwNow;
1732
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001733 // Don't wait for more than 11 msec to avoid dropping characters,
1734 // check channel while waiting for input and handle a callback from
1735 // 'balloonexpr'.
1736 if (dwWaitTime > 11)
1737 dwWaitTime = 11;
1738
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001739# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001740 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001741 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001742# endif
1743# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001744 // When waiting very briefly don't trigger timers.
1745 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001746 {
1747 long due_time;
1748
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001749 // Trigger timers and then get the time in msec until the next
1750 // one is due. Wait up to that time.
1751 due_time = check_due_timer();
1752 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001753 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001754 // timer may have used feedkeys().
1755 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001756 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001757 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1758 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001759 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001760# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001761 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001762# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001763 // Wait for either an event on the console input or a
1764 // message in the client-server window.
1765 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1766 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001767# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001768 wait_for_single_object(g_hConIn, dwWaitTime)
1769 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001770# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001771 )
1772 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001773 }
1774
1775 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001776 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001777
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001778# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02001779 // May have to redraw if the cursor ends up in the wrong place.
1780 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01001781 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001782 {
1783 CONSOLE_SCREEN_BUFFER_INFO csbi;
1784
1785 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1786 {
1787 if (csbi.dwCursorPosition.Y != msg_row)
1788 {
matveyte08795e2021-05-07 15:00:17 +02001789 // The screen is now messed up, must redraw the command
1790 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01001791 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02001792 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001793 redrawcmd();
1794 }
1795 }
1796 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001797# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001798
1799 if (cRecords > 0)
1800 {
1801 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1802 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001803# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01001804 // Windows IME sends two '\n's with only one 'ENTER'. First:
1805 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00001806 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001807 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1808 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001809 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001810 continue;
1811 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001812# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001813 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1814 NULL, FALSE))
1815 return TRUE;
1816 }
1817
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001818 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001819
1820 if (ir.EventType == FOCUS_EVENT)
1821 handle_focus_event(ir);
1822 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001823 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001824 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1825
Bram Moolenaar36698e32019-12-11 22:57:40 +01001826 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001827 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001828 if (dwSize.X != Columns || dwSize.Y != Rows)
1829 {
1830 CONSOLE_SCREEN_BUFFER_INFO csbi;
1831 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01001832 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001833 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01001834 if (dwSize.X != Columns || dwSize.Y != Rows)
1835 {
1836 ResizeConBuf(g_hConOut, dwSize);
1837 shell_resized();
1838 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001839 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001840 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001841 else if (ir.EventType == MOUSE_EVENT
1842 && decode_mouse_event(&ir.Event.MouseEvent))
1843 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001844 }
1845 else if (msec == 0)
1846 break;
1847 }
1848
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001849# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01001850 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001851 if (input_available())
1852 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001853# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001854
Bram Moolenaar071d4272004-06-13 20:20:40 +00001855 return FALSE;
1856}
1857
Bram Moolenaar071d4272004-06-13 20:20:40 +00001858/*
1859 * return non-zero if a character is available
1860 */
1861 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001862mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001863{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001864# ifdef VIMDLL
1865 if (gui.in_use)
1866 return TRUE;
1867# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001868 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001869}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001870
1871# if defined(FEAT_TERMINAL) || defined(PROTO)
1872/*
1873 * Check for any pending input or messages.
1874 */
1875 int
1876mch_check_messages(void)
1877{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001878# ifdef VIMDLL
1879 if (gui.in_use)
1880 return TRUE;
1881# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001882 return WaitForChar(0L, TRUE);
1883}
1884# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001885
1886/*
1887 * Create the console input. Used when reading stdin doesn't work.
1888 */
1889 static void
1890create_conin(void)
1891{
1892 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1893 FILE_SHARE_READ|FILE_SHARE_WRITE,
1894 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001895 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001896 did_create_conin = TRUE;
1897}
1898
1899/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001900 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001901 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001902 static WCHAR
1903tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001904{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001905 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001906
1907 for (;;)
1908 {
1909 INPUT_RECORD ir;
1910 DWORD cRecords = 0;
1911
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001912# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001913 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001914 if (input_available())
1915 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001916 if (g_nMouseClick != -1)
1917 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001918# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001919 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001920 {
1921 if (did_create_conin)
1922 read_error_exit();
1923 create_conin();
1924 continue;
1925 }
1926
1927 if (ir.EventType == KEY_EVENT)
1928 {
1929 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1930 pmodifiers, TRUE))
1931 return ch;
1932 }
1933 else if (ir.EventType == FOCUS_EVENT)
1934 handle_focus_event(ir);
1935 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1936 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001937 else if (ir.EventType == MOUSE_EVENT)
1938 {
1939 if (decode_mouse_event(&ir.Event.MouseEvent))
1940 return 0;
1941 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001942 }
1943}
Bram Moolenaar0f873732019-12-05 20:28:46 +01001944#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001945
1946
1947/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001948 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001949 * Get one or more characters from the keyboard or the mouse.
1950 * If time == 0, do not wait for characters.
1951 * If time == n, wait a short time for characters.
1952 * If time == -1, wait forever for characters.
1953 * Returns the number of characters read into buf.
1954 */
1955 int
1956mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001957 char_u *buf UNUSED,
1958 int maxlen UNUSED,
1959 long time UNUSED,
1960 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001961{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001962#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001963
1964 int len;
1965 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001966# ifdef VIMDLL
1967// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
1968# define TYPEAHEADSPACE 6
1969# else
1970# define TYPEAHEADSPACE 0
1971# endif
1972# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001973 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001974 static int typeaheadlen = 0;
1975
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001976# ifdef VIMDLL
1977 if (gui.in_use)
1978 return 0;
1979# endif
1980
Bram Moolenaar0f873732019-12-05 20:28:46 +01001981 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001982 if (typeaheadlen > 0)
1983 goto theend;
1984
Bram Moolenaar071d4272004-06-13 20:20:40 +00001985 if (time >= 0)
1986 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001987 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00001988 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001989 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001990 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00001991 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001992 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00001993
Bram Moolenaar3918c952005-03-15 22:34:55 +00001994 /*
1995 * If there is no character available within 2 seconds (default)
1996 * write the autoscript file to disk. Or cause the CursorHold event
1997 * to be triggered.
1998 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001999 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002000 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00002001 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002002 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00002003 buf[0] = K_SPECIAL;
2004 buf[1] = KS_EXTRA;
2005 buf[2] = (int)KE_CURSORHOLD;
2006 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002007 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00002008 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002009 }
2010 }
2011
2012 /*
2013 * Try to read as many characters as there are, until the buffer is full.
2014 */
2015
Bram Moolenaar0f873732019-12-05 20:28:46 +01002016 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002017 g_fCBrkPressed = FALSE;
2018
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002019# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002020 if (fdDump)
2021 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002022# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002023
Bram Moolenaar0f873732019-12-05 20:28:46 +01002024 // Keep looping until there is something in the typeahead buffer and more
2025 // to get and still room in the buffer (up to two bytes for a char and
2026 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002027 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01002028 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002029 {
2030 if (typebuf_changed(tb_change_cnt))
2031 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002032 // "buf" may be invalid now if a client put something in the
2033 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002034 typeaheadlen = 0;
2035 break;
2036 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002037 if (g_nMouseClick != -1)
2038 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002039# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002040 if (fdDump)
2041 fprintf(fdDump, "{%02x @ %d, %d}",
2042 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002043# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01002044 char_u modifiers = ((char_u *)(&g_nMouseClick))[0];
2045 char_u scroll_dir = ((char_u *)(&g_nMouseClick))[1];
2046
2047 if (scroll_dir == KE_MOUSEDOWN
2048 || scroll_dir == KE_MOUSEUP
2049 || scroll_dir == KE_MOUSELEFT
2050 || scroll_dir == KE_MOUSERIGHT)
2051 {
2052 if (modifiers > 0)
2053 {
2054 typeahead[typeaheadlen++] = CSI;
2055 typeahead[typeaheadlen++] = KS_MODIFIER;
2056 typeahead[typeaheadlen++] = modifiers;
2057 }
2058 typeahead[typeaheadlen++] = CSI;
2059 typeahead[typeaheadlen++] = KS_EXTRA;
2060 typeahead[typeaheadlen++] = scroll_dir;
2061 g_nMouseClick = -1;
2062 }
2063 else
2064 {
2065 typeahead[typeaheadlen++] = ESC + 128;
2066 typeahead[typeaheadlen++] = 'M';
2067 typeahead[typeaheadlen++] = g_nMouseClick;
2068 typeahead[typeaheadlen++] = g_xMouse + '!';
2069 typeahead[typeaheadlen++] = g_yMouse + '!';
2070 g_nMouseClick = -1;
2071 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002072 }
2073 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002074 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002075 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002076 int modifiers = 0;
2077
2078 c = tgetch(&modifiers, &ch2);
2079
2080 if (typebuf_changed(tb_change_cnt))
2081 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002082 // "buf" may be invalid now if a client put something in the
2083 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002084 typeaheadlen = 0;
2085 break;
2086 }
2087
2088 if (c == Ctrl_C && ctrl_c_interrupts)
2089 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002090# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002091 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002092# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002093 got_int = TRUE;
2094 }
2095
Bram Moolenaar071d4272004-06-13 20:20:40 +00002096 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002097 {
2098 int n = 1;
2099
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002100 if (ch2 == NUL)
2101 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002102 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002103 char_u *p;
2104 WCHAR ch[2];
2105
2106 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002107 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002108 {
2109 ch[1] = tgetch(&modifiers, &ch2);
2110 n++;
2111 }
2112 p = utf16_to_enc(ch, &n);
2113 if (p != NULL)
2114 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002115 for (i = 0, j = 0; i < n; i++)
2116 {
2117 typeahead[typeaheadlen + j++] = p[i];
2118# ifdef VIMDLL
2119 if (p[i] == CSI)
2120 {
2121 typeahead[typeaheadlen + j++] = KS_EXTRA;
2122 typeahead[typeaheadlen + j++] = KE_CSI;
2123 }
2124# endif
2125 }
2126 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002127 vim_free(p);
2128 }
2129 }
2130 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002131 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002132 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002133# ifdef VIMDLL
2134 if (c == CSI)
2135 {
2136 typeahead[typeaheadlen + 1] = KS_EXTRA;
2137 typeahead[typeaheadlen + 2] = KE_CSI;
2138 n = 3;
2139 }
2140# endif
2141 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002142 if (ch2 != NUL)
2143 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002144 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002145 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002146 switch (ch2)
2147 {
2148 case (WCHAR)'\324': // SHIFT+Insert
2149 case (WCHAR)'\325': // CTRL+Insert
2150 case (WCHAR)'\327': // SHIFT+Delete
2151 case (WCHAR)'\330': // CTRL+Delete
2152 typeahead[typeaheadlen + n] = (char_u)ch2;
2153 n++;
2154 break;
2155
2156 default:
2157 typeahead[typeaheadlen + n] = 3;
2158 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2159 n += 2;
2160 break;
2161 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002162 }
2163 else
2164 {
2165 typeahead[typeaheadlen + n] = 3;
2166 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2167 n += 2;
2168 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002169 }
2170
Bram Moolenaar0f873732019-12-05 20:28:46 +01002171 // Use the ALT key to set the 8th bit of the character
2172 // when it's one byte, the 8th bit isn't set yet and not
2173 // using a double-byte encoding (would become a lead
2174 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002175 if ((modifiers & MOD_MASK_ALT)
2176 && n == 1
2177 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002178 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002179 )
2180 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002181 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2182 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002183 modifiers &= ~MOD_MASK_ALT;
2184 }
2185
2186 if (modifiers != 0)
2187 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002188 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002189 mch_memmove(typeahead + typeaheadlen + 3,
2190 typeahead + typeaheadlen, n);
2191 typeahead[typeaheadlen++] = K_SPECIAL;
2192 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2193 typeahead[typeaheadlen++] = modifiers;
2194 }
2195
2196 typeaheadlen += n;
2197
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002198# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002199 if (fdDump)
2200 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002201# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002202 }
2203 }
2204 }
2205
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002206# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002207 if (fdDump)
2208 {
2209 fputs("]\n", fdDump);
2210 fflush(fdDump);
2211 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002212# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002213
Bram Moolenaar071d4272004-06-13 20:20:40 +00002214theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002215 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002216 len = 0;
2217 while (len < maxlen && typeaheadlen > 0)
2218 {
2219 buf[len++] = typeahead[0];
2220 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2221 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002222# ifdef FEAT_JOB_CHANNEL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002223 if (len > 0)
2224 {
2225 buf[len] = NUL;
2226 ch_log(NULL, "raw key input: \"%s\"", buf);
2227 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002228# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002229 return len;
2230
Bram Moolenaar0f873732019-12-05 20:28:46 +01002231#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002232 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002233#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002234}
2235
Bram Moolenaar82881492012-11-20 16:53:39 +01002236#ifndef PROTO
2237# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002238# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002239# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002240#endif
2241
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002242/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002243 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002244 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2245 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002246 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002247 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002248 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002249executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002250{
LemonBoy40fd7e62022-05-05 20:18:16 +01002251 int attrs = win32_getattrs((char_u *)name);
2252
2253 // The file doesn't exist or is a folder.
2254 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2255 return FALSE;
2256 // Check if the file is an AppExecLink, a special alias used by Windows
2257 // Store for its apps.
2258 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002259 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002260 char_u *res = resolve_appexeclink((char_u *)name);
2261 if (res == NULL)
2262 return FALSE;
2263 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002264 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002265 *path = res;
2266 else
2267 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002268 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002269 else if (path != NULL)
2270 *path = FullName_save((char_u *)name, FALSE);
2271 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002272}
2273
2274/*
2275 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2276 * If "use_path" is FALSE: Return TRUE if "name" exists.
2277 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2278 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2279 * the allocated memory.
2280 */
2281 static int
2282executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2283{
2284 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2285 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2286 // UTF-8.
2287 char_u buf[_MAX_PATH * 3];
2288 size_t len = STRLEN(name);
2289 size_t tmplen;
2290 char_u *p, *e, *e2;
2291 char_u *pathbuf = NULL;
2292 char_u *pathext = NULL;
2293 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002294 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002295 int noext = FALSE;
2296 int retval = FALSE;
2297
2298 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002299 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002300
2301 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002302 shname = gettail(p_sh);
2303 if (strstr((char *)shname, "sh") != NULL &&
2304 !(strstr((char *)shname, "powershell") != NULL
2305 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002306 noext = TRUE;
2307
2308 if (use_pathext)
2309 {
2310 pathext = mch_getenv("PATHEXT");
2311 if (pathext == NULL)
2312 pathext = (char_u *)".com;.exe;.bat;.cmd";
2313
2314 if (noext == FALSE)
2315 {
2316 /*
2317 * Loop over all extensions in $PATHEXT.
2318 * Check "name" ends with extension.
2319 */
2320 p = pathext;
2321 while (*p)
2322 {
2323 if (p[0] == ';'
2324 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2325 {
2326 // Skip empty or single ".".
2327 ++p;
2328 continue;
2329 }
2330 e = vim_strchr(p, ';');
2331 if (e == NULL)
2332 e = p + STRLEN(p);
2333 tmplen = e - p;
2334
2335 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2336 {
2337 noext = TRUE;
2338 break;
2339 }
2340
2341 p = e;
2342 }
2343 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002344 }
2345
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002346 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002347 if (pathext == NULL)
2348 pathext = (char_u *)".";
2349 else if (noext == TRUE)
2350 {
2351 if (pathextbuf == NULL)
2352 pathextbuf = alloc(STRLEN(pathext) + 3);
2353 if (pathextbuf == NULL)
2354 {
2355 retval = FALSE;
2356 goto theend;
2357 }
2358 STRCPY(pathextbuf, ".;");
2359 STRCAT(pathextbuf, pathext);
2360 pathext = pathextbuf;
2361 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002362
Bram Moolenaar95da1362020-05-30 18:37:55 +02002363 // Use $PATH when "use_path" is TRUE and "name" is basename.
2364 if (use_path && gettail((char_u *)name) == (char_u *)name)
2365 {
2366 p = mch_getenv("PATH");
2367 if (p != NULL)
2368 {
2369 pathbuf = alloc(STRLEN(p) + 3);
2370 if (pathbuf == NULL)
2371 {
2372 retval = FALSE;
2373 goto theend;
2374 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002375
2376 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2377 STRCPY(pathbuf, ".;");
2378 else
2379 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002380 STRCAT(pathbuf, p);
2381 }
2382 }
2383
2384 /*
2385 * Walk through all entries in $PATH to check if "name" exists there and
2386 * is an executable file.
2387 */
2388 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2389 while (*p)
2390 {
2391 if (*p == ';') // Skip empty entry
2392 {
2393 ++p;
2394 continue;
2395 }
2396 e = vim_strchr(p, ';');
2397 if (e == NULL)
2398 e = p + STRLEN(p);
2399
2400 if (e - p + len + 2 > sizeof(buf))
2401 {
2402 retval = FALSE;
2403 goto theend;
2404 }
2405 // A single "." that means current dir.
2406 if (e - p == 1 && *p == '.')
2407 STRCPY(buf, name);
2408 else
2409 {
2410 vim_strncpy(buf, p, e - p);
2411 add_pathsep(buf);
2412 STRCAT(buf, name);
2413 }
2414 tmplen = STRLEN(buf);
2415
2416 /*
2417 * Loop over all extensions in $PATHEXT.
2418 * Check "name" with extension added.
2419 */
2420 p = pathext;
2421 while (*p)
2422 {
2423 if (*p == ';')
2424 {
2425 // Skip empty entry
2426 ++p;
2427 continue;
2428 }
2429 e2 = vim_strchr(p, (int)';');
2430 if (e2 == NULL)
2431 e2 = p + STRLEN(p);
2432
2433 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2434 {
2435 // Not a single "." that means no extension is added.
2436 if (e2 - p + tmplen + 1 > sizeof(buf))
2437 {
2438 retval = FALSE;
2439 goto theend;
2440 }
2441 vim_strncpy(buf + tmplen, p, e2 - p);
2442 }
2443 if (executable_file((char *)buf, path))
2444 {
2445 retval = TRUE;
2446 goto theend;
2447 }
2448
2449 p = e2;
2450 }
2451
2452 p = e;
2453 }
2454
2455theend:
2456 free(pathextbuf);
2457 free(pathbuf);
2458 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002459}
2460
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002461#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2462 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002463/*
2464 * Bad parameter handler.
2465 *
2466 * Certain MS CRT functions will intentionally crash when passed invalid
2467 * parameters to highlight possible security holes. Setting this function as
2468 * the bad parameter handler will prevent the crash.
2469 *
2470 * In debug builds the parameters contain CRT information that might help track
2471 * down the source of a problem, but in non-debug builds the arguments are all
2472 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2473 * worth allowing these to make debugging of issues easier.
2474 */
2475 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002476bad_param_handler(const wchar_t *expression UNUSED,
2477 const wchar_t *function UNUSED,
2478 const wchar_t *file UNUSED,
2479 unsigned int line UNUSED,
2480 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002481{
2482}
2483
2484# define SET_INVALID_PARAM_HANDLER \
2485 ((void)_set_invalid_parameter_handler(bad_param_handler))
2486#else
2487# define SET_INVALID_PARAM_HANDLER
2488#endif
2489
Bram Moolenaar4f974752019-02-17 17:44:42 +01002490#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002491
2492/*
2493 * GUI version of mch_init().
2494 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002495 static void
2496mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002497{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002498# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002499 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002500# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002501
Bram Moolenaar0f873732019-12-05 20:28:46 +01002502 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002503 SET_INVALID_PARAM_HANDLER;
2504
Bram Moolenaar0f873732019-12-05 20:28:46 +01002505 // Let critical errors result in a failure, not in a dialog box. Required
2506 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002507 SetErrorMode(SEM_FAILCRITICALERRORS);
2508
Bram Moolenaar0f873732019-12-05 20:28:46 +01002509 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002510
Bram Moolenaar0f873732019-12-05 20:28:46 +01002511 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002512 Rows = 25;
2513 Columns = 80;
2514
Bram Moolenaar0f873732019-12-05 20:28:46 +01002515 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002516 {
2517 char_u vimrun_location[_MAX_PATH + 4];
2518
Bram Moolenaar0f873732019-12-05 20:28:46 +01002519 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002520 STRCPY(vimrun_location, exe_name);
2521 STRCPY(gettail(vimrun_location), "vimrun.exe");
2522 if (mch_getperm(vimrun_location) >= 0)
2523 {
2524 if (*skiptowhite(vimrun_location) != NUL)
2525 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002526 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002527 mch_memmove(vimrun_location + 1, vimrun_location,
2528 STRLEN(vimrun_location) + 1);
2529 *vimrun_location = '"';
2530 STRCPY(gettail(vimrun_location), "vimrun\" ");
2531 }
2532 else
2533 STRCPY(gettail(vimrun_location), "vimrun ");
2534
2535 vimrun_path = (char *)vim_strsave(vimrun_location);
2536 s_dont_use_vimrun = FALSE;
2537 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002538 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002539 s_dont_use_vimrun = FALSE;
2540
Bram Moolenaar0f873732019-12-05 20:28:46 +01002541 // Don't give the warning for a missing vimrun.exe right now, but only
2542 // when vimrun was supposed to be used. Don't bother people that do
2543 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002544 if (s_dont_use_vimrun)
2545 need_vimrun_warning = TRUE;
2546 }
2547
2548 /*
2549 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2550 * Otherwise the default "findstr /n" is used.
2551 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002552 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01002553 set_option_value_give_err((char_u *)"grepprg",
2554 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002555
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002556# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002557 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002558# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002559
2560 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002561}
2562
2563
Bram Moolenaar0f873732019-12-05 20:28:46 +01002564#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002565
2566#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002567
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002568# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2569# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002570
2571/*
2572 * ClearConsoleBuffer()
2573 * Description:
2574 * Clears the entire contents of the console screen buffer, using the
2575 * specified attribute.
2576 * Returns:
2577 * TRUE on success
2578 */
2579 static BOOL
2580ClearConsoleBuffer(WORD wAttribute)
2581{
2582 CONSOLE_SCREEN_BUFFER_INFO csbi;
2583 COORD coord;
2584 DWORD NumCells, dummy;
2585
2586 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2587 return FALSE;
2588
2589 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2590 coord.X = 0;
2591 coord.Y = 0;
2592 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2593 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002594 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002595 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2596 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002597 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002598
2599 return TRUE;
2600}
2601
2602/*
2603 * FitConsoleWindow()
2604 * Description:
2605 * Checks if the console window will fit within given buffer dimensions.
2606 * Also, if requested, will shrink the window to fit.
2607 * Returns:
2608 * TRUE on success
2609 */
2610 static BOOL
2611FitConsoleWindow(
2612 COORD dwBufferSize,
2613 BOOL WantAdjust)
2614{
2615 CONSOLE_SCREEN_BUFFER_INFO csbi;
2616 COORD dwWindowSize;
2617 BOOL NeedAdjust = FALSE;
2618
2619 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2620 {
2621 /*
2622 * A buffer resize will fail if the current console window does
2623 * not lie completely within that buffer. To avoid this, we might
2624 * have to move and possibly shrink the window.
2625 */
2626 if (csbi.srWindow.Right >= dwBufferSize.X)
2627 {
2628 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2629 if (dwWindowSize.X > dwBufferSize.X)
2630 dwWindowSize.X = dwBufferSize.X;
2631 csbi.srWindow.Right = dwBufferSize.X - 1;
2632 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2633 NeedAdjust = TRUE;
2634 }
2635 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2636 {
2637 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2638 if (dwWindowSize.Y > dwBufferSize.Y)
2639 dwWindowSize.Y = dwBufferSize.Y;
2640 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2641 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2642 NeedAdjust = TRUE;
2643 }
2644 if (NeedAdjust && WantAdjust)
2645 {
2646 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2647 return FALSE;
2648 }
2649 return TRUE;
2650 }
2651
2652 return FALSE;
2653}
2654
2655typedef struct ConsoleBufferStruct
2656{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002657 BOOL IsValid;
2658 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002659 PCHAR_INFO Buffer;
2660 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002661 PSMALL_RECT Regions;
2662 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002663} ConsoleBuffer;
2664
2665/*
2666 * SaveConsoleBuffer()
2667 * Description:
2668 * Saves important information about the console buffer, including the
2669 * actual buffer contents. The saved information is suitable for later
2670 * restoration by RestoreConsoleBuffer().
2671 * Returns:
2672 * TRUE if all information was saved; FALSE otherwise
2673 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2674 */
2675 static BOOL
2676SaveConsoleBuffer(
2677 ConsoleBuffer *cb)
2678{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002679 DWORD NumCells;
2680 COORD BufferCoord;
2681 SMALL_RECT ReadRegion;
2682 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002683 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002684
Bram Moolenaar071d4272004-06-13 20:20:40 +00002685 if (cb == NULL)
2686 return FALSE;
2687
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002688 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002689 {
2690 cb->IsValid = FALSE;
2691 return FALSE;
2692 }
2693 cb->IsValid = TRUE;
2694
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002695 /*
2696 * Allocate a buffer large enough to hold the entire console screen
2697 * buffer. If this ConsoleBuffer structure has already been initialized
2698 * with a buffer of the correct size, then just use that one.
2699 */
2700 if (!cb->IsValid || cb->Buffer == NULL ||
2701 cb->BufferSize.X != cb->Info.dwSize.X ||
2702 cb->BufferSize.Y != cb->Info.dwSize.Y)
2703 {
2704 cb->BufferSize.X = cb->Info.dwSize.X;
2705 cb->BufferSize.Y = cb->Info.dwSize.Y;
2706 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2707 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002708 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002709 if (cb->Buffer == NULL)
2710 return FALSE;
2711 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002712
2713 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002714 * We will now copy the console screen buffer into our buffer.
2715 * ReadConsoleOutput() seems to be limited as far as how much you
2716 * can read at a time. Empirically, this number seems to be about
2717 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2718 * in chunks until it is all copied. The chunks will all have the
2719 * same horizontal characteristics, so initialize them now. The
2720 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002721 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002722 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002723 ReadRegion.Left = 0;
2724 ReadRegion.Right = cb->Info.dwSize.X - 1;
2725 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002726
2727 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2728 if (cb->Regions == NULL || numregions != cb->NumRegions)
2729 {
2730 cb->NumRegions = numregions;
2731 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002732 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002733 if (cb->Regions == NULL)
2734 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002735 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002736 return FALSE;
2737 }
2738 }
2739
2740 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002741 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002742 /*
2743 * Read into position (0, Y) in our buffer.
2744 */
2745 BufferCoord.Y = Y;
2746 /*
2747 * Read the region whose top left corner is (0, Y) and whose bottom
2748 * right corner is (width - 1, Y + Y_incr - 1). This should define
2749 * a region of size width by Y_incr. Don't worry if this region is
2750 * too large for the remaining buffer; it will be cropped.
2751 */
2752 ReadRegion.Top = Y;
2753 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002754 if (!ReadConsoleOutputW(g_hConOut, // output handle
2755 cb->Buffer, // our buffer
2756 cb->BufferSize, // dimensions of our buffer
2757 BufferCoord, // offset in our buffer
2758 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002759 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002760 VIM_CLEAR(cb->Buffer);
2761 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002762 return FALSE;
2763 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002764 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002765 }
2766
2767 return TRUE;
2768}
2769
2770/*
2771 * RestoreConsoleBuffer()
2772 * Description:
2773 * Restores important information about the console buffer, including the
2774 * actual buffer contents, if desired. The information to restore is in
2775 * the same format used by SaveConsoleBuffer().
2776 * Returns:
2777 * TRUE on success
2778 */
2779 static BOOL
2780RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002781 ConsoleBuffer *cb,
2782 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002783{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002784 COORD BufferCoord;
2785 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002786 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002787
2788 if (cb == NULL || !cb->IsValid)
2789 return FALSE;
2790
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002791 /*
2792 * Before restoring the buffer contents, clear the current buffer, and
2793 * restore the cursor position and window information. Doing this now
2794 * prevents old buffer contents from "flashing" onto the screen.
2795 */
2796 if (RestoreScreen)
2797 ClearConsoleBuffer(cb->Info.wAttributes);
2798
2799 FitConsoleWindow(cb->Info.dwSize, TRUE);
2800 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2801 return FALSE;
2802 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2803 return FALSE;
2804
2805 if (!RestoreScreen)
2806 {
2807 /*
2808 * No need to restore the screen buffer contents, so we're done.
2809 */
2810 return TRUE;
2811 }
2812
2813 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2814 return FALSE;
2815 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2816 return FALSE;
2817
2818 /*
2819 * Restore the screen buffer contents.
2820 */
2821 if (cb->Buffer != NULL)
2822 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002823 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002824 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002825 BufferCoord.X = cb->Regions[i].Left;
2826 BufferCoord.Y = cb->Regions[i].Top;
2827 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01002828 if (!WriteConsoleOutputW(g_hConOut, // output handle
2829 cb->Buffer, // our buffer
2830 cb->BufferSize, // dimensions of our buffer
2831 BufferCoord, // offset in our buffer
2832 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02002833 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002834 }
2835 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002836
2837 return TRUE;
2838}
2839
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002840# define FEAT_RESTORE_ORIG_SCREEN
2841# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002842static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002843# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002844static ConsoleBuffer g_cbNonTermcap = { 0 };
2845static ConsoleBuffer g_cbTermcap = { 0 };
2846
Bram Moolenaar071d4272004-06-13 20:20:40 +00002847char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01002848HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00002849static HICON g_hOrigIconSmall = NULL;
2850static HICON g_hOrigIcon = NULL;
2851static HICON g_hVimIcon = NULL;
2852static BOOL g_fCanChangeIcon = FALSE;
2853
Bram Moolenaar071d4272004-06-13 20:20:40 +00002854/*
2855 * GetConsoleIcon()
2856 * Description:
2857 * Attempts to retrieve the small icon and/or the big icon currently in
2858 * use by a given window.
2859 * Returns:
2860 * TRUE on success
2861 */
2862 static BOOL
2863GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002864 HWND hWnd,
2865 HICON *phIconSmall,
2866 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002867{
2868 if (hWnd == NULL)
2869 return FALSE;
2870
2871 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002872 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2873 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002874 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002875 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2876 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002877 return TRUE;
2878}
2879
2880/*
2881 * SetConsoleIcon()
2882 * Description:
2883 * Attempts to change the small icon and/or the big icon currently in
2884 * use by a given window.
2885 * Returns:
2886 * TRUE on success
2887 */
2888 static BOOL
2889SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002890 HWND hWnd,
2891 HICON hIconSmall,
2892 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002893{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002894 if (hWnd == NULL)
2895 return FALSE;
2896
2897 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002898 SendMessage(hWnd, WM_SETICON,
2899 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002900 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002901 SendMessage(hWnd, WM_SETICON,
2902 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002903 return TRUE;
2904}
2905
2906/*
2907 * SaveConsoleTitleAndIcon()
2908 * Description:
2909 * Saves the current console window title in g_szOrigTitle, for later
2910 * restoration. Also, attempts to obtain a handle to the console window,
2911 * and use it to save the small and big icons currently in use by the
2912 * console window. This is not always possible on some versions of Windows;
2913 * nor is it possible when running Vim remotely using Telnet (since the
2914 * console window the user sees is owned by a remote process).
2915 */
2916 static void
2917SaveConsoleTitleAndIcon(void)
2918{
Bram Moolenaar0f873732019-12-05 20:28:46 +01002919 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002920 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2921 return;
2922
2923 /*
2924 * Obtain a handle to the console window using GetConsoleWindow() from
2925 * KERNEL32.DLL; we need to handle in order to change the window icon.
2926 * This function only exists on NT-based Windows, starting with Windows
2927 * 2000. On older operating systems, we can't change the window icon
2928 * anyway.
2929 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002930 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002931 if (g_hWnd == NULL)
2932 return;
2933
Bram Moolenaar0f873732019-12-05 20:28:46 +01002934 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002935 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2936 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2937 return;
2938
Bram Moolenaar0f873732019-12-05 20:28:46 +01002939 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01002940 if (
2941# ifdef FEAT_LIBCALL
2942 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
2943# endif
2944 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002945 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002946 if (g_hVimIcon != NULL)
2947 g_fCanChangeIcon = TRUE;
2948}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002949
2950static int g_fWindInitCalled = FALSE;
2951static int g_fTermcapMode = FALSE;
2952static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002953
2954/*
2955 * non-GUI version of mch_init().
2956 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002957 static void
2958mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002959{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002960# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002961 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002962# endif
2963# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002964 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002965# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002966
Bram Moolenaar0f873732019-12-05 20:28:46 +01002967 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002968 SET_INVALID_PARAM_HANDLER;
2969
Bram Moolenaar0f873732019-12-05 20:28:46 +01002970 // Let critical errors result in a failure, not in a dialog box. Required
2971 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002972 SetErrorMode(SEM_FAILCRITICALERRORS);
2973
Bram Moolenaar0f873732019-12-05 20:28:46 +01002974 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002975 out_flush();
2976
Bram Moolenaar0f873732019-12-05 20:28:46 +01002977 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00002978 if (read_cmd_fd == 0)
2979 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2980 else
2981 create_conin();
2982 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2983
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002984# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01002985 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002986 SaveConsoleBuffer(&g_cbOrig);
2987 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002988# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01002989 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002990 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2991 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002992# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002993 if (cterm_normal_fg_color == 0)
2994 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2995 if (cterm_normal_bg_color == 0)
2996 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2997
Bram Moolenaarbdace832019-03-02 10:13:42 +01002998 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002999 g_color_index_fg = g_attrDefault & 0xf;
3000 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
3001
Bram Moolenaar0f873732019-12-05 20:28:46 +01003002 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00003003 update_tcap(g_attrCurrent);
3004
3005 GetConsoleCursorInfo(g_hConOut, &g_cci);
3006 GetConsoleMode(g_hConIn, &g_cmodein);
3007 GetConsoleMode(g_hConOut, &g_cmodeout);
3008
Bram Moolenaar071d4272004-06-13 20:20:40 +00003009 SaveConsoleTitleAndIcon();
3010 /*
3011 * Set both the small and big icons of the console window to Vim's icon.
3012 * Note that Vim presently only has one size of icon (32x32), but it
3013 * automatically gets scaled down to 16x16 when setting the small icon.
3014 */
3015 if (g_fCanChangeIcon)
3016 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003017
3018 ui_get_shellsize();
3019
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003020# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003021 fdDump = fopen("dump", "wt");
3022
3023 if (fdDump)
3024 {
3025 time_t t;
3026
3027 time(&t);
3028 fputs(ctime(&t), fdDump);
3029 fflush(fdDump);
3030 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003031# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003032
3033 g_fWindInitCalled = TRUE;
3034
Bram Moolenaar071d4272004-06-13 20:20:40 +00003035 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003036
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003037# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003038 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003039# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003040
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02003041 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003042 vtp_init();
Bram Moolenaar06b7b582020-05-30 17:49:25 +02003043 wt_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003044}
3045
3046/*
3047 * non-GUI version of mch_exit().
3048 * Shut down and exit with status `r'
3049 * Careful: mch_exit() may be called before mch_init()!
3050 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003051 static void
3052mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003053{
Bram Moolenaar955f1982017-02-05 15:10:51 +01003054 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003055
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003056 vtp_exit();
3057
Bram Moolenaar955f1982017-02-05 15:10:51 +01003058 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003059 if (g_fWindInitCalled)
3060 settmode(TMODE_COOK);
3061
Bram Moolenaar0f873732019-12-05 20:28:46 +01003062 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00003063
3064 if (g_fWindInitCalled)
3065 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02003066 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003067 /*
3068 * Restore both the small and big icons of the console window to
3069 * what they were at startup. Don't do this when the window is
3070 * closed, Vim would hang here.
3071 */
3072 if (g_fCanChangeIcon && !g_fForceExit)
3073 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003074
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003075# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003076 if (fdDump)
3077 {
3078 time_t t;
3079
3080 time(&t);
3081 fputs(ctime(&t), fdDump);
3082 fclose(fdDump);
3083 }
3084 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003085# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003086 }
3087
3088 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003089 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003090 SetConsoleMode(g_hConOut, g_cmodeout);
3091
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003092# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003093 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003094# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003095
3096 exit(r);
3097}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003098#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003099
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003100 void
3101mch_init(void)
3102{
3103#ifdef VIMDLL
3104 if (gui.starting)
3105 mch_init_g();
3106 else
3107 mch_init_c();
3108#elif defined(FEAT_GUI_MSWIN)
3109 mch_init_g();
3110#else
3111 mch_init_c();
3112#endif
3113}
3114
3115 void
3116mch_exit(int r)
3117{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003118#ifdef FEAT_NETBEANS_INTG
3119 netbeans_send_disconnect();
3120#endif
3121
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003122#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003123 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003124 mch_exit_g(r);
3125 else
3126 mch_exit_c(r);
3127#elif defined(FEAT_GUI_MSWIN)
3128 mch_exit_g(r);
3129#else
3130 mch_exit_c(r);
3131#endif
3132}
3133
Bram Moolenaar071d4272004-06-13 20:20:40 +00003134/*
3135 * Do we have an interactive window?
3136 */
3137 int
3138mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003139 int argc UNUSED,
3140 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003141{
3142 get_exe_name();
3143
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003144#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003145 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003146#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003147# ifdef VIMDLL
3148 if (gui.in_use)
3149 return OK;
3150# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003151 if (isatty(1))
3152 return OK;
3153 return FAIL;
3154#endif
3155}
3156
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003157/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003158 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003159 * When "len" is > 0, also expand short to long filenames.
3160 */
3161 void
3162fname_case(
3163 char_u *name,
3164 int len)
3165{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003166 int flen;
3167 WCHAR *p;
3168 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003169
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003170 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003171 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003172 return;
3173
3174 slash_adjust(name);
3175
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003176 p = enc_to_utf16(name, NULL);
3177 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003178 return;
3179
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003180 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003181 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003182 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003183
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003184 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003185 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003186 if (len > 0 || flen >= (int)STRLEN(q))
3187 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3188 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003189 }
3190 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003191 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003192}
3193
3194
3195/*
3196 * Insert user name in s[len].
3197 */
3198 int
3199mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003200 char_u *s,
3201 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003202{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003203 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003204 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003205
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003206 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003207 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003208 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003209
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003210 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003211 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003212 vim_strncpy(s, p, len - 1);
3213 vim_free(p);
3214 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003215 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003216 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003217 s[0] = NUL;
3218 return FAIL;
3219}
3220
3221
3222/*
3223 * Insert host name in s[len].
3224 */
3225 void
3226mch_get_host_name(
3227 char_u *s,
3228 int len)
3229{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003230 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003231 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003232
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003233 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003234 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003235 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003236
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003237 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003238 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003239 vim_strncpy(s, p, len - 1);
3240 vim_free(p);
3241 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003242 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003243 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003244}
3245
3246
3247/*
3248 * return process ID
3249 */
3250 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003251mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003252{
3253 return (long)GetCurrentProcessId();
3254}
3255
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003256/*
3257 * return TRUE if process "pid" is still running
3258 */
3259 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003260mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003261{
3262 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3263 DWORD status = 0;
3264 int ret = FALSE;
3265
3266 if (hProcess == NULL)
3267 return FALSE; // might not have access
3268 if (GetExitCodeProcess(hProcess, &status) )
3269 ret = status == STILL_ACTIVE;
3270 CloseHandle(hProcess);
3271 return ret;
3272}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003273
3274/*
3275 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3276 * Return OK for success, FAIL for failure.
3277 */
3278 int
3279mch_dirname(
3280 char_u *buf,
3281 int len)
3282{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003283 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003284
Bram Moolenaar071d4272004-06-13 20:20:40 +00003285 /*
3286 * Originally this was:
3287 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3288 * But the Win32s known bug list says that getcwd() doesn't work
3289 * so use the Win32 system call instead. <Negri>
3290 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003291 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003292 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003293 WCHAR wcbuf[_MAX_PATH + 1];
3294 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003295
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003296 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003297 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003298 p = utf16_to_enc(wcbuf, NULL);
3299 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003300 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003301 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003302 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003303 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003304 }
3305 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003306 if (p == NULL)
3307 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003308
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003309 if (p != NULL)
3310 {
3311 vim_strncpy(buf, p, len - 1);
3312 vim_free(p);
3313 return OK;
3314 }
3315 }
3316 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003317}
3318
3319/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003320 * Get file permissions for "name".
3321 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003322 */
3323 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003324mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003325{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003326 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003327 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003328
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003329 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003330 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003331}
3332
3333
3334/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003335 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003336 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003337 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003338 */
3339 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003340mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003341{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003342 long n;
3343 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003344
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003345 p = enc_to_utf16(name, NULL);
3346 if (p == NULL)
3347 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003348
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003349 n = _wchmod(p, perm);
3350 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003351 if (n == -1)
3352 return FAIL;
3353
3354 win32_set_archive(name);
3355
3356 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003357}
3358
3359/*
3360 * Set hidden flag for "name".
3361 */
3362 void
3363mch_hide(char_u *name)
3364{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003365 int attrs = win32_getattrs(name);
3366 if (attrs == -1)
3367 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003368
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003369 attrs |= FILE_ATTRIBUTE_HIDDEN;
3370 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003371}
3372
3373/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003374 * Return TRUE if file "name" exists and is hidden.
3375 */
3376 int
3377mch_ishidden(char_u *name)
3378{
3379 int f = win32_getattrs(name);
3380
3381 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003382 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003383
3384 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3385}
3386
3387/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003388 * return TRUE if "name" is a directory
3389 * return FALSE if "name" is not a directory or upon error
3390 */
3391 int
3392mch_isdir(char_u *name)
3393{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003394 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003395
3396 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003397 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003398
3399 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3400}
3401
3402/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003403 * return TRUE if "name" is a directory, NOT a symlink to a directory
3404 * return FALSE if "name" is not a directory
3405 * return FALSE for error
3406 */
3407 int
3408mch_isrealdir(char_u *name)
3409{
3410 return mch_isdir(name) && !mch_is_symbolic_link(name);
3411}
3412
3413/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003414 * Create directory "name".
3415 * Return 0 on success, -1 on error.
3416 */
3417 int
3418mch_mkdir(char_u *name)
3419{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003420 WCHAR *p;
3421 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003422
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003423 p = enc_to_utf16(name, NULL);
3424 if (p == NULL)
3425 return -1;
3426 retval = _wmkdir(p);
3427 vim_free(p);
3428 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003429}
3430
3431/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003432 * Delete directory "name".
3433 * Return 0 on success, -1 on error.
3434 */
3435 int
3436mch_rmdir(char_u *name)
3437{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003438 WCHAR *p;
3439 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003440
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003441 p = enc_to_utf16(name, NULL);
3442 if (p == NULL)
3443 return -1;
3444 retval = _wrmdir(p);
3445 vim_free(p);
3446 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003447}
3448
3449/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003450 * Return TRUE if file "fname" has more than one link.
3451 */
3452 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003453mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003454{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003455 BY_HANDLE_FILE_INFORMATION info;
3456
3457 return win32_fileinfo(fname, &info) == FILEINFO_OK
3458 && info.nNumberOfLinks > 1;
3459}
3460
3461/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003462 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003463 */
3464 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003465mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003466{
3467 HANDLE hFind;
3468 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003469 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003470 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003471 WIN32_FIND_DATAW findDataW;
3472
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003473 wn = enc_to_utf16(name, NULL);
3474 if (wn == NULL)
3475 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003476
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003477 hFind = FindFirstFileW(wn, &findDataW);
3478 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003479 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003480 {
3481 fileFlags = findDataW.dwFileAttributes;
3482 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003483 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003484 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003485
3486 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003487 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3488 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003489 res = TRUE;
3490
3491 return res;
3492}
3493
3494/*
3495 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3496 * link.
3497 */
3498 int
3499mch_is_linked(char_u *fname)
3500{
3501 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3502 return TRUE;
3503 return FALSE;
3504}
3505
3506/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003507 * Get the by-handle-file-information for "fname".
3508 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003509 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003510 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3511 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3512 */
3513 int
3514win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3515{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003516 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003517 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003518 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003519
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003520 wn = enc_to_utf16(fname, NULL);
3521 if (wn == NULL)
3522 return FILEINFO_ENC_FAIL;
3523
3524 hFile = CreateFileW(wn, // file name
3525 GENERIC_READ, // access mode
3526 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3527 NULL, // security descriptor
3528 OPEN_EXISTING, // creation disposition
3529 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3530 NULL); // handle to template file
3531 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003532
3533 if (hFile != INVALID_HANDLE_VALUE)
3534 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003535 if (GetFileInformationByHandle(hFile, info) != 0)
3536 res = FILEINFO_OK;
3537 else
3538 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003539 CloseHandle(hFile);
3540 }
3541
Bram Moolenaar03f48552006-02-28 23:52:23 +00003542 return res;
3543}
3544
3545/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003546 * get file attributes for `name'
3547 * -1 : error
3548 * else FILE_ATTRIBUTE_* defined in winnt.h
3549 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003550 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003551win32_getattrs(char_u *name)
3552{
3553 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003554 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003555
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003556 p = enc_to_utf16(name, NULL);
3557 if (p == NULL)
3558 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003559
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003560 attr = GetFileAttributesW(p);
3561 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003562
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003563 return attr;
3564}
3565
3566/*
3567 * set file attributes for `name' to `attrs'
3568 *
3569 * return -1 for failure, 0 otherwise
3570 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003571 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003572win32_setattrs(char_u *name, int attrs)
3573{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003574 int res;
3575 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003576
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003577 p = enc_to_utf16(name, NULL);
3578 if (p == NULL)
3579 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003580
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003581 res = SetFileAttributesW(p, attrs);
3582 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003583
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003584 return res ? 0 : -1;
3585}
3586
3587/*
3588 * Set archive flag for "name".
3589 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003590 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003591win32_set_archive(char_u *name)
3592{
3593 int attrs = win32_getattrs(name);
3594 if (attrs == -1)
3595 return -1;
3596
3597 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3598 return win32_setattrs(name, attrs);
3599}
3600
3601/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003602 * Return TRUE if file or directory "name" is writable (not readonly).
3603 * Strange semantics of Win32: a readonly directory is writable, but you can't
3604 * delete a file. Let's say this means it is writable.
3605 */
3606 int
3607mch_writable(char_u *name)
3608{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003609 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003610
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003611 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3612 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003613}
3614
Bram Moolenaar071d4272004-06-13 20:20:40 +00003615/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003616 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003617 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003618 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3619 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003620 */
3621 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01003622mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003623{
Bram Moolenaar95da1362020-05-30 18:37:55 +02003624 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003625}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003626
3627/*
3628 * Check what "name" is:
3629 * NODE_NORMAL: file or directory (or doesn't exist)
3630 * NODE_WRITABLE: writable device, socket, fifo, etc.
3631 * NODE_OTHER: non-writable things
3632 */
3633 int
3634mch_nodetype(char_u *name)
3635{
3636 HANDLE hFile;
3637 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003638 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003639
Bram Moolenaar0f873732019-12-05 20:28:46 +01003640 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3641 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3642 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00003643 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3644 return NODE_WRITABLE;
3645
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003646 wn = enc_to_utf16(name, NULL);
3647 if (wn == NULL)
3648 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003649
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003650 hFile = CreateFileW(wn, // file name
3651 GENERIC_WRITE, // access mode
3652 0, // share mode
3653 NULL, // security descriptor
3654 OPEN_EXISTING, // creation disposition
3655 0, // file attributes
3656 NULL); // handle to template file
3657 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003658 if (hFile == INVALID_HANDLE_VALUE)
3659 return NODE_NORMAL;
3660
3661 type = GetFileType(hFile);
3662 CloseHandle(hFile);
3663 if (type == FILE_TYPE_CHAR)
3664 return NODE_WRITABLE;
3665 if (type == FILE_TYPE_DISK)
3666 return NODE_NORMAL;
3667 return NODE_OTHER;
3668}
3669
3670#ifdef HAVE_ACL
3671struct my_acl
3672{
3673 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3674 PSID pSidOwner;
3675 PSID pSidGroup;
3676 PACL pDacl;
3677 PACL pSacl;
3678};
3679#endif
3680
3681/*
3682 * Return a pointer to the ACL of file "fname" in allocated memory.
3683 * Return NULL if the ACL is not available for whatever reason.
3684 */
3685 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003686mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003687{
3688#ifndef HAVE_ACL
3689 return (vim_acl_T)NULL;
3690#else
3691 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003692 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003693
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003694 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003695 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003696 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003697 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003698
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003699 wn = enc_to_utf16(fname, NULL);
3700 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003701 {
3702 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003703 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003704 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003705
3706 // Try to retrieve the entire security descriptor.
3707 err = GetNamedSecurityInfoW(
3708 wn, // Abstract filename
3709 SE_FILE_OBJECT, // File Object
3710 OWNER_SECURITY_INFORMATION |
3711 GROUP_SECURITY_INFORMATION |
3712 DACL_SECURITY_INFORMATION |
3713 SACL_SECURITY_INFORMATION,
3714 &p->pSidOwner, // Ownership information.
3715 &p->pSidGroup, // Group membership.
3716 &p->pDacl, // Discretionary information.
3717 &p->pSacl, // For auditing purposes.
3718 &p->pSecurityDescriptor);
3719 if (err == ERROR_ACCESS_DENIED ||
3720 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003721 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003722 // Retrieve only DACL.
3723 (void)GetNamedSecurityInfoW(
3724 wn,
3725 SE_FILE_OBJECT,
3726 DACL_SECURITY_INFORMATION,
3727 NULL,
3728 NULL,
3729 &p->pDacl,
3730 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003731 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003732 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003733 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003734 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003735 mch_free_acl((vim_acl_T)p);
3736 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003737 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003738 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003739 }
3740
3741 return (vim_acl_T)p;
3742#endif
3743}
3744
Bram Moolenaar27515922013-06-29 15:36:26 +02003745#ifdef HAVE_ACL
3746/*
3747 * Check if "acl" contains inherited ACE.
3748 */
3749 static BOOL
3750is_acl_inherited(PACL acl)
3751{
3752 DWORD i;
3753 ACL_SIZE_INFORMATION acl_info;
3754 PACCESS_ALLOWED_ACE ace;
3755
3756 acl_info.AceCount = 0;
3757 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3758 for (i = 0; i < acl_info.AceCount; i++)
3759 {
3760 GetAce(acl, i, (LPVOID *)&ace);
3761 if (ace->Header.AceFlags & INHERITED_ACE)
3762 return TRUE;
3763 }
3764 return FALSE;
3765}
3766#endif
3767
Bram Moolenaar071d4272004-06-13 20:20:40 +00003768/*
3769 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3770 * Errors are ignored.
3771 * This must only be called with "acl" equal to what mch_get_acl() returned.
3772 */
3773 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003774mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003775{
3776#ifdef HAVE_ACL
3777 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003778 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003779 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003780
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003781 if (p == NULL)
3782 return;
3783
3784 wn = enc_to_utf16(fname, NULL);
3785 if (wn == NULL)
3786 return;
3787
3788 // Set security flags
3789 if (p->pSidOwner)
3790 sec_info |= OWNER_SECURITY_INFORMATION;
3791 if (p->pSidGroup)
3792 sec_info |= GROUP_SECURITY_INFORMATION;
3793 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003794 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003795 sec_info |= DACL_SECURITY_INFORMATION;
3796 // Do not inherit its parent's DACL.
3797 // If the DACL is inherited, Cygwin permissions would be changed.
3798 if (!is_acl_inherited(p->pDacl))
3799 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003800 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003801 if (p->pSacl)
3802 sec_info |= SACL_SECURITY_INFORMATION;
3803
3804 (void)SetNamedSecurityInfoW(
3805 wn, // Abstract filename
3806 SE_FILE_OBJECT, // File Object
3807 sec_info,
3808 p->pSidOwner, // Ownership information.
3809 p->pSidGroup, // Group membership.
3810 p->pDacl, // Discretionary information.
3811 p->pSacl // For auditing purposes.
3812 );
3813 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003814#endif
3815}
3816
3817 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003818mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003819{
3820#ifdef HAVE_ACL
3821 struct my_acl *p = (struct my_acl *)acl;
3822
3823 if (p != NULL)
3824 {
3825 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3826 vim_free(p);
3827 }
3828#endif
3829}
3830
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003831#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003832
3833/*
3834 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3835 */
3836 static BOOL WINAPI
3837handler_routine(
3838 DWORD dwCtrlType)
3839{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003840 INPUT_RECORD ir;
3841 DWORD out;
3842
Bram Moolenaar071d4272004-06-13 20:20:40 +00003843 switch (dwCtrlType)
3844 {
3845 case CTRL_C_EVENT:
3846 if (ctrl_c_interrupts)
3847 g_fCtrlCPressed = TRUE;
3848 return TRUE;
3849
3850 case CTRL_BREAK_EVENT:
3851 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003852 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003853 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02003854 ir.EventType = KEY_EVENT;
3855 ir.Event.KeyEvent.bKeyDown = TRUE;
3856 ir.Event.KeyEvent.wRepeatCount = 1;
3857 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3858 ir.Event.KeyEvent.wVirtualScanCode = 0;
3859 ir.Event.KeyEvent.dwControlKeyState = 0;
3860 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3861 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003862 return TRUE;
3863
Bram Moolenaar0f873732019-12-05 20:28:46 +01003864 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00003865 case CTRL_CLOSE_EVENT:
3866 case CTRL_LOGOFF_EVENT:
3867 case CTRL_SHUTDOWN_EVENT:
3868 windgoto((int)Rows - 1, 0);
3869 g_fForceExit = TRUE;
3870
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003871 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003872 (dwCtrlType == CTRL_CLOSE_EVENT
3873 ? _("close")
3874 : dwCtrlType == CTRL_LOGOFF_EVENT
3875 ? _("logoff")
3876 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003877# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00003878 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003879# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003880
Bram Moolenaar0f873732019-12-05 20:28:46 +01003881 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00003882
Bram Moolenaar0f873732019-12-05 20:28:46 +01003883 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00003884
3885 default:
3886 return FALSE;
3887 }
3888}
3889
3890
3891/*
3892 * set the tty in (raw) ? "raw" : "cooked" mode
3893 */
3894 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02003895mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003896{
3897 DWORD cmodein;
3898 DWORD cmodeout;
3899 BOOL bEnableHandler;
3900
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003901# ifdef VIMDLL
3902 if (gui.in_use)
3903 return;
3904# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003905 GetConsoleMode(g_hConIn, &cmodein);
3906 GetConsoleMode(g_hConOut, &cmodeout);
3907 if (tmode == TMODE_RAW)
3908 {
3909 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3910 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003911 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003912 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003913 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003914 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
3915 }
3916 else
3917 {
3918 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
3919 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003920 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003921# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01003922 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
3923 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003924 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003925# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003926 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003927# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003928 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003929 bEnableHandler = TRUE;
3930 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01003931 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00003932 {
3933 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3934 ENABLE_ECHO_INPUT);
3935 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3936 bEnableHandler = FALSE;
3937 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003938 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003939 SetConsoleMode(g_hConOut, cmodeout);
3940 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3941
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003942# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003943 if (fdDump)
3944 {
3945 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3946 tmode == TMODE_RAW ? "raw" :
3947 tmode == TMODE_COOK ? "cooked" : "normal",
3948 cmodein, cmodeout);
3949 fflush(fdDump);
3950 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003951# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003952}
3953
3954
3955/*
3956 * Get the size of the current window in `Rows' and `Columns'
3957 * Return OK when size could be determined, FAIL otherwise.
3958 */
3959 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003960mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003961{
3962 CONSOLE_SCREEN_BUFFER_INFO csbi;
3963
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003964# ifdef VIMDLL
3965 if (gui.in_use)
3966 return OK;
3967# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003968 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3969 {
3970 /*
3971 * For some reason, we are trying to get the screen dimensions
3972 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3973 * variables are really intended to mean the size of Vim screen
3974 * while in termcap mode.
3975 */
3976 Rows = g_cbTermcap.Info.dwSize.Y;
3977 Columns = g_cbTermcap.Info.dwSize.X;
3978 }
3979 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3980 {
3981 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3982 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3983 }
3984 else
3985 {
3986 Rows = 25;
3987 Columns = 80;
3988 }
3989 return OK;
3990}
3991
3992/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003993 * Resize console buffer to 'COORD'
3994 */
3995 static void
3996ResizeConBuf(
3997 HANDLE hConsole,
3998 COORD coordScreen)
3999{
4000 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4001 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004002# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004003 if (fdDump)
4004 {
4005 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4006 GetLastError());
4007 fflush(fdDump);
4008 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004009# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004010 }
4011}
4012
4013/*
4014 * Resize console window size to 'srWindowRect'
4015 */
4016 static void
4017ResizeWindow(
4018 HANDLE hConsole,
4019 SMALL_RECT srWindowRect)
4020{
4021 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4022 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004023# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004024 if (fdDump)
4025 {
4026 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4027 GetLastError());
4028 fflush(fdDump);
4029 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004030# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004031 }
4032}
4033
4034/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004035 * Set a console window to `xSize' * `ySize'
4036 */
4037 static void
4038ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004039 HANDLE hConsole,
4040 int xSize,
4041 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004042{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004043 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
4044 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004045 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004046 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004047 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004048
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004049# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004050 if (fdDump)
4051 {
4052 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4053 fflush(fdDump);
4054 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004055# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004056
Bram Moolenaar0f873732019-12-05 20:28:46 +01004057 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00004058 coordScreen = GetLargestConsoleWindowSize(hConsole);
4059
Bram Moolenaar0f873732019-12-05 20:28:46 +01004060 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00004061 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4062 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4063 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4064
4065 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4066 {
4067 int sx, sy;
4068
4069 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4070 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4071 if (sy < ySize || sx < xSize)
4072 {
4073 /*
4074 * Increasing number of lines/columns, do buffer first.
4075 * Use the maximal size in x and y direction.
4076 */
4077 if (sy < ySize)
4078 coordScreen.Y = ySize;
4079 else
4080 coordScreen.Y = sy;
4081 if (sx < xSize)
4082 coordScreen.X = xSize;
4083 else
4084 coordScreen.X = sx;
4085 SetConsoleScreenBufferSize(hConsole, coordScreen);
4086 }
4087 }
4088
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004089 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004090 coordScreen.X = xSize;
4091 coordScreen.Y = ySize;
4092
Bram Moolenaar2551c032018-08-23 22:38:31 +02004093 // In the new console call API, only the first time in reverse order
4094 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004095 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004096 ResizeWindow(hConsole, srWindowRect);
4097 ResizeConBuf(hConsole, coordScreen);
4098 }
4099 else
4100 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004101 // Workaround for a Windows 10 bug
4102 cursor.X = srWindowRect.Left;
4103 cursor.Y = srWindowRect.Top;
4104 SetConsoleCursorPosition(hConsole, cursor);
4105
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004106 ResizeConBuf(hConsole, coordScreen);
4107 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004108 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004109 }
4110}
4111
4112
4113/*
4114 * Set the console window to `Rows' * `Columns'
4115 */
4116 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004117mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004118{
4119 COORD coordScreen;
4120
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004121# ifdef VIMDLL
4122 if (gui.in_use)
4123 return;
4124# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004125 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004126 if (suppress_winsize != 0)
4127 {
4128 suppress_winsize = 2;
4129 return;
4130 }
4131
4132 if (term_console)
4133 {
4134 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4135
Bram Moolenaar0f873732019-12-05 20:28:46 +01004136 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004137 if (Rows > coordScreen.Y)
4138 Rows = coordScreen.Y;
4139 if (Columns > coordScreen.X)
4140 Columns = coordScreen.X;
4141
4142 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4143 }
4144}
4145
4146/*
4147 * Rows and/or Columns has changed.
4148 */
4149 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004150mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004151{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004152# ifdef VIMDLL
4153 if (gui.in_use)
4154 return;
4155# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004156 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4157}
4158
4159
4160/*
4161 * Called when started up, to set the winsize that was delayed.
4162 */
4163 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004164mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004165{
4166 if (suppress_winsize == 2)
4167 {
4168 suppress_winsize = 0;
4169 mch_set_shellsize();
4170 shell_resized();
4171 }
4172 suppress_winsize = 0;
4173}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004174#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004175
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004176 static BOOL
4177vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004178 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004179 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004180 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004181 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004182 PROCESS_INFORMATION *pi,
4183 LPVOID *env,
4184 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004185{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004186 BOOL ret = FALSE;
4187 WCHAR *wcmd, *wcwd = NULL;
4188
4189 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4190 if (wcmd == NULL)
4191 return FALSE;
4192 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004193 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004194 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4195 if (wcwd == NULL)
4196 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004197 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004198
4199 ret = CreateProcessW(
4200 NULL, // Executable name
4201 wcmd, // Command to execute
4202 NULL, // Process security attributes
4203 NULL, // Thread security attributes
4204 inherit_handles, // Inherit handles
4205 flags, // Creation flags
4206 env, // Environment
4207 wcwd, // Current directory
4208 (LPSTARTUPINFOW)si, // Startup information
4209 pi); // Process information
4210theend:
4211 vim_free(wcmd);
4212 vim_free(wcwd);
4213 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004214}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004215
4216
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004217 static HINSTANCE
4218vim_shell_execute(
4219 char *cmd,
4220 INT n_show_cmd)
4221{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004222 HINSTANCE ret;
4223 WCHAR *wcmd;
4224
4225 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4226 if (wcmd == NULL)
4227 return (HINSTANCE) 0;
4228
4229 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4230 vim_free(wcmd);
4231 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004232}
4233
4234
Bram Moolenaar4f974752019-02-17 17:44:42 +01004235#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004236
4237/*
4238 * Specialised version of system() for Win32 GUI mode.
4239 * This version proceeds as follows:
4240 * 1. Create a console window for use by the subprocess
4241 * 2. Run the subprocess (it gets the allocated console by default)
4242 * 3. Wait for the subprocess to terminate and get its exit code
4243 * 4. Prompt the user to press a key to close the console window
4244 */
4245 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004246mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004247{
4248 STARTUPINFO si;
4249 PROCESS_INFORMATION pi;
4250 DWORD ret = 0;
4251 HWND hwnd = GetFocus();
4252
4253 si.cb = sizeof(si);
4254 si.lpReserved = NULL;
4255 si.lpDesktop = NULL;
4256 si.lpTitle = NULL;
4257 si.dwFlags = STARTF_USESHOWWINDOW;
4258 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004259 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004260 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004261 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004262 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004263 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004264 else
4265 si.wShowWindow = SW_SHOWNORMAL;
4266 si.cbReserved2 = 0;
4267 si.lpReserved2 = NULL;
4268
Bram Moolenaar0f873732019-12-05 20:28:46 +01004269 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004270 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004271 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4272 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004273
Bram Moolenaar0f873732019-12-05 20:28:46 +01004274 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004275 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004276# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004277 int delay = 1;
4278
Bram Moolenaar0f873732019-12-05 20:28:46 +01004279 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004280 for (;;)
4281 {
4282 MSG msg;
4283
K.Takatab7057bd2022-01-21 11:37:07 +00004284 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004285 {
4286 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004287 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004288 delay = 1;
4289 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004290 }
4291 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4292 break;
4293
Bram Moolenaar0f873732019-12-05 20:28:46 +01004294 // We start waiting for a very short time and then increase it, so
4295 // that we respond quickly when the process is quick, and don't
4296 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004297 if (delay < 50)
4298 delay += 10;
4299 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004300# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004301 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004302# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004303
Bram Moolenaar0f873732019-12-05 20:28:46 +01004304 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004305 GetExitCodeProcess(pi.hProcess, &ret);
4306 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004307
Bram Moolenaar0f873732019-12-05 20:28:46 +01004308 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004309 CloseHandle(pi.hThread);
4310 CloseHandle(pi.hProcess);
4311
Bram Moolenaar0f873732019-12-05 20:28:46 +01004312 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004313 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4314
4315 return ret;
4316}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004317
4318/*
4319 * Thread launched by the gui to send the current buffer data to the
4320 * process. This way avoid to hang up vim totally if the children
4321 * process take a long time to process the lines.
4322 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004323 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004324sub_process_writer(LPVOID param)
4325{
4326 HANDLE g_hChildStd_IN_Wr = param;
4327 linenr_T lnum = curbuf->b_op_start.lnum;
4328 DWORD len = 0;
4329 DWORD l;
4330 char_u *lp = ml_get(lnum);
4331 char_u *s;
4332 int written = 0;
4333
4334 for (;;)
4335 {
4336 l = (DWORD)STRLEN(lp + written);
4337 if (l == 0)
4338 len = 0;
4339 else if (lp[written] == NL)
4340 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004341 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004342 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4343 }
4344 else
4345 {
4346 s = vim_strchr(lp + written, NL);
4347 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4348 s == NULL ? l : (DWORD)(s - (lp + written)),
4349 &len, NULL);
4350 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004351 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004352 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004353 // Finished a line, add a NL, unless this line should not have
4354 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004355 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004356 || (!curbuf->b_p_bin
4357 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004358 || (lnum != curbuf->b_no_eol_lnum
4359 && (lnum != curbuf->b_ml.ml_line_count
4360 || curbuf->b_p_eol)))
4361 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004362 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4363 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004364 }
4365
4366 ++lnum;
4367 if (lnum > curbuf->b_op_end.lnum)
4368 break;
4369
4370 lp = ml_get(lnum);
4371 written = 0;
4372 }
4373 else if (len > 0)
4374 written += len;
4375 }
4376
Bram Moolenaar0f873732019-12-05 20:28:46 +01004377 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004378 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004379 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004380}
4381
4382
Bram Moolenaar0f873732019-12-05 20:28:46 +01004383# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004384
4385/*
4386 * This function read from the children's stdout and write the
4387 * data on screen or in the buffer accordingly.
4388 */
4389 static void
4390dump_pipe(int options,
4391 HANDLE g_hChildStd_OUT_Rd,
4392 garray_T *ga,
4393 char_u buffer[],
4394 DWORD *buffer_off)
4395{
4396 DWORD availableBytes = 0;
4397 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004398 int ret;
4399 DWORD len;
4400 DWORD toRead;
4401 int repeatCount;
4402
Bram Moolenaar0f873732019-12-05 20:28:46 +01004403 // we query the pipe to see if there is any data to read
4404 // to avoid to perform a blocking read
4405 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4406 NULL, // optional buffer
4407 0, // buffer size
4408 NULL, // number of read bytes
4409 &availableBytes, // available bytes total
4410 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004411
4412 repeatCount = 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004413 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004414 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004415 {
4416 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004417 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004418 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004419 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004420
Bram Moolenaar0f873732019-12-05 20:28:46 +01004421 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004422 if (len == 0)
4423 break;
4424
4425 availableBytes -= len;
4426
4427 if (options & SHELL_READ)
4428 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004429 // Do NUL -> NL translation, append NL separated
4430 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004431 for (i = 0; i < len; ++i)
4432 {
4433 if (buffer[i] == NL)
4434 append_ga_line(ga);
4435 else if (buffer[i] == NUL)
4436 ga_append(ga, NL);
4437 else
4438 ga_append(ga, buffer[i]);
4439 }
4440 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004441 else if (has_mbyte)
4442 {
4443 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004444 int c;
4445 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004446
4447 len += *buffer_off;
4448 buffer[len] = NUL;
4449
Bram Moolenaar0f873732019-12-05 20:28:46 +01004450 // Check if the last character in buffer[] is
4451 // incomplete, keep these bytes for the next
4452 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004453 for (p = buffer; p < buffer + len; p += l)
4454 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004455 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004456 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004457 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004458 else if (MB_BYTE2LEN(*p) != l)
4459 break;
4460 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004461 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004462 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004463 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004464 if (len >= 12)
4465 ++p;
4466 else
4467 {
4468 *buffer_off = len;
4469 return;
4470 }
4471 }
4472 c = *p;
4473 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004474 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004475 if (p < buffer + len)
4476 {
4477 *p = c;
4478 *buffer_off = (DWORD)((buffer + len) - p);
4479 mch_memmove(buffer, p, *buffer_off);
4480 return;
4481 }
4482 *buffer_off = 0;
4483 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004484 else
4485 {
4486 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004487 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004488 }
4489
4490 windgoto(msg_row, msg_col);
4491 cursor_on();
4492 out_flush();
4493 }
4494}
4495
4496/*
4497 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4498 * for communication and doesn't open any new window.
4499 */
4500 static int
4501mch_system_piped(char *cmd, int options)
4502{
4503 STARTUPINFO si;
4504 PROCESS_INFORMATION pi;
4505 DWORD ret = 0;
4506
4507 HANDLE g_hChildStd_IN_Rd = NULL;
4508 HANDLE g_hChildStd_IN_Wr = NULL;
4509 HANDLE g_hChildStd_OUT_Rd = NULL;
4510 HANDLE g_hChildStd_OUT_Wr = NULL;
4511
Bram Moolenaar0f873732019-12-05 20:28:46 +01004512 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004513 DWORD len;
4514
Bram Moolenaar0f873732019-12-05 20:28:46 +01004515 // buffer used to receive keys
4516 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4517 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004518
4519 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004520 int noread_cnt = 0;
4521 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004522 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004523 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004524 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004525
4526 SECURITY_ATTRIBUTES saAttr;
4527
Bram Moolenaar0f873732019-12-05 20:28:46 +01004528 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004529 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4530 saAttr.bInheritHandle = TRUE;
4531 saAttr.lpSecurityDescriptor = NULL;
4532
4533 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004534 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004535 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004536 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004537 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004538 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004539 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004540 {
4541 CloseHandle(g_hChildStd_IN_Rd);
4542 CloseHandle(g_hChildStd_IN_Wr);
4543 CloseHandle(g_hChildStd_OUT_Rd);
4544 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004545 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004546 }
4547
4548 si.cb = sizeof(si);
4549 si.lpReserved = NULL;
4550 si.lpDesktop = NULL;
4551 si.lpTitle = NULL;
4552 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4553
Bram Moolenaar0f873732019-12-05 20:28:46 +01004554 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004555 si.hStdError = g_hChildStd_OUT_Wr;
4556 si.hStdOutput = g_hChildStd_OUT_Wr;
4557 si.hStdInput = g_hChildStd_IN_Rd;
4558 si.wShowWindow = SW_HIDE;
4559 si.cbReserved2 = 0;
4560 si.lpReserved2 = NULL;
4561
4562 if (options & SHELL_READ)
4563 ga_init2(&ga, 1, BUFLEN);
4564
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004565 if (cmd != NULL)
4566 {
4567 p = (char *)vim_strsave((char_u *)cmd);
4568 if (p != NULL)
4569 unescape_shellxquote((char_u *)p, p_sxe);
4570 else
4571 p = cmd;
4572 }
4573
Bram Moolenaar0f873732019-12-05 20:28:46 +01004574 // Now, run the command.
4575 // About "Inherit handles" being TRUE: this command can be litigious,
4576 // handle inheritance was deactivated for pending temp file, but, if we
4577 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004578 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4579 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004580
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004581 if (p != cmd)
4582 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004583
Bram Moolenaar0f873732019-12-05 20:28:46 +01004584 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004585 CloseHandle(g_hChildStd_IN_Rd);
4586 CloseHandle(g_hChildStd_OUT_Wr);
4587
4588 if (options & SHELL_WRITE)
4589 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004590 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004591 _beginthreadex(NULL, // security attributes
4592 0, // default stack size
4593 sub_process_writer, // function to be executed
4594 g_hChildStd_IN_Wr, // parameter
4595 0, // creation flag, start immediately
4596 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004597 CloseHandle(thread);
4598 g_hChildStd_IN_Wr = NULL;
4599 }
4600
Bram Moolenaar0f873732019-12-05 20:28:46 +01004601 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004602 for (;;)
4603 {
4604 MSG msg;
4605
K.Takatab7057bd2022-01-21 11:37:07 +00004606 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004607 {
4608 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004609 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004610 }
4611
Bram Moolenaar0f873732019-12-05 20:28:46 +01004612 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004613 if ((options & (SHELL_READ|SHELL_WRITE))
4614# ifdef FEAT_GUI
4615 || gui.in_use
4616# endif
4617 )
4618 {
4619 len = 0;
4620 if (!(options & SHELL_EXPAND)
4621 && ((options &
4622 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4623 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4624# ifdef FEAT_GUI
4625 || gui.in_use
4626# endif
4627 )
4628 && (ta_len > 0 || noread_cnt > 4))
4629 {
4630 if (ta_len == 0)
4631 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004632 // Get extra characters when we don't have any. Reset the
4633 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004634 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004635 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4636 }
4637 if (ta_len > 0 || len > 0)
4638 {
4639 /*
4640 * For pipes: Check for CTRL-C: send interrupt signal to
4641 * child. Check for CTRL-D: EOF, close pipe to child.
4642 */
4643 if (len == 1 && cmd != NULL)
4644 {
4645 if (ta_buf[ta_len] == Ctrl_C)
4646 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004647 // Learn what exit code is expected, for
4648 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004649 TerminateProcess(pi.hProcess, 9);
4650 }
4651 if (ta_buf[ta_len] == Ctrl_D)
4652 {
4653 CloseHandle(g_hChildStd_IN_Wr);
4654 g_hChildStd_IN_Wr = NULL;
4655 }
4656 }
4657
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01004658 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004659
4660 /*
4661 * For pipes: echo the typed characters. For a pty this
4662 * does not seem to work.
4663 */
4664 for (i = ta_len; i < ta_len + len; ++i)
4665 {
4666 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4667 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004668 else if (has_mbyte)
4669 {
4670 int l = (*mb_ptr2len)(ta_buf + i);
4671
4672 msg_outtrans_len(ta_buf + i, l);
4673 i += l - 1;
4674 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004675 else
4676 msg_outtrans_len(ta_buf + i, 1);
4677 }
4678 windgoto(msg_row, msg_col);
4679 out_flush();
4680
4681 ta_len += len;
4682
4683 /*
4684 * Write the characters to the child, unless EOF has been
4685 * typed for pipes. Write one character at a time, to
4686 * avoid losing too much typeahead. When writing buffer
4687 * lines, drop the typed characters (only check for
4688 * CTRL-C).
4689 */
4690 if (options & SHELL_WRITE)
4691 ta_len = 0;
4692 else if (g_hChildStd_IN_Wr != NULL)
4693 {
4694 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4695 1, &len, NULL);
4696 // if we are typing in, we want to keep things reactive
4697 delay = 1;
4698 if (len > 0)
4699 {
4700 ta_len -= len;
4701 mch_memmove(ta_buf, ta_buf + len, ta_len);
4702 }
4703 }
4704 }
4705 }
4706 }
4707
4708 if (ta_len)
4709 ui_inchar_undo(ta_buf, ta_len);
4710
4711 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4712 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004713 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004714 break;
4715 }
4716
4717 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004718 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004719
Bram Moolenaar0f873732019-12-05 20:28:46 +01004720 // We start waiting for a very short time and then increase it, so
4721 // that we respond quickly when the process is quick, and don't
4722 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004723 if (delay < 50)
4724 delay += 10;
4725 }
4726
Bram Moolenaar0f873732019-12-05 20:28:46 +01004727 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004728 CloseHandle(g_hChildStd_OUT_Rd);
4729 if (g_hChildStd_IN_Wr != NULL)
4730 CloseHandle(g_hChildStd_IN_Wr);
4731
4732 WaitForSingleObject(pi.hProcess, INFINITE);
4733
Bram Moolenaar0f873732019-12-05 20:28:46 +01004734 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004735 GetExitCodeProcess(pi.hProcess, &ret);
4736
4737 if (options & SHELL_READ)
4738 {
4739 if (ga.ga_len > 0)
4740 {
4741 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01004742 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004743 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4744 }
4745 else
4746 curbuf->b_no_eol_lnum = 0;
4747 ga_clear(&ga);
4748 }
4749
Bram Moolenaar0f873732019-12-05 20:28:46 +01004750 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004751 CloseHandle(pi.hThread);
4752 CloseHandle(pi.hProcess);
4753
4754 return ret;
4755}
4756
4757 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004758mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004759{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004760 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004761 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004762 return mch_system_piped(cmd, options);
4763 else
4764 return mch_system_classic(cmd, options);
4765}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004766#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004767
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004768#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004769 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02004770mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004771{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004772 int ret;
4773 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004774 char_u *buf;
4775 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004776
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004777 // If the command starts and ends with double quotes, enclose the command
4778 // in parentheses.
4779 len = STRLEN(cmd);
4780 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
4781 {
4782 len += 3;
4783 buf = alloc(len);
4784 if (buf == NULL)
4785 return -1;
4786 vim_snprintf((char *)buf, len, "(%s)", cmd);
4787 wcmd = enc_to_utf16(buf, NULL);
4788 free(buf);
4789 }
4790 else
4791 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4792
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004793 if (wcmd == NULL)
4794 return -1;
4795
4796 ret = _wsystem(wcmd);
4797 vim_free(wcmd);
4798 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004799}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004800
4801#endif
4802
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004803 static int
4804mch_system(char *cmd, int options)
4805{
4806#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004807 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004808 return mch_system_g(cmd, options);
4809 else
4810 return mch_system_c(cmd, options);
4811#elif defined(FEAT_GUI_MSWIN)
4812 return mch_system_g(cmd, options);
4813#else
4814 return mch_system_c(cmd, options);
4815#endif
4816}
4817
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004818#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4819/*
4820 * Use a terminal window to run a shell command in.
4821 */
4822 static int
4823mch_call_shell_terminal(
4824 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004825 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004826{
4827 jobopt_T opt;
4828 char_u *newcmd = NULL;
4829 typval_T argvar[2];
4830 long_u cmdlen;
4831 int retval = -1;
4832 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004833 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004834 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004835 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004836
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004837 if (cmd == NULL)
4838 cmdlen = STRLEN(p_sh) + 1;
4839 else
4840 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004841 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004842 if (newcmd == NULL)
4843 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004844 if (cmd == NULL)
4845 {
4846 STRCPY(newcmd, p_sh);
4847 ch_log(NULL, "starting terminal to run a shell");
4848 }
4849 else
4850 {
4851 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4852 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4853 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004854
4855 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004856
4857 argvar[0].v_type = VAR_STRING;
4858 argvar[0].vval.v_string = newcmd;
4859 argvar[1].v_type = VAR_UNKNOWN;
4860 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004861 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004862 {
4863 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004864 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004865 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004866
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004867 job = term_getjob(buf->b_term);
4868 ++job->jv_refcount;
4869
Bram Moolenaar0f873732019-12-05 20:28:46 +01004870 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004871 aucmd_prepbuf(&aco, buf);
4872
4873 clear_oparg(&oa);
4874 while (term_use_loop())
4875 {
4876 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4877 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004878 // If terminal_loop() returns OK we got a key that is handled
4879 // in Normal model. We don't do redrawing anyway.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004880 if (terminal_loop(TRUE) == OK)
4881 normal_cmd(&oa, TRUE);
4882 }
4883 else
4884 normal_cmd(&oa, TRUE);
4885 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004886 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004887 ch_log(NULL, "system command finished");
4888
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004889 job_unref(job);
4890
Bram Moolenaar0f873732019-12-05 20:28:46 +01004891 // restore curwin/curbuf and a few other things
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004892 aucmd_restbuf(&aco);
4893
4894 wait_return(TRUE);
4895 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4896
4897 vim_free(newcmd);
4898 return retval;
4899}
4900#endif
4901
Bram Moolenaar071d4272004-06-13 20:20:40 +00004902/*
4903 * Either execute a command by calling the shell or start a new shell
4904 */
4905 int
4906mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004907 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004908 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00004909{
4910 int x = 0;
4911 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004912 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004913
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01004914#ifdef FEAT_JOB_CHANNEL
4915 ch_log(NULL, "executing shell command: %s", cmd);
4916#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004917 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02004918 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004919 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004920 if (cmd == NULL)
4921 wcscat(szShellTitle, L" :sh");
4922 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004923 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004924 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004925
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004926 if (wn != NULL)
4927 {
4928 wcscat(szShellTitle, L" - !");
4929 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02004930 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004931 wcscat(szShellTitle, wn);
4932 SetConsoleTitleW(szShellTitle);
4933 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004934 }
4935 }
4936 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004937
4938 out_flush();
4939
4940#ifdef MCH_WRITE_DUMP
4941 if (fdDump)
4942 {
4943 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4944 fflush(fdDump);
4945 }
4946#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004947#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004948 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004949 if (
4950# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004951 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004952# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004953 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004954 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4955 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004956 char_u *cmdbase = cmd;
4957
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004958 if (cmdbase != NULL)
4959 // Skip a leading quote and (.
4960 while (*cmdbase == '"' || *cmdbase == '(')
4961 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004962
4963 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01004964 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
4965 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004966 {
4967 // Use a terminal window to run the command in.
4968 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004969 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004970 return x;
4971 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004972 }
4973#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004974
4975 /*
4976 * Catch all deadly signals while running the external command, because a
4977 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4978 */
4979 signal(SIGINT, SIG_IGN);
4980#if defined(__GNUC__) && !defined(__MINGW32__)
4981 signal(SIGKILL, SIG_IGN);
4982#else
4983 signal(SIGBREAK, SIG_IGN);
4984#endif
4985 signal(SIGILL, SIG_IGN);
4986 signal(SIGFPE, SIG_IGN);
4987 signal(SIGSEGV, SIG_IGN);
4988 signal(SIGTERM, SIG_IGN);
4989 signal(SIGABRT, SIG_IGN);
4990
4991 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004992 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00004993
4994 if (cmd == NULL)
4995 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004996 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004997 }
4998 else
4999 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005000 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005001 char_u *newcmd = NULL;
5002 char_u *cmdbase = cmd;
5003 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005004
Bram Moolenaar0f873732019-12-05 20:28:46 +01005005 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005006 if (*cmdbase == '"' )
5007 ++cmdbase;
5008 if (*cmdbase == '(')
5009 ++cmdbase;
5010
Bram Moolenaar1c465442017-03-12 20:10:05 +01005011 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005012 {
5013 STARTUPINFO si;
5014 PROCESS_INFORMATION pi;
5015 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005016 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005017 char_u *p;
5018
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005019 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005020 si.cb = sizeof(si);
5021 si.lpReserved = NULL;
5022 si.lpDesktop = NULL;
5023 si.lpTitle = NULL;
5024 si.dwFlags = 0;
5025 si.cbReserved2 = 0;
5026 si.lpReserved2 = NULL;
5027
5028 cmdbase = skipwhite(cmdbase + 5);
5029 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005030 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005031 {
5032 cmdbase = skipwhite(cmdbase + 4);
5033 si.dwFlags = STARTF_USESHOWWINDOW;
5034 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005035 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005036 }
5037 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005038 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005039 {
5040 cmdbase = skipwhite(cmdbase + 2);
5041 flags = CREATE_NO_WINDOW;
5042 si.dwFlags = STARTF_USESTDHANDLES;
5043 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005044 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005045 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005046 NULL, // Security att.
5047 OPEN_EXISTING, // Open flags
5048 FILE_ATTRIBUTE_NORMAL, // File att.
5049 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005050 si.hStdOutput = si.hStdInput;
5051 si.hStdError = si.hStdInput;
5052 }
5053
Bram Moolenaar0f873732019-12-05 20:28:46 +01005054 // Remove a trailing ", ) and )" if they have a match
5055 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005056 if (cmdbase > cmd)
5057 {
5058 p = cmdbase + STRLEN(cmdbase);
5059 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5060 *--p = NUL;
5061 if (p > cmdbase && p[-1] == ')'
5062 && (*cmd =='(' || cmd[1] == '('))
5063 *--p = NUL;
5064 }
5065
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005066 newcmd = cmdbase;
5067 unescape_shellxquote(cmdbase, p_sxe);
5068
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005069 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005070 * If creating new console, arguments are passed to the
5071 * 'cmd.exe' as-is. If it's not, arguments are not treated
5072 * correctly for current 'cmd.exe'. So unescape characters in
5073 * shellxescape except '|' for avoiding to be treated as
5074 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005075 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005076 if (flags != CREATE_NEW_CONSOLE)
5077 {
5078 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005079 char_u *cmd_shell = mch_getenv("COMSPEC");
5080
5081 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005082 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005083
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005084 subcmd = vim_strsave_escaped_ext(cmdbase,
5085 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005086 if (subcmd != NULL)
5087 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005088 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005089 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005090 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005091 if (newcmd != NULL)
5092 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005093 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005094 else
5095 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005096 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005097 }
5098 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005099
5100 /*
5101 * Now, start the command as a process, so that it doesn't
5102 * inherit our handles which causes unpleasant dangling swap
5103 * files if we exit before the spawned process
5104 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005105 if (vim_create_process((char *)newcmd, FALSE, flags,
5106 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005107 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005108 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5109 > (HINSTANCE)32)
5110 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005111 else
5112 {
5113 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005114#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005115# ifdef VIMDLL
5116 if (gui.in_use)
5117# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005118 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005119#endif
5120 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005121
5122 if (newcmd != cmdbase)
5123 vim_free(newcmd);
5124
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005125 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005126 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005127 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005128 CloseHandle(si.hStdInput);
5129 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005130 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005131 CloseHandle(pi.hThread);
5132 CloseHandle(pi.hProcess);
5133 }
5134 else
5135 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005136 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005137#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005138 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005139 (!s_dont_use_vimrun && p_stmp ?
5140 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5141 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005142#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005143 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005144
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005145 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005146 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005147 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005148#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005149 if (
5150# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005151 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005152# endif
5153 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005154 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005155 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5156 "External commands will not pause after completion.\n"
5157 "See :help win32-vimrun for more information.");
5158 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005159 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5160 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005161
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005162 if (wmsg != NULL && wtitle != NULL)
5163 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5164 vim_free(wmsg);
5165 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005166 need_vimrun_warning = FALSE;
5167 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005168 if (
5169# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005170 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005171# endif
5172 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005173 // Use vimrun to execute the command. It opens a console
5174 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005175 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005176 vimrun_path,
5177 (msg_silent != 0 || (options & SHELL_DOOUT))
5178 ? "-s " : "",
5179 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005180 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005181# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005182 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005183# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005184 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005185 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005186 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5187 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005188 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005189#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005190 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005191 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005192 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005193 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005194 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005195 }
5196 }
5197
5198 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005199 {
5200 // The shell may have messed with the mode, always set it.
5201 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005202 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005203 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005204
Bram Moolenaar0f873732019-12-05 20:28:46 +01005205 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005206 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005207#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005208 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005209 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005210#endif
5211 )
5212 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005213 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005214 msg_putchar('\n');
5215 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005216 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005217
5218 signal(SIGINT, SIG_DFL);
5219#if defined(__GNUC__) && !defined(__MINGW32__)
5220 signal(SIGKILL, SIG_DFL);
5221#else
5222 signal(SIGBREAK, SIG_DFL);
5223#endif
5224 signal(SIGILL, SIG_DFL);
5225 signal(SIGFPE, SIG_DFL);
5226 signal(SIGSEGV, SIG_DFL);
5227 signal(SIGTERM, SIG_DFL);
5228 signal(SIGABRT, SIG_DFL);
5229
5230 return x;
5231}
5232
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005233#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005234 static HANDLE
5235job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005236 char_u *fname,
5237 DWORD dwDesiredAccess,
5238 DWORD dwShareMode,
5239 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5240 DWORD dwCreationDisposition,
5241 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005242{
5243 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005244 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005245
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005246 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005247 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005248 return INVALID_HANDLE_VALUE;
5249
5250 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5251 lpSecurityAttributes, dwCreationDisposition,
5252 dwFlagsAndAttributes, NULL);
5253 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005254 return h;
5255}
5256
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005257/*
5258 * Turn the dictionary "env" into a NUL separated list that can be used as the
5259 * environment argument of vim_create_process().
5260 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005261 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005262win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005263{
5264 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005265 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005266 LPVOID base = GetEnvironmentStringsW();
5267
Bram Moolenaar0f873732019-12-05 20:28:46 +01005268 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005269 if (ga_grow(gap, 1) == FAIL)
5270 return;
5271
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005272 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005273 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005274 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005275 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005276 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005277 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005278 typval_T *item = &dict_lookup(hi)->di_tv;
5279 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005280 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005281 --todo;
5282 if (wkey != NULL && wval != NULL)
5283 {
5284 size_t n;
5285 size_t lkey = wcslen(wkey);
5286 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005287
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005288 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5289 continue;
5290 for (n = 0; n < lkey; n++)
5291 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5292 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5293 for (n = 0; n < lval; n++)
5294 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5295 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5296 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005297 vim_free(wkey);
5298 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005299 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005300 }
5301 }
5302
Bram Moolenaar355757a2020-02-10 22:06:32 +01005303 if (base)
5304 {
5305 WCHAR *p = (WCHAR*) base;
5306
5307 // for last \0
5308 if (ga_grow(gap, 1) == FAIL)
5309 return;
5310
5311 while (*p != 0 || *(p + 1) != 0)
5312 {
5313 if (ga_grow(gap, 1) == OK)
5314 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5315 p++;
5316 }
5317 FreeEnvironmentStrings(base);
5318 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5319 }
5320
Bram Moolenaar493359e2018-06-12 20:25:52 +02005321# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005322 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005323# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005324 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005325 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005326# endif
5327# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005328 char_u *version = get_vim_var_str(VV_VERSION);
5329 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005330# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005331 // size of "VIM_SERVERNAME=" and value,
5332 // plus "VIM_TERMINAL=" and value,
5333 // plus two terminating NULs
5334 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005335# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005336 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005337# endif
5338# ifdef FEAT_TERMINAL
5339 + 13 + version_len + 2
5340# endif
5341 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005342
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005343 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005344 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005345# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005346 for (n = 0; n < 15; n++)
5347 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5348 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005349 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005350 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5351 (WCHAR)servername[n];
5352 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005353# endif
5354# ifdef FEAT_TERMINAL
5355 if (is_terminal)
5356 {
5357 for (n = 0; n < 13; n++)
5358 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5359 (WCHAR)"VIM_TERMINAL="[n];
5360 for (n = 0; n < version_len; n++)
5361 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5362 (WCHAR)version[n];
5363 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5364 }
5365# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005366 }
5367 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005368# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005369}
5370
Bram Moolenaarb091f302019-01-19 14:37:00 +01005371/*
5372 * Create a pair of pipes.
5373 * Return TRUE for success, FALSE for failure.
5374 */
5375 static BOOL
5376create_pipe_pair(HANDLE handles[2])
5377{
5378 static LONG s;
5379 char name[64];
5380 SECURITY_ATTRIBUTES sa;
5381
5382 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5383 GetCurrentProcessId(),
5384 InterlockedIncrement(&s));
5385
5386 // Create named pipe. Max size of named pipe is 65535.
5387 handles[1] = CreateNamedPipe(
5388 name,
5389 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5390 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005391 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005392
5393 if (handles[1] == INVALID_HANDLE_VALUE)
5394 return FALSE;
5395
5396 sa.nLength = sizeof(sa);
5397 sa.bInheritHandle = TRUE;
5398 sa.lpSecurityDescriptor = NULL;
5399
5400 handles[0] = CreateFile(name,
5401 FILE_GENERIC_READ,
5402 FILE_SHARE_READ, &sa,
5403 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5404
5405 if (handles[0] == INVALID_HANDLE_VALUE)
5406 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005407 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005408 return FALSE;
5409 }
5410
5411 return TRUE;
5412}
5413
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005414 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005415mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005416{
5417 STARTUPINFO si;
5418 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005419 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005420 SECURITY_ATTRIBUTES saAttr;
5421 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005422 HANDLE ifd[2];
5423 HANDLE ofd[2];
5424 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005425 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005426
5427 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5428 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5429 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5430 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5431 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5432 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5433 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5434
5435 if (use_out_for_err && use_null_for_out)
5436 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005437
5438 ifd[0] = INVALID_HANDLE_VALUE;
5439 ifd[1] = INVALID_HANDLE_VALUE;
5440 ofd[0] = INVALID_HANDLE_VALUE;
5441 ofd[1] = INVALID_HANDLE_VALUE;
5442 efd[0] = INVALID_HANDLE_VALUE;
5443 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005444 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005445
Bram Moolenaar14207f42016-10-27 21:13:10 +02005446 jo = CreateJobObject(NULL, NULL);
5447 if (jo == NULL)
5448 {
5449 job->jv_status = JOB_FAILED;
5450 goto failed;
5451 }
5452
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005453 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005454 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005455
Bram Moolenaar76467df2016-02-12 19:30:26 +01005456 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005457 ZeroMemory(&si, sizeof(si));
5458 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005459 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005460 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005461
Bram Moolenaard8070362016-02-15 21:56:54 +01005462 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5463 saAttr.bInheritHandle = TRUE;
5464 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005465
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005466 if (use_file_for_in)
5467 {
5468 char_u *fname = options->jo_io_name[PART_IN];
5469
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005470 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5471 FILE_SHARE_READ | FILE_SHARE_WRITE,
5472 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5473 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005474 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005475 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005476 goto failed;
5477 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005478 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005479 else if (!use_null_for_in
5480 && (!create_pipe_pair(ifd)
5481 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005482 goto failed;
5483
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005484 if (use_file_for_out)
5485 {
5486 char_u *fname = options->jo_io_name[PART_OUT];
5487
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005488 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5489 FILE_SHARE_READ | FILE_SHARE_WRITE,
5490 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5491 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005492 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005493 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005494 goto failed;
5495 }
5496 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005497 else if (!use_null_for_out &&
5498 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005499 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005500 goto failed;
5501
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005502 if (use_file_for_err)
5503 {
5504 char_u *fname = options->jo_io_name[PART_ERR];
5505
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005506 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5507 FILE_SHARE_READ | FILE_SHARE_WRITE,
5508 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5509 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005510 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005511 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005512 goto failed;
5513 }
5514 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005515 else if (!use_out_for_err && !use_null_for_err &&
5516 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005517 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005518 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005519
Bram Moolenaard8070362016-02-15 21:56:54 +01005520 si.dwFlags |= STARTF_USESTDHANDLES;
5521 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005522 si.hStdOutput = ofd[1];
5523 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5524
5525 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5526 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005527 if (options->jo_set & JO_CHANNEL)
5528 {
5529 channel = options->jo_channel;
5530 if (channel != NULL)
5531 ++channel->ch_refcount;
5532 }
5533 else
5534 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005535 if (channel == NULL)
5536 goto failed;
5537 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005538
5539 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005540 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005541 CREATE_DEFAULT_ERROR_MODE |
5542 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005543 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005544 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005545 &si, &pi,
5546 ga.ga_data,
5547 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005548 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005549 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005550 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005551 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005552 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005553
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005554 ga_clear(&ga);
5555
Bram Moolenaar14207f42016-10-27 21:13:10 +02005556 if (!AssignProcessToJobObject(jo, pi.hProcess))
5557 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005558 // if failing, switch the way to terminate
5559 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005560 CloseHandle(jo);
5561 jo = NULL;
5562 }
5563 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005564 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005565 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005566 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005567 job->jv_status = JOB_STARTED;
5568
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005569 CloseHandle(ifd[0]);
5570 CloseHandle(ofd[1]);
5571 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005572 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005573
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005574 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005575 if (channel != NULL)
5576 {
5577 channel_set_pipes(channel,
5578 use_file_for_in || use_null_for_in
5579 ? INVALID_FD : (sock_T)ifd[1],
5580 use_file_for_out || use_null_for_out
5581 ? INVALID_FD : (sock_T)ofd[0],
5582 use_out_for_err || use_file_for_err || use_null_for_err
5583 ? INVALID_FD : (sock_T)efd[0]);
5584 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005585 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005586 return;
5587
5588failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005589 CloseHandle(ifd[0]);
5590 CloseHandle(ofd[0]);
5591 CloseHandle(efd[0]);
5592 CloseHandle(ifd[1]);
5593 CloseHandle(ofd[1]);
5594 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005595 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005596 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005597}
5598
5599 char *
5600mch_job_status(job_T *job)
5601{
5602 DWORD dwExitCode = 0;
5603
Bram Moolenaar76467df2016-02-12 19:30:26 +01005604 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5605 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005606 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005607 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005608 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005609 {
5610 ch_log(job->jv_channel, "Job ended");
5611 job->jv_status = JOB_ENDED;
5612 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005613 return "dead";
5614 }
5615 return "run";
5616}
5617
Bram Moolenaar97792de2016-10-15 18:36:49 +02005618 job_T *
5619mch_detect_ended_job(job_T *job_list)
5620{
5621 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5622 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5623 job_T *job = job_list;
5624
5625 while (job != NULL)
5626 {
5627 DWORD n;
5628 DWORD result;
5629
5630 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5631 && job != NULL; job = job->jv_next)
5632 {
5633 if (job->jv_status == JOB_STARTED)
5634 {
5635 jobHandles[n] = job->jv_proc_info.hProcess;
5636 jobArray[n] = job;
5637 ++n;
5638 }
5639 }
5640 if (n == 0)
5641 continue;
5642 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5643 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5644 {
5645 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5646
5647 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5648 return wait_job;
5649 }
5650 }
5651 return NULL;
5652}
5653
Bram Moolenaarfb630902016-10-29 14:55:00 +02005654 static BOOL
5655terminate_all(HANDLE process, int code)
5656{
5657 PROCESSENTRY32 pe;
5658 HANDLE h = INVALID_HANDLE_VALUE;
5659 DWORD pid = GetProcessId(process);
5660
5661 if (pid != 0)
5662 {
5663 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5664 if (h != INVALID_HANDLE_VALUE)
5665 {
5666 pe.dwSize = sizeof(PROCESSENTRY32);
5667 if (!Process32First(h, &pe))
5668 goto theend;
5669
5670 do
5671 {
5672 if (pe.th32ParentProcessID == pid)
5673 {
5674 HANDLE ph = OpenProcess(
5675 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5676 if (ph != NULL)
5677 {
5678 terminate_all(ph, code);
5679 CloseHandle(ph);
5680 }
5681 }
5682 } while (Process32Next(h, &pe));
5683
5684 CloseHandle(h);
5685 }
5686 }
5687
5688theend:
5689 return TerminateProcess(process, code);
5690}
5691
5692/*
5693 * Send a (deadly) signal to "job".
5694 * Return FAIL if it didn't work.
5695 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005696 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005697mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005698{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005699 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005700
Bram Moolenaar923d9262016-02-25 20:56:01 +01005701 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005702 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005703 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02005704 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005705 {
5706 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5707 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00005708 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005709 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01005710 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005711 }
5712
5713 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5714 return FAIL;
5715 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005716 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5717 job->jv_proc_info.dwProcessId)
5718 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005719 FreeConsole();
5720 return ret;
5721}
5722
5723/*
5724 * Clear the data related to "job".
5725 */
5726 void
5727mch_clear_job(job_T *job)
5728{
5729 if (job->jv_status != JOB_FAILED)
5730 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005731 if (job->jv_job_object != NULL)
5732 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005733 CloseHandle(job->jv_proc_info.hProcess);
5734 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005735}
5736#endif
5737
Bram Moolenaar071d4272004-06-13 20:20:40 +00005738
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005739#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005740
5741/*
5742 * Start termcap mode
5743 */
5744 static void
5745termcap_mode_start(void)
5746{
5747 DWORD cmodein;
5748
5749 if (g_fTermcapMode)
5750 return;
5751
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005752 if (!p_rs && USE_VTP)
5753 vtp_printf("\033[?1049h");
5754
Bram Moolenaar071d4272004-06-13 20:20:40 +00005755 SaveConsoleBuffer(&g_cbNonTermcap);
5756
5757 if (g_cbTermcap.IsValid)
5758 {
5759 /*
5760 * We've been in termcap mode before. Restore certain screen
5761 * characteristics, including the buffer size and the window
5762 * size. Since we will be redrawing the screen, we don't need
5763 * to restore the actual contents of the buffer.
5764 */
5765 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005766 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005767 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5768 Rows = g_cbTermcap.Info.dwSize.Y;
5769 Columns = g_cbTermcap.Info.dwSize.X;
5770 }
5771 else
5772 {
5773 /*
5774 * This is our first time entering termcap mode. Clear the console
5775 * screen buffer, and resize the buffer to match the current window
5776 * size. We will use this as the size of our editing environment.
5777 */
5778 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005779 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005780 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5781 }
5782
Bram Moolenaar071d4272004-06-13 20:20:40 +00005783 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005784
5785 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005786 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005787 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005788 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005789 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
5790 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005791 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005792 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005793 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005794 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5795 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005796 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005797 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005798
5799 redraw_later_clear();
5800 g_fTermcapMode = TRUE;
5801}
5802
5803
5804/*
5805 * End termcap mode
5806 */
5807 static void
5808termcap_mode_end(void)
5809{
5810 DWORD cmodein;
5811 ConsoleBuffer *cb;
5812 COORD coord;
5813 DWORD dwDummy;
5814
5815 if (!g_fTermcapMode)
5816 return;
5817
5818 SaveConsoleBuffer(&g_cbTermcap);
5819
5820 GetConsoleMode(g_hConIn, &cmodein);
5821 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005822 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5823 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005824
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005825# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005826 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005827# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005828 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005829# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005830 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01005831 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005832 SetConsoleCursorInfo(g_hConOut, &g_cci);
5833
5834 if (p_rs || exiting)
5835 {
5836 /*
5837 * Clear anything that happens to be on the current line.
5838 */
5839 coord.X = 0;
5840 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5841 FillConsoleOutputCharacter(g_hConOut, ' ',
5842 cb->Info.dwSize.X, coord, &dwDummy);
5843 /*
5844 * The following is just for aesthetics. If we are exiting without
5845 * restoring the screen, then we want to have a prompt string
5846 * appear at the bottom line. However, the command interpreter
5847 * seems to always advance the cursor one line before displaying
5848 * the prompt string, which causes the screen to scroll. To
5849 * counter this, move the cursor up one line before exiting.
5850 */
5851 if (exiting && !p_rs)
5852 coord.Y--;
5853 /*
5854 * Position the cursor at the leftmost column of the desired row.
5855 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005856 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005857 }
5858
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005859 if (!p_rs && USE_VTP)
Bram Moolenaar0afdcf82020-04-01 18:29:10 +02005860 vtp_printf("\033[?1049l");
5861
Bram Moolenaar071d4272004-06-13 20:20:40 +00005862 g_fTermcapMode = FALSE;
5863}
Bram Moolenaar0f873732019-12-05 20:28:46 +01005864#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005865
5866
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005867#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005868 void
5869mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005870 char_u *s UNUSED,
5871 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005872{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005873 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00005874}
5875
5876#else
5877
5878/*
5879 * clear `n' chars, starting from `coord'
5880 */
5881 static void
5882clear_chars(
5883 COORD coord,
5884 DWORD n)
5885{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005886 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02005887 {
5888 DWORD dwDummy;
5889
5890 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5891 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
5892 &dwDummy);
5893 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005894 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005895 {
5896 set_console_color_rgb();
5897 gotoxy(coord.X + 1, coord.Y + 1);
5898 vtp_printf("\033[%dX", n);
5899 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005900}
5901
5902
5903/*
5904 * Clear the screen
5905 */
5906 static void
5907clear_screen(void)
5908{
5909 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005910
5911 if (!USE_VTP)
5912 clear_chars(g_coord, Rows * Columns);
5913 else
5914 {
5915 set_console_color_rgb();
5916 gotoxy(1, 1);
5917 vtp_printf("\033[2J");
5918 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005919}
5920
5921
5922/*
5923 * Clear to end of display
5924 */
5925 static void
5926clear_to_end_of_display(void)
5927{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005928 COORD save = g_coord;
5929
5930 if (!USE_VTP)
5931 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005932 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005933 else
5934 {
5935 set_console_color_rgb();
5936 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5937 vtp_printf("\033[0J");
5938
5939 gotoxy(save.X + 1, save.Y + 1);
5940 g_coord = save;
5941 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005942}
5943
5944
5945/*
5946 * Clear to end of line
5947 */
5948 static void
5949clear_to_end_of_line(void)
5950{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005951 COORD save = g_coord;
5952
5953 if (!USE_VTP)
5954 clear_chars(g_coord, Columns - g_coord.X);
5955 else
5956 {
5957 set_console_color_rgb();
5958 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5959 vtp_printf("\033[0K");
5960
5961 gotoxy(save.X + 1, save.Y + 1);
5962 g_coord = save;
5963 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005964}
5965
5966
5967/*
5968 * Scroll the scroll region up by `cLines' lines
5969 */
5970 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005971scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005972{
5973 COORD oldcoord = g_coord;
5974
5975 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5976 delete_lines(cLines);
5977
5978 g_coord = oldcoord;
5979}
5980
5981
5982/*
5983 * Set the scroll region
5984 */
5985 static void
5986set_scroll_region(
5987 unsigned left,
5988 unsigned top,
5989 unsigned right,
5990 unsigned bottom)
5991{
5992 if (left >= right
5993 || top >= bottom
5994 || right > (unsigned) Columns - 1
5995 || bottom > (unsigned) Rows - 1)
5996 return;
5997
5998 g_srScrollRegion.Left = left;
5999 g_srScrollRegion.Top = top;
6000 g_srScrollRegion.Right = right;
6001 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006002}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006003
Bram Moolenaar6982f422019-02-16 16:48:01 +01006004 static void
6005set_scroll_region_tb(
6006 unsigned top,
6007 unsigned bottom)
6008{
6009 if (top >= bottom || bottom > (unsigned)Rows - 1)
6010 return;
6011
6012 g_srScrollRegion.Top = top;
6013 g_srScrollRegion.Bottom = bottom;
6014}
6015
6016 static void
6017set_scroll_region_lr(
6018 unsigned left,
6019 unsigned right)
6020{
6021 if (left >= right || right > (unsigned)Columns - 1)
6022 return;
6023
6024 g_srScrollRegion.Left = left;
6025 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006026}
6027
6028
6029/*
6030 * Insert `cLines' lines at the current cursor position
6031 */
6032 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006033insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006034{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006035 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006036 COORD dest;
6037 CHAR_INFO fill;
6038
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006039 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6040
Bram Moolenaar6982f422019-02-16 16:48:01 +01006041 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006042 dest.Y = g_coord.Y + cLines;
6043
Bram Moolenaar6982f422019-02-16 16:48:01 +01006044 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006045 source.Top = g_coord.Y;
6046 source.Right = g_srScrollRegion.Right;
6047 source.Bottom = g_srScrollRegion.Bottom - cLines;
6048
Bram Moolenaar6982f422019-02-16 16:48:01 +01006049 clip.Left = g_srScrollRegion.Left;
6050 clip.Top = g_coord.Y;
6051 clip.Right = g_srScrollRegion.Right;
6052 clip.Bottom = g_srScrollRegion.Bottom;
6053
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006054 fill.Char.AsciiChar = ' ';
6055 if (!USE_VTP)
6056 fill.Attributes = g_attrCurrent;
6057 else
6058 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006059
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006060 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006061
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006062 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6063
Bram Moolenaar6982f422019-02-16 16:48:01 +01006064 // Here we have to deal with a win32 console flake: If the scroll
6065 // region looks like abc and we scroll c to a and fill with d we get
6066 // cbd... if we scroll block c one line at a time to a, we get cdd...
6067 // vim expects cdd consistently... So we have to deal with that
6068 // here... (this also occurs scrolling the same way in the other
6069 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006070
6071 if (source.Bottom < dest.Y)
6072 {
6073 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006074 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006075
Bram Moolenaar6982f422019-02-16 16:48:01 +01006076 coord.X = source.Left;
6077 for (i = clip.Top; i < dest.Y; ++i)
6078 {
6079 coord.Y = i;
6080 clear_chars(coord, source.Right - source.Left + 1);
6081 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006082 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006083
6084 if (USE_WT)
6085 {
6086 COORD coord;
6087 int i;
6088
6089 coord.X = source.Left;
6090 for (i = source.Top; i < dest.Y; ++i)
6091 {
6092 coord.Y = i;
6093 clear_chars(coord, source.Right - source.Left + 1);
6094 }
6095 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006096}
6097
6098
6099/*
6100 * Delete `cLines' lines at the current cursor position
6101 */
6102 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006103delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006104{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006105 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006106 COORD dest;
6107 CHAR_INFO fill;
6108 int nb;
6109
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006110 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6111
Bram Moolenaar6982f422019-02-16 16:48:01 +01006112 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006113 dest.Y = g_coord.Y;
6114
Bram Moolenaar6982f422019-02-16 16:48:01 +01006115 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006116 source.Top = g_coord.Y + cLines;
6117 source.Right = g_srScrollRegion.Right;
6118 source.Bottom = g_srScrollRegion.Bottom;
6119
Bram Moolenaar6982f422019-02-16 16:48:01 +01006120 clip.Left = g_srScrollRegion.Left;
6121 clip.Top = g_coord.Y;
6122 clip.Right = g_srScrollRegion.Right;
6123 clip.Bottom = g_srScrollRegion.Bottom;
6124
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006125 fill.Char.AsciiChar = ' ';
6126 if (!USE_VTP)
6127 fill.Attributes = g_attrCurrent;
6128 else
6129 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006130
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006131 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006132
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006133 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6134
Bram Moolenaar6982f422019-02-16 16:48:01 +01006135 // Here we have to deal with a win32 console flake; See insert_lines()
6136 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006137
6138 nb = dest.Y + (source.Bottom - source.Top) + 1;
6139
6140 if (nb < source.Top)
6141 {
6142 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006143 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006144
Bram Moolenaar6982f422019-02-16 16:48:01 +01006145 coord.X = source.Left;
6146 for (i = nb; i < clip.Bottom; ++i)
6147 {
6148 coord.Y = i;
6149 clear_chars(coord, source.Right - source.Left + 1);
6150 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006151 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006152
6153 if (USE_WT)
6154 {
6155 COORD coord;
6156 int i;
6157
6158 coord.X = source.Left;
6159 for (i = nb; i <= source.Bottom; ++i)
6160 {
6161 coord.Y = i;
6162 clear_chars(coord, source.Right - source.Left + 1);
6163 }
6164 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006165}
6166
6167
6168/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006169 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006170 */
6171 static void
6172gotoxy(
6173 unsigned x,
6174 unsigned y)
6175{
6176 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6177 return;
6178
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006179 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006180 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006181 // There are reports of double-width characters not displayed
6182 // correctly. This workaround should fix it, similar to how it's done
6183 // for VTP.
6184 g_coord.X = 0;
6185 SetConsoleCursorPosition(g_hConOut, g_coord);
6186
Bram Moolenaar2313b612019-09-27 14:14:32 +02006187 // external cursor coords are 1-based; internal are 0-based
6188 g_coord.X = x - 1;
6189 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006190 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006191 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006192 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006193 {
6194 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006195 // destruction. Insider build bug. Always enabled because it's cheap
6196 // and avoids mistakes with recognizing the build.
6197 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006198
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006199 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006200
6201 g_coord.X = x - 1;
6202 g_coord.Y = y - 1;
6203 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006204}
6205
6206
6207/*
6208 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006209 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006210 */
6211 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006212textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006213{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006214 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006215
6216 SetConsoleTextAttribute(g_hConOut, wAttr);
6217}
6218
6219
6220 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006221textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006222{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006223 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006224
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006225 if (!USE_VTP)
6226 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6227 else
6228 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006229}
6230
6231
6232 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006233textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006234{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006235 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006236
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006237 if (!USE_VTP)
6238 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6239 else
6240 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006241}
6242
6243
6244/*
6245 * restore the default text attribute (whatever we started with)
6246 */
6247 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006248normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006249{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006250 if (!USE_VTP)
6251 textattr(g_attrDefault);
6252 else
6253 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006254}
6255
6256
6257static WORD g_attrPreStandout = 0;
6258
6259/*
6260 * Make the text standout, by brightening it
6261 */
6262 static void
6263standout(void)
6264{
6265 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006266
Bram Moolenaar071d4272004-06-13 20:20:40 +00006267 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6268}
6269
6270
6271/*
6272 * Turn off standout mode
6273 */
6274 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006275standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006276{
6277 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006278 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006279
6280 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006281}
6282
6283
6284/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006285 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006286 */
6287 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006288mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006289{
6290 char_u *p;
6291 int n;
6292
6293 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6294 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006295 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006296# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006297 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006298# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006299 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006300 {
6301 p = T_ME + 2;
6302 n = getdigits(&p);
6303 if (*p == 'm' && n > 0)
6304 {
6305 cterm_normal_fg_color = (n & 0xf) + 1;
6306 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6307 }
6308 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006309# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006310 cterm_normal_fg_gui_color = INVALCOLOR;
6311 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006312# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006313}
6314
6315
6316/*
6317 * visual bell: flash the screen
6318 */
6319 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006320visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006321{
6322 COORD coordOrigin = {0, 0};
6323 WORD attrFlash = ~g_attrCurrent & 0xff;
6324
6325 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006326 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006327
6328 if (oldattrs == NULL)
6329 return;
6330 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6331 coordOrigin, &dwDummy);
6332 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6333 coordOrigin, &dwDummy);
6334
Bram Moolenaar0f873732019-12-05 20:28:46 +01006335 Sleep(15); // wait for 15 msec
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006336 if (!USE_VTP)
6337 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006338 coordOrigin, &dwDummy);
6339 vim_free(oldattrs);
6340}
6341
6342
6343/*
6344 * Make the cursor visible or invisible
6345 */
6346 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006347cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006348{
6349 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006350
6351 if (USE_VTP)
6352 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6353
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006354# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006355 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006356# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006357}
6358
6359
6360/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006361 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006362 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006363 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006364 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006365write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006366 char_u *pchBuf,
6367 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006368{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006369 COORD coord = g_coord;
6370 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006371 DWORD n, cchwritten;
6372 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006373 static WCHAR *unicodebuf = NULL;
6374 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006375 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006376 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006377 static WCHAR *utf8spbuf = NULL;
6378 static int utf8splength;
6379 static DWORD utf8spcells;
6380 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006381
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006382 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006383 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006384 utf8usingbuf = &unicodebuf;
6385 do
6386 {
6387 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6388 unicodebuf, unibuflen);
6389 if (length && length <= unibuflen)
6390 break;
6391 vim_free(unicodebuf);
6392 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6393 unibuflen = unibuflen ? 0 : length;
6394 } while(1);
6395 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006396 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006397 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6398 {
6399 if (utf8usingbuf != &utf8spbuf)
6400 {
6401 if (utf8spbuf == NULL)
6402 {
6403 cells = mb_string2cells((char_u *)" ", 1);
6404 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6405 utf8spbuf = LALLOC_MULT(WCHAR, length);
6406 if (utf8spbuf != NULL)
6407 {
6408 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6409 utf8usingbuf = &utf8spbuf;
6410 utf8splength = length;
6411 utf8spcells = cells;
6412 }
6413 }
6414 else
6415 {
6416 utf8usingbuf = &utf8spbuf;
6417 length = utf8splength;
6418 cells = utf8spcells;
6419 }
6420 }
6421 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006422
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006423 if (!USE_VTP)
6424 {
6425 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6426 coord, &written);
6427 // When writing fails or didn't write a single character, pretend one
6428 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006429 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006430 coord, &cchwritten) == 0
6431 || cchwritten == 0 || cchwritten == (DWORD)-1)
6432 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006433 }
6434 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006435 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006436 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006437 NULL) == 0 || cchwritten == 0)
6438 cchwritten = 1;
6439 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006440
K.Takata135e1522022-01-29 15:27:58 +00006441 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006442 {
6443 written = cbToWrite;
6444 g_coord.X += (SHORT)cells;
6445 }
6446 else
6447 {
6448 char_u *p = pchBuf;
6449 for (n = 0; n < cchwritten; n++)
6450 MB_CPTR_ADV(p);
6451 written = p - pchBuf;
6452 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006453 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006454
6455 while (g_coord.X > g_srScrollRegion.Right)
6456 {
6457 g_coord.X -= (SHORT) Columns;
6458 if (g_coord.Y < g_srScrollRegion.Bottom)
6459 g_coord.Y++;
6460 }
6461
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006462 // Cursor under VTP is always in the correct position, no need to reset.
6463 if (!USE_VTP)
6464 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006465
6466 return written;
6467}
6468
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006469 static char_u *
6470get_seq(
6471 int *args,
6472 int *count,
6473 char_u *head)
6474{
6475 int argc;
6476 char_u *p;
6477
6478 if (head == NULL || *head != '\033')
6479 return NULL;
6480
6481 argc = 0;
6482 p = head;
6483 ++p;
6484 do
6485 {
6486 ++p;
6487 args[argc] = getdigits(&p);
6488 argc += (argc < 15) ? 1 : 0;
6489 } while (*p == ';');
6490 *count = argc;
6491
6492 return p;
6493}
6494
6495 static char_u *
6496get_sgr(
6497 int *args,
6498 int *count,
6499 char_u *head)
6500{
6501 char_u *p = get_seq(args, count, head);
6502
6503 return (p && *p == 'm') ? ++p : NULL;
6504}
6505
6506/*
6507 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6508 */
6509 static char_u *
6510sgrn2(
6511 char_u *head,
6512 int n)
6513{
6514 int argc;
6515 int args[16];
6516 char_u *p = get_sgr(args, &argc, head);
6517
6518 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6519}
6520
6521/*
6522 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6523 */
6524 static char_u *
6525sgrnc(
6526 char_u *head,
6527 int n)
6528{
6529 int argc;
6530 int args[16];
6531 char_u *p = get_sgr(args, &argc, head);
6532
6533 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6534 ? p : NULL;
6535}
6536
6537 static char_u *
6538skipblank(char_u *q)
6539{
6540 char_u *p = q;
6541
6542 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6543 ++p;
6544 return p;
6545}
6546
6547/*
6548 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6549 * NULL.
6550 */
6551 static char_u *
6552sgrn2c(
6553 char_u *head,
6554 int n)
6555{
6556 char_u *p = sgrn2(head, n);
6557
6558 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6559}
6560
6561/*
6562 * If there is only a newline between the sequence immediately following it,
6563 * a pointer to the character following the newline is returned.
6564 * Otherwise NULL.
6565 */
6566 static char_u *
6567sgrn2cn(
6568 char_u *head,
6569 int n)
6570{
6571 char_u *p = sgrn2(head, n);
6572
6573 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6574}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006575
6576/*
6577 * mch_write(): write the output buffer to the screen, translating ESC
6578 * sequences into calls to console output routines.
6579 */
6580 void
6581mch_write(
6582 char_u *s,
6583 int len)
6584{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006585 char_u *end = s + len;
6586
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006587# ifdef VIMDLL
6588 if (gui.in_use)
6589 return;
6590# endif
6591
Bram Moolenaar071d4272004-06-13 20:20:40 +00006592 if (!term_console)
6593 {
6594 write(1, s, (unsigned)len);
6595 return;
6596 }
6597
Bram Moolenaar0f873732019-12-05 20:28:46 +01006598 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00006599 while (len--)
6600 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006601 int prefix = -1;
6602 char_u ch;
6603
6604 // While processing a sequence, on rare occasions it seems that another
6605 // sequence may be inserted asynchronously.
6606 if (len < 0)
6607 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006608 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006609 return;
6610 }
6611
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006612 while (s + ++prefix < end)
6613 {
6614 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006615 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6616 && ch != '\a' && ch != '\033'))
6617 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006618 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006619
6620 if (p_wd)
6621 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006622 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006623 if (prefix != 0)
6624 prefix = 1;
6625 }
6626
6627 if (prefix != 0)
6628 {
6629 DWORD nWritten;
6630
6631 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006632# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006633 if (fdDump)
6634 {
6635 fputc('>', fdDump);
6636 fwrite(s, sizeof(char_u), nWritten, fdDump);
6637 fputs("<\n", fdDump);
6638 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006639# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006640 len -= (nWritten - 1);
6641 s += nWritten;
6642 }
6643 else if (s[0] == '\n')
6644 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006645 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00006646 if (g_coord.Y == g_srScrollRegion.Bottom)
6647 {
6648 scroll(1);
6649 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6650 }
6651 else
6652 {
6653 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6654 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006655# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006656 if (fdDump)
6657 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006658# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006659 s++;
6660 }
6661 else if (s[0] == '\r')
6662 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006663 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00006664 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006665# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006666 if (fdDump)
6667 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006668# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006669 s++;
6670 }
6671 else if (s[0] == '\b')
6672 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006673 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00006674 if (g_coord.X > g_srScrollRegion.Left)
6675 g_coord.X--;
6676 else if (g_coord.Y > g_srScrollRegion.Top)
6677 {
6678 g_coord.X = g_srScrollRegion.Right;
6679 g_coord.Y--;
6680 }
6681 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006682# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006683 if (fdDump)
6684 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006685# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006686 s++;
6687 }
6688 else if (s[0] == '\a')
6689 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006690 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00006691 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006692# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006693 if (fdDump)
6694 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006695# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006696 s++;
6697 }
6698 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6699 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006700# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006701 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006702# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006703 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006704 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006705 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006706
6707 switch (s[2])
6708 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006709 case '0': case '1': case '2': case '3': case '4':
6710 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006711 if (*(p = get_seq(args, &argc, s)) != 'm')
6712 goto notsgr;
6713
6714 p = s;
6715
6716 // Handling frequent optional sequences. Output to the screen
6717 // takes too long, so do not output as much as possible.
6718
6719 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
6720 // resetFG,FG,BG are omitted.
6721 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006722 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006723 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
6724 len = len + 1 - (int)(p - s);
6725 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006726 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006727 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006728
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006729 // If FG,BG,BG,FG of SGR are connected, the first FG can be
6730 // omitted.
6731 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
6732 p = sp;
6733
6734 // If FG,BG,FG,BG of SGR are connected, the first FG can be
6735 // omitted.
6736 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
6737 p = sp;
6738
6739 // If BG,BG of SGR are connected, the first BG can be omitted.
6740 if (sgrn2((sp = sgrn2(p, 48)), 48))
6741 p = sp;
6742
6743 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01006744 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006745 if (sgrn2((sp = sgrnc(p, 39)), 38))
6746 p = sp;
6747
6748 p = get_seq(args, &argc, p);
6749
6750notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006751 arg1 = args[0];
6752 arg2 = args[1];
6753 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006754 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006755 if (argc == 1 && args[0] == 0)
6756 normvideo();
6757 else if (argc == 1)
6758 {
6759 if (USE_VTP)
6760 textcolor((WORD) arg1);
6761 else
6762 textattr((WORD) arg1);
6763 }
6764 else if (USE_VTP)
6765 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006766 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006767 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006768 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006769 gotoxy(arg2, arg1);
6770 }
6771 else if (argc == 2 && *p == 'r')
6772 {
6773 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6774 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006775 else if (argc == 2 && *p == 'R')
6776 {
6777 set_scroll_region_tb(arg1, arg2);
6778 }
6779 else if (argc == 2 && *p == 'V')
6780 {
6781 set_scroll_region_lr(arg1, arg2);
6782 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006783 else if (argc == 1 && *p == 'A')
6784 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006785 gotoxy(g_coord.X + 1,
6786 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6787 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006788 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006789 {
6790 textbackground((WORD) arg1);
6791 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006792 else if (argc == 1 && *p == 'C')
6793 {
6794 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6795 g_coord.Y + 1);
6796 }
6797 else if (argc == 1 && *p == 'f')
6798 {
6799 textcolor((WORD) arg1);
6800 }
6801 else if (argc == 1 && *p == 'H')
6802 {
6803 gotoxy(1, arg1);
6804 }
6805 else if (argc == 1 && *p == 'L')
6806 {
6807 insert_lines(arg1);
6808 }
6809 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006810 {
6811 delete_lines(arg1);
6812 }
6813
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006814 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006815 s = p + 1;
6816 break;
6817
Bram Moolenaar071d4272004-06-13 20:20:40 +00006818 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006819 gotoxy(g_coord.X + 1,
6820 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6821 goto got3;
6822
6823 case 'B':
6824 visual_bell();
6825 goto got3;
6826
6827 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006828 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6829 g_coord.Y + 1);
6830 goto got3;
6831
6832 case 'E':
6833 termcap_mode_end();
6834 goto got3;
6835
6836 case 'F':
6837 standout();
6838 goto got3;
6839
6840 case 'f':
6841 standend();
6842 goto got3;
6843
6844 case 'H':
6845 gotoxy(1, 1);
6846 goto got3;
6847
6848 case 'j':
6849 clear_to_end_of_display();
6850 goto got3;
6851
6852 case 'J':
6853 clear_screen();
6854 goto got3;
6855
6856 case 'K':
6857 clear_to_end_of_line();
6858 goto got3;
6859
6860 case 'L':
6861 insert_lines(1);
6862 goto got3;
6863
6864 case 'M':
6865 delete_lines(1);
6866 goto got3;
6867
6868 case 'S':
6869 termcap_mode_start();
6870 goto got3;
6871
6872 case 'V':
6873 cursor_visible(TRUE);
6874 goto got3;
6875
6876 case 'v':
6877 cursor_visible(FALSE);
6878 goto got3;
6879
6880 got3:
6881 s += 3;
6882 len -= 2;
6883 }
6884
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006885# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006886 if (fdDump)
6887 {
6888 fputs("ESC | ", fdDump);
6889 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6890 fputc('\n', fdDump);
6891 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006892# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006893 }
K.Takatadf5320c2022-09-01 13:20:16 +01006894 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
6895 {
6896 int l = 2;
6897
6898 if (isdigit(s[l]))
6899 l++;
6900 if (s[l] == ' ' && s[l + 1] == 'q')
6901 {
6902 // DECSCUSR (cursor style) sequences
6903 if (USE_VTP || USE_WT)
6904 vtp_printf("%.*s", l + 2, s); // Pass through
6905 s += l + 2;
6906 len -= l + 1;
6907 }
6908 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006909 else
6910 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006911 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00006912 DWORD nWritten;
6913
6914 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006915# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006916 if (fdDump)
6917 {
6918 fputc('>', fdDump);
6919 fwrite(s, sizeof(char_u), nWritten, fdDump);
6920 fputs("<\n", fdDump);
6921 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006922# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006923
6924 len -= (nWritten - 1);
6925 s += nWritten;
6926 }
6927 }
6928
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006929# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006930 if (fdDump)
6931 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006932# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006933}
6934
Bram Moolenaar0f873732019-12-05 20:28:46 +01006935#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006936
6937
6938/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006939 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006940 */
6941 void
6942mch_delay(
6943 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02006944 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006945{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006946#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006947 Sleep((int)msec); // never wait for input
6948#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006949# ifdef VIMDLL
6950 if (gui.in_use)
6951 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006952 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006953 return;
6954 }
6955# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02006956 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006957# ifdef FEAT_MZSCHEME
6958 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6959 {
6960 int towait = p_mzq;
6961
Bram Moolenaar0f873732019-12-05 20:28:46 +01006962 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006963 while (msec > 0)
6964 {
6965 mzvim_check_threads();
6966 if (msec < towait)
6967 towait = msec;
6968 Sleep(towait);
6969 msec -= towait;
6970 }
6971 }
6972 else
6973# endif
6974 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006975 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006976 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006977#endif
6978}
6979
6980
6981/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006982 * This version of remove is not scared by a readonly (backup) file.
6983 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006984 * Return 0 for success, -1 for failure.
6985 */
6986 int
6987mch_remove(char_u *name)
6988{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006989 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006990 int n;
6991
Bram Moolenaar203258c2016-01-17 22:15:16 +01006992 /*
6993 * On Windows, deleting a directory's symbolic link is done by
6994 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6995 */
6996 if (mch_isdir(name) && mch_is_symbolic_link(name))
6997 return mch_rmdir(name);
6998
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006999 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
7000
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007001 wn = enc_to_utf16(name, NULL);
7002 if (wn == NULL)
7003 return -1;
7004
7005 n = DeleteFileW(wn) ? 0 : -1;
7006 vim_free(wn);
7007 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007008}
7009
7010
7011/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007012 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007013 */
7014 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007015mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007016{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007017#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7018# ifdef VIMDLL
7019 if (!gui.in_use)
7020# endif
7021 if (g_fCtrlCPressed || g_fCBrkPressed)
7022 {
7023 ctrl_break_was_pressed = g_fCBrkPressed;
7024 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7025 got_int = TRUE;
7026 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007027#endif
7028}
7029
Bram Moolenaar0f873732019-12-05 20:28:46 +01007030// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007031#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007032
7033/*
7034 * How much main memory in KiB that can be used by VIM.
7035 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007036 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007037mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007038{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007039 MEMORYSTATUSEX ms;
7040
Bram Moolenaar0f873732019-12-05 20:28:46 +01007041 // Need to use GlobalMemoryStatusEx() when there is more memory than
7042 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007043 ms.dwLength = sizeof(MEMORYSTATUSEX);
7044 GlobalMemoryStatusEx(&ms);
7045 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007046 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007047 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007048 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007049 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007050 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007051 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007052 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007053 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007054 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007055 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007056 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007057}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007058
Bram Moolenaar071d4272004-06-13 20:20:40 +00007059/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007060 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00007061 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
7062 * file whose short file name is "FOO.BAR" (its long file name will
7063 * be correct: "foo.bar~"). Because a file can be accessed by
7064 * either its SFN or its LFN, "foo.bar" has effectively been
7065 * renamed to "foo.bar", which is not at all what was wanted. This
7066 * seems to happen only when renaming files with three-character
7067 * extensions by appending a suffix that does not include ".".
7068 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
7069 *
7070 * There is another problem, which isn't really a bug but isn't right either:
7071 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
7072 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
7073 * service pack 6. Doesn't seem to happen on Windows 98.
7074 *
7075 * Like rename(), returns 0 upon success, non-zero upon failure.
7076 * Should probably set errno appropriately when errors occur.
7077 */
7078 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007079mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007080{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007081 WCHAR *p;
7082 int i;
7083 WCHAR szTempFile[_MAX_PATH + 1];
7084 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007085 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007086
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007087 // No need to play tricks unless the file name contains a "~" as the
7088 // seventh character.
7089 p = wold;
7090 for (i = 0; wold[i] != NUL; ++i)
7091 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
7092 && wold[i + 1] != 0)
7093 p = wold + i + 1;
7094 if ((int)(wold + i - p) < 8 || p[6] != '~')
7095 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007096
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007097 // Get base path of new file name. Undocumented feature: If pszNewFile is
7098 // a directory, no error is returned and pszFilePart will be NULL.
7099 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007100 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007101 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007102
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007103 // Get (and create) a unique temporary file name in directory of new file
7104 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007105 return -2;
7106
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007107 // blow the temp file away
7108 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007109 return -3;
7110
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007111 // rename old file to the temp file
7112 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007113 return -4;
7114
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007115 // now create an empty file called pszOldFile; this prevents the operating
7116 // system using pszOldFile as an alias (SFN) if we're renaming within the
7117 // same directory. For example, we're editing a file called
7118 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7119 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7120 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7121 // cause all sorts of problems later in buf_write(). So, we create an
7122 // empty file called filena~1.txt and the system will have to find some
7123 // other SFN for filena~1.txt~, such as filena~2.txt
7124 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007125 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7126 return -5;
7127 if (!CloseHandle(hf))
7128 return -6;
7129
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007130 // rename the temp file to the new file
7131 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007132 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007133 // Renaming failed. Rename the file back to its old name, so that it
7134 // looks like nothing happened.
7135 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007136 return -7;
7137 }
7138
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007139 // Seems to be left around on Novell filesystems
7140 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007141
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007142 // finally, remove the empty old file
7143 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007144 return -8;
7145
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007146 return 0;
7147}
7148
7149
7150/*
7151 * Converts the filenames to UTF-16, then call mch_wrename().
7152 * Like rename(), returns 0 upon success, non-zero upon failure.
7153 */
7154 int
7155mch_rename(
7156 const char *pszOldFile,
7157 const char *pszNewFile)
7158{
7159 WCHAR *wold = NULL;
7160 WCHAR *wnew = NULL;
7161 int retval = -1;
7162
7163 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7164 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7165 if (wold != NULL && wnew != NULL)
7166 retval = mch_wrename(wold, wnew);
7167 vim_free(wold);
7168 vim_free(wnew);
7169 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007170}
7171
7172/*
7173 * Get the default shell for the current hardware platform
7174 */
7175 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007176default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007177{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007178 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007179}
7180
7181/*
7182 * mch_access() extends access() to do more detailed check on network drives.
7183 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7184 */
7185 int
7186mch_access(char *n, int p)
7187{
7188 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007189 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007190 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007191
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007192 wn = enc_to_utf16((char_u *)n, NULL);
7193 if (wn == NULL)
7194 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007195
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007196 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007197 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007198 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007199
7200 if (p & R_OK)
7201 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007202 // Read check is performed by seeing if we can do a find file on
7203 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007204 int i;
7205 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007206
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007207 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7208 TempNameW[i] = wn[i];
7209 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7210 TempNameW[i++] = '\\';
7211 TempNameW[i++] = '*';
7212 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007213
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007214 hFile = FindFirstFileW(TempNameW, &d);
7215 if (hFile == INVALID_HANDLE_VALUE)
7216 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007217 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007218 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007219 }
7220
7221 if (p & W_OK)
7222 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007223 // Trying to create a temporary file in the directory should catch
7224 // directories on read-only network shares. However, in
7225 // directories whose ACL allows writes but denies deletes will end
7226 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007227 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7228 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007229 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007230 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007231 }
7232 }
7233 else
7234 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007235 // Don't consider a file read-only if another process has opened it.
7236 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7237
Bram Moolenaar0f873732019-12-05 20:28:46 +01007238 // Trying to open the file for the required access does ACL, read-only
7239 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007240 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7241 | ((p & R_OK) ? GENERIC_READ : 0);
7242
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007243 hFile = CreateFileW(wn, access_mode, share_mode,
7244 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007245 if (hFile == INVALID_HANDLE_VALUE)
7246 goto getout;
7247 CloseHandle(hFile);
7248 }
7249
Bram Moolenaar0f873732019-12-05 20:28:46 +01007250 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007251getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007252 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007253 return retval;
7254}
7255
Bram Moolenaar071d4272004-06-13 20:20:40 +00007256/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007257 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007258 */
7259 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007260mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007261{
7262 WCHAR *wn;
7263 int f;
7264
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007265 wn = enc_to_utf16((char_u *)name, NULL);
7266 if (wn == NULL)
7267 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007268
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007269 f = _wopen(wn, flags, mode);
7270 vim_free(wn);
7271 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007272}
7273
7274/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007275 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007276 */
7277 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007278mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007279{
7280 WCHAR *wn, *wm;
7281 FILE *f = NULL;
7282
Bram Moolenaara12a1612019-01-24 16:39:02 +01007283#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007284 // Work around an annoying assertion in the Microsoft debug CRT
7285 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007286 char newMode = mode[strlen(mode) - 1];
7287 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007288
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007289 _get_fmode(&oldMode);
7290 if (newMode == 't')
7291 _set_fmode(_O_TEXT);
7292 else if (newMode == 'b')
7293 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007294#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007295 wn = enc_to_utf16((char_u *)name, NULL);
7296 wm = enc_to_utf16((char_u *)mode, NULL);
7297 if (wn != NULL && wm != NULL)
7298 f = _wfopen(wn, wm);
7299 vim_free(wn);
7300 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007301
Bram Moolenaara12a1612019-01-24 16:39:02 +01007302#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007303 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007304#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007305 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007306}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007307
Bram Moolenaar071d4272004-06-13 20:20:40 +00007308/*
7309 * SUB STREAM (aka info stream) handling:
7310 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007311 * NTFS can have sub streams for each file. The normal contents of a file is
7312 * stored in the main stream, and extra contents (author information, title and
7313 * so on) can be stored in a sub stream. After Windows 2000, the user can
7314 * access and store this information in sub streams via an explorer's property
7315 * menu item in the right click menu. This information in sub streams was lost
7316 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007317 *
7318 * Incomplete explanation:
7319 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7320 * More useful info and an example:
7321 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7322 */
7323
7324/*
7325 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7326 * and write to stream "substream" of file "to".
7327 * Errors are ignored.
7328 */
7329 static void
7330copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7331{
7332 HANDLE hTo;
7333 WCHAR *to_name;
7334
7335 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7336 wcscpy(to_name, to);
7337 wcscat(to_name, substream);
7338
7339 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7340 FILE_ATTRIBUTE_NORMAL, NULL);
7341 if (hTo != INVALID_HANDLE_VALUE)
7342 {
7343 long done;
7344 DWORD todo;
7345 DWORD readcnt, written;
7346 char buf[4096];
7347
Bram Moolenaar0f873732019-12-05 20:28:46 +01007348 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007349 for (done = 0; done < len; done += written)
7350 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007351 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007352 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7353 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007354 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7355 FALSE, FALSE, context)
7356 || readcnt != todo
7357 || !WriteFile(hTo, buf, todo, &written, NULL)
7358 || written != todo)
7359 break;
7360 }
7361 CloseHandle(hTo);
7362 }
7363
7364 free(to_name);
7365}
7366
7367/*
7368 * Copy info streams from file "from" to file "to".
7369 */
7370 static void
7371copy_infostreams(char_u *from, char_u *to)
7372{
7373 WCHAR *fromw;
7374 WCHAR *tow;
7375 HANDLE sh;
7376 WIN32_STREAM_ID sid;
7377 int headersize;
7378 WCHAR streamname[_MAX_PATH];
7379 DWORD readcount;
7380 void *context = NULL;
7381 DWORD lo, hi;
7382 int len;
7383
Bram Moolenaar0f873732019-12-05 20:28:46 +01007384 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007385 fromw = enc_to_utf16(from, NULL);
7386 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007387 if (fromw != NULL && tow != NULL)
7388 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007389 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007390 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7391 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7392 if (sh != INVALID_HANDLE_VALUE)
7393 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007394 // Use BackupRead() to find the info streams. Repeat until we
7395 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007396 for (;;)
7397 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007398 // Get the header to find the length of the stream name. If
7399 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007400 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007401 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007402 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7403 &readcount, FALSE, FALSE, &context)
7404 || readcount == 0)
7405 break;
7406
Bram Moolenaar0f873732019-12-05 20:28:46 +01007407 // We only deal with streams that have a name. The normal
7408 // file data appears to be without a name, even though docs
7409 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007410 if (sid.dwStreamNameSize > 0)
7411 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007412 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007413 if (!BackupRead(sh, (LPBYTE)streamname,
7414 sid.dwStreamNameSize,
7415 &readcount, FALSE, FALSE, &context))
7416 break;
7417
Bram Moolenaar0f873732019-12-05 20:28:46 +01007418 // Copy an info stream with a name ":anything:$DATA".
7419 // Skip "::$DATA", it has no stream name (examples suggest
7420 // it might be used for the normal file contents).
7421 // Note that BackupRead() counts bytes, but the name is in
7422 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007423 len = readcount / sizeof(WCHAR);
7424 streamname[len] = 0;
7425 if (len > 7 && wcsicmp(streamname + len - 6,
7426 L":$DATA") == 0)
7427 {
7428 streamname[len - 6] = 0;
7429 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007430 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007431 }
7432 }
7433
Bram Moolenaar0f873732019-12-05 20:28:46 +01007434 // Advance to the next stream. We might try seeking too far,
7435 // but BackupSeek() doesn't skip over stream borders, thus
7436 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007437 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007438 &lo, &hi, &context);
7439 }
7440
Bram Moolenaar0f873732019-12-05 20:28:46 +01007441 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007442 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7443
7444 CloseHandle(sh);
7445 }
7446 }
7447 vim_free(fromw);
7448 vim_free(tow);
7449}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007450
7451/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007452 * ntdll.dll definitions
7453 */
7454#define FileEaInformation 7
7455#ifndef STATUS_SUCCESS
7456# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7457#endif
7458
7459typedef struct _FILE_FULL_EA_INFORMATION_ {
7460 ULONG NextEntryOffset;
7461 UCHAR Flags;
7462 UCHAR EaNameLength;
7463 USHORT EaValueLength;
7464 CHAR EaName[1];
7465} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7466
7467typedef struct _FILE_EA_INFORMATION_ {
7468 ULONG EaSize;
7469} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7470
Paul Ollis65745772022-06-05 16:55:54 +01007471#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007472typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7473 PHANDLE FileHandle,
7474 ACCESS_MASK DesiredAccess,
7475 POBJECT_ATTRIBUTES ObjectAttributes,
7476 PIO_STATUS_BLOCK IoStatusBlock,
7477 ULONG ShareAccess,
7478 ULONG OpenOptions);
7479typedef NTSTATUS (NTAPI *PfnNtClose)(
7480 HANDLE Handle);
7481typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007482 HANDLE FileHandle,
7483 PIO_STATUS_BLOCK IoStatusBlock,
7484 PVOID Buffer,
7485 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007486typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7487 HANDLE FileHandle,
7488 PIO_STATUS_BLOCK IoStatusBlock,
7489 PVOID Buffer,
7490 ULONG Length,
7491 BOOLEAN ReturnSingleEntry,
7492 PVOID EaList,
7493 ULONG EaListLength,
7494 PULONG EaIndex,
7495 BOOLEAN RestartScan);
7496typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007497 HANDLE FileHandle,
7498 PIO_STATUS_BLOCK IoStatusBlock,
7499 PVOID FileInformation,
7500 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007501 FILE_INFORMATION_CLASS FileInformationClass);
7502typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7503 PUNICODE_STRING DestinationString,
7504 PCWSTR SourceString);
7505
7506PfnNtOpenFile pNtOpenFile = NULL;
7507PfnNtClose pNtClose = NULL;
7508PfnNtSetEaFile pNtSetEaFile = NULL;
7509PfnNtQueryEaFile pNtQueryEaFile = NULL;
7510PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7511PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01007512#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007513
7514/*
7515 * Load ntdll.dll functions.
7516 */
7517 static BOOL
7518load_ntdll(void)
7519{
7520 static int loaded = -1;
7521
7522 if (loaded == -1)
7523 {
7524 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7525 if (hNtdll != NULL)
7526 {
7527 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7528 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7529 pNtSetEaFile = (PfnNtSetEaFile)
7530 GetProcAddress(hNtdll, "NtSetEaFile");
7531 pNtQueryEaFile = (PfnNtQueryEaFile)
7532 GetProcAddress(hNtdll, "NtQueryEaFile");
7533 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7534 GetProcAddress(hNtdll, "NtQueryInformationFile");
7535 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7536 GetProcAddress(hNtdll, "RtlInitUnicodeString");
7537 }
7538 if (pNtOpenFile == NULL
7539 || pNtClose == NULL
7540 || pNtSetEaFile == NULL
7541 || pNtQueryEaFile == NULL
7542 || pNtQueryInformationFile == NULL
7543 || pRtlInitUnicodeString == NULL)
7544 loaded = FALSE;
7545 else
7546 loaded = TRUE;
7547 }
7548 return (BOOL) loaded;
7549}
7550
7551/*
7552 * Copy extended attributes (EA) from file "from" to file "to".
7553 */
7554 static void
7555copy_extattr(char_u *from, char_u *to)
7556{
7557 char_u *fromf = NULL;
7558 char_u *tof = NULL;
7559 WCHAR *fromw = NULL;
7560 WCHAR *tow = NULL;
7561 UNICODE_STRING u;
7562 HANDLE h;
7563 OBJECT_ATTRIBUTES oa;
7564 IO_STATUS_BLOCK iosb;
7565 FILE_EA_INFORMATION_ eainfo = {0};
7566 void *ea = NULL;
7567
7568 if (!load_ntdll())
7569 return;
7570
7571 // Convert the file names to the fully qualified object names.
7572 fromf = alloc(STRLEN(from) + 5);
7573 tof = alloc(STRLEN(to) + 5);
7574 if (fromf == NULL || tof == NULL)
7575 goto theend;
7576 STRCPY(fromf, "\\??\\");
7577 STRCAT(fromf, from);
7578 STRCPY(tof, "\\??\\");
7579 STRCAT(tof, to);
7580
7581 // Convert the names to wide characters.
7582 fromw = enc_to_utf16(fromf, NULL);
7583 tow = enc_to_utf16(tof, NULL);
7584 if (fromw == NULL || tow == NULL)
7585 goto theend;
7586
7587 // Get the EA.
7588 pRtlInitUnicodeString(&u, fromw);
7589 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7590 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7591 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7592 goto theend;
7593 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7594 FileEaInformation);
7595 if (eainfo.EaSize != 0)
7596 {
7597 ea = alloc(eainfo.EaSize);
7598 if (ea != NULL)
7599 {
7600 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7601 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7602 {
7603 vim_free(ea);
7604 ea = NULL;
7605 }
7606 }
7607 }
7608 pNtClose(h);
7609
7610 // Set the EA.
7611 if (ea != NULL)
7612 {
7613 pRtlInitUnicodeString(&u, tow);
7614 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7615 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7616 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7617 goto theend;
7618
7619 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
7620 pNtClose(h);
7621 }
7622
7623theend:
7624 vim_free(fromf);
7625 vim_free(tof);
7626 vim_free(fromw);
7627 vim_free(tow);
7628 vim_free(ea);
7629}
7630
7631/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007632 * Copy file attributes from file "from" to file "to".
7633 * For Windows NT and later we copy info streams.
7634 * Always returns zero, errors are ignored.
7635 */
7636 int
7637mch_copy_file_attribute(char_u *from, char_u *to)
7638{
Bram Moolenaar0f873732019-12-05 20:28:46 +01007639 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007640 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007641 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007642 return 0;
7643}
7644
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007645
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007646/*
K.Takatadc73b4b2021-06-08 18:32:36 +02007647 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007648 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007649static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007650static LPWSTR *ArglistW = NULL;
7651static int global_argc = 0;
7652static char **global_argv;
7653
Bram Moolenaar0f873732019-12-05 20:28:46 +01007654static int used_file_argc = 0; // last argument in global_argv[] used
7655 // for the argument list.
7656static int *used_file_indexes = NULL; // indexes in global_argv[] for
7657 // command line arguments added to
7658 // the argument list
7659static int used_file_count = 0; // nr of entries in used_file_indexes
7660static int used_file_literal = FALSE; // take file names literally
7661static int used_file_full_path = FALSE; // file name was full path
7662static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007663static int used_alist_count = 0;
7664
7665
7666/*
7667 * Get the command line arguments. Unicode version.
7668 * Returns argc. Zero when something fails.
7669 */
7670 int
7671get_cmd_argsW(char ***argvp)
7672{
7673 char **argv = NULL;
7674 int argc = 0;
7675 int i;
7676
Bram Moolenaar14993322014-09-09 12:25:33 +02007677 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007678 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7679 if (ArglistW != NULL)
7680 {
7681 argv = malloc((nArgsW + 1) * sizeof(char *));
7682 if (argv != NULL)
7683 {
7684 argc = nArgsW;
7685 argv[argc] = NULL;
7686 for (i = 0; i < argc; ++i)
7687 {
7688 int len;
7689
K.Takatadc73b4b2021-06-08 18:32:36 +02007690 // Convert each Unicode argument to UTF-8.
7691 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007692 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007693 (LPSTR *)&argv[i], &len, 0, 0);
7694 if (argv[i] == NULL)
7695 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007696 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007697 while (i > 0)
7698 free(argv[--i]);
7699 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007700 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007701 argc = 0;
7702 }
7703 }
7704 }
7705 }
7706
7707 global_argc = argc;
7708 global_argv = argv;
7709 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007710 {
7711 if (used_file_indexes != NULL)
7712 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007713 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007714 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007715
7716 if (argvp != NULL)
7717 *argvp = argv;
7718 return argc;
7719}
7720
7721 void
7722free_cmd_argsW(void)
7723{
7724 if (ArglistW != NULL)
7725 {
7726 GlobalFree(ArglistW);
7727 ArglistW = NULL;
7728 }
7729}
7730
7731/*
7732 * Remember "name" is an argument that was added to the argument list.
7733 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7734 * is called.
7735 */
7736 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007737used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007738{
7739 int i;
7740
7741 if (used_file_indexes == NULL)
7742 return;
7743 for (i = used_file_argc + 1; i < global_argc; ++i)
7744 if (STRCMP(global_argv[i], name) == 0)
7745 {
7746 used_file_argc = i;
7747 used_file_indexes[used_file_count++] = i;
7748 break;
7749 }
7750 used_file_literal = literal;
7751 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007752 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007753}
7754
7755/*
7756 * Remember the length of the argument list as it was. If it changes then we
7757 * leave it alone when 'encoding' is set.
7758 */
7759 void
7760set_alist_count(void)
7761{
7762 used_alist_count = GARGCOUNT;
7763}
7764
7765/*
7766 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02007767 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007768 * and convert them to 'encoding'.
7769 */
7770 void
7771fix_arg_enc(void)
7772{
7773 int i;
7774 int idx;
7775 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007776 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007777
Bram Moolenaar0f873732019-12-05 20:28:46 +01007778 // Safety checks:
7779 // - if argument count differs between the wide and non-wide argument
7780 // list, something must be wrong.
7781 // - the file name arguments must have been located.
7782 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007783 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007784 || ArglistW == NULL
7785 || used_file_indexes == NULL
7786 || used_file_count == 0
7787 || used_alist_count != GARGCOUNT)
7788 return;
7789
Bram Moolenaar0f873732019-12-05 20:28:46 +01007790 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007791 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007792 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007793 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00007794 for (i = 0; i < GARGCOUNT; ++i)
7795 fnum_list[i] = GARGLIST[i].ae_fnum;
7796
Bram Moolenaar0f873732019-12-05 20:28:46 +01007797 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007798 alist_clear(&global_alist);
7799 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007800 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007801
7802 for (i = 0; i < used_file_count; ++i)
7803 {
7804 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007805 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007806 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007807 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007808 int literal = used_file_literal;
7809
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007810#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01007811 // When using diff mode may need to concatenate file name to
7812 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007813 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7814 && !mch_isdir(alist_name(&GARGLIST[0])))
7815 {
7816 char_u *r;
7817
7818 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7819 if (r != NULL)
7820 {
7821 vim_free(str);
7822 str = r;
7823 }
7824 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007825#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01007826 // Re-use the old buffer by renaming it. When not using literal
7827 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00007828 if (used_file_literal)
7829 buf_set_name(fnum_list[i], str);
7830
Bram Moolenaar0f873732019-12-05 20:28:46 +01007831 // Check backtick literal. backtick literal is already expanded in
7832 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007833 if (literal == FALSE)
7834 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007835 size_t len = STRLEN(str);
7836
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007837 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7838 literal = TRUE;
7839 }
7840 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007841 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007842 }
7843
7844 if (!used_file_literal)
7845 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007846 // Now expand wildcards in the arguments.
7847 // Temporarily add '(' and ')' to 'isfname'. These are valid
7848 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00007849 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01007850 // Also, unset wildignore to not be influenced by this option.
7851 // The arguments specified in command-line should be kept even if
7852 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00007853 // Use :legacy so that it also works when in Vim9 script.
7854 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
7855 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007856 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00007857 do_cmdline_cmd(
7858 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
7859 do_cmdline_cmd(
7860 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007861 }
7862
Bram Moolenaar0f873732019-12-05 20:28:46 +01007863 // If wildcard expansion failed, we are editing the first file of the
7864 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007865 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7866 {
7867 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00007868 if (GARGCOUNT == 1 && used_file_full_path
7869 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
7870 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007871 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007872
7873 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007874}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007875
7876 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007877mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007878{
7879 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007880 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007881
Bram Moolenaar964b3742019-05-24 18:54:09 +02007882 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007883 if (envbuf == NULL)
7884 return -1;
7885
7886 sprintf((char *)envbuf, "%s=%s", var, value);
7887
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007888 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007889
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007890 vim_free(envbuf);
7891 if (p == NULL)
7892 return -1;
7893 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007894#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007895 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007896#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007897 // Unlike Un*x systems, we can free the string for _wputenv().
7898 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007899
7900 return 0;
7901}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007902
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007903/*
7904 * Support for 256 colors and 24-bit colors was added in Windows 10
7905 * version 1703 (Creators update).
7906 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007907#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7908
7909/*
7910 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02007911 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007912 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007913#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007914
7915/*
7916 * ConPTY differences between versions, need different logic.
7917 * version 1903 (May 2019 update).
7918 */
7919#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
7920
7921/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007922 * version 1909 (November 2019 update).
7923 */
7924#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
7925
7926/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007927 * Stay ahead of the next update, and when it's done, fix this.
7928 * version ? (2020 update, temporarily use the build number of insider preview)
7929 */
7930#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
7931
7932/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02007933 * Confirm until this version. Also the logic changes.
7934 * insider preview.
7935 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02007936#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007937
7938/*
7939 * Not stable now.
7940 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007941#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007942
7943 static void
7944vtp_flag_init(void)
7945{
7946 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007947#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007948 DWORD mode;
7949 HANDLE out;
7950
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007951# ifdef VIMDLL
7952 if (!gui.in_use)
7953# endif
7954 {
7955 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007956
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007957 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7958 GetConsoleMode(out, &mode);
7959 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7960 if (SetConsoleMode(out, mode) == 0)
7961 vtp_working = 0;
7962 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007963#endif
7964
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007965 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007966 conpty_working = 1;
7967 if (ver >= CONPTY_STABLE_BUILD)
7968 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007969
Bram Moolenaar57da6982019-09-13 22:30:11 +02007970 if (ver <= CONPTY_INSIDER_BUILD)
7971 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007972 if (ver <= CONPTY_1909_BUILD)
7973 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02007974 if (ver <= CONPTY_1903_BUILD)
7975 conpty_type = 2;
7976 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
7977 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007978
7979 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
7980 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007981}
7982
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007983#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007984
7985 static void
7986vtp_init(void)
7987{
K.Takata27b53be2022-09-18 12:25:49 +01007988 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007989# ifdef FEAT_TERMGUICOLORS
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01007990 COLORREF fg;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007991# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007992
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007993 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01007994 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007995 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7996 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
Bram Moolenaardf543822020-01-30 11:53:59 +01007997 store_console_bg_rgb = save_console_bg_rgb;
7998 store_console_fg_rgb = save_console_fg_rgb;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007999
8000# ifdef FEAT_TERMGUICOLORS
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008001 if (!USE_WT)
8002 {
8003 COLORREF bg;
8004 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
8005 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8006 default_console_color_bg = bg;
8007 }
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008008 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008009 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008010 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008011# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008012
8013 set_console_color_rgb();
8014}
8015
8016 static void
8017vtp_exit(void)
8018{
Bram Moolenaardf543822020-01-30 11:53:59 +01008019 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008020}
8021
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008022 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008023vtp_printf(
8024 char *format,
8025 ...)
8026{
8027 char_u buf[100];
8028 va_list list;
8029 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008030 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008031
8032 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008033 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008034 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008035 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008036 return (int)result;
8037}
8038
8039 static void
8040vtp_sgr_bulk(
8041 int arg)
8042{
8043 int args[1];
8044
8045 args[0] = arg;
8046 vtp_sgr_bulks(1, args);
8047}
8048
K.Takata6e1d31e2022-02-03 13:05:32 +00008049# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008050 if ((*p-- = "0123456789"[(n = x % 10)]) \
8051 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8052 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8053
K.Takata6e1d31e2022-02-03 13:05:32 +00008054# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008055 case x: \
8056 FAST256(newargs[x - 1]);
8057
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008058 static void
8059vtp_sgr_bulks(
8060 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008061 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008062{
K.Takata6e1d31e2022-02-03 13:05:32 +00008063# define MAXSGR 16
8064# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008065 char_u buf[SGRBUFSIZE];
8066 char_u *p;
8067 int in, out;
8068 int newargs[16];
8069 static int sgrfgr = -1, sgrfgg, sgrfgb;
8070 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008071
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008072 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008073 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008074 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008075 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008076 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008077 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008078
8079 in = out = 0;
8080 while (in < argc)
8081 {
8082 int s = args[in];
8083 int copylen = 1;
8084
8085 if (s == 38)
8086 {
8087 if (argc - in >= 5 && args[in + 1] == 2)
8088 {
8089 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8090 && sgrfgb == args[in + 4])
8091 {
8092 in += 5;
8093 copylen = 0;
8094 }
8095 else
8096 {
8097 sgrfgr = args[in + 2];
8098 sgrfgg = args[in + 3];
8099 sgrfgb = args[in + 4];
8100 copylen = 5;
8101 }
8102 }
8103 else if (argc - in >= 3 && args[in + 1] == 5)
8104 {
8105 sgrfgr = -1;
8106 copylen = 3;
8107 }
8108 }
8109 else if (s == 48)
8110 {
8111 if (argc - in >= 5 && args[in + 1] == 2)
8112 {
8113 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8114 && sgrbgb == args[in + 4])
8115 {
8116 in += 5;
8117 copylen = 0;
8118 }
8119 else
8120 {
8121 sgrbgr = args[in + 2];
8122 sgrbgg = args[in + 3];
8123 sgrbgb = args[in + 4];
8124 copylen = 5;
8125 }
8126 }
8127 else if (argc - in >= 3 && args[in + 1] == 5)
8128 {
8129 sgrbgr = -1;
8130 copylen = 3;
8131 }
8132 }
8133 else if (30 <= s && s <= 39)
8134 sgrfgr = -1;
8135 else if (90 <= s && s <= 97)
8136 sgrfgr = -1;
8137 else if (40 <= s && s <= 49)
8138 sgrbgr = -1;
8139 else if (100 <= s && s <= 107)
8140 sgrbgr = -1;
8141 else if (s == 0)
8142 sgrfgr = sgrbgr = -1;
8143
8144 while (copylen--)
8145 newargs[out++] = args[in++];
8146 }
8147
8148 p = &buf[sizeof(buf) - 1];
8149 *p-- = 'm';
8150
8151 switch (out)
8152 {
8153 int n, m;
8154 DWORD r;
8155
8156 FAST256CASE(16);
8157 *p-- = ';';
8158 FAST256CASE(15);
8159 *p-- = ';';
8160 FAST256CASE(14);
8161 *p-- = ';';
8162 FAST256CASE(13);
8163 *p-- = ';';
8164 FAST256CASE(12);
8165 *p-- = ';';
8166 FAST256CASE(11);
8167 *p-- = ';';
8168 FAST256CASE(10);
8169 *p-- = ';';
8170 FAST256CASE(9);
8171 *p-- = ';';
8172 FAST256CASE(8);
8173 *p-- = ';';
8174 FAST256CASE(7);
8175 *p-- = ';';
8176 FAST256CASE(6);
8177 *p-- = ';';
8178 FAST256CASE(5);
8179 *p-- = ';';
8180 FAST256CASE(4);
8181 *p-- = ';';
8182 FAST256CASE(3);
8183 *p-- = ';';
8184 FAST256CASE(2);
8185 *p-- = ';';
8186 FAST256CASE(1);
8187 *p-- = '[';
8188 *p = '\033';
8189 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8190 default:
8191 break;
8192 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008193}
8194
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008195 static void
8196wt_init(void)
8197{
8198 wt_working = (mch_getenv("WT_SESSION") != NULL);
8199}
8200
8201 int
8202use_wt(void)
8203{
8204 return USE_WT;
8205}
8206
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008207# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008208 static int
8209ctermtoxterm(
8210 int cterm)
8211{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008212 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008213
8214 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8215 return (((int)r << 16) | ((int)g << 8) | (int)b);
8216}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008217# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008218
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008219 static void
8220set_console_color_rgb(void)
8221{
8222# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008223 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008224 guicolor_T fg, bg;
8225 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008226
8227 if (!USE_VTP)
8228 return;
8229
Bram Moolenaara050b942019-12-02 21:35:31 +01008230 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8231
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008232 if (USE_WT)
8233 {
8234 term_fg_rgb_color(fg);
8235 term_bg_rgb_color(bg);
8236 return;
8237 }
8238
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008239 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8240 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8241
8242 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008243 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008244
8245 csbi.cbSize = sizeof(csbi);
8246 csbi.srWindow.Right += 1;
8247 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008248 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8249 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008250 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8251 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
K.Takata27b53be2022-09-18 12:25:49 +01008252 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008253# endif
8254}
8255
Bram Moolenaara050b942019-12-02 21:35:31 +01008256# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8257 void
8258get_default_console_color(
8259 int *cterm_fg,
8260 int *cterm_bg,
8261 guicolor_T *gui_fg,
8262 guicolor_T *gui_bg)
8263{
8264 int id;
8265 guicolor_T guifg = INVALCOLOR;
8266 guicolor_T guibg = INVALCOLOR;
8267 int ctermfg = 0;
8268 int ctermbg = 0;
8269
8270 id = syn_name2id((char_u *)"Normal");
8271 if (id > 0 && p_tgc)
8272 syn_id2colors(id, &guifg, &guibg);
8273 if (guifg == INVALCOLOR)
8274 {
8275 ctermfg = -1;
8276 if (id > 0)
8277 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8278 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
8279 : default_console_color_fg;
8280 cterm_normal_fg_gui_color = guifg;
8281 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8282 }
8283 if (guibg == INVALCOLOR)
8284 {
8285 ctermbg = -1;
8286 if (id > 0)
8287 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
K.Takatae53a0d42022-09-05 21:45:11 +01008288 if (USE_WT)
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008289 {
8290 cterm_normal_bg_gui_color = guibg =
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01008291 ctermbg != -1 ? ctermtoxterm(ctermbg) : INVALCOLOR;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008292 if (ctermbg < 0)
8293 ctermbg = 0;
8294 }
K.Takatae53a0d42022-09-05 21:45:11 +01008295 else
8296 {
8297 guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8298 : default_console_color_bg;
8299 cterm_normal_bg_gui_color = guibg;
8300 ctermbg = ctermbg < 0 ? 0 : ctermbg;
8301 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008302 }
8303
8304 *cterm_fg = ctermfg;
8305 *cterm_bg = ctermbg;
8306 *gui_fg = guifg;
8307 *gui_bg = guibg;
8308}
8309# endif
8310
Bram Moolenaardf543822020-01-30 11:53:59 +01008311/*
8312 * Set the console colors to the original colors or the last set colors.
8313 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008314 static void
8315reset_console_color_rgb(void)
8316{
8317# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008318 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008319
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008320 if (USE_WT)
8321 return;
8322
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008323 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008324 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008325
8326 csbi.cbSize = sizeof(csbi);
8327 csbi.srWindow.Right += 1;
8328 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008329 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8330 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008331 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008332# endif
8333}
8334
8335/*
8336 * Set the console colors to the original colors.
8337 */
8338 static void
8339restore_console_color_rgb(void)
8340{
8341# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008342 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008343
8344 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008345 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008346
8347 csbi.cbSize = sizeof(csbi);
8348 csbi.srWindow.Right += 1;
8349 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008350 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8351 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008352 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008353# endif
8354}
8355
8356 void
8357control_console_color_rgb(void)
8358{
8359 if (USE_VTP)
8360 set_console_color_rgb();
8361 else
8362 reset_console_color_rgb();
8363}
8364
8365 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008366use_vtp(void)
8367{
8368 return USE_VTP;
8369}
8370
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008371 int
8372is_term_win32(void)
8373{
8374 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8375}
8376
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008377 int
8378has_vtp_working(void)
8379{
8380 return vtp_working;
8381}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008382
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008383#endif
8384
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008385 int
8386has_conpty_working(void)
8387{
8388 return conpty_working;
8389}
8390
8391 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008392get_conpty_type(void)
8393{
8394 return conpty_type;
8395}
8396
8397 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008398is_conpty_stable(void)
8399{
8400 return conpty_stable;
8401}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008402
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008403 int
8404get_conpty_fix_type(void)
8405{
8406 return conpty_fix_type;
8407}
8408
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008409#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008410 void
8411resize_console_buf(void)
8412{
8413 CONSOLE_SCREEN_BUFFER_INFO csbi;
8414 COORD coord;
8415 SMALL_RECT newsize;
8416
8417 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8418 {
8419 coord.X = SRWIDTH(csbi.srWindow);
8420 coord.Y = SRHEIGHT(csbi.srWindow);
8421 SetConsoleScreenBufferSize(g_hConOut, coord);
8422
8423 newsize.Left = 0;
8424 newsize.Top = 0;
8425 newsize.Right = coord.X - 1;
8426 newsize.Bottom = coord.Y - 1;
8427 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8428
8429 SetConsoleScreenBufferSize(g_hConOut, coord);
8430 }
8431}
8432#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008433
8434 char *
8435GetWin32Error(void)
8436{
K.Takatad68b2fc2022-02-12 11:18:37 +00008437 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008438 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008439
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008440 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8441 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008442 if (oldmsg != NULL)
8443 LocalFree(oldmsg);
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008444 if (msg != NULL)
8445 {
8446 // remove trailing \r\n
8447 char *pcrlf = strstr(msg, "\r\n");
8448 if (pcrlf != NULL)
8449 *pcrlf = '\0';
K.Takatad68b2fc2022-02-12 11:18:37 +00008450 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008451 }
8452 return msg;
8453}
Paul Ollis65745772022-06-05 16:55:54 +01008454
8455#if defined(FEAT_RELTIME) || defined(PROTO)
8456static HANDLE timer_handle;
8457static int timer_active = FALSE;
8458
8459/*
8460 * Calls to start_timeout alternate the return value pointer between the two
8461 * entries in timeout_flags. If the previously active timeout is very close to
8462 * expiring when start_timeout() is called then a race condition means that the
8463 * set_flag() function may still be invoked after the previous timer is
8464 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8465 * timeouts.
8466 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008467static sig_atomic_t timeout_flags[2];
8468static int timeout_flag_idx = 0;
8469static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01008470
8471
8472 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01008473set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01008474{
8475 int *timeout_flag = (int *)param;
8476
8477 *timeout_flag = TRUE;
8478}
8479
8480/*
8481 * Stop any active timeout.
8482 */
8483 void
8484stop_timeout(void)
8485{
8486 if (timer_active)
8487 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01008488 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01008489 timer_active = FALSE;
8490 if (!ret && GetLastError() != ERROR_IO_PENDING)
8491 {
8492 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
8493 }
8494 }
8495 *timeout_flag = FALSE;
8496}
8497
8498/*
8499 * Start the timeout timer.
8500 *
8501 * The period is defined in milliseconds.
8502 *
8503 * The return value is a pointer to a flag that is initialised to 0. If the
8504 * timeout expires, the flag is set to 1. This will only return pointers to
8505 * static memory; i.e. any pointer returned by this function may always be
8506 * safely dereferenced.
8507 *
8508 * This function is not expected to fail, but if it does it still returns a
8509 * valid flag pointer; the flag will remain stuck at zero.
8510 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008511 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01008512start_timeout(long msec)
8513{
Paul Ollis65745772022-06-05 16:55:54 +01008514 BOOL ret;
8515
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008516 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01008517
8518 stop_timeout();
8519 ret = CreateTimerQueueTimer(
8520 &timer_handle, NULL, set_flag, timeout_flag,
8521 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
8522 if (!ret)
8523 {
8524 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
8525 }
8526 else
8527 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008528 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01008529 timer_active = TRUE;
8530 *timeout_flag = FALSE;
8531 }
8532 return timeout_flag;
8533}
8534#endif