blob: acbc4cb7d067b2b85f6af0df431f939af2b68d5d [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;
Christopher Plewright1140b512022-11-12 18:46:05 +0000205static void wt_init(void);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200206
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200207static int g_color_index_bg = 0;
208static int g_color_index_fg = 7;
209
210# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +0000211static guicolor_T save_console_bg_rgb;
212static guicolor_T save_console_fg_rgb;
213static guicolor_T store_console_bg_rgb;
214static guicolor_T store_console_fg_rgb;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +0100215static int default_console_color_bg = 0x000000; // black
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200216static int default_console_color_fg = 0xc0c0c0; // white
Christopher Plewright38804d62022-11-09 23:55:52 +0000217# define USE_VTP (vtp_working && is_term_win32())
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200218# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100219# else
220# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200221# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100222# endif
223
224static void set_console_color_rgb(void);
225static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100226static void restore_console_color_rgb(void);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100227#endif
228
Bram Moolenaar0f873732019-12-05 20:28:46 +0100229// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100230#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
231# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
232#endif
233
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200234#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100235static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000236#endif
237
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200238static char_u *exe_path = NULL;
239
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100240static BOOL win8_or_later = FALSE;
Christopher Plewright1140b512022-11-12 18:46:05 +0000241static BOOL win11_or_later = FALSE;
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100242
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100243/*
244 * Get version number including build number
245 */
246typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100247#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100248 (((major) << 24) | ((minor) << 16) | (build))
249
250 static DWORD
251get_build_number(void)
252{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100253 OSVERSIONINFOW osver;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100254 HMODULE hNtdll;
255 PfnRtlGetVersion pRtlGetVersion;
256 DWORD ver = MAKE_VER(0, 0, 0);
257
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100258 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100259 hNtdll = GetModuleHandle("ntdll.dll");
260 if (hNtdll != NULL)
261 {
262 pRtlGetVersion =
263 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
264 pRtlGetVersion(&osver);
265 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
266 min(osver.dwMinorVersion, 255),
267 min(osver.dwBuildNumber, 32767));
268 }
269 return ver;
270}
271
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200272#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200273 static BOOL
274is_ambiwidth_event(
275 INPUT_RECORD *ir)
276{
277 return ir->EventType == KEY_EVENT
278 && ir->Event.KeyEvent.bKeyDown
279 && ir->Event.KeyEvent.wRepeatCount == 1
280 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
281 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000282 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200283 && ir->Event.KeyEvent.dwControlKeyState == 2;
284}
285
286 static void
287make_ambiwidth_event(
288 INPUT_RECORD *down,
289 INPUT_RECORD *up)
290{
291 down->Event.KeyEvent.wVirtualKeyCode = 0;
292 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000293 down->Event.KeyEvent.uChar.UnicodeChar
294 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200295 down->Event.KeyEvent.dwControlKeyState = 0;
296}
297
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100298/*
299 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100300 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100301 */
302 static BOOL
303read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100304 HANDLE hInput,
305 INPUT_RECORD *lpBuffer,
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100306 int nLength,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100307 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100308{
309 enum
310 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100311 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100312 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100313 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100314 static DWORD s_dwIndex = 0;
315 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100316 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100317 int head;
318 int tail;
319 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200320 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100321
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200322 if (nLength == -2)
323 return (s_dwMax > 0) ? TRUE : FALSE;
324
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100325 if (!win8_or_later)
326 {
327 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200328 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
329 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100330 }
331
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100332 if (s_dwMax == 0)
333 {
Christopher Plewright38804d62022-11-09 23:55:52 +0000334 if (!vtp_working && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200335 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200336 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
337 if (dwEvents == 0 && nLength == -1)
338 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
339 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100340 s_dwIndex = 0;
341 s_dwMax = dwEvents;
342 if (dwEvents == 0)
343 {
344 *lpEvents = 0;
345 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100346 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100347
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200348 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
349 if (is_ambiwidth_event(&s_irCache[i]))
350 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
351
Bram Moolenaardd415a62014-02-05 14:02:27 +0100352 if (s_dwMax > 1)
353 {
354 head = 0;
355 tail = s_dwMax - 1;
356 while (head != tail)
357 {
358 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
359 && s_irCache[head + 1].EventType
360 == WINDOW_BUFFER_SIZE_EVENT)
361 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100362 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100363 for (i = head; i < tail; ++i)
364 s_irCache[i] = s_irCache[i + 1];
365 --tail;
366 continue;
367 }
368 head++;
369 }
370 s_dwMax = tail + 1;
371 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100372 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100373
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200374 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
375 {
376 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
377 {
378 s_irPseudo = s_irCache[s_dwIndex];
379 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
380 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
381 *lpBuffer = s_irPseudo;
382 *lpEvents = 1;
383 return TRUE;
384 }
385 }
386
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100387 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200388 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100389 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100390 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100391 return TRUE;
392}
393
394/*
395 * Version of PeekConsoleInput() that works with IME.
396 */
397 static BOOL
398peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100399 HANDLE hInput,
400 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200401 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100402 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100403{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100404 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100405}
406
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100407# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200408 static DWORD
409msg_wait_for_multiple_objects(
410 DWORD nCount,
411 LPHANDLE pHandles,
412 BOOL fWaitAll,
413 DWORD dwMilliseconds,
414 DWORD dwWakeMask)
415{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100416 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200417 return WAIT_OBJECT_0;
418 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
419 dwMilliseconds, dwWakeMask);
420}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100421# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200422
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100423# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200424 static DWORD
425wait_for_single_object(
426 HANDLE hHandle,
427 DWORD dwMilliseconds)
428{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100429 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200430 return WAIT_OBJECT_0;
431 return WaitForSingleObject(hHandle, dwMilliseconds);
432}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100433# endif
434#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200435
Bram Moolenaar071d4272004-06-13 20:20:40 +0000436 static void
437get_exe_name(void)
438{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100439 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
440 // as the maximum length that works (plus a NUL byte).
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100441#define MAX_ENV_PATH_LEN 8192
442 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200443 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000444
445 if (exe_name == NULL)
446 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100447 // store the name of the executable, may be used for $VIM
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100448 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000449 if (*temp != NUL)
450 exe_name = FullName_save((char_u *)temp, FALSE);
451 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000452
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200453 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000454 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200455 exe_path = vim_strnsave(exe_name, gettail_sep(exe_name) - exe_name);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200456 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000457 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100458 // Append our starting directory to $PATH, so that when doing
459 // "!xxd" it's found in our starting directory. Needed because
460 // SearchPath() also looks there.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200461 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100462 if (p == NULL
463 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200464 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100465 if (p == NULL || *p == NUL)
466 temp[0] = NUL;
467 else
468 {
469 STRCPY(temp, p);
470 STRCAT(temp, ";");
471 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200472 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100473 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200474 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000475 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000476 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000477}
478
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200479/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100480 * Unescape characters in "p" that appear in "escaped".
481 */
482 static void
483unescape_shellxquote(char_u *p, char_u *escaped)
484{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100485 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100486 int n;
487
488 while (*p != NUL)
489 {
490 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
491 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100492 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100493 p += n;
494 l -= n;
495 }
496}
497
498/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200499 * Load library "name".
500 */
501 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000502vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200503{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200504 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200505
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200506 // No need to load any library when registering OLE.
507 if (found_register_arg)
508 return dll;
509
Bram Moolenaar0f873732019-12-05 20:28:46 +0100510 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
511 // vimLoadLib() recursively, which causes a stack overflow.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200512 if (exe_path == NULL)
513 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200514 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200515 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200516 WCHAR old_dirw[MAXPATHL];
517
518 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
519 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100520 // Change directory to where the executable is, both to make
521 // sure we find a .dll there and to avoid looking for a .dll
522 // in the current directory.
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100523 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200524 dll = LoadLibrary(name);
525 SetCurrentDirectoryW(old_dirw);
526 return dll;
527 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200528 }
529 return dll;
530}
531
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200532#if defined(VIMDLL) || defined(PROTO)
533/*
534 * Check if the current executable file is for the GUI subsystem.
535 */
536 int
537mch_is_gui_executable(void)
538{
539 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
540 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
541 PIMAGE_NT_HEADERS pPE;
542
543 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
544 return FALSE;
545 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
546 if (pPE->Signature != IMAGE_NT_SIGNATURE)
547 return FALSE;
548 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
549 return TRUE;
550 return FALSE;
551}
552#endif
553
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000554#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
555 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100556/*
557 * Get related information about 'funcname' which is imported by 'hInst'.
558 * If 'info' is 0, return the function address.
559 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000560 * If 'info' is 2, hook the function with 'ptr', and return the original
561 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100562 */
563 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000564get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
565 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100566{
567 PBYTE pImage = (PBYTE)hInst;
568 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
569 PIMAGE_NT_HEADERS pPE;
570 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100571 PIMAGE_THUNK_DATA pIAT; // Import Address Table
572 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100573 PIMAGE_IMPORT_BY_NAME pImpName;
574
575 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
576 return NULL;
577 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
578 if (pPE->Signature != IMAGE_NT_SIGNATURE)
579 return NULL;
580 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
581 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
582 .VirtualAddress);
583 for (; pImpDesc->FirstThunk; ++pImpDesc)
584 {
585 if (!pImpDesc->OriginalFirstThunk)
586 continue;
587 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
588 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
589 for (; pIAT->u1.Function; ++pIAT, ++pINT)
590 {
591 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
592 continue;
593 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
594 + (UINT_PTR)(pINT->u1.AddressOfData));
595 if (strcmp((char *)pImpName->Name, funcname) == 0)
596 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000597 void *original;
598 DWORD old, new = PAGE_READWRITE;
599
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100600 switch (info)
601 {
602 case 0:
603 return (void *)pIAT->u1.Function;
604 case 1:
605 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000606 case 2:
607 original = (void *)pIAT->u1.Function;
608 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
609 new, &old);
610 pIAT->u1.Function = (UINT_PTR)ptr;
611 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
612 old, &new);
613 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100614 default:
615 return NULL;
616 }
617 }
618 }
619 }
620 return NULL;
621}
622
623/*
624 * Get the module handle which 'funcname' in 'hInst' is imported from.
625 */
626 HINSTANCE
627find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
628{
629 char *modulename;
630
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000631 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100632 if (modulename != NULL)
633 return GetModuleHandleA(modulename);
634 return NULL;
635}
636
637/*
638 * Get the address of 'funcname' which is imported by 'hInst' DLL.
639 */
640 void *
641get_dll_import_func(HINSTANCE hInst, const char *funcname)
642{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000643 return get_imported_func_info(hInst, funcname, 0, NULL);
644}
645
646/*
647 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
648 * and return the original function address.
649 */
650 void *
651hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
652{
653 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100654}
655#endif
656
Bram Moolenaar071d4272004-06-13 20:20:40 +0000657#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
658# ifndef GETTEXT_DLL
659# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200660# define GETTEXT_DLL_ALT1 "libintl-8.dll"
661# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000662# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100663// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000664static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200665static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000666static char *null_libintl_textdomain(const char *);
667static char *null_libintl_bindtextdomain(const char *, const char *);
668static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100669static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000670
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200671static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000672char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200673char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
674 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000675char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
676char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000677 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000678char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
679 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100680int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000681
682 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100683dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000684{
685 int i;
686 static struct
687 {
688 char *name;
689 FARPROC *ptr;
690 } libintl_entry[] =
691 {
692 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200693 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000694 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
695 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
696 {NULL, NULL}
697 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100698 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000699
Bram Moolenaar7554c542018-10-06 15:03:15 +0200700 // No need to initialize twice.
701 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000702 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200703 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100704 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100705# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100706 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200707 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100708# endif
709# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200710 if (!hLibintlDLL)
711 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100712# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100713 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000714 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200715 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000716 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200717 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000718 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200719 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000720 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200721 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000722 }
723 for (i = 0; libintl_entry[i].name != NULL
724 && libintl_entry[i].ptr != NULL; ++i)
725 {
K.Takata54119102022-02-03 13:33:03 +0000726 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000727 libintl_entry[i].name)) == NULL)
728 {
729 dyn_libintl_end();
730 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000731 {
732 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000733 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000734 verbose_leave();
735 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000736 return 0;
737 }
738 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000739
Bram Moolenaar0f873732019-12-05 20:28:46 +0100740 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100741 dyn_libintl_bind_textdomain_codeset = (char *(*)(const char *, const char *))
742 GetProcAddress(hLibintlDLL, "bind_textdomain_codeset");
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000743 if (dyn_libintl_bind_textdomain_codeset == NULL)
744 dyn_libintl_bind_textdomain_codeset =
745 null_libintl_bind_textdomain_codeset;
746
Bram Moolenaar0f873732019-12-05 20:28:46 +0100747 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100748 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
749 if (hmsvcrt != NULL)
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100750 dyn_libintl_wputenv = (int (*)(const wchar_t *))
751 GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100752 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
753 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100754
Bram Moolenaar071d4272004-06-13 20:20:40 +0000755 return 1;
756}
757
758 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100759dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000760{
761 if (hLibintlDLL)
762 FreeLibrary(hLibintlDLL);
763 hLibintlDLL = NULL;
764 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200765 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000766 dyn_libintl_textdomain = null_libintl_textdomain;
767 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000768 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100769 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000770}
771
772 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000773null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000774{
775 return (char*)msgid;
776}
777
778 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200779null_libintl_ngettext(
780 const char *msgid,
781 const char *msgid_plural,
782 unsigned long n)
783{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200784 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200785}
786
Bram Moolenaaree695f72016-08-03 22:08:45 +0200787 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100788null_libintl_bindtextdomain(
789 const char *domainname UNUSED,
790 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000791{
792 return NULL;
793}
794
795 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100796null_libintl_bind_textdomain_codeset(
797 const char *domainname UNUSED,
798 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000799{
800 return NULL;
801}
802
803 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100804null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000805{
806 return NULL;
807}
808
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200809 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100810null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100811{
812 return 0;
813}
814
Bram Moolenaar0f873732019-12-05 20:28:46 +0100815#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000816
Bram Moolenaar0f873732019-12-05 20:28:46 +0100817// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000818
819#ifndef VER_PLATFORM_WIN32_WINDOWS
820# define VER_PLATFORM_WIN32_WINDOWS 1
821#endif
822
Bram Moolenaar071d4272004-06-13 20:20:40 +0000823#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100824# ifndef PROTO
825# include <aclapi.h>
826# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200827# ifndef PROTECTED_DACL_SECURITY_INFORMATION
828# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
829# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000830#endif
831
Bram Moolenaar27515922013-06-29 15:36:26 +0200832#ifdef HAVE_ACL
833/*
834 * Enables or disables the specified privilege.
835 */
836 static BOOL
837win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
838{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100839 BOOL bResult;
840 LUID luid;
841 HANDLE hToken;
842 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200843
844 if (!OpenProcessToken(GetCurrentProcess(),
845 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
846 return FALSE;
847
848 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
849 {
850 CloseHandle(hToken);
851 return FALSE;
852 }
853
Bram Moolenaar45500912014-07-09 20:51:07 +0200854 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200855 tokenPrivileges.Privileges[0].Luid = luid;
856 tokenPrivileges.Privileges[0].Attributes = bEnable ?
857 SE_PRIVILEGE_ENABLED : 0;
858
859 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
860 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
861
862 CloseHandle(hToken);
863
864 return bResult && GetLastError() == ERROR_SUCCESS;
865}
866#endif
867
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100868#ifdef _MSC_VER
869// Suppress the deprecation warning for using GetVersionEx().
870// It is needed for implementing "windowsversion()".
871# pragma warning(push)
872# pragma warning(disable: 4996)
873#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000874/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200875 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000876 */
877 void
878PlatformId(void)
879{
880 static int done = FALSE;
881
882 if (!done)
883 {
884 OSVERSIONINFO ovi;
885
886 ovi.dwOSVersionInfoSize = sizeof(ovi);
887 GetVersionEx(&ovi);
888
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200889#ifdef FEAT_EVAL
Bram Moolenaar0c1e3742019-12-27 13:49:24 +0100890 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
891 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200892#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100893 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
894 || ovi.dwMajorVersion > 6)
895 win8_or_later = TRUE;
896
Christopher Plewright1140b512022-11-12 18:46:05 +0000897 if ((ovi.dwMajorVersion == 10 && ovi.dwBuildNumber >= 22000)
898 || ovi.dwMajorVersion > 10)
899 win11_or_later = TRUE;
900
Bram Moolenaar071d4272004-06-13 20:20:40 +0000901#ifdef HAVE_ACL
Bram Moolenaar0f873732019-12-05 20:28:46 +0100902 // Enable privilege for getting or setting SACLs.
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200903 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000904#endif
905 done = TRUE;
906 }
907}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100908#ifdef _MSC_VER
909# pragma warning(pop)
910#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000911
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200912#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000913
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100914# define SHIFT (SHIFT_PRESSED)
915# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
916# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
917# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000918
919
Bram Moolenaar0f873732019-12-05 20:28:46 +0100920// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
921// We map function keys to their ANSI terminal equivalents, as produced
922// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
923// ANSI key with a value >= '\300' is nonstandard, but provided anyway
924// so that the user can have access to all SHIFT-, CTRL-, and ALT-
925// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000926
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000927static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000928{
929 WORD wVirtKey;
930 BOOL fAnsiKey;
931 int chAlone;
932 int chShift;
933 int chCtrl;
934 int chAlt;
935} VirtKeyMap[] =
936{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200937// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000938 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
939
940 { VK_F1, TRUE, ';', 'T', '^', 'h', },
941 { VK_F2, TRUE, '<', 'U', '_', 'i', },
942 { VK_F3, TRUE, '=', 'V', '`', 'j', },
943 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
944 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
945 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
946 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
947 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
948 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
949 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200950 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
951 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000952
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200953 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
954 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
955 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
956 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
957 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
958 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
959 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
960 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
961 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
962 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100963 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000964
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200965 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000966
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100967# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200968 // Most people don't have F13-F20, but what the hell...
969 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
970 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
971 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
972 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
973 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
974 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
975 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
976 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100977# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200978 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
979 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
980 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
981 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000982
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200983 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
984 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
985 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
986 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
987 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
988 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
989 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
990 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
991 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
992 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100993 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000994};
995
996
Bram Moolenaar0f873732019-12-05 20:28:46 +0100997/*
998 * The return code indicates key code size.
999 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001000 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001001win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001002 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001003{
1004 UINT uMods = pker->dwControlKeyState;
1005 static int s_iIsDead = 0;
1006 static WORD awAnsiCode[2];
1007 static BYTE abKeystate[256];
1008
1009
1010 if (s_iIsDead == 2)
1011 {
K.Takata972db232022-02-04 10:45:38 +00001012 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001013 s_iIsDead = 0;
1014 return 1;
1015 }
1016
K.Takata972db232022-02-04 10:45:38 +00001017 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001018 return 1;
1019
Bram Moolenaara80faa82020-04-12 19:37:17 +02001020 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001021
Bram Moolenaar0f873732019-12-05 20:28:46 +01001022 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001023 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001024
1025 if (uMods & SHIFT_PRESSED)
1026 abKeystate[VK_SHIFT] = 0x80;
1027 if (uMods & CAPSLOCK_ON)
1028 abKeystate[VK_CAPITAL] = 1;
1029
1030 if ((uMods & ALT_GR) == ALT_GR)
1031 {
1032 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1033 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1034 }
1035
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001036 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1037 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001038
1039 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001040 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001041
1042 return s_iIsDead;
1043}
1044
Bram Moolenaar071d4272004-06-13 20:20:40 +00001045static BOOL g_fJustGotFocus = FALSE;
1046
1047/*
1048 * Decode a KEY_EVENT into one or two keystrokes
1049 */
1050 static BOOL
1051decode_key_event(
1052 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001053 WCHAR *pch,
1054 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001055 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001056 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001057{
1058 int i;
1059 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1060
1061 *pch = *pch2 = NUL;
1062 g_fJustGotFocus = FALSE;
1063
Bram Moolenaar0f873732019-12-05 20:28:46 +01001064 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001065 if (!pker->bKeyDown)
1066 return FALSE;
1067
Bram Moolenaar0f873732019-12-05 20:28:46 +01001068 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001069 switch (pker->wVirtualKeyCode)
1070 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001071 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001072 case VK_SHIFT:
1073 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001074 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001075 return FALSE;
1076
1077 default:
1078 break;
1079 }
1080
Bram Moolenaar0f873732019-12-05 20:28:46 +01001081 // special cases
K.Takata972db232022-02-04 10:45:38 +00001082 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0
1083 && pker->uChar.UnicodeChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001084 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001085 // Ctrl-6 is Ctrl-^
Bram Moolenaar071d4272004-06-13 20:20:40 +00001086 if (pker->wVirtualKeyCode == '6')
1087 {
1088 *pch = Ctrl_HAT;
1089 return TRUE;
1090 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001091 // Ctrl-2 is Ctrl-@
Bram Moolenaar071d4272004-06-13 20:20:40 +00001092 else if (pker->wVirtualKeyCode == '2')
1093 {
1094 *pch = NUL;
1095 return TRUE;
1096 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001097 // Ctrl-- is Ctrl-_
Bram Moolenaar071d4272004-06-13 20:20:40 +00001098 else if (pker->wVirtualKeyCode == 0xBD)
1099 {
1100 *pch = Ctrl__;
1101 return TRUE;
1102 }
1103 }
1104
Bram Moolenaar0f873732019-12-05 20:28:46 +01001105 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001106 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1107 {
1108 *pch = K_NUL;
1109 *pch2 = '\017';
1110 return TRUE;
1111 }
1112
K.Takataeeec2542021-06-02 13:28:16 +02001113 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001114 {
1115 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1116 {
1117 if (nModifs == 0)
1118 *pch = VirtKeyMap[i].chAlone;
1119 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1120 *pch = VirtKeyMap[i].chShift;
1121 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1122 *pch = VirtKeyMap[i].chCtrl;
1123 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1124 *pch = VirtKeyMap[i].chAlt;
1125
1126 if (*pch != 0)
1127 {
1128 if (VirtKeyMap[i].fAnsiKey)
1129 {
1130 *pch2 = *pch;
1131 *pch = K_NUL;
1132 }
1133
1134 return TRUE;
1135 }
1136 }
1137 }
1138
1139 i = win32_kbd_patch_key(pker);
1140
1141 if (i < 0)
1142 *pch = NUL;
1143 else
1144 {
K.Takata972db232022-02-04 10:45:38 +00001145 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001146
1147 if (pmodifiers != NULL)
1148 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001149 // Pass on the ALT key as a modifier, but only when not combined
1150 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001151 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1152 *pmodifiers |= MOD_MASK_ALT;
1153
Bram Moolenaar0f873732019-12-05 20:28:46 +01001154 // Pass on SHIFT only for special keys, because we don't know when
1155 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001156 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1157 *pmodifiers |= MOD_MASK_SHIFT;
1158
Bram Moolenaar0f873732019-12-05 20:28:46 +01001159 // Pass on CTRL only for non-special keys, because we don't know
1160 // when it's already included with the character. And not when
1161 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001162 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1163 && *pch >= 0x20 && *pch < 0x80)
1164 *pmodifiers |= MOD_MASK_CTRL;
1165 }
1166 }
1167
1168 return (*pch != NUL);
1169}
1170
Bram Moolenaar0f873732019-12-05 20:28:46 +01001171#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001172
1173
Bram Moolenaar071d4272004-06-13 20:20:40 +00001174/*
1175 * For the GUI the mouse handling is in gui_w32.c.
1176 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001177#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001178 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001179mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001180{
1181}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001182#else
Bram Moolenaar0f873732019-12-05 20:28:46 +01001183static int g_fMouseAvail = FALSE; // mouse present
1184static int g_fMouseActive = FALSE; // mouse enabled
1185static int g_nMouseClick = -1; // mouse status
1186static int g_xMouse; // mouse x coordinate
1187static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001188static DWORD g_cmodein = 0; // Original console input mode
1189static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001190
1191/*
1192 * Enable or disable mouse input
1193 */
1194 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001195mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001196{
1197 DWORD cmodein;
1198
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001199# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001200 if (gui.in_use)
1201 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001202# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001203 if (!g_fMouseAvail)
1204 return;
1205
1206 g_fMouseActive = on;
1207 GetConsoleMode(g_hConIn, &cmodein);
1208
1209 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001210 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001211 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001212 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1213 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001214 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001215 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001216 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001217 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1218 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001219
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001220 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001221}
1222
Bram Moolenaar157d8132018-03-06 17:09:20 +01001223
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001224# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001225/*
1226 * Called when 'balloonevalterm' changed.
1227 */
1228 void
1229mch_bevalterm_changed(void)
1230{
1231 mch_setmouse(g_fMouseActive);
1232}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001233# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001234
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{
Christopher Plewright2a46f812022-10-16 19:47:45 +01001259 int horizontal = (pmer->dwEventFlags == MOUSE_HWHEELED);
1260 int zDelta = pmer->dwButtonState;
1261
1262 g_xMouse = pmer->dwMousePosition.X;
1263 g_yMouse = pmer->dwMousePosition.Y;
1264
K.Takata161b6ac2022-11-14 15:31:07 +00001265# ifdef FEAT_PROP_POPUP
Christopher Plewright605d02a2022-10-19 11:54:46 +01001266 int lcol = g_xMouse;
1267 int lrow = g_yMouse;
Christopher Plewright38804d62022-11-09 23:55:52 +00001268 win_T *wp = mouse_find_win(&lrow, &lcol, FIND_POPUP);
Christopher Plewright2a46f812022-10-16 19:47:45 +01001269 if (wp != NULL && popup_is_popup(wp))
1270 {
1271 g_nMouseClick = -1;
1272 cmdarg_T cap;
1273 oparg_T oa;
1274 CLEAR_FIELD(cap);
1275 clear_oparg(&oa);
1276 cap.oap = &oa;
1277 if (horizontal)
1278 {
1279 cap.arg = zDelta < 0 ? MSCR_LEFT : MSCR_RIGHT;
1280 cap.cmdchar = zDelta < 0 ? K_MOUSELEFT : K_MOUSERIGHT;
1281 }
1282 else
1283 {
1284 cap.cmdchar = zDelta < 0 ? K_MOUSEUP : K_MOUSEDOWN;
1285 cap.arg = zDelta < 0 ? MSCR_UP : MSCR_DOWN;
1286 }
1287
1288 // Mouse hovers over popup window, scroll it if possible.
1289 mouse_row = wp->w_winrow;
1290 mouse_col = wp->w_wincol;
1291 nv_mousescroll(&cap);
1292 update_screen(0);
1293 setcursor();
1294 out_flush();
1295 return;
1296 }
K.Takata161b6ac2022-11-14 15:31:07 +00001297# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01001298 mouse_col = g_xMouse;
1299 mouse_row = g_yMouse;
1300
1301 char_u modifiers = 0;
1302 char_u direction = 0;
1303
1304 // Decode the direction into an event that Vim can process
1305 if (horizontal)
1306 direction = zDelta >= 0 ? KE_MOUSELEFT : KE_MOUSERIGHT;
1307 else
1308 direction = zDelta >= 0 ? KE_MOUSEDOWN : KE_MOUSEUP;
1309
dundargocc57b5bc2022-11-02 13:30:51 +00001310 // Decode the win32 console key modifiers into Vim mouse modifiers.
Christopher Plewright2a46f812022-10-16 19:47:45 +01001311 if (pmer->dwControlKeyState & SHIFT_PRESSED)
Christopher Plewright605d02a2022-10-19 11:54:46 +01001312 modifiers |= MOD_MASK_SHIFT; // MOUSE_SHIFT;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001313 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
Christopher Plewright605d02a2022-10-19 11:54:46 +01001314 modifiers |= MOD_MASK_CTRL; // MOUSE_CTRL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001315 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1316 modifiers |= MOD_MASK_ALT; // MOUSE_ALT;
1317
1318 // add (bitwise or) the scroll direction and the key modifier chars
1319 // together.
1320 g_nMouseClick = ((direction << 8) | modifiers);
1321
1322 return;
1323}
1324
Bram Moolenaar071d4272004-06-13 20:20:40 +00001325/*
1326 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1327 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1328 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1329 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1330 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1331 * and we return the mouse position in g_xMouse and g_yMouse.
1332 *
1333 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1334 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1335 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1336 *
1337 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1338 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1339 *
1340 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1341 * moves, even if it stays within the same character cell. We ignore
1342 * all MOUSE_MOVED messages if the position hasn't really changed, and
1343 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1344 * we're only interested in MOUSE_DRAG).
1345 *
1346 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1347 * 2-button mouses by pressing the left & right buttons simultaneously.
1348 * In practice, it's almost impossible to click both at the same time,
1349 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1350 * in such cases, if the user is clicking quickly.
1351 */
1352 static BOOL
1353decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001354 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001355{
1356 static int s_nOldButton = -1;
1357 static int s_nOldMouseClick = -1;
1358 static int s_xOldMouse = -1;
1359 static int s_yOldMouse = -1;
1360 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001361# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001362 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001363# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001364 static int s_cClicks = 1;
1365 static BOOL s_fReleased = TRUE;
1366 static DWORD s_dwLastClickTime = 0;
1367 static BOOL s_fNextIsMiddle = FALSE;
1368
Bram Moolenaar0f873732019-12-05 20:28:46 +01001369 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001370
1371 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1372 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1373 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1374 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1375
1376 int nButton;
1377
1378 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1379 cButtons = 2;
1380
1381 if (!g_fMouseAvail || !g_fMouseActive)
1382 {
1383 g_nMouseClick = -1;
1384 return FALSE;
1385 }
1386
Bram Moolenaar0f873732019-12-05 20:28:46 +01001387 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001388 if (g_fJustGotFocus)
1389 {
1390 g_fJustGotFocus = FALSE;
1391 return FALSE;
1392 }
1393
Christopher Plewright605d02a2022-10-19 11:54:46 +01001394 // If there is an unprocessed mouse click drop this one.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001395 if (g_nMouseClick != -1)
1396 return TRUE;
Christopher Plewright605d02a2022-10-19 11:54:46 +01001397
Christopher Plewright2a46f812022-10-16 19:47:45 +01001398 if (pmer->dwEventFlags == MOUSE_WHEELED
1399 || pmer->dwEventFlags == MOUSE_HWHEELED)
1400 {
1401 decode_mouse_wheel(pmer);
1402 return TRUE; // we now should have a mouse scroll in g_nMouseClick
1403 }
Christopher Plewright605d02a2022-10-19 11:54:46 +01001404
Bram Moolenaar071d4272004-06-13 20:20:40 +00001405 nButton = -1;
1406 g_xMouse = pmer->dwMousePosition.X;
1407 g_yMouse = pmer->dwMousePosition.Y;
1408
1409 if (pmer->dwEventFlags == MOUSE_MOVED)
1410 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001411 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1412 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001413 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1414 return FALSE;
1415 }
1416
Bram Moolenaar0f873732019-12-05 20:28:46 +01001417 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001418 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1419 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001420 nButton = MOUSE_RELEASE;
1421
Bram Moolenaar0f873732019-12-05 20:28:46 +01001422 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001423 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001424 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001425# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001426 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001427 if (p_bevalterm)
1428 nButton = MOUSE_DRAG;
1429 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001430# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001431 return FALSE;
1432 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001433
Bram Moolenaar071d4272004-06-13 20:20:40 +00001434 s_fReleased = TRUE;
1435 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001436 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001437 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001438 // on a 2-button mouse, hold down left and right buttons
1439 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001440
1441 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1442 {
1443 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1444
Bram Moolenaar0f873732019-12-05 20:28:46 +01001445 // if either left or right button only is pressed, see if the
1446 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001447 if (dwLR == LEFT || dwLR == RIGHT)
1448 {
1449 for (;;)
1450 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001451 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001452 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1453 != WAIT_OBJECT_0)
1454 break;
1455 else
1456 {
1457 DWORD cRecords = 0;
1458 INPUT_RECORD ir;
1459 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1460
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001461 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001462
1463 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1464 || !(pmer2->dwButtonState & LEFT_RIGHT))
1465 break;
1466 else
1467 {
1468 if (pmer2->dwEventFlags != MOUSE_MOVED)
1469 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001470 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001471
1472 return decode_mouse_event(pmer2);
1473 }
1474 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1475 s_yOldMouse == pmer2->dwMousePosition.Y)
1476 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001477 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001478 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001479
Bram Moolenaar0f873732019-12-05 20:28:46 +01001480 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001481 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001482
1483 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1484 break;
1485 }
1486 else
1487 break;
1488 }
1489 }
1490 }
1491 }
1492 }
1493
1494 if (s_fNextIsMiddle)
1495 {
1496 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1497 ? MOUSE_DRAG : MOUSE_MIDDLE;
1498 s_fNextIsMiddle = FALSE;
1499 }
1500 else if (cButtons == 2 &&
1501 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1502 {
1503 nButton = MOUSE_MIDDLE;
1504
1505 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1506 {
1507 s_fNextIsMiddle = TRUE;
1508 nButton = MOUSE_RELEASE;
1509 }
1510 }
1511 else if ((pmer->dwButtonState & LEFT) == LEFT)
1512 nButton = MOUSE_LEFT;
1513 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1514 nButton = MOUSE_MIDDLE;
1515 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1516 nButton = MOUSE_RIGHT;
1517
1518 if (! s_fReleased && ! s_fNextIsMiddle
1519 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1520 return FALSE;
1521
1522 s_fReleased = s_fNextIsMiddle;
1523 }
1524
1525 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1526 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001527 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001528 if (nButton != -1 && nButton != MOUSE_RELEASE)
1529 {
1530 DWORD dwCurrentTime = GetTickCount();
1531
1532 if (s_xOldMouse != g_xMouse
1533 || s_yOldMouse != g_yMouse
1534 || s_nOldButton != nButton
1535 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001536# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001537 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001538# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001539 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1540 {
1541 s_cClicks = 1;
1542 }
1543 else if (++s_cClicks > 4)
1544 {
1545 s_cClicks = 1;
1546 }
1547
1548 s_dwLastClickTime = dwCurrentTime;
1549 }
1550 }
1551 else if (pmer->dwEventFlags == MOUSE_MOVED)
1552 {
1553 if (nButton != -1 && nButton != MOUSE_RELEASE)
1554 nButton = MOUSE_DRAG;
1555
1556 s_cClicks = 1;
1557 }
1558
1559 if (nButton == -1)
1560 return FALSE;
1561
1562 if (nButton != MOUSE_RELEASE)
1563 s_nOldButton = nButton;
1564
1565 g_nMouseClick = nButton;
1566
1567 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1568 g_nMouseClick |= MOUSE_SHIFT;
1569 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1570 g_nMouseClick |= MOUSE_CTRL;
1571 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1572 g_nMouseClick |= MOUSE_ALT;
1573
1574 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1575 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1576
Bram Moolenaar0f873732019-12-05 20:28:46 +01001577 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001578 if (s_xOldMouse == g_xMouse
1579 && s_yOldMouse == g_yMouse
1580 && s_nOldMouseClick == g_nMouseClick)
1581 {
1582 g_nMouseClick = -1;
1583 return FALSE;
1584 }
1585
1586 s_xOldMouse = g_xMouse;
1587 s_yOldMouse = g_yMouse;
1588 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001589# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001590 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001591# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001592 s_nOldMouseClick = g_nMouseClick;
1593
1594 return TRUE;
1595}
1596
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001597#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001598
1599
1600#ifdef MCH_CURSOR_SHAPE
1601/*
1602 * Set the shape of the cursor.
1603 * 'thickness' can be from 1 (thin) to 99 (block)
1604 */
1605 static void
1606mch_set_cursor_shape(int thickness)
1607{
Christopher Plewright38804d62022-11-09 23:55:52 +00001608 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01001609 {
1610 if (*T_CSI == NUL)
1611 {
1612 // If 't_SI' is not set, use the default cursor styles.
1613 if (thickness < 50)
1614 vtp_printf("\033[3 q"); // underline
1615 else
1616 vtp_printf("\033[0 q"); // default
1617 }
1618 }
1619 else
1620 {
1621 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1622 ConsoleCursorInfo.dwSize = thickness;
1623 ConsoleCursorInfo.bVisible = s_cursor_visible;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001624
K.Takatadf5320c2022-09-01 13:20:16 +01001625 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1626 if (s_cursor_visible)
1627 SetConsoleCursorPosition(g_hConOut, g_coord);
1628 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001629}
1630
1631 void
1632mch_update_cursor(void)
1633{
1634 int idx;
1635 int thickness;
1636
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001637# ifdef VIMDLL
1638 if (gui.in_use)
1639 return;
1640# endif
1641
Bram Moolenaar071d4272004-06-13 20:20:40 +00001642 /*
1643 * How the cursor is drawn depends on the current mode.
1644 */
1645 idx = get_shape_idx(FALSE);
1646
1647 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001648 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00001649 else
1650 thickness = shape_table[idx].percentage;
1651 mch_set_cursor_shape(thickness);
1652}
1653#endif
1654
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001655#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001656/*
1657 * Handle FOCUS_EVENT.
1658 */
1659 static void
1660handle_focus_event(INPUT_RECORD ir)
1661{
1662 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1663 ui_focus_change((int)g_fJustGotFocus);
1664}
1665
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001666static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1667
Bram Moolenaar071d4272004-06-13 20:20:40 +00001668/*
1669 * Wait until console input from keyboard or mouse is available,
1670 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001671 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001672 * Return TRUE if something is available FALSE if not.
1673 */
1674 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001675WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001676{
1677 DWORD dwNow = 0, dwEndTime = 0;
1678 INPUT_RECORD ir;
1679 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001680 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001681# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001682 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001683# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001684
1685 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001686 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001687 dwEndTime = GetTickCount() + msec;
1688 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001689 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001690 dwEndTime = INFINITE;
1691
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001692 // We need to loop until the end of the time period, because
1693 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001694 for (;;)
1695 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001696 // Only process messages when waiting.
1697 if (msec != 0)
1698 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001699# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001700 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001701# endif
1702# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001703 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001704# endif
1705# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001706 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001707# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001708 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001709
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001710 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001711# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001712 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001713# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001714 )
1715 return TRUE;
1716
1717 if (msec > 0)
1718 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001719 // If the specified wait time has passed, return. Beware that
1720 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001721 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001722 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001723 break;
1724 }
1725 if (msec != 0)
1726 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001727 DWORD dwWaitTime = dwEndTime - dwNow;
1728
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001729 // Don't wait for more than 11 msec to avoid dropping characters,
1730 // check channel while waiting for input and handle a callback from
1731 // 'balloonexpr'.
1732 if (dwWaitTime > 11)
1733 dwWaitTime = 11;
1734
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001735# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001736 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001737 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001738# endif
1739# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001740 // When waiting very briefly don't trigger timers.
1741 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001742 {
1743 long due_time;
1744
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001745 // Trigger timers and then get the time in msec until the next
1746 // one is due. Wait up to that time.
1747 due_time = check_due_timer();
1748 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001749 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001750 // timer may have used feedkeys().
1751 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001752 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001753 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1754 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001755 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001756# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001757 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001758# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001759 // Wait for either an event on the console input or a
1760 // message in the client-server window.
1761 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1762 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001763# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001764 wait_for_single_object(g_hConIn, dwWaitTime)
1765 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001766# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001767 )
1768 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001769 }
1770
1771 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001772 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001773
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001774# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02001775 // May have to redraw if the cursor ends up in the wrong place.
1776 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01001777 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001778 {
1779 CONSOLE_SCREEN_BUFFER_INFO csbi;
1780
1781 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1782 {
1783 if (csbi.dwCursorPosition.Y != msg_row)
1784 {
matveyte08795e2021-05-07 15:00:17 +02001785 // The screen is now messed up, must redraw the command
1786 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01001787 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02001788 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001789 redrawcmd();
1790 }
1791 }
1792 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001793# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001794
1795 if (cRecords > 0)
1796 {
1797 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1798 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001799# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01001800 // Windows IME sends two '\n's with only one 'ENTER'. First:
1801 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00001802 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001803 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1804 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001805 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001806 continue;
1807 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001808# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001809 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1810 NULL, FALSE))
1811 return TRUE;
1812 }
1813
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001814 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001815
1816 if (ir.EventType == FOCUS_EVENT)
1817 handle_focus_event(ir);
1818 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001819 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001820 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1821
Bram Moolenaar36698e32019-12-11 22:57:40 +01001822 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001823 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001824 if (dwSize.X != Columns || dwSize.Y != Rows)
1825 {
1826 CONSOLE_SCREEN_BUFFER_INFO csbi;
1827 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01001828 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001829 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01001830 if (dwSize.X != Columns || dwSize.Y != Rows)
1831 {
1832 ResizeConBuf(g_hConOut, dwSize);
1833 shell_resized();
1834 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001835 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001836 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001837 else if (ir.EventType == MOUSE_EVENT
1838 && decode_mouse_event(&ir.Event.MouseEvent))
1839 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001840 }
1841 else if (msec == 0)
1842 break;
1843 }
1844
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001845# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01001846 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001847 if (input_available())
1848 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001849# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001850
Bram Moolenaar071d4272004-06-13 20:20:40 +00001851 return FALSE;
1852}
1853
Bram Moolenaar071d4272004-06-13 20:20:40 +00001854/*
1855 * return non-zero if a character is available
1856 */
1857 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001858mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001859{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001860# ifdef VIMDLL
1861 if (gui.in_use)
1862 return TRUE;
1863# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001864 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001865}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001866
1867# if defined(FEAT_TERMINAL) || defined(PROTO)
1868/*
1869 * Check for any pending input or messages.
1870 */
1871 int
1872mch_check_messages(void)
1873{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001874# ifdef VIMDLL
1875 if (gui.in_use)
1876 return TRUE;
1877# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001878 return WaitForChar(0L, TRUE);
1879}
1880# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001881
1882/*
1883 * Create the console input. Used when reading stdin doesn't work.
1884 */
1885 static void
1886create_conin(void)
1887{
1888 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1889 FILE_SHARE_READ|FILE_SHARE_WRITE,
1890 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001891 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001892 did_create_conin = TRUE;
1893}
1894
1895/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001896 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001897 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001898 static WCHAR
1899tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001900{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001901 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001902
1903 for (;;)
1904 {
1905 INPUT_RECORD ir;
1906 DWORD cRecords = 0;
1907
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001908# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001909 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001910 if (input_available())
1911 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001912 if (g_nMouseClick != -1)
1913 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001914# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001915 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001916 {
1917 if (did_create_conin)
1918 read_error_exit();
1919 create_conin();
1920 continue;
1921 }
1922
1923 if (ir.EventType == KEY_EVENT)
1924 {
1925 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1926 pmodifiers, TRUE))
1927 return ch;
1928 }
1929 else if (ir.EventType == FOCUS_EVENT)
1930 handle_focus_event(ir);
1931 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1932 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001933 else if (ir.EventType == MOUSE_EVENT)
1934 {
1935 if (decode_mouse_event(&ir.Event.MouseEvent))
1936 return 0;
1937 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001938 }
1939}
Bram Moolenaar0f873732019-12-05 20:28:46 +01001940#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001941
1942
1943/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001944 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001945 * Get one or more characters from the keyboard or the mouse.
1946 * If time == 0, do not wait for characters.
1947 * If time == n, wait a short time for characters.
1948 * If time == -1, wait forever for characters.
1949 * Returns the number of characters read into buf.
1950 */
1951 int
1952mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001953 char_u *buf UNUSED,
1954 int maxlen UNUSED,
1955 long time UNUSED,
1956 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001957{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001958#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001959
1960 int len;
1961 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001962# ifdef VIMDLL
1963// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
1964# define TYPEAHEADSPACE 6
1965# else
1966# define TYPEAHEADSPACE 0
1967# endif
1968# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001969 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001970 static int typeaheadlen = 0;
1971
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001972# ifdef VIMDLL
1973 if (gui.in_use)
1974 return 0;
1975# endif
1976
Bram Moolenaar0f873732019-12-05 20:28:46 +01001977 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001978 if (typeaheadlen > 0)
1979 goto theend;
1980
Bram Moolenaar071d4272004-06-13 20:20:40 +00001981 if (time >= 0)
1982 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001983 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00001984 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001985 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001986 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00001987 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001988 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00001989
Bram Moolenaar3918c952005-03-15 22:34:55 +00001990 /*
1991 * If there is no character available within 2 seconds (default)
1992 * write the autoscript file to disk. Or cause the CursorHold event
1993 * to be triggered.
1994 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001995 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001996 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001997 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001998 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001999 buf[0] = K_SPECIAL;
2000 buf[1] = KS_EXTRA;
2001 buf[2] = (int)KE_CURSORHOLD;
2002 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002003 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00002004 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002005 }
2006 }
2007
2008 /*
2009 * Try to read as many characters as there are, until the buffer is full.
2010 */
2011
Bram Moolenaar0f873732019-12-05 20:28:46 +01002012 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002013 g_fCBrkPressed = FALSE;
2014
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002015# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002016 if (fdDump)
2017 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002018# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002019
Bram Moolenaar0f873732019-12-05 20:28:46 +01002020 // Keep looping until there is something in the typeahead buffer and more
2021 // to get and still room in the buffer (up to two bytes for a char and
2022 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002023 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01002024 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002025 {
2026 if (typebuf_changed(tb_change_cnt))
2027 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002028 // "buf" may be invalid now if a client put something in the
2029 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002030 typeaheadlen = 0;
2031 break;
2032 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002033 if (g_nMouseClick != -1)
2034 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002035# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002036 if (fdDump)
2037 fprintf(fdDump, "{%02x @ %d, %d}",
2038 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002039# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01002040 char_u modifiers = ((char_u *)(&g_nMouseClick))[0];
2041 char_u scroll_dir = ((char_u *)(&g_nMouseClick))[1];
2042
2043 if (scroll_dir == KE_MOUSEDOWN
2044 || scroll_dir == KE_MOUSEUP
2045 || scroll_dir == KE_MOUSELEFT
2046 || scroll_dir == KE_MOUSERIGHT)
2047 {
2048 if (modifiers > 0)
2049 {
Christopher Plewright03193062022-11-22 12:58:27 +00002050 // use K_SPECIAL instead of CSI to make mappings work
2051 typeahead[typeaheadlen++] = K_SPECIAL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002052 typeahead[typeaheadlen++] = KS_MODIFIER;
2053 typeahead[typeaheadlen++] = modifiers;
2054 }
2055 typeahead[typeaheadlen++] = CSI;
2056 typeahead[typeaheadlen++] = KS_EXTRA;
2057 typeahead[typeaheadlen++] = scroll_dir;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002058 }
2059 else
2060 {
2061 typeahead[typeaheadlen++] = ESC + 128;
2062 typeahead[typeaheadlen++] = 'M';
2063 typeahead[typeaheadlen++] = g_nMouseClick;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002064 }
Christopher Plewright36446bb2022-11-23 22:28:08 +00002065
2066 // Pass the pointer coordinates of the mouse event in 2 bytes,
2067 // allowing for > 223 columns. Both for click and scroll events.
2068 // This is the same as what is used for the GUI.
2069 typeahead[typeaheadlen++] = (char_u)(g_xMouse / 128 + ' ' + 1);
2070 typeahead[typeaheadlen++] = (char_u)(g_xMouse % 128 + ' ' + 1);
2071 typeahead[typeaheadlen++] = (char_u)(g_yMouse / 128 + ' ' + 1);
2072 typeahead[typeaheadlen++] = (char_u)(g_yMouse % 128 + ' ' + 1);
2073
2074 g_nMouseClick = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002075 }
2076 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002077 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002078 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002079 int modifiers = 0;
2080
2081 c = tgetch(&modifiers, &ch2);
2082
2083 if (typebuf_changed(tb_change_cnt))
2084 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002085 // "buf" may be invalid now if a client put something in the
2086 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002087 typeaheadlen = 0;
2088 break;
2089 }
2090
2091 if (c == Ctrl_C && ctrl_c_interrupts)
2092 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002093# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002094 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002095# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002096 got_int = TRUE;
2097 }
2098
Bram Moolenaar071d4272004-06-13 20:20:40 +00002099 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002100 {
2101 int n = 1;
2102
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002103 if (ch2 == NUL)
2104 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002105 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002106 char_u *p;
2107 WCHAR ch[2];
2108
2109 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002110 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002111 {
2112 ch[1] = tgetch(&modifiers, &ch2);
2113 n++;
2114 }
2115 p = utf16_to_enc(ch, &n);
2116 if (p != NULL)
2117 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002118 for (i = 0, j = 0; i < n; i++)
2119 {
2120 typeahead[typeaheadlen + j++] = p[i];
2121# ifdef VIMDLL
2122 if (p[i] == CSI)
2123 {
2124 typeahead[typeaheadlen + j++] = KS_EXTRA;
2125 typeahead[typeaheadlen + j++] = KE_CSI;
2126 }
2127# endif
2128 }
2129 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002130 vim_free(p);
2131 }
2132 }
2133 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002134 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002135 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002136# ifdef VIMDLL
2137 if (c == CSI)
2138 {
2139 typeahead[typeaheadlen + 1] = KS_EXTRA;
2140 typeahead[typeaheadlen + 2] = KE_CSI;
2141 n = 3;
2142 }
2143# endif
2144 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002145 if (ch2 != NUL)
2146 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002147 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002148 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002149 switch (ch2)
2150 {
2151 case (WCHAR)'\324': // SHIFT+Insert
2152 case (WCHAR)'\325': // CTRL+Insert
2153 case (WCHAR)'\327': // SHIFT+Delete
2154 case (WCHAR)'\330': // CTRL+Delete
2155 typeahead[typeaheadlen + n] = (char_u)ch2;
2156 n++;
2157 break;
2158
2159 default:
2160 typeahead[typeaheadlen + n] = 3;
2161 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2162 n += 2;
2163 break;
2164 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002165 }
2166 else
2167 {
2168 typeahead[typeaheadlen + n] = 3;
2169 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2170 n += 2;
2171 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002172 }
2173
Bram Moolenaar0f873732019-12-05 20:28:46 +01002174 // Use the ALT key to set the 8th bit of the character
2175 // when it's one byte, the 8th bit isn't set yet and not
2176 // using a double-byte encoding (would become a lead
2177 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002178 if ((modifiers & MOD_MASK_ALT)
2179 && n == 1
2180 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002181 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002182 )
2183 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002184 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2185 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002186 modifiers &= ~MOD_MASK_ALT;
2187 }
2188
2189 if (modifiers != 0)
2190 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002191 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002192 mch_memmove(typeahead + typeaheadlen + 3,
2193 typeahead + typeaheadlen, n);
2194 typeahead[typeaheadlen++] = K_SPECIAL;
2195 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2196 typeahead[typeaheadlen++] = modifiers;
2197 }
2198
2199 typeaheadlen += n;
2200
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002201# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002202 if (fdDump)
2203 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002204# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002205 }
2206 }
2207 }
2208
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002209# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002210 if (fdDump)
2211 {
2212 fputs("]\n", fdDump);
2213 fflush(fdDump);
2214 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002215# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002216
Bram Moolenaar071d4272004-06-13 20:20:40 +00002217theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002218 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002219 len = 0;
2220 while (len < maxlen && typeaheadlen > 0)
2221 {
2222 buf[len++] = typeahead[0];
2223 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2224 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002225# ifdef FEAT_JOB_CHANNEL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002226 if (len > 0)
2227 {
2228 buf[len] = NUL;
2229 ch_log(NULL, "raw key input: \"%s\"", buf);
2230 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002231# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002232 return len;
2233
Bram Moolenaar0f873732019-12-05 20:28:46 +01002234#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002235 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002236#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002237}
2238
Bram Moolenaar82881492012-11-20 16:53:39 +01002239#ifndef PROTO
2240# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002241# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002242# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002243#endif
2244
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002245/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002246 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002247 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2248 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002249 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002250 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002251 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002252executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002253{
LemonBoy40fd7e62022-05-05 20:18:16 +01002254 int attrs = win32_getattrs((char_u *)name);
2255
2256 // The file doesn't exist or is a folder.
2257 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2258 return FALSE;
2259 // Check if the file is an AppExecLink, a special alias used by Windows
2260 // Store for its apps.
2261 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002262 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002263 char_u *res = resolve_appexeclink((char_u *)name);
2264 if (res == NULL)
2265 return FALSE;
2266 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002267 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002268 *path = res;
2269 else
2270 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002271 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002272 else if (path != NULL)
2273 *path = FullName_save((char_u *)name, FALSE);
2274 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002275}
2276
2277/*
2278 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2279 * If "use_path" is FALSE: Return TRUE if "name" exists.
2280 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2281 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2282 * the allocated memory.
2283 */
2284 static int
2285executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2286{
2287 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2288 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2289 // UTF-8.
2290 char_u buf[_MAX_PATH * 3];
2291 size_t len = STRLEN(name);
2292 size_t tmplen;
2293 char_u *p, *e, *e2;
2294 char_u *pathbuf = NULL;
2295 char_u *pathext = NULL;
2296 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002297 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002298 int noext = FALSE;
2299 int retval = FALSE;
2300
2301 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002302 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002303
2304 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002305 shname = gettail(p_sh);
2306 if (strstr((char *)shname, "sh") != NULL &&
2307 !(strstr((char *)shname, "powershell") != NULL
2308 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002309 noext = TRUE;
2310
2311 if (use_pathext)
2312 {
2313 pathext = mch_getenv("PATHEXT");
2314 if (pathext == NULL)
2315 pathext = (char_u *)".com;.exe;.bat;.cmd";
2316
2317 if (noext == FALSE)
2318 {
2319 /*
2320 * Loop over all extensions in $PATHEXT.
2321 * Check "name" ends with extension.
2322 */
2323 p = pathext;
2324 while (*p)
2325 {
2326 if (p[0] == ';'
2327 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2328 {
2329 // Skip empty or single ".".
2330 ++p;
2331 continue;
2332 }
2333 e = vim_strchr(p, ';');
2334 if (e == NULL)
2335 e = p + STRLEN(p);
2336 tmplen = e - p;
2337
2338 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2339 {
2340 noext = TRUE;
2341 break;
2342 }
2343
2344 p = e;
2345 }
2346 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002347 }
2348
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002349 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002350 if (pathext == NULL)
2351 pathext = (char_u *)".";
2352 else if (noext == TRUE)
2353 {
2354 if (pathextbuf == NULL)
2355 pathextbuf = alloc(STRLEN(pathext) + 3);
2356 if (pathextbuf == NULL)
2357 {
2358 retval = FALSE;
2359 goto theend;
2360 }
2361 STRCPY(pathextbuf, ".;");
2362 STRCAT(pathextbuf, pathext);
2363 pathext = pathextbuf;
2364 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002365
Bram Moolenaar95da1362020-05-30 18:37:55 +02002366 // Use $PATH when "use_path" is TRUE and "name" is basename.
2367 if (use_path && gettail((char_u *)name) == (char_u *)name)
2368 {
2369 p = mch_getenv("PATH");
2370 if (p != NULL)
2371 {
2372 pathbuf = alloc(STRLEN(p) + 3);
2373 if (pathbuf == NULL)
2374 {
2375 retval = FALSE;
2376 goto theend;
2377 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002378
2379 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2380 STRCPY(pathbuf, ".;");
2381 else
2382 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002383 STRCAT(pathbuf, p);
2384 }
2385 }
2386
2387 /*
2388 * Walk through all entries in $PATH to check if "name" exists there and
2389 * is an executable file.
2390 */
2391 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2392 while (*p)
2393 {
2394 if (*p == ';') // Skip empty entry
2395 {
2396 ++p;
2397 continue;
2398 }
2399 e = vim_strchr(p, ';');
2400 if (e == NULL)
2401 e = p + STRLEN(p);
2402
2403 if (e - p + len + 2 > sizeof(buf))
2404 {
2405 retval = FALSE;
2406 goto theend;
2407 }
2408 // A single "." that means current dir.
2409 if (e - p == 1 && *p == '.')
2410 STRCPY(buf, name);
2411 else
2412 {
2413 vim_strncpy(buf, p, e - p);
2414 add_pathsep(buf);
2415 STRCAT(buf, name);
2416 }
2417 tmplen = STRLEN(buf);
2418
2419 /*
2420 * Loop over all extensions in $PATHEXT.
2421 * Check "name" with extension added.
2422 */
2423 p = pathext;
2424 while (*p)
2425 {
2426 if (*p == ';')
2427 {
2428 // Skip empty entry
2429 ++p;
2430 continue;
2431 }
2432 e2 = vim_strchr(p, (int)';');
2433 if (e2 == NULL)
2434 e2 = p + STRLEN(p);
2435
2436 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2437 {
2438 // Not a single "." that means no extension is added.
2439 if (e2 - p + tmplen + 1 > sizeof(buf))
2440 {
2441 retval = FALSE;
2442 goto theend;
2443 }
2444 vim_strncpy(buf + tmplen, p, e2 - p);
2445 }
2446 if (executable_file((char *)buf, path))
2447 {
2448 retval = TRUE;
2449 goto theend;
2450 }
2451
2452 p = e2;
2453 }
2454
2455 p = e;
2456 }
2457
2458theend:
2459 free(pathextbuf);
2460 free(pathbuf);
2461 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002462}
2463
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002464#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2465 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002466/*
2467 * Bad parameter handler.
2468 *
2469 * Certain MS CRT functions will intentionally crash when passed invalid
2470 * parameters to highlight possible security holes. Setting this function as
2471 * the bad parameter handler will prevent the crash.
2472 *
2473 * In debug builds the parameters contain CRT information that might help track
2474 * down the source of a problem, but in non-debug builds the arguments are all
2475 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2476 * worth allowing these to make debugging of issues easier.
2477 */
2478 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002479bad_param_handler(const wchar_t *expression UNUSED,
2480 const wchar_t *function UNUSED,
2481 const wchar_t *file UNUSED,
2482 unsigned int line UNUSED,
2483 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002484{
2485}
2486
2487# define SET_INVALID_PARAM_HANDLER \
2488 ((void)_set_invalid_parameter_handler(bad_param_handler))
2489#else
2490# define SET_INVALID_PARAM_HANDLER
2491#endif
2492
Bram Moolenaar4f974752019-02-17 17:44:42 +01002493#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002494
2495/*
2496 * GUI version of mch_init().
2497 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002498 static void
2499mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002500{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002501# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002502 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002503# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002504
Bram Moolenaar0f873732019-12-05 20:28:46 +01002505 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002506 SET_INVALID_PARAM_HANDLER;
2507
Bram Moolenaar0f873732019-12-05 20:28:46 +01002508 // Let critical errors result in a failure, not in a dialog box. Required
2509 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002510 SetErrorMode(SEM_FAILCRITICALERRORS);
2511
Bram Moolenaar0f873732019-12-05 20:28:46 +01002512 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002513
Bram Moolenaar0f873732019-12-05 20:28:46 +01002514 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002515 Rows = 25;
2516 Columns = 80;
2517
Bram Moolenaar0f873732019-12-05 20:28:46 +01002518 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519 {
2520 char_u vimrun_location[_MAX_PATH + 4];
2521
Bram Moolenaar0f873732019-12-05 20:28:46 +01002522 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002523 STRCPY(vimrun_location, exe_name);
2524 STRCPY(gettail(vimrun_location), "vimrun.exe");
2525 if (mch_getperm(vimrun_location) >= 0)
2526 {
2527 if (*skiptowhite(vimrun_location) != NUL)
2528 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002529 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002530 mch_memmove(vimrun_location + 1, vimrun_location,
2531 STRLEN(vimrun_location) + 1);
2532 *vimrun_location = '"';
2533 STRCPY(gettail(vimrun_location), "vimrun\" ");
2534 }
2535 else
2536 STRCPY(gettail(vimrun_location), "vimrun ");
2537
2538 vimrun_path = (char *)vim_strsave(vimrun_location);
2539 s_dont_use_vimrun = FALSE;
2540 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002541 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002542 s_dont_use_vimrun = FALSE;
2543
Bram Moolenaar0f873732019-12-05 20:28:46 +01002544 // Don't give the warning for a missing vimrun.exe right now, but only
2545 // when vimrun was supposed to be used. Don't bother people that do
2546 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002547 if (s_dont_use_vimrun)
2548 need_vimrun_warning = TRUE;
2549 }
2550
2551 /*
2552 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2553 * Otherwise the default "findstr /n" is used.
2554 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002555 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01002556 set_option_value_give_err((char_u *)"grepprg",
2557 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002558
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002559# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002560 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002561# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002562
2563 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002564}
2565
2566
Bram Moolenaar0f873732019-12-05 20:28:46 +01002567#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002568
2569#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002570
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002571# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2572# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002573
2574/*
2575 * ClearConsoleBuffer()
2576 * Description:
2577 * Clears the entire contents of the console screen buffer, using the
2578 * specified attribute.
2579 * Returns:
2580 * TRUE on success
2581 */
2582 static BOOL
2583ClearConsoleBuffer(WORD wAttribute)
2584{
2585 CONSOLE_SCREEN_BUFFER_INFO csbi;
2586 COORD coord;
2587 DWORD NumCells, dummy;
2588
2589 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2590 return FALSE;
2591
2592 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2593 coord.X = 0;
2594 coord.Y = 0;
2595 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2596 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002597 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002598 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2599 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002600 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002601
2602 return TRUE;
2603}
2604
2605/*
2606 * FitConsoleWindow()
2607 * Description:
2608 * Checks if the console window will fit within given buffer dimensions.
2609 * Also, if requested, will shrink the window to fit.
2610 * Returns:
2611 * TRUE on success
2612 */
2613 static BOOL
2614FitConsoleWindow(
2615 COORD dwBufferSize,
2616 BOOL WantAdjust)
2617{
2618 CONSOLE_SCREEN_BUFFER_INFO csbi;
2619 COORD dwWindowSize;
2620 BOOL NeedAdjust = FALSE;
2621
2622 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2623 {
2624 /*
2625 * A buffer resize will fail if the current console window does
2626 * not lie completely within that buffer. To avoid this, we might
2627 * have to move and possibly shrink the window.
2628 */
2629 if (csbi.srWindow.Right >= dwBufferSize.X)
2630 {
2631 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2632 if (dwWindowSize.X > dwBufferSize.X)
2633 dwWindowSize.X = dwBufferSize.X;
2634 csbi.srWindow.Right = dwBufferSize.X - 1;
2635 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2636 NeedAdjust = TRUE;
2637 }
2638 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2639 {
2640 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2641 if (dwWindowSize.Y > dwBufferSize.Y)
2642 dwWindowSize.Y = dwBufferSize.Y;
2643 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2644 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2645 NeedAdjust = TRUE;
2646 }
2647 if (NeedAdjust && WantAdjust)
2648 {
2649 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2650 return FALSE;
2651 }
2652 return TRUE;
2653 }
2654
2655 return FALSE;
2656}
2657
2658typedef struct ConsoleBufferStruct
2659{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002660 BOOL IsValid;
2661 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002662 PCHAR_INFO Buffer;
2663 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002664 PSMALL_RECT Regions;
2665 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002666} ConsoleBuffer;
2667
2668/*
2669 * SaveConsoleBuffer()
2670 * Description:
2671 * Saves important information about the console buffer, including the
2672 * actual buffer contents. The saved information is suitable for later
2673 * restoration by RestoreConsoleBuffer().
2674 * Returns:
2675 * TRUE if all information was saved; FALSE otherwise
2676 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2677 */
2678 static BOOL
2679SaveConsoleBuffer(
2680 ConsoleBuffer *cb)
2681{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002682 DWORD NumCells;
2683 COORD BufferCoord;
2684 SMALL_RECT ReadRegion;
2685 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002686 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002687
Bram Moolenaar071d4272004-06-13 20:20:40 +00002688 if (cb == NULL)
2689 return FALSE;
2690
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002691 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002692 {
2693 cb->IsValid = FALSE;
2694 return FALSE;
2695 }
2696 cb->IsValid = TRUE;
2697
Christopher Plewright1140b512022-11-12 18:46:05 +00002698 // VTP uses alternate screen buffer.
2699 // No need to save buffer contents for restoration.
2700 if (win11_or_later && vtp_working)
2701 return TRUE;
2702
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002703 /*
2704 * Allocate a buffer large enough to hold the entire console screen
2705 * buffer. If this ConsoleBuffer structure has already been initialized
2706 * with a buffer of the correct size, then just use that one.
2707 */
2708 if (!cb->IsValid || cb->Buffer == NULL ||
2709 cb->BufferSize.X != cb->Info.dwSize.X ||
2710 cb->BufferSize.Y != cb->Info.dwSize.Y)
2711 {
2712 cb->BufferSize.X = cb->Info.dwSize.X;
2713 cb->BufferSize.Y = cb->Info.dwSize.Y;
2714 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2715 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002716 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002717 if (cb->Buffer == NULL)
2718 return FALSE;
2719 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002720
2721 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002722 * We will now copy the console screen buffer into our buffer.
2723 * ReadConsoleOutput() seems to be limited as far as how much you
2724 * can read at a time. Empirically, this number seems to be about
2725 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2726 * in chunks until it is all copied. The chunks will all have the
2727 * same horizontal characteristics, so initialize them now. The
2728 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002729 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002730 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002731 ReadRegion.Left = 0;
2732 ReadRegion.Right = cb->Info.dwSize.X - 1;
2733 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002734
2735 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2736 if (cb->Regions == NULL || numregions != cb->NumRegions)
2737 {
2738 cb->NumRegions = numregions;
2739 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002740 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002741 if (cb->Regions == NULL)
2742 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002743 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002744 return FALSE;
2745 }
2746 }
2747
2748 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002749 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002750 /*
2751 * Read into position (0, Y) in our buffer.
2752 */
2753 BufferCoord.Y = Y;
2754 /*
2755 * Read the region whose top left corner is (0, Y) and whose bottom
2756 * right corner is (width - 1, Y + Y_incr - 1). This should define
2757 * a region of size width by Y_incr. Don't worry if this region is
2758 * too large for the remaining buffer; it will be cropped.
2759 */
2760 ReadRegion.Top = Y;
2761 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002762 if (!ReadConsoleOutputW(g_hConOut, // output handle
2763 cb->Buffer, // our buffer
2764 cb->BufferSize, // dimensions of our buffer
2765 BufferCoord, // offset in our buffer
2766 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002767 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002768 VIM_CLEAR(cb->Buffer);
2769 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002770 return FALSE;
2771 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002772 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002773 }
2774
2775 return TRUE;
2776}
2777
2778/*
2779 * RestoreConsoleBuffer()
2780 * Description:
2781 * Restores important information about the console buffer, including the
2782 * actual buffer contents, if desired. The information to restore is in
2783 * the same format used by SaveConsoleBuffer().
2784 * Returns:
2785 * TRUE on success
2786 */
2787 static BOOL
2788RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002789 ConsoleBuffer *cb,
2790 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002791{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002792 COORD BufferCoord;
2793 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002794 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002795
Christopher Plewright1140b512022-11-12 18:46:05 +00002796 // VTP uses alternate screen buffer.
2797 // No need to restore buffer contents.
2798 if (win11_or_later && vtp_working)
2799 return TRUE;
2800
Bram Moolenaar071d4272004-06-13 20:20:40 +00002801 if (cb == NULL || !cb->IsValid)
2802 return FALSE;
2803
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002804 /*
2805 * Before restoring the buffer contents, clear the current buffer, and
2806 * restore the cursor position and window information. Doing this now
2807 * prevents old buffer contents from "flashing" onto the screen.
2808 */
2809 if (RestoreScreen)
2810 ClearConsoleBuffer(cb->Info.wAttributes);
2811
2812 FitConsoleWindow(cb->Info.dwSize, TRUE);
2813 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2814 return FALSE;
2815 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2816 return FALSE;
2817
2818 if (!RestoreScreen)
2819 {
2820 /*
2821 * No need to restore the screen buffer contents, so we're done.
2822 */
2823 return TRUE;
2824 }
2825
2826 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2827 return FALSE;
2828 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2829 return FALSE;
2830
2831 /*
2832 * Restore the screen buffer contents.
2833 */
2834 if (cb->Buffer != NULL)
2835 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002836 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002837 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002838 BufferCoord.X = cb->Regions[i].Left;
2839 BufferCoord.Y = cb->Regions[i].Top;
2840 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01002841 if (!WriteConsoleOutputW(g_hConOut, // output handle
2842 cb->Buffer, // our buffer
2843 cb->BufferSize, // dimensions of our buffer
2844 BufferCoord, // offset in our buffer
2845 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02002846 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002847 }
2848 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002849
2850 return TRUE;
2851}
2852
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002853# define FEAT_RESTORE_ORIG_SCREEN
2854# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002855static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002856# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002857static ConsoleBuffer g_cbNonTermcap = { 0 };
2858static ConsoleBuffer g_cbTermcap = { 0 };
2859
Bram Moolenaar071d4272004-06-13 20:20:40 +00002860char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01002861HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00002862static HICON g_hOrigIconSmall = NULL;
2863static HICON g_hOrigIcon = NULL;
2864static HICON g_hVimIcon = NULL;
2865static BOOL g_fCanChangeIcon = FALSE;
2866
Bram Moolenaar071d4272004-06-13 20:20:40 +00002867/*
2868 * GetConsoleIcon()
2869 * Description:
2870 * Attempts to retrieve the small icon and/or the big icon currently in
2871 * use by a given window.
2872 * Returns:
2873 * TRUE on success
2874 */
2875 static BOOL
2876GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002877 HWND hWnd,
2878 HICON *phIconSmall,
2879 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002880{
2881 if (hWnd == NULL)
2882 return FALSE;
2883
2884 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002885 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2886 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002887 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002888 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2889 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002890 return TRUE;
2891}
2892
2893/*
2894 * SetConsoleIcon()
2895 * Description:
2896 * Attempts to change the small icon and/or the big icon currently in
2897 * use by a given window.
2898 * Returns:
2899 * TRUE on success
2900 */
2901 static BOOL
2902SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002903 HWND hWnd,
2904 HICON hIconSmall,
2905 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002906{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002907 if (hWnd == NULL)
2908 return FALSE;
2909
2910 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002911 SendMessage(hWnd, WM_SETICON,
2912 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002913 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002914 SendMessage(hWnd, WM_SETICON,
2915 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002916 return TRUE;
2917}
2918
2919/*
2920 * SaveConsoleTitleAndIcon()
2921 * Description:
2922 * Saves the current console window title in g_szOrigTitle, for later
2923 * restoration. Also, attempts to obtain a handle to the console window,
2924 * and use it to save the small and big icons currently in use by the
2925 * console window. This is not always possible on some versions of Windows;
2926 * nor is it possible when running Vim remotely using Telnet (since the
2927 * console window the user sees is owned by a remote process).
2928 */
2929 static void
2930SaveConsoleTitleAndIcon(void)
2931{
Bram Moolenaar0f873732019-12-05 20:28:46 +01002932 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002933 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2934 return;
2935
2936 /*
2937 * Obtain a handle to the console window using GetConsoleWindow() from
2938 * KERNEL32.DLL; we need to handle in order to change the window icon.
2939 * This function only exists on NT-based Windows, starting with Windows
2940 * 2000. On older operating systems, we can't change the window icon
2941 * anyway.
2942 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002943 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002944 if (g_hWnd == NULL)
2945 return;
2946
Bram Moolenaar0f873732019-12-05 20:28:46 +01002947 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002948 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2949 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2950 return;
2951
Bram Moolenaar0f873732019-12-05 20:28:46 +01002952 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01002953 if (
2954# ifdef FEAT_LIBCALL
2955 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
2956# endif
2957 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002958 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002959 if (g_hVimIcon != NULL)
2960 g_fCanChangeIcon = TRUE;
2961}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002962
2963static int g_fWindInitCalled = FALSE;
2964static int g_fTermcapMode = FALSE;
2965static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002966
2967/*
2968 * non-GUI version of mch_init().
2969 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002970 static void
2971mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002972{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002973# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002974 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002975# endif
2976# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002977 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002978# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002979
Bram Moolenaar0f873732019-12-05 20:28:46 +01002980 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002981 SET_INVALID_PARAM_HANDLER;
2982
Bram Moolenaar0f873732019-12-05 20:28:46 +01002983 // Let critical errors result in a failure, not in a dialog box. Required
2984 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002985 SetErrorMode(SEM_FAILCRITICALERRORS);
2986
Bram Moolenaar0f873732019-12-05 20:28:46 +01002987 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002988 out_flush();
2989
Bram Moolenaar0f873732019-12-05 20:28:46 +01002990 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00002991 if (read_cmd_fd == 0)
2992 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2993 else
2994 create_conin();
2995 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2996
Christopher Plewright38804d62022-11-09 23:55:52 +00002997 wt_init();
2998 vtp_flag_init();
2999 vtp_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003000# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01003001 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003002 SaveConsoleBuffer(&g_cbOrig);
3003 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003004# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01003005 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003006 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
3007 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003008# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003009 if (cterm_normal_fg_color == 0)
3010 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
3011 if (cterm_normal_bg_color == 0)
3012 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
3013
Bram Moolenaarbdace832019-03-02 10:13:42 +01003014 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02003015 g_color_index_fg = g_attrDefault & 0xf;
3016 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
3017
Bram Moolenaar0f873732019-12-05 20:28:46 +01003018 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00003019 update_tcap(g_attrCurrent);
3020
3021 GetConsoleCursorInfo(g_hConOut, &g_cci);
3022 GetConsoleMode(g_hConIn, &g_cmodein);
3023 GetConsoleMode(g_hConOut, &g_cmodeout);
3024
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025 SaveConsoleTitleAndIcon();
3026 /*
3027 * Set both the small and big icons of the console window to Vim's icon.
3028 * Note that Vim presently only has one size of icon (32x32), but it
3029 * automatically gets scaled down to 16x16 when setting the small icon.
3030 */
3031 if (g_fCanChangeIcon)
3032 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003033
3034 ui_get_shellsize();
3035
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003036# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003037 fdDump = fopen("dump", "wt");
3038
3039 if (fdDump)
3040 {
3041 time_t t;
3042
3043 time(&t);
3044 fputs(ctime(&t), fdDump);
3045 fflush(fdDump);
3046 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003047# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048
3049 g_fWindInitCalled = TRUE;
3050
Bram Moolenaar071d4272004-06-13 20:20:40 +00003051 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003052
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003053# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003054 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003055# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003056}
3057
3058/*
3059 * non-GUI version of mch_exit().
3060 * Shut down and exit with status `r'
3061 * Careful: mch_exit() may be called before mch_init()!
3062 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003063 static void
3064mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003065{
Bram Moolenaar955f1982017-02-05 15:10:51 +01003066 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003067
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003068 vtp_exit();
3069
Bram Moolenaar955f1982017-02-05 15:10:51 +01003070 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003071 if (g_fWindInitCalled)
3072 settmode(TMODE_COOK);
3073
Bram Moolenaar0f873732019-12-05 20:28:46 +01003074 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00003075
3076 if (g_fWindInitCalled)
3077 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02003078 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003079 /*
3080 * Restore both the small and big icons of the console window to
3081 * what they were at startup. Don't do this when the window is
3082 * closed, Vim would hang here.
3083 */
3084 if (g_fCanChangeIcon && !g_fForceExit)
3085 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003086
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003087# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003088 if (fdDump)
3089 {
3090 time_t t;
3091
3092 time(&t);
3093 fputs(ctime(&t), fdDump);
3094 fclose(fdDump);
3095 }
3096 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003097# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003098 }
3099
3100 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003101 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003102 SetConsoleMode(g_hConOut, g_cmodeout);
3103
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003104# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003105 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003106# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003107
3108 exit(r);
3109}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003110#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003111
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003112 void
3113mch_init(void)
3114{
3115#ifdef VIMDLL
3116 if (gui.starting)
3117 mch_init_g();
3118 else
3119 mch_init_c();
3120#elif defined(FEAT_GUI_MSWIN)
3121 mch_init_g();
3122#else
3123 mch_init_c();
3124#endif
3125}
3126
3127 void
3128mch_exit(int r)
3129{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003130#ifdef FEAT_NETBEANS_INTG
3131 netbeans_send_disconnect();
3132#endif
3133
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003134#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003135 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003136 mch_exit_g(r);
3137 else
3138 mch_exit_c(r);
3139#elif defined(FEAT_GUI_MSWIN)
3140 mch_exit_g(r);
3141#else
3142 mch_exit_c(r);
3143#endif
3144}
3145
Bram Moolenaar071d4272004-06-13 20:20:40 +00003146/*
3147 * Do we have an interactive window?
3148 */
3149 int
3150mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003151 int argc UNUSED,
3152 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003153{
3154 get_exe_name();
3155
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003156#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003157 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003158#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003159# ifdef VIMDLL
3160 if (gui.in_use)
3161 return OK;
3162# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003163 if (isatty(1))
3164 return OK;
3165 return FAIL;
3166#endif
3167}
3168
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003169/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003170 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003171 * When "len" is > 0, also expand short to long filenames.
3172 */
3173 void
3174fname_case(
3175 char_u *name,
3176 int len)
3177{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003178 int flen;
3179 WCHAR *p;
3180 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003181
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003182 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003183 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003184 return;
3185
3186 slash_adjust(name);
3187
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003188 p = enc_to_utf16(name, NULL);
3189 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003190 return;
3191
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003192 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003193 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003194 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003195
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003196 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003197 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003198 if (len > 0 || flen >= (int)STRLEN(q))
3199 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3200 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003201 }
3202 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003203 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003204}
3205
3206
3207/*
3208 * Insert user name in s[len].
3209 */
3210 int
3211mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003212 char_u *s,
3213 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003214{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003215 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003216 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003217
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003218 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003219 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003220 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003221
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003222 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003223 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003224 vim_strncpy(s, p, len - 1);
3225 vim_free(p);
3226 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003227 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003228 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003229 s[0] = NUL;
3230 return FAIL;
3231}
3232
3233
3234/*
3235 * Insert host name in s[len].
3236 */
3237 void
3238mch_get_host_name(
3239 char_u *s,
3240 int len)
3241{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003242 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003243 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003244
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003245 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003246 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003247 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003248
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003249 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003250 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003251 vim_strncpy(s, p, len - 1);
3252 vim_free(p);
3253 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003254 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003255 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003256}
3257
3258
3259/*
3260 * return process ID
3261 */
3262 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003263mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003264{
3265 return (long)GetCurrentProcessId();
3266}
3267
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003268/*
3269 * return TRUE if process "pid" is still running
3270 */
3271 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003272mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003273{
3274 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3275 DWORD status = 0;
3276 int ret = FALSE;
3277
3278 if (hProcess == NULL)
3279 return FALSE; // might not have access
3280 if (GetExitCodeProcess(hProcess, &status) )
3281 ret = status == STILL_ACTIVE;
3282 CloseHandle(hProcess);
3283 return ret;
3284}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003285
3286/*
3287 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3288 * Return OK for success, FAIL for failure.
3289 */
3290 int
3291mch_dirname(
3292 char_u *buf,
3293 int len)
3294{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003295 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003296
Bram Moolenaar071d4272004-06-13 20:20:40 +00003297 /*
3298 * Originally this was:
3299 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3300 * But the Win32s known bug list says that getcwd() doesn't work
3301 * so use the Win32 system call instead. <Negri>
3302 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003303 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003304 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003305 WCHAR wcbuf[_MAX_PATH + 1];
3306 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003307
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003308 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003309 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003310 p = utf16_to_enc(wcbuf, NULL);
3311 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003312 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003313 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003314 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003315 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003316 }
3317 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003318 if (p == NULL)
3319 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003320
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003321 if (p != NULL)
3322 {
3323 vim_strncpy(buf, p, len - 1);
3324 vim_free(p);
3325 return OK;
3326 }
3327 }
3328 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003329}
3330
3331/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003332 * Get file permissions for "name".
3333 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003334 */
3335 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003336mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003337{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003338 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003339 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003340
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003341 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003342 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003343}
3344
3345
3346/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003347 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003348 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003349 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003350 */
3351 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003352mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003353{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003354 long n;
3355 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003356
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003357 p = enc_to_utf16(name, NULL);
3358 if (p == NULL)
3359 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003360
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003361 n = _wchmod(p, perm);
3362 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003363 if (n == -1)
3364 return FAIL;
3365
3366 win32_set_archive(name);
3367
3368 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003369}
3370
3371/*
3372 * Set hidden flag for "name".
3373 */
3374 void
3375mch_hide(char_u *name)
3376{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003377 int attrs = win32_getattrs(name);
3378 if (attrs == -1)
3379 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003380
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003381 attrs |= FILE_ATTRIBUTE_HIDDEN;
3382 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003383}
3384
3385/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003386 * Return TRUE if file "name" exists and is hidden.
3387 */
3388 int
3389mch_ishidden(char_u *name)
3390{
3391 int f = win32_getattrs(name);
3392
3393 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003394 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003395
3396 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3397}
3398
3399/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003400 * return TRUE if "name" is a directory
3401 * return FALSE if "name" is not a directory or upon error
3402 */
3403 int
3404mch_isdir(char_u *name)
3405{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003406 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003407
3408 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003409 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003410
3411 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3412}
3413
3414/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003415 * return TRUE if "name" is a directory, NOT a symlink to a directory
3416 * return FALSE if "name" is not a directory
3417 * return FALSE for error
3418 */
3419 int
3420mch_isrealdir(char_u *name)
3421{
3422 return mch_isdir(name) && !mch_is_symbolic_link(name);
3423}
3424
3425/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003426 * Create directory "name".
3427 * Return 0 on success, -1 on error.
3428 */
3429 int
3430mch_mkdir(char_u *name)
3431{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003432 WCHAR *p;
3433 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003434
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003435 p = enc_to_utf16(name, NULL);
3436 if (p == NULL)
3437 return -1;
3438 retval = _wmkdir(p);
3439 vim_free(p);
3440 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003441}
3442
3443/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003444 * Delete directory "name".
3445 * Return 0 on success, -1 on error.
3446 */
3447 int
3448mch_rmdir(char_u *name)
3449{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003450 WCHAR *p;
3451 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003452
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003453 p = enc_to_utf16(name, NULL);
3454 if (p == NULL)
3455 return -1;
3456 retval = _wrmdir(p);
3457 vim_free(p);
3458 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003459}
3460
3461/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003462 * Return TRUE if file "fname" has more than one link.
3463 */
3464 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003465mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003466{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003467 BY_HANDLE_FILE_INFORMATION info;
3468
3469 return win32_fileinfo(fname, &info) == FILEINFO_OK
3470 && info.nNumberOfLinks > 1;
3471}
3472
3473/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003474 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003475 */
3476 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003477mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003478{
3479 HANDLE hFind;
3480 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003481 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003482 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003483 WIN32_FIND_DATAW findDataW;
3484
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003485 wn = enc_to_utf16(name, NULL);
3486 if (wn == NULL)
3487 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003488
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003489 hFind = FindFirstFileW(wn, &findDataW);
3490 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003491 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003492 {
3493 fileFlags = findDataW.dwFileAttributes;
3494 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003495 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003496 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003497
3498 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003499 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3500 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003501 res = TRUE;
3502
3503 return res;
3504}
3505
3506/*
3507 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3508 * link.
3509 */
3510 int
3511mch_is_linked(char_u *fname)
3512{
3513 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3514 return TRUE;
3515 return FALSE;
3516}
3517
3518/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003519 * Get the by-handle-file-information for "fname".
3520 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003521 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003522 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3523 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3524 */
3525 int
3526win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3527{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003528 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003529 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003530 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003531
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003532 wn = enc_to_utf16(fname, NULL);
3533 if (wn == NULL)
3534 return FILEINFO_ENC_FAIL;
3535
3536 hFile = CreateFileW(wn, // file name
3537 GENERIC_READ, // access mode
3538 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3539 NULL, // security descriptor
3540 OPEN_EXISTING, // creation disposition
3541 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3542 NULL); // handle to template file
3543 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003544
3545 if (hFile != INVALID_HANDLE_VALUE)
3546 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003547 if (GetFileInformationByHandle(hFile, info) != 0)
3548 res = FILEINFO_OK;
3549 else
3550 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003551 CloseHandle(hFile);
3552 }
3553
Bram Moolenaar03f48552006-02-28 23:52:23 +00003554 return res;
3555}
3556
3557/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003558 * get file attributes for `name'
3559 * -1 : error
3560 * else FILE_ATTRIBUTE_* defined in winnt.h
3561 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003562 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003563win32_getattrs(char_u *name)
3564{
3565 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003566 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003567
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003568 p = enc_to_utf16(name, NULL);
3569 if (p == NULL)
3570 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003571
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003572 attr = GetFileAttributesW(p);
3573 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003574
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003575 return attr;
3576}
3577
3578/*
3579 * set file attributes for `name' to `attrs'
3580 *
3581 * return -1 for failure, 0 otherwise
3582 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003583 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003584win32_setattrs(char_u *name, int attrs)
3585{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003586 int res;
3587 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003588
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003589 p = enc_to_utf16(name, NULL);
3590 if (p == NULL)
3591 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003592
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003593 res = SetFileAttributesW(p, attrs);
3594 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003595
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003596 return res ? 0 : -1;
3597}
3598
3599/*
3600 * Set archive flag for "name".
3601 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003602 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003603win32_set_archive(char_u *name)
3604{
3605 int attrs = win32_getattrs(name);
3606 if (attrs == -1)
3607 return -1;
3608
3609 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3610 return win32_setattrs(name, attrs);
3611}
3612
3613/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003614 * Return TRUE if file or directory "name" is writable (not readonly).
3615 * Strange semantics of Win32: a readonly directory is writable, but you can't
3616 * delete a file. Let's say this means it is writable.
3617 */
3618 int
3619mch_writable(char_u *name)
3620{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003621 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003622
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003623 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3624 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003625}
3626
Bram Moolenaar071d4272004-06-13 20:20:40 +00003627/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003628 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003629 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003630 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3631 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003632 */
3633 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01003634mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003635{
Bram Moolenaar95da1362020-05-30 18:37:55 +02003636 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003637}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003638
3639/*
3640 * Check what "name" is:
3641 * NODE_NORMAL: file or directory (or doesn't exist)
3642 * NODE_WRITABLE: writable device, socket, fifo, etc.
3643 * NODE_OTHER: non-writable things
3644 */
3645 int
3646mch_nodetype(char_u *name)
3647{
3648 HANDLE hFile;
3649 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003650 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003651
Bram Moolenaar0f873732019-12-05 20:28:46 +01003652 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3653 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3654 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00003655 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3656 return NODE_WRITABLE;
3657
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003658 wn = enc_to_utf16(name, NULL);
3659 if (wn == NULL)
3660 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003661
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003662 hFile = CreateFileW(wn, // file name
3663 GENERIC_WRITE, // access mode
3664 0, // share mode
3665 NULL, // security descriptor
3666 OPEN_EXISTING, // creation disposition
3667 0, // file attributes
3668 NULL); // handle to template file
3669 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003670 if (hFile == INVALID_HANDLE_VALUE)
3671 return NODE_NORMAL;
3672
3673 type = GetFileType(hFile);
3674 CloseHandle(hFile);
3675 if (type == FILE_TYPE_CHAR)
3676 return NODE_WRITABLE;
3677 if (type == FILE_TYPE_DISK)
3678 return NODE_NORMAL;
3679 return NODE_OTHER;
3680}
3681
3682#ifdef HAVE_ACL
3683struct my_acl
3684{
3685 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3686 PSID pSidOwner;
3687 PSID pSidGroup;
3688 PACL pDacl;
3689 PACL pSacl;
3690};
3691#endif
3692
3693/*
3694 * Return a pointer to the ACL of file "fname" in allocated memory.
3695 * Return NULL if the ACL is not available for whatever reason.
3696 */
3697 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003698mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003699{
3700#ifndef HAVE_ACL
3701 return (vim_acl_T)NULL;
3702#else
3703 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003704 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003705
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003706 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003707 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003708 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003709 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003710
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003711 wn = enc_to_utf16(fname, NULL);
3712 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003713 {
3714 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003715 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003716 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003717
3718 // Try to retrieve the entire security descriptor.
3719 err = GetNamedSecurityInfoW(
3720 wn, // Abstract filename
3721 SE_FILE_OBJECT, // File Object
3722 OWNER_SECURITY_INFORMATION |
3723 GROUP_SECURITY_INFORMATION |
3724 DACL_SECURITY_INFORMATION |
3725 SACL_SECURITY_INFORMATION,
3726 &p->pSidOwner, // Ownership information.
3727 &p->pSidGroup, // Group membership.
3728 &p->pDacl, // Discretionary information.
3729 &p->pSacl, // For auditing purposes.
3730 &p->pSecurityDescriptor);
3731 if (err == ERROR_ACCESS_DENIED ||
3732 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003733 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003734 // Retrieve only DACL.
3735 (void)GetNamedSecurityInfoW(
3736 wn,
3737 SE_FILE_OBJECT,
3738 DACL_SECURITY_INFORMATION,
3739 NULL,
3740 NULL,
3741 &p->pDacl,
3742 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003743 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003744 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003745 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003746 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003747 mch_free_acl((vim_acl_T)p);
3748 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003749 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003750 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003751 }
3752
3753 return (vim_acl_T)p;
3754#endif
3755}
3756
Bram Moolenaar27515922013-06-29 15:36:26 +02003757#ifdef HAVE_ACL
3758/*
3759 * Check if "acl" contains inherited ACE.
3760 */
3761 static BOOL
3762is_acl_inherited(PACL acl)
3763{
3764 DWORD i;
3765 ACL_SIZE_INFORMATION acl_info;
3766 PACCESS_ALLOWED_ACE ace;
3767
3768 acl_info.AceCount = 0;
3769 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3770 for (i = 0; i < acl_info.AceCount; i++)
3771 {
3772 GetAce(acl, i, (LPVOID *)&ace);
3773 if (ace->Header.AceFlags & INHERITED_ACE)
3774 return TRUE;
3775 }
3776 return FALSE;
3777}
3778#endif
3779
Bram Moolenaar071d4272004-06-13 20:20:40 +00003780/*
3781 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3782 * Errors are ignored.
3783 * This must only be called with "acl" equal to what mch_get_acl() returned.
3784 */
3785 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003786mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003787{
3788#ifdef HAVE_ACL
3789 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003790 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003791 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003792
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003793 if (p == NULL)
3794 return;
3795
3796 wn = enc_to_utf16(fname, NULL);
3797 if (wn == NULL)
3798 return;
3799
3800 // Set security flags
3801 if (p->pSidOwner)
3802 sec_info |= OWNER_SECURITY_INFORMATION;
3803 if (p->pSidGroup)
3804 sec_info |= GROUP_SECURITY_INFORMATION;
3805 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003806 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003807 sec_info |= DACL_SECURITY_INFORMATION;
3808 // Do not inherit its parent's DACL.
3809 // If the DACL is inherited, Cygwin permissions would be changed.
3810 if (!is_acl_inherited(p->pDacl))
3811 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003812 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003813 if (p->pSacl)
3814 sec_info |= SACL_SECURITY_INFORMATION;
3815
3816 (void)SetNamedSecurityInfoW(
3817 wn, // Abstract filename
3818 SE_FILE_OBJECT, // File Object
3819 sec_info,
3820 p->pSidOwner, // Ownership information.
3821 p->pSidGroup, // Group membership.
3822 p->pDacl, // Discretionary information.
3823 p->pSacl // For auditing purposes.
3824 );
3825 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003826#endif
3827}
3828
3829 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003830mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003831{
3832#ifdef HAVE_ACL
3833 struct my_acl *p = (struct my_acl *)acl;
3834
3835 if (p != NULL)
3836 {
3837 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3838 vim_free(p);
3839 }
3840#endif
3841}
3842
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003843#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003844
3845/*
3846 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3847 */
3848 static BOOL WINAPI
3849handler_routine(
3850 DWORD dwCtrlType)
3851{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003852 INPUT_RECORD ir;
3853 DWORD out;
3854
Bram Moolenaar071d4272004-06-13 20:20:40 +00003855 switch (dwCtrlType)
3856 {
3857 case CTRL_C_EVENT:
3858 if (ctrl_c_interrupts)
3859 g_fCtrlCPressed = TRUE;
3860 return TRUE;
3861
3862 case CTRL_BREAK_EVENT:
3863 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003864 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003865 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02003866 ir.EventType = KEY_EVENT;
3867 ir.Event.KeyEvent.bKeyDown = TRUE;
3868 ir.Event.KeyEvent.wRepeatCount = 1;
3869 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3870 ir.Event.KeyEvent.wVirtualScanCode = 0;
3871 ir.Event.KeyEvent.dwControlKeyState = 0;
3872 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3873 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003874 return TRUE;
3875
Bram Moolenaar0f873732019-12-05 20:28:46 +01003876 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00003877 case CTRL_CLOSE_EVENT:
3878 case CTRL_LOGOFF_EVENT:
3879 case CTRL_SHUTDOWN_EVENT:
3880 windgoto((int)Rows - 1, 0);
3881 g_fForceExit = TRUE;
3882
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003883 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003884 (dwCtrlType == CTRL_CLOSE_EVENT
3885 ? _("close")
3886 : dwCtrlType == CTRL_LOGOFF_EVENT
3887 ? _("logoff")
3888 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003889# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00003890 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003891# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003892
Bram Moolenaar0f873732019-12-05 20:28:46 +01003893 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00003894
Bram Moolenaar0f873732019-12-05 20:28:46 +01003895 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00003896
3897 default:
3898 return FALSE;
3899 }
3900}
3901
3902
3903/*
3904 * set the tty in (raw) ? "raw" : "cooked" mode
3905 */
3906 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02003907mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003908{
3909 DWORD cmodein;
3910 DWORD cmodeout;
3911 BOOL bEnableHandler;
3912
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003913# ifdef VIMDLL
3914 if (gui.in_use)
3915 return;
3916# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003917 GetConsoleMode(g_hConIn, &cmodein);
3918 GetConsoleMode(g_hConOut, &cmodeout);
3919 if (tmode == TMODE_RAW)
3920 {
3921 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3922 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003923 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003924 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003925 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003926 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
3927 }
3928 else
3929 {
3930 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
3931 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003932 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003933# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01003934 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
3935 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003936 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003937# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003938 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003939# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003940 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003941 bEnableHandler = TRUE;
3942 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01003943 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00003944 {
3945 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3946 ENABLE_ECHO_INPUT);
3947 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3948 bEnableHandler = FALSE;
3949 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003950 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003951 SetConsoleMode(g_hConOut, cmodeout);
3952 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3953
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003954# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003955 if (fdDump)
3956 {
3957 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3958 tmode == TMODE_RAW ? "raw" :
3959 tmode == TMODE_COOK ? "cooked" : "normal",
3960 cmodein, cmodeout);
3961 fflush(fdDump);
3962 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003963# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003964}
3965
3966
3967/*
3968 * Get the size of the current window in `Rows' and `Columns'
3969 * Return OK when size could be determined, FAIL otherwise.
3970 */
3971 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003972mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003973{
3974 CONSOLE_SCREEN_BUFFER_INFO csbi;
3975
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003976# ifdef VIMDLL
3977 if (gui.in_use)
3978 return OK;
3979# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003980 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3981 {
3982 /*
3983 * For some reason, we are trying to get the screen dimensions
3984 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3985 * variables are really intended to mean the size of Vim screen
3986 * while in termcap mode.
3987 */
3988 Rows = g_cbTermcap.Info.dwSize.Y;
3989 Columns = g_cbTermcap.Info.dwSize.X;
3990 }
3991 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3992 {
3993 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3994 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3995 }
3996 else
3997 {
3998 Rows = 25;
3999 Columns = 80;
4000 }
4001 return OK;
4002}
4003
4004/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004005 * Resize console buffer to 'COORD'
4006 */
4007 static void
4008ResizeConBuf(
4009 HANDLE hConsole,
4010 COORD coordScreen)
4011{
4012 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4013 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004014# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004015 if (fdDump)
4016 {
4017 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4018 GetLastError());
4019 fflush(fdDump);
4020 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004021# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004022 }
4023}
4024
4025/*
4026 * Resize console window size to 'srWindowRect'
4027 */
4028 static void
4029ResizeWindow(
4030 HANDLE hConsole,
4031 SMALL_RECT srWindowRect)
4032{
4033 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4034 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004035# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004036 if (fdDump)
4037 {
4038 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4039 GetLastError());
4040 fflush(fdDump);
4041 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004042# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004043 }
4044}
4045
4046/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004047 * Set a console window to `xSize' * `ySize'
4048 */
4049 static void
4050ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004051 HANDLE hConsole,
4052 int xSize,
4053 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004054{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004055 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
4056 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004057 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004058 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004059 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004060
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004061# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004062 if (fdDump)
4063 {
4064 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4065 fflush(fdDump);
4066 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004067# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004068
Bram Moolenaar0f873732019-12-05 20:28:46 +01004069 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00004070 coordScreen = GetLargestConsoleWindowSize(hConsole);
4071
Bram Moolenaar0f873732019-12-05 20:28:46 +01004072 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00004073 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4074 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4075 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4076
4077 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4078 {
4079 int sx, sy;
4080
4081 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4082 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4083 if (sy < ySize || sx < xSize)
4084 {
4085 /*
4086 * Increasing number of lines/columns, do buffer first.
4087 * Use the maximal size in x and y direction.
4088 */
4089 if (sy < ySize)
4090 coordScreen.Y = ySize;
4091 else
4092 coordScreen.Y = sy;
4093 if (sx < xSize)
4094 coordScreen.X = xSize;
4095 else
4096 coordScreen.X = sx;
4097 SetConsoleScreenBufferSize(hConsole, coordScreen);
4098 }
4099 }
4100
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004101 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004102 coordScreen.X = xSize;
4103 coordScreen.Y = ySize;
4104
Bram Moolenaar2551c032018-08-23 22:38:31 +02004105 // In the new console call API, only the first time in reverse order
4106 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004107 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004108 ResizeWindow(hConsole, srWindowRect);
4109 ResizeConBuf(hConsole, coordScreen);
4110 }
4111 else
4112 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004113 // Workaround for a Windows 10 bug
4114 cursor.X = srWindowRect.Left;
4115 cursor.Y = srWindowRect.Top;
4116 SetConsoleCursorPosition(hConsole, cursor);
4117
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004118 ResizeConBuf(hConsole, coordScreen);
4119 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004120 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004121 }
4122}
4123
4124
4125/*
4126 * Set the console window to `Rows' * `Columns'
4127 */
4128 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004129mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004130{
4131 COORD coordScreen;
4132
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004133# ifdef VIMDLL
4134 if (gui.in_use)
4135 return;
4136# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004137 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004138 if (suppress_winsize != 0)
4139 {
4140 suppress_winsize = 2;
4141 return;
4142 }
4143
4144 if (term_console)
4145 {
4146 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4147
Bram Moolenaar0f873732019-12-05 20:28:46 +01004148 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004149 if (Rows > coordScreen.Y)
4150 Rows = coordScreen.Y;
4151 if (Columns > coordScreen.X)
4152 Columns = coordScreen.X;
4153
4154 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4155 }
4156}
4157
4158/*
4159 * Rows and/or Columns has changed.
4160 */
4161 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004162mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004163{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004164# ifdef VIMDLL
4165 if (gui.in_use)
4166 return;
4167# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004168 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4169}
4170
4171
4172/*
4173 * Called when started up, to set the winsize that was delayed.
4174 */
4175 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004176mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004177{
4178 if (suppress_winsize == 2)
4179 {
4180 suppress_winsize = 0;
4181 mch_set_shellsize();
4182 shell_resized();
4183 }
4184 suppress_winsize = 0;
4185}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004186#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004187
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004188 static BOOL
4189vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004190 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004191 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004192 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004193 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004194 PROCESS_INFORMATION *pi,
4195 LPVOID *env,
4196 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004197{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004198 BOOL ret = FALSE;
4199 WCHAR *wcmd, *wcwd = NULL;
4200
4201 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4202 if (wcmd == NULL)
4203 return FALSE;
4204 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004205 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004206 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4207 if (wcwd == NULL)
4208 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004209 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004210
4211 ret = CreateProcessW(
4212 NULL, // Executable name
4213 wcmd, // Command to execute
4214 NULL, // Process security attributes
4215 NULL, // Thread security attributes
4216 inherit_handles, // Inherit handles
4217 flags, // Creation flags
4218 env, // Environment
4219 wcwd, // Current directory
4220 (LPSTARTUPINFOW)si, // Startup information
4221 pi); // Process information
4222theend:
4223 vim_free(wcmd);
4224 vim_free(wcwd);
4225 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004226}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004227
4228
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004229 static HINSTANCE
4230vim_shell_execute(
4231 char *cmd,
4232 INT n_show_cmd)
4233{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004234 HINSTANCE ret;
4235 WCHAR *wcmd;
4236
4237 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4238 if (wcmd == NULL)
4239 return (HINSTANCE) 0;
4240
4241 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4242 vim_free(wcmd);
4243 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004244}
4245
4246
Bram Moolenaar4f974752019-02-17 17:44:42 +01004247#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004248
4249/*
4250 * Specialised version of system() for Win32 GUI mode.
4251 * This version proceeds as follows:
4252 * 1. Create a console window for use by the subprocess
4253 * 2. Run the subprocess (it gets the allocated console by default)
4254 * 3. Wait for the subprocess to terminate and get its exit code
4255 * 4. Prompt the user to press a key to close the console window
4256 */
4257 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004258mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004259{
4260 STARTUPINFO si;
4261 PROCESS_INFORMATION pi;
4262 DWORD ret = 0;
4263 HWND hwnd = GetFocus();
4264
4265 si.cb = sizeof(si);
4266 si.lpReserved = NULL;
4267 si.lpDesktop = NULL;
4268 si.lpTitle = NULL;
4269 si.dwFlags = STARTF_USESHOWWINDOW;
4270 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004271 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004272 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004273 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004274 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004275 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004276 else
4277 si.wShowWindow = SW_SHOWNORMAL;
4278 si.cbReserved2 = 0;
4279 si.lpReserved2 = NULL;
4280
Bram Moolenaar0f873732019-12-05 20:28:46 +01004281 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004282 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004283 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4284 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004285
Bram Moolenaar0f873732019-12-05 20:28:46 +01004286 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004287 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004288# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004289 int delay = 1;
4290
Bram Moolenaar0f873732019-12-05 20:28:46 +01004291 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004292 for (;;)
4293 {
4294 MSG msg;
4295
K.Takatab7057bd2022-01-21 11:37:07 +00004296 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004297 {
4298 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004299 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004300 delay = 1;
4301 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004302 }
4303 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4304 break;
4305
Bram Moolenaar0f873732019-12-05 20:28:46 +01004306 // We start waiting for a very short time and then increase it, so
4307 // that we respond quickly when the process is quick, and don't
4308 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004309 if (delay < 50)
4310 delay += 10;
4311 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004312# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004313 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004314# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004315
Bram Moolenaar0f873732019-12-05 20:28:46 +01004316 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004317 GetExitCodeProcess(pi.hProcess, &ret);
4318 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004319
Bram Moolenaar0f873732019-12-05 20:28:46 +01004320 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004321 CloseHandle(pi.hThread);
4322 CloseHandle(pi.hProcess);
4323
Bram Moolenaar0f873732019-12-05 20:28:46 +01004324 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004325 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4326
4327 return ret;
4328}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004329
4330/*
4331 * Thread launched by the gui to send the current buffer data to the
4332 * process. This way avoid to hang up vim totally if the children
4333 * process take a long time to process the lines.
4334 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004335 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004336sub_process_writer(LPVOID param)
4337{
4338 HANDLE g_hChildStd_IN_Wr = param;
4339 linenr_T lnum = curbuf->b_op_start.lnum;
4340 DWORD len = 0;
4341 DWORD l;
4342 char_u *lp = ml_get(lnum);
4343 char_u *s;
4344 int written = 0;
4345
4346 for (;;)
4347 {
4348 l = (DWORD)STRLEN(lp + written);
4349 if (l == 0)
4350 len = 0;
4351 else if (lp[written] == NL)
4352 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004353 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004354 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4355 }
4356 else
4357 {
4358 s = vim_strchr(lp + written, NL);
4359 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4360 s == NULL ? l : (DWORD)(s - (lp + written)),
4361 &len, NULL);
4362 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004363 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004364 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004365 // Finished a line, add a NL, unless this line should not have
4366 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004367 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004368 || (!curbuf->b_p_bin
4369 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004370 || (lnum != curbuf->b_no_eol_lnum
4371 && (lnum != curbuf->b_ml.ml_line_count
4372 || curbuf->b_p_eol)))
4373 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004374 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4375 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004376 }
4377
4378 ++lnum;
4379 if (lnum > curbuf->b_op_end.lnum)
4380 break;
4381
4382 lp = ml_get(lnum);
4383 written = 0;
4384 }
4385 else if (len > 0)
4386 written += len;
4387 }
4388
Bram Moolenaar0f873732019-12-05 20:28:46 +01004389 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004390 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004391 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004392}
4393
4394
Bram Moolenaar0f873732019-12-05 20:28:46 +01004395# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004396
4397/*
4398 * This function read from the children's stdout and write the
4399 * data on screen or in the buffer accordingly.
4400 */
4401 static void
4402dump_pipe(int options,
4403 HANDLE g_hChildStd_OUT_Rd,
4404 garray_T *ga,
4405 char_u buffer[],
4406 DWORD *buffer_off)
4407{
4408 DWORD availableBytes = 0;
4409 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004410 int ret;
4411 DWORD len;
4412 DWORD toRead;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004413
Bram Moolenaar0f873732019-12-05 20:28:46 +01004414 // we query the pipe to see if there is any data to read
4415 // to avoid to perform a blocking read
4416 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4417 NULL, // optional buffer
4418 0, // buffer size
4419 NULL, // number of read bytes
4420 &availableBytes, // available bytes total
4421 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004422
Bram Moolenaar0f873732019-12-05 20:28:46 +01004423 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004424 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004425 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01004426 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004427 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004428 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004429
Bram Moolenaar0f873732019-12-05 20:28:46 +01004430 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004431 if (len == 0)
4432 break;
4433
4434 availableBytes -= len;
4435
4436 if (options & SHELL_READ)
4437 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004438 // Do NUL -> NL translation, append NL separated
4439 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004440 for (i = 0; i < len; ++i)
4441 {
4442 if (buffer[i] == NL)
4443 append_ga_line(ga);
4444 else if (buffer[i] == NUL)
4445 ga_append(ga, NL);
4446 else
4447 ga_append(ga, buffer[i]);
4448 }
4449 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004450 else if (has_mbyte)
4451 {
4452 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004453 int c;
4454 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004455
4456 len += *buffer_off;
4457 buffer[len] = NUL;
4458
Bram Moolenaar0f873732019-12-05 20:28:46 +01004459 // Check if the last character in buffer[] is
4460 // incomplete, keep these bytes for the next
4461 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004462 for (p = buffer; p < buffer + len; p += l)
4463 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004464 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004465 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004466 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004467 else if (MB_BYTE2LEN(*p) != l)
4468 break;
4469 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004470 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004471 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004472 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004473 if (len >= 12)
4474 ++p;
4475 else
4476 {
4477 *buffer_off = len;
4478 return;
4479 }
4480 }
4481 c = *p;
4482 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004483 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004484 if (p < buffer + len)
4485 {
4486 *p = c;
4487 *buffer_off = (DWORD)((buffer + len) - p);
4488 mch_memmove(buffer, p, *buffer_off);
4489 return;
4490 }
4491 *buffer_off = 0;
4492 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004493 else
4494 {
4495 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004496 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004497 }
4498
4499 windgoto(msg_row, msg_col);
4500 cursor_on();
4501 out_flush();
4502 }
4503}
4504
4505/*
4506 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4507 * for communication and doesn't open any new window.
4508 */
4509 static int
4510mch_system_piped(char *cmd, int options)
4511{
4512 STARTUPINFO si;
4513 PROCESS_INFORMATION pi;
4514 DWORD ret = 0;
4515
4516 HANDLE g_hChildStd_IN_Rd = NULL;
4517 HANDLE g_hChildStd_IN_Wr = NULL;
4518 HANDLE g_hChildStd_OUT_Rd = NULL;
4519 HANDLE g_hChildStd_OUT_Wr = NULL;
4520
Bram Moolenaar0f873732019-12-05 20:28:46 +01004521 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004522 DWORD len;
4523
Bram Moolenaar0f873732019-12-05 20:28:46 +01004524 // buffer used to receive keys
4525 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4526 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004527
4528 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004529 int noread_cnt = 0;
4530 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004531 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004532 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004533 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004534
4535 SECURITY_ATTRIBUTES saAttr;
4536
Bram Moolenaar0f873732019-12-05 20:28:46 +01004537 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004538 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4539 saAttr.bInheritHandle = TRUE;
4540 saAttr.lpSecurityDescriptor = NULL;
4541
4542 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004543 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004544 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004545 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004546 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004547 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004548 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004549 {
4550 CloseHandle(g_hChildStd_IN_Rd);
4551 CloseHandle(g_hChildStd_IN_Wr);
4552 CloseHandle(g_hChildStd_OUT_Rd);
4553 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004554 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004555 }
4556
4557 si.cb = sizeof(si);
4558 si.lpReserved = NULL;
4559 si.lpDesktop = NULL;
4560 si.lpTitle = NULL;
4561 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4562
Bram Moolenaar0f873732019-12-05 20:28:46 +01004563 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004564 si.hStdError = g_hChildStd_OUT_Wr;
4565 si.hStdOutput = g_hChildStd_OUT_Wr;
4566 si.hStdInput = g_hChildStd_IN_Rd;
4567 si.wShowWindow = SW_HIDE;
4568 si.cbReserved2 = 0;
4569 si.lpReserved2 = NULL;
4570
4571 if (options & SHELL_READ)
4572 ga_init2(&ga, 1, BUFLEN);
4573
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004574 if (cmd != NULL)
4575 {
4576 p = (char *)vim_strsave((char_u *)cmd);
4577 if (p != NULL)
4578 unescape_shellxquote((char_u *)p, p_sxe);
4579 else
4580 p = cmd;
4581 }
4582
Bram Moolenaar0f873732019-12-05 20:28:46 +01004583 // Now, run the command.
4584 // About "Inherit handles" being TRUE: this command can be litigious,
4585 // handle inheritance was deactivated for pending temp file, but, if we
4586 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004587 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4588 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004589
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004590 if (p != cmd)
4591 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004592
Bram Moolenaar0f873732019-12-05 20:28:46 +01004593 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004594 CloseHandle(g_hChildStd_IN_Rd);
4595 CloseHandle(g_hChildStd_OUT_Wr);
4596
4597 if (options & SHELL_WRITE)
4598 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004599 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004600 _beginthreadex(NULL, // security attributes
4601 0, // default stack size
4602 sub_process_writer, // function to be executed
4603 g_hChildStd_IN_Wr, // parameter
4604 0, // creation flag, start immediately
4605 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004606 CloseHandle(thread);
4607 g_hChildStd_IN_Wr = NULL;
4608 }
4609
Bram Moolenaar0f873732019-12-05 20:28:46 +01004610 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004611 for (;;)
4612 {
4613 MSG msg;
4614
K.Takatab7057bd2022-01-21 11:37:07 +00004615 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004616 {
4617 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004618 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004619 }
4620
Bram Moolenaar0f873732019-12-05 20:28:46 +01004621 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004622 if ((options & (SHELL_READ|SHELL_WRITE))
4623# ifdef FEAT_GUI
4624 || gui.in_use
4625# endif
4626 )
4627 {
4628 len = 0;
4629 if (!(options & SHELL_EXPAND)
4630 && ((options &
4631 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4632 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4633# ifdef FEAT_GUI
4634 || gui.in_use
4635# endif
4636 )
4637 && (ta_len > 0 || noread_cnt > 4))
4638 {
4639 if (ta_len == 0)
4640 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004641 // Get extra characters when we don't have any. Reset the
4642 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004643 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004644 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4645 }
4646 if (ta_len > 0 || len > 0)
4647 {
4648 /*
4649 * For pipes: Check for CTRL-C: send interrupt signal to
4650 * child. Check for CTRL-D: EOF, close pipe to child.
4651 */
4652 if (len == 1 && cmd != NULL)
4653 {
4654 if (ta_buf[ta_len] == Ctrl_C)
4655 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004656 // Learn what exit code is expected, for
4657 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004658 TerminateProcess(pi.hProcess, 9);
4659 }
4660 if (ta_buf[ta_len] == Ctrl_D)
4661 {
4662 CloseHandle(g_hChildStd_IN_Wr);
4663 g_hChildStd_IN_Wr = NULL;
4664 }
4665 }
4666
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01004667 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004668
4669 /*
4670 * For pipes: echo the typed characters. For a pty this
4671 * does not seem to work.
4672 */
4673 for (i = ta_len; i < ta_len + len; ++i)
4674 {
4675 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4676 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004677 else if (has_mbyte)
4678 {
4679 int l = (*mb_ptr2len)(ta_buf + i);
4680
4681 msg_outtrans_len(ta_buf + i, l);
4682 i += l - 1;
4683 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004684 else
4685 msg_outtrans_len(ta_buf + i, 1);
4686 }
4687 windgoto(msg_row, msg_col);
4688 out_flush();
4689
4690 ta_len += len;
4691
4692 /*
4693 * Write the characters to the child, unless EOF has been
4694 * typed for pipes. Write one character at a time, to
4695 * avoid losing too much typeahead. When writing buffer
4696 * lines, drop the typed characters (only check for
4697 * CTRL-C).
4698 */
4699 if (options & SHELL_WRITE)
4700 ta_len = 0;
4701 else if (g_hChildStd_IN_Wr != NULL)
4702 {
4703 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4704 1, &len, NULL);
4705 // if we are typing in, we want to keep things reactive
4706 delay = 1;
4707 if (len > 0)
4708 {
4709 ta_len -= len;
4710 mch_memmove(ta_buf, ta_buf + len, ta_len);
4711 }
4712 }
4713 }
4714 }
4715 }
4716
4717 if (ta_len)
4718 ui_inchar_undo(ta_buf, ta_len);
4719
4720 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4721 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004722 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004723 break;
4724 }
4725
4726 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004727 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004728
Bram Moolenaar0f873732019-12-05 20:28:46 +01004729 // We start waiting for a very short time and then increase it, so
4730 // that we respond quickly when the process is quick, and don't
4731 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004732 if (delay < 50)
4733 delay += 10;
4734 }
4735
Bram Moolenaar0f873732019-12-05 20:28:46 +01004736 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004737 CloseHandle(g_hChildStd_OUT_Rd);
4738 if (g_hChildStd_IN_Wr != NULL)
4739 CloseHandle(g_hChildStd_IN_Wr);
4740
4741 WaitForSingleObject(pi.hProcess, INFINITE);
4742
Bram Moolenaar0f873732019-12-05 20:28:46 +01004743 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004744 GetExitCodeProcess(pi.hProcess, &ret);
4745
4746 if (options & SHELL_READ)
4747 {
4748 if (ga.ga_len > 0)
4749 {
4750 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01004751 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004752 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4753 }
4754 else
4755 curbuf->b_no_eol_lnum = 0;
4756 ga_clear(&ga);
4757 }
4758
Bram Moolenaar0f873732019-12-05 20:28:46 +01004759 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004760 CloseHandle(pi.hThread);
4761 CloseHandle(pi.hProcess);
4762
4763 return ret;
4764}
4765
4766 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004767mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004768{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004769 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004770 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004771 return mch_system_piped(cmd, options);
4772 else
4773 return mch_system_classic(cmd, options);
4774}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004775#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004776
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004777#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004778 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02004779mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004780{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004781 int ret;
4782 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004783 char_u *buf;
4784 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004785
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004786 // If the command starts and ends with double quotes, enclose the command
4787 // in parentheses.
4788 len = STRLEN(cmd);
4789 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
4790 {
4791 len += 3;
4792 buf = alloc(len);
4793 if (buf == NULL)
4794 return -1;
4795 vim_snprintf((char *)buf, len, "(%s)", cmd);
4796 wcmd = enc_to_utf16(buf, NULL);
4797 free(buf);
4798 }
4799 else
4800 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4801
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004802 if (wcmd == NULL)
4803 return -1;
4804
4805 ret = _wsystem(wcmd);
4806 vim_free(wcmd);
4807 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004808}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004809
4810#endif
4811
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004812 static int
4813mch_system(char *cmd, int options)
4814{
4815#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004816 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004817 return mch_system_g(cmd, options);
4818 else
4819 return mch_system_c(cmd, options);
4820#elif defined(FEAT_GUI_MSWIN)
4821 return mch_system_g(cmd, options);
4822#else
4823 return mch_system_c(cmd, options);
4824#endif
4825}
4826
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004827#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4828/*
4829 * Use a terminal window to run a shell command in.
4830 */
4831 static int
4832mch_call_shell_terminal(
4833 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004834 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004835{
4836 jobopt_T opt;
4837 char_u *newcmd = NULL;
4838 typval_T argvar[2];
4839 long_u cmdlen;
4840 int retval = -1;
4841 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004842 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004843 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004844 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004845
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004846 if (cmd == NULL)
4847 cmdlen = STRLEN(p_sh) + 1;
4848 else
4849 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004850 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004851 if (newcmd == NULL)
4852 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004853 if (cmd == NULL)
4854 {
4855 STRCPY(newcmd, p_sh);
4856 ch_log(NULL, "starting terminal to run a shell");
4857 }
4858 else
4859 {
4860 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4861 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4862 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004863
4864 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004865
4866 argvar[0].v_type = VAR_STRING;
4867 argvar[0].vval.v_string = newcmd;
4868 argvar[1].v_type = VAR_UNKNOWN;
4869 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004870 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004871 {
4872 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004873 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004874 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004875
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004876 job = term_getjob(buf->b_term);
4877 ++job->jv_refcount;
4878
Bram Moolenaar0f873732019-12-05 20:28:46 +01004879 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004880 aucmd_prepbuf(&aco, buf);
Bram Moolenaare76062c2022-11-28 18:51:43 +00004881 if (curbuf == buf)
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004882 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00004883 // Only do this when a window was found for "buf".
4884 clear_oparg(&oa);
4885 while (term_use_loop())
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004886 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00004887 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4888 {
4889 // If terminal_loop() returns OK we got a key that is handled
4890 // in Normal model. We don't do redrawing anyway.
4891 if (terminal_loop(TRUE) == OK)
4892 normal_cmd(&oa, TRUE);
4893 }
4894 else
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004895 normal_cmd(&oa, TRUE);
4896 }
Bram Moolenaare76062c2022-11-28 18:51:43 +00004897 retval = job->jv_exitval;
4898 ch_log(NULL, "system command finished");
4899
4900 job_unref(job);
4901
4902 // restore curwin/curbuf and a few other things
4903 aucmd_restbuf(&aco);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004904 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004905
4906 wait_return(TRUE);
4907 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4908
4909 vim_free(newcmd);
4910 return retval;
4911}
4912#endif
4913
Bram Moolenaar071d4272004-06-13 20:20:40 +00004914/*
4915 * Either execute a command by calling the shell or start a new shell
4916 */
4917 int
4918mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004919 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004920 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00004921{
4922 int x = 0;
4923 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004924 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004925
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01004926#ifdef FEAT_JOB_CHANNEL
4927 ch_log(NULL, "executing shell command: %s", cmd);
4928#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004929 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02004930 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004931 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004932 if (cmd == NULL)
4933 wcscat(szShellTitle, L" :sh");
4934 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004935 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004936 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004937
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004938 if (wn != NULL)
4939 {
4940 wcscat(szShellTitle, L" - !");
4941 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02004942 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004943 wcscat(szShellTitle, wn);
4944 SetConsoleTitleW(szShellTitle);
4945 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004946 }
4947 }
4948 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004949
4950 out_flush();
4951
4952#ifdef MCH_WRITE_DUMP
4953 if (fdDump)
4954 {
4955 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4956 fflush(fdDump);
4957 }
4958#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004959#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004960 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004961 if (
4962# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004963 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004964# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004965 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004966 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4967 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004968 char_u *cmdbase = cmd;
4969
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004970 if (cmdbase != NULL)
4971 // Skip a leading quote and (.
4972 while (*cmdbase == '"' || *cmdbase == '(')
4973 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004974
4975 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01004976 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
4977 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004978 {
4979 // Use a terminal window to run the command in.
4980 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004981 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004982 return x;
4983 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004984 }
4985#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004986
4987 /*
4988 * Catch all deadly signals while running the external command, because a
4989 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4990 */
4991 signal(SIGINT, SIG_IGN);
4992#if defined(__GNUC__) && !defined(__MINGW32__)
4993 signal(SIGKILL, SIG_IGN);
4994#else
4995 signal(SIGBREAK, SIG_IGN);
4996#endif
4997 signal(SIGILL, SIG_IGN);
4998 signal(SIGFPE, SIG_IGN);
4999 signal(SIGSEGV, SIG_IGN);
5000 signal(SIGTERM, SIG_IGN);
5001 signal(SIGABRT, SIG_IGN);
5002
5003 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005004 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00005005
5006 if (cmd == NULL)
5007 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005008 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005009 }
5010 else
5011 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005012 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005013 char_u *newcmd = NULL;
5014 char_u *cmdbase = cmd;
5015 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005016
Bram Moolenaar0f873732019-12-05 20:28:46 +01005017 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005018 if (*cmdbase == '"' )
5019 ++cmdbase;
5020 if (*cmdbase == '(')
5021 ++cmdbase;
5022
Bram Moolenaar1c465442017-03-12 20:10:05 +01005023 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005024 {
5025 STARTUPINFO si;
5026 PROCESS_INFORMATION pi;
5027 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005028 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005029 char_u *p;
5030
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005031 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005032 si.cb = sizeof(si);
5033 si.lpReserved = NULL;
5034 si.lpDesktop = NULL;
5035 si.lpTitle = NULL;
5036 si.dwFlags = 0;
5037 si.cbReserved2 = 0;
5038 si.lpReserved2 = NULL;
5039
5040 cmdbase = skipwhite(cmdbase + 5);
5041 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005042 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005043 {
5044 cmdbase = skipwhite(cmdbase + 4);
5045 si.dwFlags = STARTF_USESHOWWINDOW;
5046 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005047 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005048 }
5049 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005050 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005051 {
5052 cmdbase = skipwhite(cmdbase + 2);
5053 flags = CREATE_NO_WINDOW;
5054 si.dwFlags = STARTF_USESTDHANDLES;
5055 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005056 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005057 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005058 NULL, // Security att.
5059 OPEN_EXISTING, // Open flags
5060 FILE_ATTRIBUTE_NORMAL, // File att.
5061 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005062 si.hStdOutput = si.hStdInput;
5063 si.hStdError = si.hStdInput;
5064 }
5065
Bram Moolenaar0f873732019-12-05 20:28:46 +01005066 // Remove a trailing ", ) and )" if they have a match
5067 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005068 if (cmdbase > cmd)
5069 {
5070 p = cmdbase + STRLEN(cmdbase);
5071 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5072 *--p = NUL;
5073 if (p > cmdbase && p[-1] == ')'
5074 && (*cmd =='(' || cmd[1] == '('))
5075 *--p = NUL;
5076 }
5077
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005078 newcmd = cmdbase;
5079 unescape_shellxquote(cmdbase, p_sxe);
5080
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005081 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005082 * If creating new console, arguments are passed to the
5083 * 'cmd.exe' as-is. If it's not, arguments are not treated
5084 * correctly for current 'cmd.exe'. So unescape characters in
5085 * shellxescape except '|' for avoiding to be treated as
5086 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005087 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005088 if (flags != CREATE_NEW_CONSOLE)
5089 {
5090 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005091 char_u *cmd_shell = mch_getenv("COMSPEC");
5092
5093 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005094 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005095
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005096 subcmd = vim_strsave_escaped_ext(cmdbase,
5097 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005098 if (subcmd != NULL)
5099 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005100 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005101 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005102 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005103 if (newcmd != NULL)
5104 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005105 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005106 else
5107 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005108 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005109 }
5110 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005111
5112 /*
5113 * Now, start the command as a process, so that it doesn't
5114 * inherit our handles which causes unpleasant dangling swap
5115 * files if we exit before the spawned process
5116 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005117 if (vim_create_process((char *)newcmd, FALSE, flags,
5118 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005119 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005120 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5121 > (HINSTANCE)32)
5122 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005123 else
5124 {
5125 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005126#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005127# ifdef VIMDLL
5128 if (gui.in_use)
5129# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005130 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005131#endif
5132 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005133
5134 if (newcmd != cmdbase)
5135 vim_free(newcmd);
5136
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005137 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005138 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005139 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005140 CloseHandle(si.hStdInput);
5141 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005142 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005143 CloseHandle(pi.hThread);
5144 CloseHandle(pi.hProcess);
5145 }
5146 else
5147 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005148 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005149#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005150 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005151 (!s_dont_use_vimrun && p_stmp ?
5152 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5153 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005154#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005155 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005156
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005157 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005158 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005159 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005160#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005161 if (
5162# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005163 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005164# endif
5165 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005166 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005167 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5168 "External commands will not pause after completion.\n"
5169 "See :help win32-vimrun for more information.");
5170 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005171 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5172 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005173
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005174 if (wmsg != NULL && wtitle != NULL)
5175 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5176 vim_free(wmsg);
5177 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005178 need_vimrun_warning = FALSE;
5179 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005180 if (
5181# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005182 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005183# endif
5184 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005185 // Use vimrun to execute the command. It opens a console
5186 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005187 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005188 vimrun_path,
5189 (msg_silent != 0 || (options & SHELL_DOOUT))
5190 ? "-s " : "",
5191 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005192 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005193# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005194 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005195# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005196 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005197 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005198 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5199 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005200 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005201#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005202 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005203 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005204 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005205 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005206 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005207 }
5208 }
5209
5210 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005211 {
5212 // The shell may have messed with the mode, always set it.
5213 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005214 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005215 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005216
Bram Moolenaar0f873732019-12-05 20:28:46 +01005217 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005218 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005219#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005220 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005221 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005222#endif
5223 )
5224 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005225 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005226 msg_putchar('\n');
5227 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005228 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005229
5230 signal(SIGINT, SIG_DFL);
5231#if defined(__GNUC__) && !defined(__MINGW32__)
5232 signal(SIGKILL, SIG_DFL);
5233#else
5234 signal(SIGBREAK, SIG_DFL);
5235#endif
5236 signal(SIGILL, SIG_DFL);
5237 signal(SIGFPE, SIG_DFL);
5238 signal(SIGSEGV, SIG_DFL);
5239 signal(SIGTERM, SIG_DFL);
5240 signal(SIGABRT, SIG_DFL);
5241
5242 return x;
5243}
5244
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005245#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005246 static HANDLE
5247job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005248 char_u *fname,
5249 DWORD dwDesiredAccess,
5250 DWORD dwShareMode,
5251 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5252 DWORD dwCreationDisposition,
5253 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005254{
5255 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005256 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005257
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005258 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005259 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005260 return INVALID_HANDLE_VALUE;
5261
5262 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5263 lpSecurityAttributes, dwCreationDisposition,
5264 dwFlagsAndAttributes, NULL);
5265 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005266 return h;
5267}
5268
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005269/*
5270 * Turn the dictionary "env" into a NUL separated list that can be used as the
5271 * environment argument of vim_create_process().
5272 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005273 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005274win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005275{
5276 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005277 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005278 LPVOID base = GetEnvironmentStringsW();
5279
Bram Moolenaar0f873732019-12-05 20:28:46 +01005280 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005281 if (ga_grow(gap, 1) == FAIL)
5282 return;
5283
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005284 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005285 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005286 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005287 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005288 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005289 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005290 typval_T *item = &dict_lookup(hi)->di_tv;
5291 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005292 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005293 --todo;
5294 if (wkey != NULL && wval != NULL)
5295 {
5296 size_t n;
5297 size_t lkey = wcslen(wkey);
5298 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005299
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005300 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5301 continue;
5302 for (n = 0; n < lkey; n++)
5303 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5304 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5305 for (n = 0; n < lval; n++)
5306 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5307 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5308 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005309 vim_free(wkey);
5310 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005311 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005312 }
5313 }
5314
Bram Moolenaar355757a2020-02-10 22:06:32 +01005315 if (base)
5316 {
5317 WCHAR *p = (WCHAR*) base;
5318
5319 // for last \0
5320 if (ga_grow(gap, 1) == FAIL)
5321 return;
5322
5323 while (*p != 0 || *(p + 1) != 0)
5324 {
5325 if (ga_grow(gap, 1) == OK)
5326 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5327 p++;
5328 }
5329 FreeEnvironmentStrings(base);
5330 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5331 }
5332
Bram Moolenaar493359e2018-06-12 20:25:52 +02005333# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005334 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005335# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005336 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005337 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005338# endif
5339# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005340 char_u *version = get_vim_var_str(VV_VERSION);
5341 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005342# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005343 // size of "VIM_SERVERNAME=" and value,
5344 // plus "VIM_TERMINAL=" and value,
5345 // plus two terminating NULs
5346 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005347# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005348 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005349# endif
5350# ifdef FEAT_TERMINAL
5351 + 13 + version_len + 2
5352# endif
5353 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005354
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005355 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005356 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005357# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005358 for (n = 0; n < 15; n++)
5359 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5360 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005361 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005362 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5363 (WCHAR)servername[n];
5364 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005365# endif
5366# ifdef FEAT_TERMINAL
5367 if (is_terminal)
5368 {
5369 for (n = 0; n < 13; n++)
5370 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5371 (WCHAR)"VIM_TERMINAL="[n];
5372 for (n = 0; n < version_len; n++)
5373 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5374 (WCHAR)version[n];
5375 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5376 }
5377# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005378 }
5379 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005380# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005381}
5382
Bram Moolenaarb091f302019-01-19 14:37:00 +01005383/*
5384 * Create a pair of pipes.
5385 * Return TRUE for success, FALSE for failure.
5386 */
5387 static BOOL
5388create_pipe_pair(HANDLE handles[2])
5389{
5390 static LONG s;
5391 char name[64];
5392 SECURITY_ATTRIBUTES sa;
5393
5394 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5395 GetCurrentProcessId(),
5396 InterlockedIncrement(&s));
5397
5398 // Create named pipe. Max size of named pipe is 65535.
5399 handles[1] = CreateNamedPipe(
5400 name,
5401 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5402 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005403 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005404
5405 if (handles[1] == INVALID_HANDLE_VALUE)
5406 return FALSE;
5407
5408 sa.nLength = sizeof(sa);
5409 sa.bInheritHandle = TRUE;
5410 sa.lpSecurityDescriptor = NULL;
5411
5412 handles[0] = CreateFile(name,
5413 FILE_GENERIC_READ,
5414 FILE_SHARE_READ, &sa,
5415 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5416
5417 if (handles[0] == INVALID_HANDLE_VALUE)
5418 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005419 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005420 return FALSE;
5421 }
5422
5423 return TRUE;
5424}
5425
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005426 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005427mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005428{
5429 STARTUPINFO si;
5430 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005431 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005432 SECURITY_ATTRIBUTES saAttr;
5433 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005434 HANDLE ifd[2];
5435 HANDLE ofd[2];
5436 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005437 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005438
5439 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5440 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5441 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5442 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5443 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5444 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5445 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5446
5447 if (use_out_for_err && use_null_for_out)
5448 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005449
5450 ifd[0] = INVALID_HANDLE_VALUE;
5451 ifd[1] = INVALID_HANDLE_VALUE;
5452 ofd[0] = INVALID_HANDLE_VALUE;
5453 ofd[1] = INVALID_HANDLE_VALUE;
5454 efd[0] = INVALID_HANDLE_VALUE;
5455 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005456 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005457
Bram Moolenaar14207f42016-10-27 21:13:10 +02005458 jo = CreateJobObject(NULL, NULL);
5459 if (jo == NULL)
5460 {
5461 job->jv_status = JOB_FAILED;
5462 goto failed;
5463 }
5464
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005465 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005466 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005467
Bram Moolenaar76467df2016-02-12 19:30:26 +01005468 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005469 ZeroMemory(&si, sizeof(si));
5470 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005471 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005472 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005473
Bram Moolenaard8070362016-02-15 21:56:54 +01005474 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5475 saAttr.bInheritHandle = TRUE;
5476 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005477
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005478 if (use_file_for_in)
5479 {
5480 char_u *fname = options->jo_io_name[PART_IN];
5481
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005482 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5483 FILE_SHARE_READ | FILE_SHARE_WRITE,
5484 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5485 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005486 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005487 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005488 goto failed;
5489 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005490 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005491 else if (!use_null_for_in
5492 && (!create_pipe_pair(ifd)
5493 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005494 goto failed;
5495
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005496 if (use_file_for_out)
5497 {
5498 char_u *fname = options->jo_io_name[PART_OUT];
5499
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005500 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5501 FILE_SHARE_READ | FILE_SHARE_WRITE,
5502 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5503 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005504 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005505 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005506 goto failed;
5507 }
5508 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005509 else if (!use_null_for_out &&
5510 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005511 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005512 goto failed;
5513
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005514 if (use_file_for_err)
5515 {
5516 char_u *fname = options->jo_io_name[PART_ERR];
5517
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005518 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5519 FILE_SHARE_READ | FILE_SHARE_WRITE,
5520 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5521 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005522 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005523 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005524 goto failed;
5525 }
5526 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005527 else if (!use_out_for_err && !use_null_for_err &&
5528 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005529 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005530 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005531
Bram Moolenaard8070362016-02-15 21:56:54 +01005532 si.dwFlags |= STARTF_USESTDHANDLES;
5533 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005534 si.hStdOutput = ofd[1];
5535 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5536
5537 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5538 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005539 if (options->jo_set & JO_CHANNEL)
5540 {
5541 channel = options->jo_channel;
5542 if (channel != NULL)
5543 ++channel->ch_refcount;
5544 }
5545 else
5546 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005547 if (channel == NULL)
5548 goto failed;
5549 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005550
5551 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005552 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005553 CREATE_DEFAULT_ERROR_MODE |
5554 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005555 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005556 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005557 &si, &pi,
5558 ga.ga_data,
5559 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005560 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005561 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005562 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005563 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005564 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005565
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005566 ga_clear(&ga);
5567
Bram Moolenaar14207f42016-10-27 21:13:10 +02005568 if (!AssignProcessToJobObject(jo, pi.hProcess))
5569 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005570 // if failing, switch the way to terminate
5571 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005572 CloseHandle(jo);
5573 jo = NULL;
5574 }
5575 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005576 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005577 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005578 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005579 job->jv_status = JOB_STARTED;
5580
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005581 CloseHandle(ifd[0]);
5582 CloseHandle(ofd[1]);
5583 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005584 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005585
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005586 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005587 if (channel != NULL)
5588 {
5589 channel_set_pipes(channel,
5590 use_file_for_in || use_null_for_in
5591 ? INVALID_FD : (sock_T)ifd[1],
5592 use_file_for_out || use_null_for_out
5593 ? INVALID_FD : (sock_T)ofd[0],
5594 use_out_for_err || use_file_for_err || use_null_for_err
5595 ? INVALID_FD : (sock_T)efd[0]);
5596 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005597 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005598 return;
5599
5600failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005601 CloseHandle(ifd[0]);
5602 CloseHandle(ofd[0]);
5603 CloseHandle(efd[0]);
5604 CloseHandle(ifd[1]);
5605 CloseHandle(ofd[1]);
5606 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005607 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005608 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005609}
5610
5611 char *
5612mch_job_status(job_T *job)
5613{
5614 DWORD dwExitCode = 0;
5615
Bram Moolenaar76467df2016-02-12 19:30:26 +01005616 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5617 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005618 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005619 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005620 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005621 {
5622 ch_log(job->jv_channel, "Job ended");
5623 job->jv_status = JOB_ENDED;
5624 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005625 return "dead";
5626 }
5627 return "run";
5628}
5629
Bram Moolenaar97792de2016-10-15 18:36:49 +02005630 job_T *
5631mch_detect_ended_job(job_T *job_list)
5632{
5633 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5634 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5635 job_T *job = job_list;
5636
5637 while (job != NULL)
5638 {
5639 DWORD n;
5640 DWORD result;
5641
5642 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5643 && job != NULL; job = job->jv_next)
5644 {
5645 if (job->jv_status == JOB_STARTED)
5646 {
5647 jobHandles[n] = job->jv_proc_info.hProcess;
5648 jobArray[n] = job;
5649 ++n;
5650 }
5651 }
5652 if (n == 0)
5653 continue;
5654 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5655 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5656 {
5657 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5658
5659 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5660 return wait_job;
5661 }
5662 }
5663 return NULL;
5664}
5665
Bram Moolenaarfb630902016-10-29 14:55:00 +02005666 static BOOL
5667terminate_all(HANDLE process, int code)
5668{
5669 PROCESSENTRY32 pe;
5670 HANDLE h = INVALID_HANDLE_VALUE;
5671 DWORD pid = GetProcessId(process);
5672
5673 if (pid != 0)
5674 {
5675 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5676 if (h != INVALID_HANDLE_VALUE)
5677 {
5678 pe.dwSize = sizeof(PROCESSENTRY32);
5679 if (!Process32First(h, &pe))
5680 goto theend;
5681
5682 do
5683 {
5684 if (pe.th32ParentProcessID == pid)
5685 {
5686 HANDLE ph = OpenProcess(
5687 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5688 if (ph != NULL)
5689 {
5690 terminate_all(ph, code);
5691 CloseHandle(ph);
5692 }
5693 }
5694 } while (Process32Next(h, &pe));
5695
5696 CloseHandle(h);
5697 }
5698 }
5699
5700theend:
5701 return TerminateProcess(process, code);
5702}
5703
5704/*
5705 * Send a (deadly) signal to "job".
5706 * Return FAIL if it didn't work.
5707 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005708 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005709mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005710{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005711 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005712
Bram Moolenaar923d9262016-02-25 20:56:01 +01005713 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005714 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005715 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02005716 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005717 {
5718 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5719 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00005720 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005721 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01005722 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005723 }
5724
5725 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5726 return FAIL;
5727 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005728 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5729 job->jv_proc_info.dwProcessId)
5730 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005731 FreeConsole();
5732 return ret;
5733}
5734
5735/*
5736 * Clear the data related to "job".
5737 */
5738 void
5739mch_clear_job(job_T *job)
5740{
5741 if (job->jv_status != JOB_FAILED)
5742 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005743 if (job->jv_job_object != NULL)
5744 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005745 CloseHandle(job->jv_proc_info.hProcess);
5746 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005747}
5748#endif
5749
Bram Moolenaar071d4272004-06-13 20:20:40 +00005750
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005751#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005752
5753/*
5754 * Start termcap mode
5755 */
5756 static void
5757termcap_mode_start(void)
5758{
5759 DWORD cmodein;
5760
5761 if (g_fTermcapMode)
5762 return;
5763
Christopher Plewright1140b512022-11-12 18:46:05 +00005764 // VTP uses alternate screen buffer.
5765 // Switch to a new alternate screen buffer.
5766 if (win11_or_later && p_rs && vtp_working)
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005767 vtp_printf("\033[?1049h");
5768
Bram Moolenaar071d4272004-06-13 20:20:40 +00005769 SaveConsoleBuffer(&g_cbNonTermcap);
5770
5771 if (g_cbTermcap.IsValid)
5772 {
5773 /*
5774 * We've been in termcap mode before. Restore certain screen
5775 * characteristics, including the buffer size and the window
5776 * size. Since we will be redrawing the screen, we don't need
5777 * to restore the actual contents of the buffer.
5778 */
5779 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005780 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005781 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5782 Rows = g_cbTermcap.Info.dwSize.Y;
5783 Columns = g_cbTermcap.Info.dwSize.X;
5784 }
5785 else
5786 {
5787 /*
5788 * This is our first time entering termcap mode. Clear the console
5789 * screen buffer, and resize the buffer to match the current window
5790 * size. We will use this as the size of our editing environment.
5791 */
5792 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005793 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005794 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5795 }
5796
Bram Moolenaar071d4272004-06-13 20:20:40 +00005797 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005798
5799 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005800 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005801 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005802 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005803 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
5804 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005805 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005806 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005807 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005808 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5809 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005810 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005811 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005812
5813 redraw_later_clear();
5814 g_fTermcapMode = TRUE;
5815}
5816
5817
5818/*
5819 * End termcap mode
5820 */
5821 static void
5822termcap_mode_end(void)
5823{
5824 DWORD cmodein;
5825 ConsoleBuffer *cb;
5826 COORD coord;
5827 DWORD dwDummy;
5828
5829 if (!g_fTermcapMode)
5830 return;
5831
5832 SaveConsoleBuffer(&g_cbTermcap);
5833
5834 GetConsoleMode(g_hConIn, &cmodein);
5835 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005836 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5837 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005838
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005839# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005840 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005841# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005842 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005843# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005844 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01005845 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005846
Christopher Plewright1140b512022-11-12 18:46:05 +00005847 // VTP uses alternate screen buffer.
5848 // Switch back to main screen buffer.
5849 if (exiting && win11_or_later && p_rs && vtp_working)
5850 vtp_printf("\033[?1049l");
5851
5852 if (!USE_WT && (p_rs || exiting))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005853 {
5854 /*
5855 * Clear anything that happens to be on the current line.
5856 */
5857 coord.X = 0;
5858 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
Christopher Plewright1140b512022-11-12 18:46:05 +00005859 if (!vtp_working)
5860 FillConsoleOutputCharacter(g_hConOut, ' ',
5861 cb->Info.dwSize.X, coord, &dwDummy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005862 /*
5863 * The following is just for aesthetics. If we are exiting without
5864 * restoring the screen, then we want to have a prompt string
5865 * appear at the bottom line. However, the command interpreter
5866 * seems to always advance the cursor one line before displaying
5867 * the prompt string, which causes the screen to scroll. To
5868 * counter this, move the cursor up one line before exiting.
5869 */
5870 if (exiting && !p_rs)
5871 coord.Y--;
5872 /*
5873 * Position the cursor at the leftmost column of the desired row.
5874 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005875 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005876 }
Christopher Plewright1140b512022-11-12 18:46:05 +00005877 SetConsoleCursorInfo(g_hConOut, &g_cci);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005878 g_fTermcapMode = FALSE;
5879}
Christopher Plewright38804d62022-11-09 23:55:52 +00005880#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00005881
5882
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005883#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005884 void
5885mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005886 char_u *s UNUSED,
5887 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005888{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005889 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00005890}
5891
5892#else
5893
5894/*
5895 * clear `n' chars, starting from `coord'
5896 */
5897 static void
5898clear_chars(
5899 COORD coord,
5900 DWORD n)
5901{
Christopher Plewright38804d62022-11-09 23:55:52 +00005902 if (!vtp_working)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02005903 {
5904 DWORD dwDummy;
5905
5906 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5907 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
5908 &dwDummy);
5909 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005910 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005911 {
5912 set_console_color_rgb();
5913 gotoxy(coord.X + 1, coord.Y + 1);
5914 vtp_printf("\033[%dX", n);
5915 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005916}
5917
5918
5919/*
5920 * Clear the screen
5921 */
5922 static void
5923clear_screen(void)
5924{
5925 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005926
Christopher Plewright38804d62022-11-09 23:55:52 +00005927 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005928 clear_chars(g_coord, Rows * Columns);
5929 else
5930 {
5931 set_console_color_rgb();
5932 gotoxy(1, 1);
5933 vtp_printf("\033[2J");
5934 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005935}
5936
5937
5938/*
5939 * Clear to end of display
5940 */
5941 static void
5942clear_to_end_of_display(void)
5943{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005944 COORD save = g_coord;
5945
Christopher Plewright38804d62022-11-09 23:55:52 +00005946 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005947 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005948 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005949 else
5950 {
5951 set_console_color_rgb();
5952 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5953 vtp_printf("\033[0J");
5954
5955 gotoxy(save.X + 1, save.Y + 1);
5956 g_coord = save;
5957 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005958}
5959
5960
5961/*
5962 * Clear to end of line
5963 */
5964 static void
5965clear_to_end_of_line(void)
5966{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005967 COORD save = g_coord;
5968
Christopher Plewright38804d62022-11-09 23:55:52 +00005969 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005970 clear_chars(g_coord, Columns - g_coord.X);
5971 else
5972 {
5973 set_console_color_rgb();
5974 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5975 vtp_printf("\033[0K");
5976
5977 gotoxy(save.X + 1, save.Y + 1);
5978 g_coord = save;
5979 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005980}
5981
5982
5983/*
5984 * Scroll the scroll region up by `cLines' lines
5985 */
5986 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005987scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005988{
5989 COORD oldcoord = g_coord;
5990
5991 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5992 delete_lines(cLines);
5993
5994 g_coord = oldcoord;
5995}
5996
5997
5998/*
5999 * Set the scroll region
6000 */
6001 static void
6002set_scroll_region(
6003 unsigned left,
6004 unsigned top,
6005 unsigned right,
6006 unsigned bottom)
6007{
6008 if (left >= right
6009 || top >= bottom
6010 || right > (unsigned) Columns - 1
6011 || bottom > (unsigned) Rows - 1)
6012 return;
6013
6014 g_srScrollRegion.Left = left;
6015 g_srScrollRegion.Top = top;
6016 g_srScrollRegion.Right = right;
6017 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006018}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006019
Bram Moolenaar6982f422019-02-16 16:48:01 +01006020 static void
6021set_scroll_region_tb(
6022 unsigned top,
6023 unsigned bottom)
6024{
6025 if (top >= bottom || bottom > (unsigned)Rows - 1)
6026 return;
6027
6028 g_srScrollRegion.Top = top;
6029 g_srScrollRegion.Bottom = bottom;
6030}
6031
6032 static void
6033set_scroll_region_lr(
6034 unsigned left,
6035 unsigned right)
6036{
6037 if (left >= right || right > (unsigned)Columns - 1)
6038 return;
6039
6040 g_srScrollRegion.Left = left;
6041 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006042}
6043
6044
6045/*
6046 * Insert `cLines' lines at the current cursor position
6047 */
6048 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006049insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006050{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006051 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006052 COORD dest;
6053 CHAR_INFO fill;
6054
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006055 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6056
Bram Moolenaar6982f422019-02-16 16:48:01 +01006057 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006058 dest.Y = g_coord.Y + cLines;
6059
Bram Moolenaar6982f422019-02-16 16:48:01 +01006060 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006061 source.Top = g_coord.Y;
6062 source.Right = g_srScrollRegion.Right;
6063 source.Bottom = g_srScrollRegion.Bottom - cLines;
6064
Bram Moolenaar6982f422019-02-16 16:48:01 +01006065 clip.Left = g_srScrollRegion.Left;
6066 clip.Top = g_coord.Y;
6067 clip.Right = g_srScrollRegion.Right;
6068 clip.Bottom = g_srScrollRegion.Bottom;
6069
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006070 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006071 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006072# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006073 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006074# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006075 ))
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006076 fill.Attributes = g_attrCurrent;
6077 else
6078 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006079
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006080 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006081
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006082 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6083
Bram Moolenaar6982f422019-02-16 16:48:01 +01006084 // Here we have to deal with a win32 console flake: If the scroll
6085 // region looks like abc and we scroll c to a and fill with d we get
6086 // cbd... if we scroll block c one line at a time to a, we get cdd...
6087 // vim expects cdd consistently... So we have to deal with that
6088 // here... (this also occurs scrolling the same way in the other
6089 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006090
6091 if (source.Bottom < dest.Y)
6092 {
6093 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006094 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006095
Bram Moolenaar6982f422019-02-16 16:48:01 +01006096 coord.X = source.Left;
6097 for (i = clip.Top; i < dest.Y; ++i)
6098 {
6099 coord.Y = i;
6100 clear_chars(coord, source.Right - source.Left + 1);
6101 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006102 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006103
Christopher Plewright38804d62022-11-09 23:55:52 +00006104 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006105 {
6106 COORD coord;
6107 int i;
6108
6109 coord.X = source.Left;
6110 for (i = source.Top; i < dest.Y; ++i)
6111 {
6112 coord.Y = i;
6113 clear_chars(coord, source.Right - source.Left + 1);
6114 }
6115 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006116}
6117
6118
6119/*
6120 * Delete `cLines' lines at the current cursor position
6121 */
6122 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006123delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006124{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006125 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006126 COORD dest;
6127 CHAR_INFO fill;
6128 int nb;
6129
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006130 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6131
Bram Moolenaar6982f422019-02-16 16:48:01 +01006132 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006133 dest.Y = g_coord.Y;
6134
Bram Moolenaar6982f422019-02-16 16:48:01 +01006135 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006136 source.Top = g_coord.Y + cLines;
6137 source.Right = g_srScrollRegion.Right;
6138 source.Bottom = g_srScrollRegion.Bottom;
6139
Bram Moolenaar6982f422019-02-16 16:48:01 +01006140 clip.Left = g_srScrollRegion.Left;
6141 clip.Top = g_coord.Y;
6142 clip.Right = g_srScrollRegion.Right;
6143 clip.Bottom = g_srScrollRegion.Bottom;
6144
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006145 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006146 if (!vtp_working)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006147 fill.Attributes = g_attrCurrent;
6148 else
6149 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006150
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006151 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006152
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006153 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6154
Bram Moolenaar6982f422019-02-16 16:48:01 +01006155 // Here we have to deal with a win32 console flake; See insert_lines()
6156 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006157
6158 nb = dest.Y + (source.Bottom - source.Top) + 1;
6159
6160 if (nb < source.Top)
6161 {
6162 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006163 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006164
Bram Moolenaar6982f422019-02-16 16:48:01 +01006165 coord.X = source.Left;
6166 for (i = nb; i < clip.Bottom; ++i)
6167 {
6168 coord.Y = i;
6169 clear_chars(coord, source.Right - source.Left + 1);
6170 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006171 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006172
Christopher Plewright38804d62022-11-09 23:55:52 +00006173 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006174 {
6175 COORD coord;
6176 int i;
6177
6178 coord.X = source.Left;
6179 for (i = nb; i <= source.Bottom; ++i)
6180 {
6181 coord.Y = i;
6182 clear_chars(coord, source.Right - source.Left + 1);
6183 }
6184 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006185}
6186
6187
6188/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006189 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006190 */
6191 static void
6192gotoxy(
6193 unsigned x,
6194 unsigned y)
6195{
6196 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6197 return;
6198
Christopher Plewright38804d62022-11-09 23:55:52 +00006199 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006200# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006201 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006202# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006203 ))
Bram Moolenaar2313b612019-09-27 14:14:32 +02006204 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006205 // There are reports of double-width characters not displayed
6206 // correctly. This workaround should fix it, similar to how it's done
6207 // for VTP.
6208 g_coord.X = 0;
6209 SetConsoleCursorPosition(g_hConOut, g_coord);
6210
Bram Moolenaar2313b612019-09-27 14:14:32 +02006211 // external cursor coords are 1-based; internal are 0-based
6212 g_coord.X = x - 1;
6213 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006214 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006215 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006216 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006217 {
6218 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006219 // destruction. Insider build bug. Always enabled because it's cheap
6220 // and avoids mistakes with recognizing the build.
6221 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006222
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006223 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006224
6225 g_coord.X = x - 1;
6226 g_coord.Y = y - 1;
6227 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006228}
6229
6230
6231/*
6232 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006233 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006234 */
6235 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006236textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006237{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006238 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006239
6240 SetConsoleTextAttribute(g_hConOut, wAttr);
6241}
6242
6243
6244 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006245textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006246{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006247 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006248
Christopher Plewright38804d62022-11-09 23:55:52 +00006249 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006250 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6251 else
6252 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006253}
6254
6255
6256 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006257textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006258{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006259 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006260
Christopher Plewright38804d62022-11-09 23:55:52 +00006261 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006262 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6263 else
6264 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006265}
6266
6267
6268/*
6269 * restore the default text attribute (whatever we started with)
6270 */
6271 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006272normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006273{
Christopher Plewright38804d62022-11-09 23:55:52 +00006274 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006275 textattr(g_attrDefault);
6276 else
6277 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006278}
6279
6280
6281static WORD g_attrPreStandout = 0;
6282
6283/*
6284 * Make the text standout, by brightening it
6285 */
6286 static void
6287standout(void)
6288{
6289 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006290
Bram Moolenaar071d4272004-06-13 20:20:40 +00006291 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6292}
6293
6294
6295/*
6296 * Turn off standout mode
6297 */
6298 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006299standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006300{
6301 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006302 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006303
6304 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006305}
6306
6307
6308/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006309 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006310 */
6311 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006312mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006313{
6314 char_u *p;
6315 int n;
6316
6317 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6318 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006319 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006320# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006321 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006322# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006323 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006324 {
6325 p = T_ME + 2;
6326 n = getdigits(&p);
6327 if (*p == 'm' && n > 0)
6328 {
6329 cterm_normal_fg_color = (n & 0xf) + 1;
6330 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6331 }
6332 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006333# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006334 cterm_normal_fg_gui_color = INVALCOLOR;
6335 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006336# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006337}
6338
6339
6340/*
6341 * visual bell: flash the screen
6342 */
6343 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006344visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006345{
6346 COORD coordOrigin = {0, 0};
6347 WORD attrFlash = ~g_attrCurrent & 0xff;
6348
6349 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006350 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006351
6352 if (oldattrs == NULL)
6353 return;
6354 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6355 coordOrigin, &dwDummy);
6356 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6357 coordOrigin, &dwDummy);
6358
Bram Moolenaar0f873732019-12-05 20:28:46 +01006359 Sleep(15); // wait for 15 msec
Christopher Plewright38804d62022-11-09 23:55:52 +00006360 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006361 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006362 coordOrigin, &dwDummy);
6363 vim_free(oldattrs);
6364}
6365
6366
6367/*
6368 * Make the cursor visible or invisible
6369 */
6370 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006371cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006372{
6373 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006374
Christopher Plewright38804d62022-11-09 23:55:52 +00006375 if (vtp_working)
Bram Moolenaar2695de62020-04-17 21:13:01 +02006376 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6377
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006378# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006379 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006380# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006381}
6382
6383
6384/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006385 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006386 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006387 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006388 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006389write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006390 char_u *pchBuf,
6391 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006392{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006393 COORD coord = g_coord;
6394 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006395 DWORD n, cchwritten;
6396 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006397 static WCHAR *unicodebuf = NULL;
6398 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006399 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006400 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006401 static WCHAR *utf8spbuf = NULL;
6402 static int utf8splength;
6403 static DWORD utf8spcells;
6404 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006405
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006406 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006407 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006408 utf8usingbuf = &unicodebuf;
6409 do
6410 {
6411 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6412 unicodebuf, unibuflen);
6413 if (length && length <= unibuflen)
6414 break;
6415 vim_free(unicodebuf);
6416 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6417 unibuflen = unibuflen ? 0 : length;
6418 } while(1);
6419 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006420 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006421 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6422 {
6423 if (utf8usingbuf != &utf8spbuf)
6424 {
6425 if (utf8spbuf == NULL)
6426 {
6427 cells = mb_string2cells((char_u *)" ", 1);
6428 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6429 utf8spbuf = LALLOC_MULT(WCHAR, length);
6430 if (utf8spbuf != NULL)
6431 {
6432 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6433 utf8usingbuf = &utf8spbuf;
6434 utf8splength = length;
6435 utf8spcells = cells;
6436 }
6437 }
6438 else
6439 {
6440 utf8usingbuf = &utf8spbuf;
6441 length = utf8splength;
6442 cells = utf8spcells;
6443 }
6444 }
6445 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006446
Christopher Plewright38804d62022-11-09 23:55:52 +00006447 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006448# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006449 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006450# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006451 ))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006452 {
6453 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6454 coord, &written);
6455 // When writing fails or didn't write a single character, pretend one
6456 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006457 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006458 coord, &cchwritten) == 0
6459 || cchwritten == 0 || cchwritten == (DWORD)-1)
6460 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006461 }
6462 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006463 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006464 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006465 NULL) == 0 || cchwritten == 0)
6466 cchwritten = 1;
6467 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006468
K.Takata135e1522022-01-29 15:27:58 +00006469 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006470 {
6471 written = cbToWrite;
6472 g_coord.X += (SHORT)cells;
6473 }
6474 else
6475 {
6476 char_u *p = pchBuf;
6477 for (n = 0; n < cchwritten; n++)
6478 MB_CPTR_ADV(p);
6479 written = p - pchBuf;
6480 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006481 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006482
6483 while (g_coord.X > g_srScrollRegion.Right)
6484 {
6485 g_coord.X -= (SHORT) Columns;
6486 if (g_coord.Y < g_srScrollRegion.Bottom)
6487 g_coord.Y++;
6488 }
6489
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006490 // Cursor under VTP is always in the correct position, no need to reset.
Christopher Plewright38804d62022-11-09 23:55:52 +00006491 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006492# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006493 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006494# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006495 ))
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006496 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006497
6498 return written;
6499}
6500
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006501 static char_u *
6502get_seq(
6503 int *args,
6504 int *count,
6505 char_u *head)
6506{
6507 int argc;
6508 char_u *p;
6509
6510 if (head == NULL || *head != '\033')
6511 return NULL;
6512
6513 argc = 0;
6514 p = head;
6515 ++p;
6516 do
6517 {
6518 ++p;
6519 args[argc] = getdigits(&p);
6520 argc += (argc < 15) ? 1 : 0;
6521 } while (*p == ';');
6522 *count = argc;
6523
6524 return p;
6525}
6526
6527 static char_u *
6528get_sgr(
6529 int *args,
6530 int *count,
6531 char_u *head)
6532{
6533 char_u *p = get_seq(args, count, head);
6534
6535 return (p && *p == 'm') ? ++p : NULL;
6536}
6537
6538/*
6539 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6540 */
6541 static char_u *
6542sgrn2(
6543 char_u *head,
6544 int n)
6545{
6546 int argc;
6547 int args[16];
6548 char_u *p = get_sgr(args, &argc, head);
6549
6550 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6551}
6552
6553/*
6554 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6555 */
6556 static char_u *
6557sgrnc(
6558 char_u *head,
6559 int n)
6560{
6561 int argc;
6562 int args[16];
6563 char_u *p = get_sgr(args, &argc, head);
6564
6565 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6566 ? p : NULL;
6567}
6568
6569 static char_u *
6570skipblank(char_u *q)
6571{
6572 char_u *p = q;
6573
6574 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6575 ++p;
6576 return p;
6577}
6578
6579/*
6580 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6581 * NULL.
6582 */
6583 static char_u *
6584sgrn2c(
6585 char_u *head,
6586 int n)
6587{
6588 char_u *p = sgrn2(head, n);
6589
6590 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6591}
6592
6593/*
6594 * If there is only a newline between the sequence immediately following it,
6595 * a pointer to the character following the newline is returned.
6596 * Otherwise NULL.
6597 */
6598 static char_u *
6599sgrn2cn(
6600 char_u *head,
6601 int n)
6602{
6603 char_u *p = sgrn2(head, n);
6604
6605 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6606}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006607
6608/*
6609 * mch_write(): write the output buffer to the screen, translating ESC
6610 * sequences into calls to console output routines.
6611 */
6612 void
6613mch_write(
6614 char_u *s,
6615 int len)
6616{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006617 char_u *end = s + len;
6618
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006619# ifdef VIMDLL
6620 if (gui.in_use)
6621 return;
6622# endif
6623
Bram Moolenaar071d4272004-06-13 20:20:40 +00006624 if (!term_console)
6625 {
6626 write(1, s, (unsigned)len);
6627 return;
6628 }
6629
Bram Moolenaar0f873732019-12-05 20:28:46 +01006630 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00006631 while (len--)
6632 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006633 int prefix = -1;
6634 char_u ch;
6635
6636 // While processing a sequence, on rare occasions it seems that another
6637 // sequence may be inserted asynchronously.
6638 if (len < 0)
6639 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006640 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006641 return;
6642 }
6643
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006644 while (s + ++prefix < end)
6645 {
6646 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006647 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6648 && ch != '\a' && ch != '\033'))
6649 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006650 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006651
6652 if (p_wd)
6653 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006654 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006655 if (prefix != 0)
6656 prefix = 1;
6657 }
6658
6659 if (prefix != 0)
6660 {
6661 DWORD nWritten;
6662
6663 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006664# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006665 if (fdDump)
6666 {
6667 fputc('>', fdDump);
6668 fwrite(s, sizeof(char_u), nWritten, fdDump);
6669 fputs("<\n", fdDump);
6670 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006671# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006672 len -= (nWritten - 1);
6673 s += nWritten;
6674 }
6675 else if (s[0] == '\n')
6676 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006677 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00006678 if (g_coord.Y == g_srScrollRegion.Bottom)
6679 {
6680 scroll(1);
6681 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6682 }
6683 else
6684 {
6685 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6686 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006687# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006688 if (fdDump)
6689 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006690# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006691 s++;
6692 }
6693 else if (s[0] == '\r')
6694 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006695 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00006696 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006697# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006698 if (fdDump)
6699 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006700# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006701 s++;
6702 }
6703 else if (s[0] == '\b')
6704 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006705 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00006706 if (g_coord.X > g_srScrollRegion.Left)
6707 g_coord.X--;
6708 else if (g_coord.Y > g_srScrollRegion.Top)
6709 {
6710 g_coord.X = g_srScrollRegion.Right;
6711 g_coord.Y--;
6712 }
6713 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006714# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006715 if (fdDump)
6716 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006717# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006718 s++;
6719 }
6720 else if (s[0] == '\a')
6721 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006722 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00006723 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006724# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006725 if (fdDump)
6726 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006727# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006728 s++;
6729 }
6730 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6731 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006732# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006733 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006734# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006735 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006736 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006737 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006738
6739 switch (s[2])
6740 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006741 case '0': case '1': case '2': case '3': case '4':
6742 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006743 if (*(p = get_seq(args, &argc, s)) != 'm')
6744 goto notsgr;
6745
6746 p = s;
6747
6748 // Handling frequent optional sequences. Output to the screen
6749 // takes too long, so do not output as much as possible.
6750
6751 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
6752 // resetFG,FG,BG are omitted.
6753 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006754 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006755 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
6756 len = len + 1 - (int)(p - s);
6757 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006758 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006759 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006760
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006761 // If FG,BG,BG,FG of SGR are connected, the first FG can be
6762 // omitted.
6763 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
6764 p = sp;
6765
6766 // If FG,BG,FG,BG of SGR are connected, the first FG can be
6767 // omitted.
6768 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
6769 p = sp;
6770
6771 // If BG,BG of SGR are connected, the first BG can be omitted.
6772 if (sgrn2((sp = sgrn2(p, 48)), 48))
6773 p = sp;
6774
6775 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01006776 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006777 if (sgrn2((sp = sgrnc(p, 39)), 38))
6778 p = sp;
6779
6780 p = get_seq(args, &argc, p);
6781
6782notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006783 arg1 = args[0];
6784 arg2 = args[1];
6785 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006786 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006787 if (argc == 1 && args[0] == 0)
6788 normvideo();
6789 else if (argc == 1)
6790 {
Christopher Plewright38804d62022-11-09 23:55:52 +00006791 if (vtp_working
6792# ifdef FEAT_TERMGUICOLORS
6793 && (p_tgc || t_colors >= 256)
6794# endif
6795 )
6796 textcolor((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006797 else
Christopher Plewright38804d62022-11-09 23:55:52 +00006798 textattr((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006799 }
Christopher Plewright38804d62022-11-09 23:55:52 +00006800 else if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006801 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006802 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006803 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006804 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006805 gotoxy(arg2, arg1);
6806 }
6807 else if (argc == 2 && *p == 'r')
6808 {
6809 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6810 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006811 else if (argc == 2 && *p == 'R')
6812 {
6813 set_scroll_region_tb(arg1, arg2);
6814 }
6815 else if (argc == 2 && *p == 'V')
6816 {
6817 set_scroll_region_lr(arg1, arg2);
6818 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006819 else if (argc == 1 && *p == 'A')
6820 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006821 gotoxy(g_coord.X + 1,
6822 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6823 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006824 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006825 {
6826 textbackground((WORD) arg1);
6827 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006828 else if (argc == 1 && *p == 'C')
6829 {
6830 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6831 g_coord.Y + 1);
6832 }
6833 else if (argc == 1 && *p == 'f')
6834 {
6835 textcolor((WORD) arg1);
6836 }
6837 else if (argc == 1 && *p == 'H')
6838 {
6839 gotoxy(1, arg1);
6840 }
6841 else if (argc == 1 && *p == 'L')
6842 {
6843 insert_lines(arg1);
6844 }
6845 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006846 {
6847 delete_lines(arg1);
6848 }
6849
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006850 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006851 s = p + 1;
6852 break;
6853
Bram Moolenaar071d4272004-06-13 20:20:40 +00006854 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006855 gotoxy(g_coord.X + 1,
6856 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6857 goto got3;
6858
6859 case 'B':
6860 visual_bell();
6861 goto got3;
6862
6863 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006864 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6865 g_coord.Y + 1);
6866 goto got3;
6867
6868 case 'E':
6869 termcap_mode_end();
6870 goto got3;
6871
6872 case 'F':
6873 standout();
6874 goto got3;
6875
6876 case 'f':
6877 standend();
6878 goto got3;
6879
6880 case 'H':
6881 gotoxy(1, 1);
6882 goto got3;
6883
6884 case 'j':
6885 clear_to_end_of_display();
6886 goto got3;
6887
6888 case 'J':
6889 clear_screen();
6890 goto got3;
6891
6892 case 'K':
6893 clear_to_end_of_line();
6894 goto got3;
6895
6896 case 'L':
6897 insert_lines(1);
6898 goto got3;
6899
6900 case 'M':
6901 delete_lines(1);
6902 goto got3;
6903
6904 case 'S':
6905 termcap_mode_start();
6906 goto got3;
6907
6908 case 'V':
6909 cursor_visible(TRUE);
6910 goto got3;
6911
6912 case 'v':
6913 cursor_visible(FALSE);
6914 goto got3;
6915
6916 got3:
6917 s += 3;
6918 len -= 2;
6919 }
6920
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006921# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006922 if (fdDump)
6923 {
6924 fputs("ESC | ", fdDump);
6925 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6926 fputc('\n', fdDump);
6927 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006928# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006929 }
K.Takatadf5320c2022-09-01 13:20:16 +01006930 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
6931 {
6932 int l = 2;
6933
6934 if (isdigit(s[l]))
6935 l++;
6936 if (s[l] == ' ' && s[l + 1] == 'q')
6937 {
6938 // DECSCUSR (cursor style) sequences
Christopher Plewright38804d62022-11-09 23:55:52 +00006939 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01006940 vtp_printf("%.*s", l + 2, s); // Pass through
6941 s += l + 2;
6942 len -= l + 1;
6943 }
6944 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006945 else
6946 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006947 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00006948 DWORD nWritten;
6949
6950 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006951# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006952 if (fdDump)
6953 {
6954 fputc('>', fdDump);
6955 fwrite(s, sizeof(char_u), nWritten, fdDump);
6956 fputs("<\n", fdDump);
6957 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006958# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006959
6960 len -= (nWritten - 1);
6961 s += nWritten;
6962 }
6963 }
6964
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006965# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006966 if (fdDump)
6967 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006968# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006969}
6970
Bram Moolenaar0f873732019-12-05 20:28:46 +01006971#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006972
6973
6974/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006975 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006976 */
6977 void
6978mch_delay(
6979 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02006980 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006981{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006982#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006983 Sleep((int)msec); // never wait for input
6984#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006985# ifdef VIMDLL
6986 if (gui.in_use)
6987 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006988 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006989 return;
6990 }
6991# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02006992 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006993# ifdef FEAT_MZSCHEME
6994 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6995 {
6996 int towait = p_mzq;
6997
Bram Moolenaar0f873732019-12-05 20:28:46 +01006998 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006999 while (msec > 0)
7000 {
7001 mzvim_check_threads();
7002 if (msec < towait)
7003 towait = msec;
7004 Sleep(towait);
7005 msec -= towait;
7006 }
7007 }
7008 else
7009# endif
7010 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007011 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007012 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007013#endif
7014}
7015
7016
7017/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01007018 * This version of remove is not scared by a readonly (backup) file.
7019 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007020 * Return 0 for success, -1 for failure.
7021 */
7022 int
7023mch_remove(char_u *name)
7024{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007025 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007026 int n;
7027
Bram Moolenaar203258c2016-01-17 22:15:16 +01007028 /*
7029 * On Windows, deleting a directory's symbolic link is done by
7030 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
7031 */
7032 if (mch_isdir(name) && mch_is_symbolic_link(name))
7033 return mch_rmdir(name);
7034
Bram Moolenaar12b559e2013-06-12 22:41:37 +02007035 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
7036
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007037 wn = enc_to_utf16(name, NULL);
7038 if (wn == NULL)
7039 return -1;
7040
7041 n = DeleteFileW(wn) ? 0 : -1;
7042 vim_free(wn);
7043 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007044}
7045
7046
7047/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007048 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007049 */
7050 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007051mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007052{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007053#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7054# ifdef VIMDLL
7055 if (!gui.in_use)
7056# endif
7057 if (g_fCtrlCPressed || g_fCBrkPressed)
7058 {
7059 ctrl_break_was_pressed = g_fCBrkPressed;
7060 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7061 got_int = TRUE;
7062 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007063#endif
7064}
7065
Bram Moolenaar0f873732019-12-05 20:28:46 +01007066// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007067#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007068
7069/*
7070 * How much main memory in KiB that can be used by VIM.
7071 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007072 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007073mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007074{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007075 MEMORYSTATUSEX ms;
7076
Bram Moolenaar0f873732019-12-05 20:28:46 +01007077 // Need to use GlobalMemoryStatusEx() when there is more memory than
7078 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007079 ms.dwLength = sizeof(MEMORYSTATUSEX);
7080 GlobalMemoryStatusEx(&ms);
7081 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007082 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007083 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007084 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007085 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007086 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007087 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007088 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007089 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007090 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007091 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007092 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007093}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007094
Bram Moolenaar071d4272004-06-13 20:20:40 +00007095/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007096 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00007097 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
7098 * file whose short file name is "FOO.BAR" (its long file name will
7099 * be correct: "foo.bar~"). Because a file can be accessed by
7100 * either its SFN or its LFN, "foo.bar" has effectively been
7101 * renamed to "foo.bar", which is not at all what was wanted. This
7102 * seems to happen only when renaming files with three-character
7103 * extensions by appending a suffix that does not include ".".
7104 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
7105 *
7106 * There is another problem, which isn't really a bug but isn't right either:
7107 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
7108 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
7109 * service pack 6. Doesn't seem to happen on Windows 98.
7110 *
7111 * Like rename(), returns 0 upon success, non-zero upon failure.
7112 * Should probably set errno appropriately when errors occur.
7113 */
7114 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007115mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007116{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007117 WCHAR *p;
7118 int i;
7119 WCHAR szTempFile[_MAX_PATH + 1];
7120 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007121 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007122
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007123 // No need to play tricks unless the file name contains a "~" as the
7124 // seventh character.
7125 p = wold;
7126 for (i = 0; wold[i] != NUL; ++i)
7127 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
7128 && wold[i + 1] != 0)
7129 p = wold + i + 1;
7130 if ((int)(wold + i - p) < 8 || p[6] != '~')
7131 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007132
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007133 // Get base path of new file name. Undocumented feature: If pszNewFile is
7134 // a directory, no error is returned and pszFilePart will be NULL.
7135 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007136 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007137 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007138
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007139 // Get (and create) a unique temporary file name in directory of new file
7140 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007141 return -2;
7142
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007143 // blow the temp file away
7144 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007145 return -3;
7146
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007147 // rename old file to the temp file
7148 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007149 return -4;
7150
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007151 // now create an empty file called pszOldFile; this prevents the operating
7152 // system using pszOldFile as an alias (SFN) if we're renaming within the
7153 // same directory. For example, we're editing a file called
7154 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7155 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7156 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7157 // cause all sorts of problems later in buf_write(). So, we create an
7158 // empty file called filena~1.txt and the system will have to find some
7159 // other SFN for filena~1.txt~, such as filena~2.txt
7160 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007161 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7162 return -5;
7163 if (!CloseHandle(hf))
7164 return -6;
7165
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007166 // rename the temp file to the new file
7167 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007168 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007169 // Renaming failed. Rename the file back to its old name, so that it
7170 // looks like nothing happened.
7171 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007172 return -7;
7173 }
7174
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007175 // Seems to be left around on Novell filesystems
7176 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007177
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007178 // finally, remove the empty old file
7179 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007180 return -8;
7181
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007182 return 0;
7183}
7184
7185
7186/*
7187 * Converts the filenames to UTF-16, then call mch_wrename().
7188 * Like rename(), returns 0 upon success, non-zero upon failure.
7189 */
7190 int
7191mch_rename(
7192 const char *pszOldFile,
7193 const char *pszNewFile)
7194{
7195 WCHAR *wold = NULL;
7196 WCHAR *wnew = NULL;
7197 int retval = -1;
7198
7199 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7200 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7201 if (wold != NULL && wnew != NULL)
7202 retval = mch_wrename(wold, wnew);
7203 vim_free(wold);
7204 vim_free(wnew);
7205 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007206}
7207
7208/*
7209 * Get the default shell for the current hardware platform
7210 */
7211 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007212default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007213{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007214 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007215}
7216
7217/*
7218 * mch_access() extends access() to do more detailed check on network drives.
7219 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7220 */
7221 int
7222mch_access(char *n, int p)
7223{
7224 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007225 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007226 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007227
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007228 wn = enc_to_utf16((char_u *)n, NULL);
7229 if (wn == NULL)
7230 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007231
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007232 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007233 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007234 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007235
7236 if (p & R_OK)
7237 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007238 // Read check is performed by seeing if we can do a find file on
7239 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007240 int i;
7241 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007242
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007243 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7244 TempNameW[i] = wn[i];
7245 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7246 TempNameW[i++] = '\\';
7247 TempNameW[i++] = '*';
7248 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007249
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007250 hFile = FindFirstFileW(TempNameW, &d);
7251 if (hFile == INVALID_HANDLE_VALUE)
7252 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007253 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007254 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007255 }
7256
7257 if (p & W_OK)
7258 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007259 // Trying to create a temporary file in the directory should catch
7260 // directories on read-only network shares. However, in
7261 // directories whose ACL allows writes but denies deletes will end
7262 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007263 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7264 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007265 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007266 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007267 }
7268 }
7269 else
7270 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007271 // Don't consider a file read-only if another process has opened it.
7272 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7273
Bram Moolenaar0f873732019-12-05 20:28:46 +01007274 // Trying to open the file for the required access does ACL, read-only
7275 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007276 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7277 | ((p & R_OK) ? GENERIC_READ : 0);
7278
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007279 hFile = CreateFileW(wn, access_mode, share_mode,
7280 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007281 if (hFile == INVALID_HANDLE_VALUE)
7282 goto getout;
7283 CloseHandle(hFile);
7284 }
7285
Bram Moolenaar0f873732019-12-05 20:28:46 +01007286 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007287getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007288 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007289 return retval;
7290}
7291
Bram Moolenaar071d4272004-06-13 20:20:40 +00007292/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007293 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007294 */
7295 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007296mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007297{
7298 WCHAR *wn;
7299 int f;
7300
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007301 wn = enc_to_utf16((char_u *)name, NULL);
7302 if (wn == NULL)
7303 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007304
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007305 f = _wopen(wn, flags, mode);
7306 vim_free(wn);
7307 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007308}
7309
7310/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007311 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007312 */
7313 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007314mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007315{
7316 WCHAR *wn, *wm;
7317 FILE *f = NULL;
7318
Bram Moolenaara12a1612019-01-24 16:39:02 +01007319#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007320 // Work around an annoying assertion in the Microsoft debug CRT
7321 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007322 char newMode = mode[strlen(mode) - 1];
7323 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007324
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007325 _get_fmode(&oldMode);
7326 if (newMode == 't')
7327 _set_fmode(_O_TEXT);
7328 else if (newMode == 'b')
7329 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007330#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007331 wn = enc_to_utf16((char_u *)name, NULL);
7332 wm = enc_to_utf16((char_u *)mode, NULL);
7333 if (wn != NULL && wm != NULL)
7334 f = _wfopen(wn, wm);
7335 vim_free(wn);
7336 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007337
Bram Moolenaara12a1612019-01-24 16:39:02 +01007338#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007339 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007340#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007341 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007342}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007343
Bram Moolenaar071d4272004-06-13 20:20:40 +00007344/*
7345 * SUB STREAM (aka info stream) handling:
7346 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007347 * NTFS can have sub streams for each file. The normal contents of a file is
7348 * stored in the main stream, and extra contents (author information, title and
7349 * so on) can be stored in a sub stream. After Windows 2000, the user can
7350 * access and store this information in sub streams via an explorer's property
7351 * menu item in the right click menu. This information in sub streams was lost
7352 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007353 *
7354 * Incomplete explanation:
7355 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7356 * More useful info and an example:
7357 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7358 */
7359
7360/*
7361 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7362 * and write to stream "substream" of file "to".
7363 * Errors are ignored.
7364 */
7365 static void
7366copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7367{
7368 HANDLE hTo;
7369 WCHAR *to_name;
7370
7371 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7372 wcscpy(to_name, to);
7373 wcscat(to_name, substream);
7374
7375 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7376 FILE_ATTRIBUTE_NORMAL, NULL);
7377 if (hTo != INVALID_HANDLE_VALUE)
7378 {
7379 long done;
7380 DWORD todo;
7381 DWORD readcnt, written;
7382 char buf[4096];
7383
Bram Moolenaar0f873732019-12-05 20:28:46 +01007384 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007385 for (done = 0; done < len; done += written)
7386 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007387 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007388 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7389 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007390 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7391 FALSE, FALSE, context)
7392 || readcnt != todo
7393 || !WriteFile(hTo, buf, todo, &written, NULL)
7394 || written != todo)
7395 break;
7396 }
7397 CloseHandle(hTo);
7398 }
7399
7400 free(to_name);
7401}
7402
7403/*
7404 * Copy info streams from file "from" to file "to".
7405 */
7406 static void
7407copy_infostreams(char_u *from, char_u *to)
7408{
7409 WCHAR *fromw;
7410 WCHAR *tow;
7411 HANDLE sh;
7412 WIN32_STREAM_ID sid;
7413 int headersize;
7414 WCHAR streamname[_MAX_PATH];
7415 DWORD readcount;
7416 void *context = NULL;
7417 DWORD lo, hi;
7418 int len;
7419
Bram Moolenaar0f873732019-12-05 20:28:46 +01007420 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007421 fromw = enc_to_utf16(from, NULL);
7422 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007423 if (fromw != NULL && tow != NULL)
7424 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007425 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007426 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7427 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7428 if (sh != INVALID_HANDLE_VALUE)
7429 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007430 // Use BackupRead() to find the info streams. Repeat until we
7431 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007432 for (;;)
7433 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007434 // Get the header to find the length of the stream name. If
7435 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007436 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007437 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007438 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7439 &readcount, FALSE, FALSE, &context)
7440 || readcount == 0)
7441 break;
7442
Bram Moolenaar0f873732019-12-05 20:28:46 +01007443 // We only deal with streams that have a name. The normal
7444 // file data appears to be without a name, even though docs
7445 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007446 if (sid.dwStreamNameSize > 0)
7447 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007448 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007449 if (!BackupRead(sh, (LPBYTE)streamname,
7450 sid.dwStreamNameSize,
7451 &readcount, FALSE, FALSE, &context))
7452 break;
7453
Bram Moolenaar0f873732019-12-05 20:28:46 +01007454 // Copy an info stream with a name ":anything:$DATA".
7455 // Skip "::$DATA", it has no stream name (examples suggest
7456 // it might be used for the normal file contents).
7457 // Note that BackupRead() counts bytes, but the name is in
7458 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007459 len = readcount / sizeof(WCHAR);
7460 streamname[len] = 0;
7461 if (len > 7 && wcsicmp(streamname + len - 6,
7462 L":$DATA") == 0)
7463 {
7464 streamname[len - 6] = 0;
7465 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007466 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007467 }
7468 }
7469
Bram Moolenaar0f873732019-12-05 20:28:46 +01007470 // Advance to the next stream. We might try seeking too far,
7471 // but BackupSeek() doesn't skip over stream borders, thus
7472 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007473 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007474 &lo, &hi, &context);
7475 }
7476
Bram Moolenaar0f873732019-12-05 20:28:46 +01007477 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007478 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7479
7480 CloseHandle(sh);
7481 }
7482 }
7483 vim_free(fromw);
7484 vim_free(tow);
7485}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007486
7487/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007488 * ntdll.dll definitions
7489 */
7490#define FileEaInformation 7
7491#ifndef STATUS_SUCCESS
7492# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7493#endif
7494
7495typedef struct _FILE_FULL_EA_INFORMATION_ {
7496 ULONG NextEntryOffset;
7497 UCHAR Flags;
7498 UCHAR EaNameLength;
7499 USHORT EaValueLength;
7500 CHAR EaName[1];
7501} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7502
7503typedef struct _FILE_EA_INFORMATION_ {
7504 ULONG EaSize;
7505} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7506
Paul Ollis65745772022-06-05 16:55:54 +01007507#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007508typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7509 PHANDLE FileHandle,
7510 ACCESS_MASK DesiredAccess,
7511 POBJECT_ATTRIBUTES ObjectAttributes,
7512 PIO_STATUS_BLOCK IoStatusBlock,
7513 ULONG ShareAccess,
7514 ULONG OpenOptions);
7515typedef NTSTATUS (NTAPI *PfnNtClose)(
7516 HANDLE Handle);
7517typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007518 HANDLE FileHandle,
7519 PIO_STATUS_BLOCK IoStatusBlock,
7520 PVOID Buffer,
7521 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007522typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7523 HANDLE FileHandle,
7524 PIO_STATUS_BLOCK IoStatusBlock,
7525 PVOID Buffer,
7526 ULONG Length,
7527 BOOLEAN ReturnSingleEntry,
7528 PVOID EaList,
7529 ULONG EaListLength,
7530 PULONG EaIndex,
7531 BOOLEAN RestartScan);
7532typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007533 HANDLE FileHandle,
7534 PIO_STATUS_BLOCK IoStatusBlock,
7535 PVOID FileInformation,
7536 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007537 FILE_INFORMATION_CLASS FileInformationClass);
7538typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7539 PUNICODE_STRING DestinationString,
7540 PCWSTR SourceString);
7541
7542PfnNtOpenFile pNtOpenFile = NULL;
7543PfnNtClose pNtClose = NULL;
7544PfnNtSetEaFile pNtSetEaFile = NULL;
7545PfnNtQueryEaFile pNtQueryEaFile = NULL;
7546PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7547PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01007548#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007549
7550/*
7551 * Load ntdll.dll functions.
7552 */
7553 static BOOL
7554load_ntdll(void)
7555{
7556 static int loaded = -1;
7557
7558 if (loaded == -1)
7559 {
7560 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7561 if (hNtdll != NULL)
7562 {
7563 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7564 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7565 pNtSetEaFile = (PfnNtSetEaFile)
7566 GetProcAddress(hNtdll, "NtSetEaFile");
7567 pNtQueryEaFile = (PfnNtQueryEaFile)
7568 GetProcAddress(hNtdll, "NtQueryEaFile");
7569 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7570 GetProcAddress(hNtdll, "NtQueryInformationFile");
7571 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7572 GetProcAddress(hNtdll, "RtlInitUnicodeString");
7573 }
7574 if (pNtOpenFile == NULL
7575 || pNtClose == NULL
7576 || pNtSetEaFile == NULL
7577 || pNtQueryEaFile == NULL
7578 || pNtQueryInformationFile == NULL
7579 || pRtlInitUnicodeString == NULL)
7580 loaded = FALSE;
7581 else
7582 loaded = TRUE;
7583 }
7584 return (BOOL) loaded;
7585}
7586
7587/*
7588 * Copy extended attributes (EA) from file "from" to file "to".
7589 */
7590 static void
7591copy_extattr(char_u *from, char_u *to)
7592{
7593 char_u *fromf = NULL;
7594 char_u *tof = NULL;
7595 WCHAR *fromw = NULL;
7596 WCHAR *tow = NULL;
7597 UNICODE_STRING u;
7598 HANDLE h;
7599 OBJECT_ATTRIBUTES oa;
7600 IO_STATUS_BLOCK iosb;
7601 FILE_EA_INFORMATION_ eainfo = {0};
7602 void *ea = NULL;
7603
7604 if (!load_ntdll())
7605 return;
7606
7607 // Convert the file names to the fully qualified object names.
7608 fromf = alloc(STRLEN(from) + 5);
7609 tof = alloc(STRLEN(to) + 5);
7610 if (fromf == NULL || tof == NULL)
7611 goto theend;
7612 STRCPY(fromf, "\\??\\");
7613 STRCAT(fromf, from);
7614 STRCPY(tof, "\\??\\");
7615 STRCAT(tof, to);
7616
7617 // Convert the names to wide characters.
7618 fromw = enc_to_utf16(fromf, NULL);
7619 tow = enc_to_utf16(tof, NULL);
7620 if (fromw == NULL || tow == NULL)
7621 goto theend;
7622
7623 // Get the EA.
7624 pRtlInitUnicodeString(&u, fromw);
7625 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7626 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7627 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7628 goto theend;
7629 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7630 FileEaInformation);
7631 if (eainfo.EaSize != 0)
7632 {
7633 ea = alloc(eainfo.EaSize);
7634 if (ea != NULL)
7635 {
7636 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7637 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7638 {
7639 vim_free(ea);
7640 ea = NULL;
7641 }
7642 }
7643 }
7644 pNtClose(h);
7645
7646 // Set the EA.
7647 if (ea != NULL)
7648 {
7649 pRtlInitUnicodeString(&u, tow);
7650 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7651 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7652 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7653 goto theend;
7654
7655 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
7656 pNtClose(h);
7657 }
7658
7659theend:
7660 vim_free(fromf);
7661 vim_free(tof);
7662 vim_free(fromw);
7663 vim_free(tow);
7664 vim_free(ea);
7665}
7666
7667/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007668 * Copy file attributes from file "from" to file "to".
7669 * For Windows NT and later we copy info streams.
7670 * Always returns zero, errors are ignored.
7671 */
7672 int
7673mch_copy_file_attribute(char_u *from, char_u *to)
7674{
Bram Moolenaar0f873732019-12-05 20:28:46 +01007675 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007676 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007677 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007678 return 0;
7679}
7680
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007681
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007682/*
K.Takatadc73b4b2021-06-08 18:32:36 +02007683 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007684 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007685static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007686static LPWSTR *ArglistW = NULL;
7687static int global_argc = 0;
7688static char **global_argv;
7689
Bram Moolenaar0f873732019-12-05 20:28:46 +01007690static int used_file_argc = 0; // last argument in global_argv[] used
7691 // for the argument list.
7692static int *used_file_indexes = NULL; // indexes in global_argv[] for
7693 // command line arguments added to
7694 // the argument list
7695static int used_file_count = 0; // nr of entries in used_file_indexes
7696static int used_file_literal = FALSE; // take file names literally
7697static int used_file_full_path = FALSE; // file name was full path
7698static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007699static int used_alist_count = 0;
7700
7701
7702/*
7703 * Get the command line arguments. Unicode version.
7704 * Returns argc. Zero when something fails.
7705 */
7706 int
7707get_cmd_argsW(char ***argvp)
7708{
7709 char **argv = NULL;
7710 int argc = 0;
7711 int i;
7712
Bram Moolenaar14993322014-09-09 12:25:33 +02007713 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007714 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7715 if (ArglistW != NULL)
7716 {
7717 argv = malloc((nArgsW + 1) * sizeof(char *));
7718 if (argv != NULL)
7719 {
7720 argc = nArgsW;
7721 argv[argc] = NULL;
7722 for (i = 0; i < argc; ++i)
7723 {
7724 int len;
7725
K.Takatadc73b4b2021-06-08 18:32:36 +02007726 // Convert each Unicode argument to UTF-8.
7727 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007728 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007729 (LPSTR *)&argv[i], &len, 0, 0);
7730 if (argv[i] == NULL)
7731 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007732 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007733 while (i > 0)
7734 free(argv[--i]);
7735 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007736 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007737 argc = 0;
7738 }
7739 }
7740 }
7741 }
7742
7743 global_argc = argc;
7744 global_argv = argv;
7745 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007746 {
7747 if (used_file_indexes != NULL)
7748 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007749 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007750 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007751
7752 if (argvp != NULL)
7753 *argvp = argv;
7754 return argc;
7755}
7756
7757 void
7758free_cmd_argsW(void)
7759{
7760 if (ArglistW != NULL)
7761 {
7762 GlobalFree(ArglistW);
7763 ArglistW = NULL;
7764 }
7765}
7766
7767/*
7768 * Remember "name" is an argument that was added to the argument list.
7769 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7770 * is called.
7771 */
7772 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007773used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007774{
7775 int i;
7776
7777 if (used_file_indexes == NULL)
7778 return;
7779 for (i = used_file_argc + 1; i < global_argc; ++i)
7780 if (STRCMP(global_argv[i], name) == 0)
7781 {
7782 used_file_argc = i;
7783 used_file_indexes[used_file_count++] = i;
7784 break;
7785 }
7786 used_file_literal = literal;
7787 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007788 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007789}
7790
7791/*
7792 * Remember the length of the argument list as it was. If it changes then we
7793 * leave it alone when 'encoding' is set.
7794 */
7795 void
7796set_alist_count(void)
7797{
7798 used_alist_count = GARGCOUNT;
7799}
7800
7801/*
7802 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02007803 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007804 * and convert them to 'encoding'.
7805 */
7806 void
7807fix_arg_enc(void)
7808{
7809 int i;
7810 int idx;
7811 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007812 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007813
Bram Moolenaar0f873732019-12-05 20:28:46 +01007814 // Safety checks:
7815 // - if argument count differs between the wide and non-wide argument
7816 // list, something must be wrong.
7817 // - the file name arguments must have been located.
7818 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007819 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007820 || ArglistW == NULL
7821 || used_file_indexes == NULL
7822 || used_file_count == 0
7823 || used_alist_count != GARGCOUNT)
7824 return;
7825
Bram Moolenaar0f873732019-12-05 20:28:46 +01007826 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007827 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007828 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007829 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00007830 for (i = 0; i < GARGCOUNT; ++i)
7831 fnum_list[i] = GARGLIST[i].ae_fnum;
7832
Bram Moolenaar0f873732019-12-05 20:28:46 +01007833 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007834 alist_clear(&global_alist);
7835 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007836 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007837
7838 for (i = 0; i < used_file_count; ++i)
7839 {
7840 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007841 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007842 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007843 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007844 int literal = used_file_literal;
7845
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007846#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01007847 // When using diff mode may need to concatenate file name to
7848 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007849 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7850 && !mch_isdir(alist_name(&GARGLIST[0])))
7851 {
7852 char_u *r;
7853
7854 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7855 if (r != NULL)
7856 {
7857 vim_free(str);
7858 str = r;
7859 }
7860 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007861#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01007862 // Re-use the old buffer by renaming it. When not using literal
7863 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00007864 if (used_file_literal)
7865 buf_set_name(fnum_list[i], str);
7866
Bram Moolenaar0f873732019-12-05 20:28:46 +01007867 // Check backtick literal. backtick literal is already expanded in
7868 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007869 if (literal == FALSE)
7870 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007871 size_t len = STRLEN(str);
7872
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007873 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7874 literal = TRUE;
7875 }
7876 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007877 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007878 }
7879
7880 if (!used_file_literal)
7881 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007882 // Now expand wildcards in the arguments.
7883 // Temporarily add '(' and ')' to 'isfname'. These are valid
7884 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00007885 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01007886 // Also, unset wildignore to not be influenced by this option.
7887 // The arguments specified in command-line should be kept even if
7888 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00007889 // Use :legacy so that it also works when in Vim9 script.
7890 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
7891 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007892 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00007893 do_cmdline_cmd(
7894 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
7895 do_cmdline_cmd(
7896 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007897 }
7898
Bram Moolenaar0f873732019-12-05 20:28:46 +01007899 // If wildcard expansion failed, we are editing the first file of the
7900 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007901 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7902 {
7903 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00007904 if (GARGCOUNT == 1 && used_file_full_path
7905 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
7906 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007907 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007908
7909 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007910}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007911
7912 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007913mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007914{
7915 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007916 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007917
Bram Moolenaar964b3742019-05-24 18:54:09 +02007918 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007919 if (envbuf == NULL)
7920 return -1;
7921
7922 sprintf((char *)envbuf, "%s=%s", var, value);
7923
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007924 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007925
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007926 vim_free(envbuf);
7927 if (p == NULL)
7928 return -1;
7929 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007930#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007931 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007932#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007933 // Unlike Un*x systems, we can free the string for _wputenv().
7934 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007935
7936 return 0;
7937}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007938
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007939/*
7940 * Support for 256 colors and 24-bit colors was added in Windows 10
7941 * version 1703 (Creators update).
7942 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007943#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7944
7945/*
7946 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02007947 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007948 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007949#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007950
7951/*
7952 * ConPTY differences between versions, need different logic.
7953 * version 1903 (May 2019 update).
7954 */
7955#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
7956
7957/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007958 * version 1909 (November 2019 update).
7959 */
7960#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
7961
7962/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007963 * Stay ahead of the next update, and when it's done, fix this.
7964 * version ? (2020 update, temporarily use the build number of insider preview)
7965 */
7966#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
7967
7968/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02007969 * Confirm until this version. Also the logic changes.
7970 * insider preview.
7971 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02007972#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007973
7974/*
7975 * Not stable now.
7976 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007977#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Christopher Plewright1140b512022-11-12 18:46:05 +00007978// Notes:
7979// Win 10 22H2 Final is build 19045, it's conpty is widely used.
7980// Strangely, 19045 is newer but is a lower build number than the 2020 insider
7981// preview which had a build 19587. And, not sure how stable that was?
7982// Win Server 2022 (May 10, 2022) is build 20348, its conpty is widely used.
7983// Win 11 starts from build 22000, even though the major version says 10!
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007984
7985 static void
7986vtp_flag_init(void)
7987{
7988 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007989#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007990 DWORD mode;
7991 HANDLE out;
7992
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007993# ifdef VIMDLL
7994 if (!gui.in_use)
7995# endif
7996 {
7997 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007998
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007999 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
8000 GetConsoleMode(out, &mode);
8001 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
8002 if (SetConsoleMode(out, mode) == 0)
8003 vtp_working = 0;
8004 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008005#endif
8006
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008007 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008008 conpty_working = 1;
8009 if (ver >= CONPTY_STABLE_BUILD)
8010 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008011
Bram Moolenaar57da6982019-09-13 22:30:11 +02008012 if (ver <= CONPTY_INSIDER_BUILD)
8013 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008014 if (ver <= CONPTY_1909_BUILD)
8015 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02008016 if (ver <= CONPTY_1903_BUILD)
8017 conpty_type = 2;
8018 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
8019 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008020
8021 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
8022 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008023}
8024
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008025#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008026
8027 static void
8028vtp_init(void)
8029{
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008030# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00008031 if (!vtp_working)
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008032 {
Christopher Plewright38804d62022-11-09 23:55:52 +00008033 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8034 csbi.cbSize = sizeof(csbi);
8035 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8036 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
8037 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
8038 store_console_bg_rgb = save_console_bg_rgb;
8039 store_console_fg_rgb = save_console_fg_rgb;
8040
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008041 COLORREF bg;
8042 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
8043 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8044 default_console_color_bg = bg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008045
8046 COLORREF fg;
8047 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
8048 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8049 default_console_color_fg = fg;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008050 }
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008051# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008052
8053 set_console_color_rgb();
8054}
8055
8056 static void
8057vtp_exit(void)
8058{
Bram Moolenaardf543822020-01-30 11:53:59 +01008059 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008060}
8061
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008062 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008063vtp_printf(
8064 char *format,
8065 ...)
8066{
8067 char_u buf[100];
8068 va_list list;
8069 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008070 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008071
8072 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008073 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008074 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008075 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008076 return (int)result;
8077}
8078
8079 static void
8080vtp_sgr_bulk(
8081 int arg)
8082{
8083 int args[1];
8084
8085 args[0] = arg;
8086 vtp_sgr_bulks(1, args);
8087}
8088
K.Takata6e1d31e2022-02-03 13:05:32 +00008089# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008090 if ((*p-- = "0123456789"[(n = x % 10)]) \
8091 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8092 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8093
K.Takata6e1d31e2022-02-03 13:05:32 +00008094# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008095 case x: \
8096 FAST256(newargs[x - 1]);
8097
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008098 static void
8099vtp_sgr_bulks(
8100 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008101 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008102{
K.Takata6e1d31e2022-02-03 13:05:32 +00008103# define MAXSGR 16
8104# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008105 char_u buf[SGRBUFSIZE];
8106 char_u *p;
8107 int in, out;
8108 int newargs[16];
8109 static int sgrfgr = -1, sgrfgg, sgrfgb;
8110 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008111
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008112 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008113 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008114 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008115 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008116 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008117 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008118
8119 in = out = 0;
8120 while (in < argc)
8121 {
8122 int s = args[in];
8123 int copylen = 1;
8124
8125 if (s == 38)
8126 {
8127 if (argc - in >= 5 && args[in + 1] == 2)
8128 {
8129 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8130 && sgrfgb == args[in + 4])
8131 {
8132 in += 5;
8133 copylen = 0;
8134 }
8135 else
8136 {
8137 sgrfgr = args[in + 2];
8138 sgrfgg = args[in + 3];
8139 sgrfgb = args[in + 4];
8140 copylen = 5;
8141 }
8142 }
8143 else if (argc - in >= 3 && args[in + 1] == 5)
8144 {
8145 sgrfgr = -1;
8146 copylen = 3;
8147 }
8148 }
8149 else if (s == 48)
8150 {
8151 if (argc - in >= 5 && args[in + 1] == 2)
8152 {
8153 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8154 && sgrbgb == args[in + 4])
8155 {
8156 in += 5;
8157 copylen = 0;
8158 }
8159 else
8160 {
8161 sgrbgr = args[in + 2];
8162 sgrbgg = args[in + 3];
8163 sgrbgb = args[in + 4];
8164 copylen = 5;
8165 }
8166 }
8167 else if (argc - in >= 3 && args[in + 1] == 5)
8168 {
8169 sgrbgr = -1;
8170 copylen = 3;
8171 }
8172 }
8173 else if (30 <= s && s <= 39)
8174 sgrfgr = -1;
8175 else if (90 <= s && s <= 97)
8176 sgrfgr = -1;
8177 else if (40 <= s && s <= 49)
8178 sgrbgr = -1;
8179 else if (100 <= s && s <= 107)
8180 sgrbgr = -1;
8181 else if (s == 0)
8182 sgrfgr = sgrbgr = -1;
8183
8184 while (copylen--)
8185 newargs[out++] = args[in++];
8186 }
8187
8188 p = &buf[sizeof(buf) - 1];
8189 *p-- = 'm';
8190
8191 switch (out)
8192 {
8193 int n, m;
8194 DWORD r;
8195
8196 FAST256CASE(16);
8197 *p-- = ';';
8198 FAST256CASE(15);
8199 *p-- = ';';
8200 FAST256CASE(14);
8201 *p-- = ';';
8202 FAST256CASE(13);
8203 *p-- = ';';
8204 FAST256CASE(12);
8205 *p-- = ';';
8206 FAST256CASE(11);
8207 *p-- = ';';
8208 FAST256CASE(10);
8209 *p-- = ';';
8210 FAST256CASE(9);
8211 *p-- = ';';
8212 FAST256CASE(8);
8213 *p-- = ';';
8214 FAST256CASE(7);
8215 *p-- = ';';
8216 FAST256CASE(6);
8217 *p-- = ';';
8218 FAST256CASE(5);
8219 *p-- = ';';
8220 FAST256CASE(4);
8221 *p-- = ';';
8222 FAST256CASE(3);
8223 *p-- = ';';
8224 FAST256CASE(2);
8225 *p-- = ';';
8226 FAST256CASE(1);
8227 *p-- = '[';
8228 *p = '\033';
8229 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8230 default:
8231 break;
8232 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008233}
8234
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008235 static void
8236wt_init(void)
8237{
Christopher Plewright1140b512022-11-12 18:46:05 +00008238 wt_working = mch_getenv("WT_SESSION") != NULL;
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008239}
8240
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008241# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008242 static int
8243ctermtoxterm(
8244 int cterm)
8245{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008246 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008247
8248 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8249 return (((int)r << 16) | ((int)g << 8) | (int)b);
8250}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008251# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008252
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008253 static void
8254set_console_color_rgb(void)
8255{
8256# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008257 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008258 guicolor_T fg, bg;
8259 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008260
Christopher Plewright38804d62022-11-09 23:55:52 +00008261 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008262 return;
8263
Bram Moolenaara050b942019-12-02 21:35:31 +01008264 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8265
Christopher Plewright38804d62022-11-09 23:55:52 +00008266 if (p_tgc || t_colors >= 256)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008267 {
8268 term_fg_rgb_color(fg);
8269 term_bg_rgb_color(bg);
8270 return;
8271 }
8272
Christopher Plewright38804d62022-11-09 23:55:52 +00008273 if (!conpty_working)
8274 {
8275 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8276 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008277
Christopher Plewright38804d62022-11-09 23:55:52 +00008278 csbi.cbSize = sizeof(csbi);
8279 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008280
Christopher Plewright38804d62022-11-09 23:55:52 +00008281 csbi.cbSize = sizeof(csbi);
8282 csbi.srWindow.Right += 1;
8283 csbi.srWindow.Bottom += 1;
8284 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8285 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
8286 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8287 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
8288 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8289 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008290# endif
8291}
8292
Bram Moolenaara050b942019-12-02 21:35:31 +01008293# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8294 void
8295get_default_console_color(
8296 int *cterm_fg,
8297 int *cterm_bg,
8298 guicolor_T *gui_fg,
8299 guicolor_T *gui_bg)
8300{
8301 int id;
8302 guicolor_T guifg = INVALCOLOR;
8303 guicolor_T guibg = INVALCOLOR;
8304 int ctermfg = 0;
8305 int ctermbg = 0;
Christopher Plewright38804d62022-11-09 23:55:52 +00008306 int dummynull = 0;
Bram Moolenaara050b942019-12-02 21:35:31 +01008307
8308 id = syn_name2id((char_u *)"Normal");
8309 if (id > 0 && p_tgc)
8310 syn_id2colors(id, &guifg, &guibg);
8311 if (guifg == INVALCOLOR)
8312 {
8313 ctermfg = -1;
8314 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008315 syn_id2cterm_bg(id, &ctermfg, &dummynull);
8316 if (vtp_working)
8317 {
8318 cterm_normal_fg_gui_color = guifg =
8319 ctermfg != -1 ? ctermtoxterm(ctermfg) : INVALCOLOR;
8320 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8321 }
8322 else
8323 {
8324 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
Bram Moolenaara050b942019-12-02 21:35:31 +01008325 : default_console_color_fg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008326 cterm_normal_fg_gui_color = guifg;
8327 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8328 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008329 }
8330 if (guibg == INVALCOLOR)
8331 {
8332 ctermbg = -1;
8333 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008334 syn_id2cterm_bg(id, &dummynull, &ctermbg);
8335 if (vtp_working)
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008336 {
8337 cterm_normal_bg_gui_color = guibg =
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01008338 ctermbg != -1 ? ctermtoxterm(ctermbg) : INVALCOLOR;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008339 if (ctermbg < 0)
8340 ctermbg = 0;
8341 }
K.Takatae53a0d42022-09-05 21:45:11 +01008342 else
8343 {
8344 guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8345 : default_console_color_bg;
8346 cterm_normal_bg_gui_color = guibg;
8347 ctermbg = ctermbg < 0 ? 0 : ctermbg;
8348 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008349 }
8350
8351 *cterm_fg = ctermfg;
8352 *cterm_bg = ctermbg;
8353 *gui_fg = guifg;
8354 *gui_bg = guibg;
8355}
8356# endif
8357
Bram Moolenaardf543822020-01-30 11:53:59 +01008358/*
8359 * Set the console colors to the original colors or the last set colors.
8360 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008361 static void
8362reset_console_color_rgb(void)
8363{
8364# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008365
Christopher Plewright38804d62022-11-09 23:55:52 +00008366 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008367 return;
8368
Christopher Plewright38804d62022-11-09 23:55:52 +00008369 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8370
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008371 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008372 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008373
8374 csbi.cbSize = sizeof(csbi);
8375 csbi.srWindow.Right += 1;
8376 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008377 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8378 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008379 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008380# endif
8381}
8382
8383/*
8384 * Set the console colors to the original colors.
8385 */
8386 static void
8387restore_console_color_rgb(void)
8388{
8389# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00008390 if (vtp_working)
8391 return;
8392
K.Takata27b53be2022-09-18 12:25:49 +01008393 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008394
8395 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008396 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008397
8398 csbi.cbSize = sizeof(csbi);
8399 csbi.srWindow.Right += 1;
8400 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008401 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8402 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008403 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008404# endif
8405}
8406
8407 void
8408control_console_color_rgb(void)
8409{
Christopher Plewright38804d62022-11-09 23:55:52 +00008410 if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008411 set_console_color_rgb();
8412 else
8413 reset_console_color_rgb();
8414}
8415
8416 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008417use_vtp(void)
8418{
8419 return USE_VTP;
8420}
8421
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008422 int
8423is_term_win32(void)
8424{
8425 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8426}
8427
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008428 int
8429has_vtp_working(void)
8430{
8431 return vtp_working;
8432}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008433
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008434#endif
8435
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008436 int
8437has_conpty_working(void)
8438{
8439 return conpty_working;
8440}
8441
8442 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008443get_conpty_type(void)
8444{
8445 return conpty_type;
8446}
8447
8448 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008449is_conpty_stable(void)
8450{
8451 return conpty_stable;
8452}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008453
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008454 int
8455get_conpty_fix_type(void)
8456{
8457 return conpty_fix_type;
8458}
8459
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008460#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008461 void
8462resize_console_buf(void)
8463{
8464 CONSOLE_SCREEN_BUFFER_INFO csbi;
8465 COORD coord;
8466 SMALL_RECT newsize;
8467
8468 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8469 {
8470 coord.X = SRWIDTH(csbi.srWindow);
8471 coord.Y = SRHEIGHT(csbi.srWindow);
8472 SetConsoleScreenBufferSize(g_hConOut, coord);
8473
8474 newsize.Left = 0;
8475 newsize.Top = 0;
8476 newsize.Right = coord.X - 1;
8477 newsize.Bottom = coord.Y - 1;
8478 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8479
8480 SetConsoleScreenBufferSize(g_hConOut, coord);
8481 }
8482}
8483#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008484
8485 char *
8486GetWin32Error(void)
8487{
K.Takatad68b2fc2022-02-12 11:18:37 +00008488 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008489 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008490
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008491 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8492 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008493 if (oldmsg != NULL)
8494 LocalFree(oldmsg);
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008495 if (msg != NULL)
8496 {
8497 // remove trailing \r\n
8498 char *pcrlf = strstr(msg, "\r\n");
8499 if (pcrlf != NULL)
8500 *pcrlf = '\0';
K.Takatad68b2fc2022-02-12 11:18:37 +00008501 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008502 }
8503 return msg;
8504}
Paul Ollis65745772022-06-05 16:55:54 +01008505
8506#if defined(FEAT_RELTIME) || defined(PROTO)
8507static HANDLE timer_handle;
8508static int timer_active = FALSE;
8509
8510/*
8511 * Calls to start_timeout alternate the return value pointer between the two
8512 * entries in timeout_flags. If the previously active timeout is very close to
8513 * expiring when start_timeout() is called then a race condition means that the
8514 * set_flag() function may still be invoked after the previous timer is
8515 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8516 * timeouts.
8517 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008518static sig_atomic_t timeout_flags[2];
8519static int timeout_flag_idx = 0;
8520static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01008521
8522
8523 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01008524set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01008525{
8526 int *timeout_flag = (int *)param;
8527
8528 *timeout_flag = TRUE;
8529}
8530
8531/*
8532 * Stop any active timeout.
8533 */
8534 void
8535stop_timeout(void)
8536{
8537 if (timer_active)
8538 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01008539 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01008540 timer_active = FALSE;
8541 if (!ret && GetLastError() != ERROR_IO_PENDING)
8542 {
8543 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
8544 }
8545 }
8546 *timeout_flag = FALSE;
8547}
8548
8549/*
8550 * Start the timeout timer.
8551 *
8552 * The period is defined in milliseconds.
8553 *
8554 * The return value is a pointer to a flag that is initialised to 0. If the
8555 * timeout expires, the flag is set to 1. This will only return pointers to
8556 * static memory; i.e. any pointer returned by this function may always be
8557 * safely dereferenced.
8558 *
8559 * This function is not expected to fail, but if it does it still returns a
8560 * valid flag pointer; the flag will remain stuck at zero.
8561 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008562 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01008563start_timeout(long msec)
8564{
Paul Ollis65745772022-06-05 16:55:54 +01008565 BOOL ret;
8566
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008567 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01008568
8569 stop_timeout();
8570 ret = CreateTimerQueueTimer(
8571 &timer_handle, NULL, set_flag, timeout_flag,
8572 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
8573 if (!ret)
8574 {
8575 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
8576 }
8577 else
8578 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008579 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01008580 timer_active = TRUE;
8581 *timeout_flag = FALSE;
8582 }
8583 return timeout_flag;
8584}
8585#endif