blob: d936e4f0871fde0e0662b098d2dbd3b21abc57cb [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
12 * Used for both the console version and the Win32 GUI. A lot of code is for
Bram Moolenaar4f974752019-02-17 17:44:42 +010013 * the console version only, so there is a lot of "#ifndef FEAT_GUI_MSWIN".
Bram Moolenaar071d4272004-06-13 20:20:40 +000014 *
15 * Win32 (Windows NT and Windows 95) system-dependent routines.
16 * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17 * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18 *
19 * George V. Reilly <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
Bram Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010032
Bram Moolenaar0f873732019-12-05 20:28:46 +010033// cproto fails on missing include files
Bram Moolenaar82881492012-11-20 16:53:39 +010034#ifndef PROTO
35# include <process.h>
Bram Moolenaare7bebc42021-02-01 20:50:37 +010036# include <winternl.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010037#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000038
39#undef chdir
40#ifdef __GNUC__
41# ifndef __MINGW32__
42# include <dirent.h>
43# endif
44#else
45# include <direct.h>
46#endif
47
Bram Moolenaar82881492012-11-20 16:53:39 +010048#ifndef PROTO
Bram Moolenaar651fca82021-11-29 20:39:38 +000049# if !defined(FEAT_GUI_MSWIN)
Bram Moolenaar82881492012-11-20 16:53:39 +010050# include <shellapi.h>
51# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000052#endif
53
Bram Moolenaarfb630902016-10-29 14:55:00 +020054#ifdef FEAT_JOB_CHANNEL
55# include <tlhelp32.h>
56#endif
57
Bram Moolenaar071d4272004-06-13 20:20:40 +000058#ifdef __MINGW32__
59# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
60# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
61# endif
62# ifndef RIGHTMOST_BUTTON_PRESSED
63# define RIGHTMOST_BUTTON_PRESSED 0x0002
64# endif
65# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
66# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
67# endif
68# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
69# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
70# endif
71# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
72# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
73# endif
74
75/*
76 * EventFlags
77 */
78# ifndef MOUSE_MOVED
79# define MOUSE_MOVED 0x0001
80# endif
81# ifndef DOUBLE_CLICK
82# define DOUBLE_CLICK 0x0002
83# endif
84#endif
85
Bram Moolenaar0f873732019-12-05 20:28:46 +010086// Record all output and all keyboard & mouse input
87// #define MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +000088
89#ifdef MCH_WRITE_DUMP
90FILE* fdDump = NULL;
91#endif
92
93/*
94 * When generating prototypes for Win32 on Unix, these lines make the syntax
95 * errors disappear. They do not need to be correct.
96 */
97#ifdef PROTO
Bram Moolenaar912bc4a2019-12-01 18:58:11 +010098# define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000099typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000100typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000101typedef int ACCESS_MASK;
102typedef int BOOL;
Paul Ollis65745772022-06-05 16:55:54 +0100103typedef int BOOLEAN;
104typedef int CALLBACK;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000105typedef int COLORREF;
106typedef int CONSOLE_CURSOR_INFO;
107typedef int COORD;
108typedef int DWORD;
109typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100110typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000111typedef int HDC;
112typedef int HFONT;
113typedef int HICON;
114typedef int HINSTANCE;
115typedef int HWND;
116typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200117typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000118typedef int KEY_EVENT_RECORD;
119typedef int LOGFONT;
120typedef int LPBOOL;
121typedef int LPCTSTR;
122typedef int LPDWORD;
123typedef int LPSTR;
124typedef int LPTSTR;
125typedef int LPVOID;
126typedef int MOUSE_EVENT_RECORD;
127typedef int PACL;
128typedef int PDWORD;
129typedef int PHANDLE;
130typedef int PRINTDLG;
131typedef int PSECURITY_DESCRIPTOR;
132typedef int PSID;
133typedef int SECURITY_INFORMATION;
134typedef int SHORT;
135typedef int SMALL_RECT;
136typedef int TEXTMETRIC;
137typedef int TOKEN_INFORMATION_CLASS;
138typedef int TRUSTEE;
139typedef int WORD;
140typedef int WCHAR;
141typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100142typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200143typedef int SE_OBJECT_TYPE;
144typedef int PSNSECINFO;
145typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100146typedef int STARTUPINFO;
147typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200148typedef int LPSECURITY_ATTRIBUTES;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100149# define __stdcall // empty
Bram Moolenaar071d4272004-06-13 20:20:40 +0000150#endif
151
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200152#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100153// Win32 Console handles for input and output
Bram Moolenaar071d4272004-06-13 20:20:40 +0000154static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
155static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
156
Bram Moolenaar0f873732019-12-05 20:28:46 +0100157// Win32 Screen buffer,coordinate,console I/O information
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158static SMALL_RECT g_srScrollRegion;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100159static COORD g_coord; // 0-based, but external coords are 1-based
Bram Moolenaar071d4272004-06-13 20:20:40 +0000160
Bram Moolenaar0f873732019-12-05 20:28:46 +0100161// The attribute of the screen when the editor was started
162static WORD g_attrDefault = 7; // lightgray text on black background
Bram Moolenaar071d4272004-06-13 20:20:40 +0000163static WORD g_attrCurrent;
164
Bram Moolenaar0f873732019-12-05 20:28:46 +0100165static int g_fCBrkPressed = FALSE; // set by ctrl-break interrupt
166static int g_fCtrlCPressed = FALSE; // set when ctrl-C or ctrl-break detected
167static int g_fForceExit = FALSE; // set when forcefully exiting
Bram Moolenaar071d4272004-06-13 20:20:40 +0000168
Bram Moolenaar071d4272004-06-13 20:20:40 +0000169static void scroll(unsigned cLines);
170static void set_scroll_region(unsigned left, unsigned top,
171 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100172static void set_scroll_region_tb(unsigned top, unsigned bottom);
173static void set_scroll_region_lr(unsigned left, unsigned right);
174static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000175static void delete_lines(unsigned cLines);
176static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000177static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000178static int s_cursor_visible = TRUE;
179static int did_create_conin = FALSE;
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200180#endif
181#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000182static int s_dont_use_vimrun = TRUE;
183static int need_vimrun_warning = FALSE;
184static char *vimrun_path = "vimrun ";
185#endif
186
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200187static int win32_getattrs(char_u *name);
188static int win32_setattrs(char_u *name, int attrs);
189static int win32_set_archive(char_u *name);
190
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100191static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200192static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100193static int conpty_stable = 0;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +0200194static int conpty_fix_type = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100195static void vtp_flag_init();
196
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200197#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100198static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100199static void vtp_init();
200static void vtp_exit();
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100201static void vtp_sgr_bulk(int arg);
202static void vtp_sgr_bulks(int argc, int *argv);
203
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200204static int wt_working = 0;
205static void wt_init();
206
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100207static guicolor_T save_console_bg_rgb;
208static guicolor_T save_console_fg_rgb;
Bram Moolenaardf543822020-01-30 11:53:59 +0100209static guicolor_T store_console_bg_rgb;
210static guicolor_T store_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100211
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200212static int g_color_index_bg = 0;
213static int g_color_index_fg = 7;
214
215# ifdef FEAT_TERMGUICOLORS
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +0100216static int default_console_color_bg = 0x000000; // black
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200217static int default_console_color_fg = 0xc0c0c0; // white
218# endif
219
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100220# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200221# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200222# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100223# else
224# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200225# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100226# endif
227
228static void set_console_color_rgb(void);
229static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100230static void restore_console_color_rgb(void);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100231#endif
232
Bram Moolenaar0f873732019-12-05 20:28:46 +0100233// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100234#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
235# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
236#endif
237
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200238#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100239static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000240#endif
241
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200242static char_u *exe_path = NULL;
243
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100244static BOOL win8_or_later = FALSE;
245
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200246#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100247// Dynamic loading for portability
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100248typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
249{
250 ULONG cbSize;
251 COORD dwSize;
252 COORD dwCursorPosition;
253 WORD wAttributes;
254 SMALL_RECT srWindow;
255 COORD dwMaximumWindowSize;
256 WORD wPopupAttributes;
257 BOOL bFullscreenSupported;
258 COLORREF ColorTable[16];
259} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
260typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
261static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
262typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
263static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
264static BOOL has_csbiex = FALSE;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100265#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100266
267/*
268 * Get version number including build number
269 */
270typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100271#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100272 (((major) << 24) | ((minor) << 16) | (build))
273
274 static DWORD
275get_build_number(void)
276{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100277 OSVERSIONINFOW osver;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100278 HMODULE hNtdll;
279 PfnRtlGetVersion pRtlGetVersion;
280 DWORD ver = MAKE_VER(0, 0, 0);
281
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100282 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100283 hNtdll = GetModuleHandle("ntdll.dll");
284 if (hNtdll != NULL)
285 {
286 pRtlGetVersion =
287 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
288 pRtlGetVersion(&osver);
289 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
290 min(osver.dwMinorVersion, 255),
291 min(osver.dwBuildNumber, 32767));
292 }
293 return ver;
294}
295
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200296#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200297 static BOOL
298is_ambiwidth_event(
299 INPUT_RECORD *ir)
300{
301 return ir->EventType == KEY_EVENT
302 && ir->Event.KeyEvent.bKeyDown
303 && ir->Event.KeyEvent.wRepeatCount == 1
304 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
305 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000306 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200307 && ir->Event.KeyEvent.dwControlKeyState == 2;
308}
309
310 static void
311make_ambiwidth_event(
312 INPUT_RECORD *down,
313 INPUT_RECORD *up)
314{
315 down->Event.KeyEvent.wVirtualKeyCode = 0;
316 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000317 down->Event.KeyEvent.uChar.UnicodeChar
318 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200319 down->Event.KeyEvent.dwControlKeyState = 0;
320}
321
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100322/*
323 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100324 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100325 */
326 static BOOL
327read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100328 HANDLE hInput,
329 INPUT_RECORD *lpBuffer,
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100330 int nLength,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100331 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100332{
333 enum
334 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100335 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100336 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100337 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100338 static DWORD s_dwIndex = 0;
339 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100340 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100341 int head;
342 int tail;
343 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200344 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100345
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200346 if (nLength == -2)
347 return (s_dwMax > 0) ? TRUE : FALSE;
348
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100349 if (!win8_or_later)
350 {
351 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200352 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
353 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100354 }
355
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100356 if (s_dwMax == 0)
357 {
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200358 if (!USE_WT && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200359 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200360 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
361 if (dwEvents == 0 && nLength == -1)
362 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
363 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100364 s_dwIndex = 0;
365 s_dwMax = dwEvents;
366 if (dwEvents == 0)
367 {
368 *lpEvents = 0;
369 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100370 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100371
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200372 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
373 if (is_ambiwidth_event(&s_irCache[i]))
374 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
375
Bram Moolenaardd415a62014-02-05 14:02:27 +0100376 if (s_dwMax > 1)
377 {
378 head = 0;
379 tail = s_dwMax - 1;
380 while (head != tail)
381 {
382 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
383 && s_irCache[head + 1].EventType
384 == WINDOW_BUFFER_SIZE_EVENT)
385 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100386 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100387 for (i = head; i < tail; ++i)
388 s_irCache[i] = s_irCache[i + 1];
389 --tail;
390 continue;
391 }
392 head++;
393 }
394 s_dwMax = tail + 1;
395 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100396 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100397
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200398 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
399 {
400 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
401 {
402 s_irPseudo = s_irCache[s_dwIndex];
403 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
404 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
405 *lpBuffer = s_irPseudo;
406 *lpEvents = 1;
407 return TRUE;
408 }
409 }
410
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100411 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200412 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100413 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100414 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100415 return TRUE;
416}
417
418/*
419 * Version of PeekConsoleInput() that works with IME.
420 */
421 static BOOL
422peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100423 HANDLE hInput,
424 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200425 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100426 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100427{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100428 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100429}
430
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100431# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200432 static DWORD
433msg_wait_for_multiple_objects(
434 DWORD nCount,
435 LPHANDLE pHandles,
436 BOOL fWaitAll,
437 DWORD dwMilliseconds,
438 DWORD dwWakeMask)
439{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100440 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200441 return WAIT_OBJECT_0;
442 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
443 dwMilliseconds, dwWakeMask);
444}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100445# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200446
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100447# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200448 static DWORD
449wait_for_single_object(
450 HANDLE hHandle,
451 DWORD dwMilliseconds)
452{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100453 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200454 return WAIT_OBJECT_0;
455 return WaitForSingleObject(hHandle, dwMilliseconds);
456}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100457# endif
458#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200459
Bram Moolenaar071d4272004-06-13 20:20:40 +0000460 static void
461get_exe_name(void)
462{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100463 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
464 // as the maximum length that works (plus a NUL byte).
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100465#define MAX_ENV_PATH_LEN 8192
466 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200467 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000468
469 if (exe_name == NULL)
470 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100471 // store the name of the executable, may be used for $VIM
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100472 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000473 if (*temp != NUL)
474 exe_name = FullName_save((char_u *)temp, FALSE);
475 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000476
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200477 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000478 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200479 exe_path = vim_strnsave(exe_name, gettail_sep(exe_name) - exe_name);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200480 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000481 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100482 // Append our starting directory to $PATH, so that when doing
483 // "!xxd" it's found in our starting directory. Needed because
484 // SearchPath() also looks there.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200485 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100486 if (p == NULL
487 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200488 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100489 if (p == NULL || *p == NUL)
490 temp[0] = NUL;
491 else
492 {
493 STRCPY(temp, p);
494 STRCAT(temp, ";");
495 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200496 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100497 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200498 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000499 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000500 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000501}
502
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200503/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100504 * Unescape characters in "p" that appear in "escaped".
505 */
506 static void
507unescape_shellxquote(char_u *p, char_u *escaped)
508{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100509 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100510 int n;
511
512 while (*p != NUL)
513 {
514 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
515 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100516 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100517 p += n;
518 l -= n;
519 }
520}
521
522/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200523 * Load library "name".
524 */
525 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000526vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200527{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200528 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200529
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200530 // No need to load any library when registering OLE.
531 if (found_register_arg)
532 return dll;
533
Bram Moolenaar0f873732019-12-05 20:28:46 +0100534 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
535 // vimLoadLib() recursively, which causes a stack overflow.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200536 if (exe_path == NULL)
537 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200538 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200539 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200540 WCHAR old_dirw[MAXPATHL];
541
542 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
543 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100544 // Change directory to where the executable is, both to make
545 // sure we find a .dll there and to avoid looking for a .dll
546 // in the current directory.
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100547 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200548 dll = LoadLibrary(name);
549 SetCurrentDirectoryW(old_dirw);
550 return dll;
551 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200552 }
553 return dll;
554}
555
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200556#if defined(VIMDLL) || defined(PROTO)
557/*
558 * Check if the current executable file is for the GUI subsystem.
559 */
560 int
561mch_is_gui_executable(void)
562{
563 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
564 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
565 PIMAGE_NT_HEADERS pPE;
566
567 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
568 return FALSE;
569 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
570 if (pPE->Signature != IMAGE_NT_SIGNATURE)
571 return FALSE;
572 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
573 return TRUE;
574 return FALSE;
575}
576#endif
577
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000578#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
579 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100580/*
581 * Get related information about 'funcname' which is imported by 'hInst'.
582 * If 'info' is 0, return the function address.
583 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000584 * If 'info' is 2, hook the function with 'ptr', and return the original
585 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100586 */
587 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000588get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
589 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100590{
591 PBYTE pImage = (PBYTE)hInst;
592 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
593 PIMAGE_NT_HEADERS pPE;
594 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100595 PIMAGE_THUNK_DATA pIAT; // Import Address Table
596 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100597 PIMAGE_IMPORT_BY_NAME pImpName;
598
599 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
600 return NULL;
601 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
602 if (pPE->Signature != IMAGE_NT_SIGNATURE)
603 return NULL;
604 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
605 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
606 .VirtualAddress);
607 for (; pImpDesc->FirstThunk; ++pImpDesc)
608 {
609 if (!pImpDesc->OriginalFirstThunk)
610 continue;
611 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
612 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
613 for (; pIAT->u1.Function; ++pIAT, ++pINT)
614 {
615 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
616 continue;
617 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
618 + (UINT_PTR)(pINT->u1.AddressOfData));
619 if (strcmp((char *)pImpName->Name, funcname) == 0)
620 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000621 void *original;
622 DWORD old, new = PAGE_READWRITE;
623
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100624 switch (info)
625 {
626 case 0:
627 return (void *)pIAT->u1.Function;
628 case 1:
629 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000630 case 2:
631 original = (void *)pIAT->u1.Function;
632 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
633 new, &old);
634 pIAT->u1.Function = (UINT_PTR)ptr;
635 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
636 old, &new);
637 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100638 default:
639 return NULL;
640 }
641 }
642 }
643 }
644 return NULL;
645}
646
647/*
648 * Get the module handle which 'funcname' in 'hInst' is imported from.
649 */
650 HINSTANCE
651find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
652{
653 char *modulename;
654
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000655 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100656 if (modulename != NULL)
657 return GetModuleHandleA(modulename);
658 return NULL;
659}
660
661/*
662 * Get the address of 'funcname' which is imported by 'hInst' DLL.
663 */
664 void *
665get_dll_import_func(HINSTANCE hInst, const char *funcname)
666{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000667 return get_imported_func_info(hInst, funcname, 0, NULL);
668}
669
670/*
671 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
672 * and return the original function address.
673 */
674 void *
675hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
676{
677 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100678}
679#endif
680
Bram Moolenaar071d4272004-06-13 20:20:40 +0000681#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
682# ifndef GETTEXT_DLL
683# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200684# define GETTEXT_DLL_ALT1 "libintl-8.dll"
685# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000686# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100687// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000688static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200689static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000690static char *null_libintl_textdomain(const char *);
691static char *null_libintl_bindtextdomain(const char *, const char *);
692static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100693static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000694
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200695static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000696char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200697char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
698 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000699char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
700char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000701 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000702char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
703 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100704int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000705
706 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100707dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000708{
709 int i;
710 static struct
711 {
712 char *name;
713 FARPROC *ptr;
714 } libintl_entry[] =
715 {
716 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200717 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000718 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
719 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
720 {NULL, NULL}
721 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100722 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000723
Bram Moolenaar7554c542018-10-06 15:03:15 +0200724 // No need to initialize twice.
725 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000726 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200727 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100728 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100729# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100730 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200731 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100732# endif
733# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200734 if (!hLibintlDLL)
735 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100736# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100737 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000738 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200739 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000740 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200741 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000742 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200743 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000744 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200745 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000746 }
747 for (i = 0; libintl_entry[i].name != NULL
748 && libintl_entry[i].ptr != NULL; ++i)
749 {
K.Takata54119102022-02-03 13:33:03 +0000750 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000751 libintl_entry[i].name)) == NULL)
752 {
753 dyn_libintl_end();
754 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000755 {
756 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000757 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000758 verbose_leave();
759 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000760 return 0;
761 }
762 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000763
Bram Moolenaar0f873732019-12-05 20:28:46 +0100764 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100765 dyn_libintl_bind_textdomain_codeset = (char *(*)(const char *, const char *))
766 GetProcAddress(hLibintlDLL, "bind_textdomain_codeset");
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000767 if (dyn_libintl_bind_textdomain_codeset == NULL)
768 dyn_libintl_bind_textdomain_codeset =
769 null_libintl_bind_textdomain_codeset;
770
Bram Moolenaar0f873732019-12-05 20:28:46 +0100771 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100772 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
773 if (hmsvcrt != NULL)
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100774 dyn_libintl_wputenv = (int (*)(const wchar_t *))
775 GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100776 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
777 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100778
Bram Moolenaar071d4272004-06-13 20:20:40 +0000779 return 1;
780}
781
782 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100783dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000784{
785 if (hLibintlDLL)
786 FreeLibrary(hLibintlDLL);
787 hLibintlDLL = NULL;
788 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200789 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000790 dyn_libintl_textdomain = null_libintl_textdomain;
791 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000792 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100793 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000794}
795
796 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000797null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000798{
799 return (char*)msgid;
800}
801
802 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200803null_libintl_ngettext(
804 const char *msgid,
805 const char *msgid_plural,
806 unsigned long n)
807{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200808 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200809}
810
Bram Moolenaaree695f72016-08-03 22:08:45 +0200811 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100812null_libintl_bindtextdomain(
813 const char *domainname UNUSED,
814 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000815{
816 return NULL;
817}
818
819 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100820null_libintl_bind_textdomain_codeset(
821 const char *domainname UNUSED,
822 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000823{
824 return NULL;
825}
826
827 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100828null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000829{
830 return NULL;
831}
832
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200833 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100834null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100835{
836 return 0;
837}
838
Bram Moolenaar0f873732019-12-05 20:28:46 +0100839#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000840
Bram Moolenaar0f873732019-12-05 20:28:46 +0100841// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000842
843#ifndef VER_PLATFORM_WIN32_WINDOWS
844# define VER_PLATFORM_WIN32_WINDOWS 1
845#endif
846
Bram Moolenaar071d4272004-06-13 20:20:40 +0000847#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100848# ifndef PROTO
849# include <aclapi.h>
850# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200851# ifndef PROTECTED_DACL_SECURITY_INFORMATION
852# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
853# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000854#endif
855
Bram Moolenaar27515922013-06-29 15:36:26 +0200856#ifdef HAVE_ACL
857/*
858 * Enables or disables the specified privilege.
859 */
860 static BOOL
861win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
862{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100863 BOOL bResult;
864 LUID luid;
865 HANDLE hToken;
866 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200867
868 if (!OpenProcessToken(GetCurrentProcess(),
869 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
870 return FALSE;
871
872 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
873 {
874 CloseHandle(hToken);
875 return FALSE;
876 }
877
Bram Moolenaar45500912014-07-09 20:51:07 +0200878 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200879 tokenPrivileges.Privileges[0].Luid = luid;
880 tokenPrivileges.Privileges[0].Attributes = bEnable ?
881 SE_PRIVILEGE_ENABLED : 0;
882
883 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
884 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
885
886 CloseHandle(hToken);
887
888 return bResult && GetLastError() == ERROR_SUCCESS;
889}
890#endif
891
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100892#ifdef _MSC_VER
893// Suppress the deprecation warning for using GetVersionEx().
894// It is needed for implementing "windowsversion()".
895# pragma warning(push)
896# pragma warning(disable: 4996)
897#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000898/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200899 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000900 */
901 void
902PlatformId(void)
903{
904 static int done = FALSE;
905
906 if (!done)
907 {
908 OSVERSIONINFO ovi;
909
910 ovi.dwOSVersionInfoSize = sizeof(ovi);
911 GetVersionEx(&ovi);
912
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200913#ifdef FEAT_EVAL
Bram Moolenaar0c1e3742019-12-27 13:49:24 +0100914 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
915 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200916#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100917 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
918 || ovi.dwMajorVersion > 6)
919 win8_or_later = TRUE;
920
Bram Moolenaar071d4272004-06-13 20:20:40 +0000921#ifdef HAVE_ACL
Bram Moolenaar0f873732019-12-05 20:28:46 +0100922 // Enable privilege for getting or setting SACLs.
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200923 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000924#endif
925 done = TRUE;
926 }
927}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100928#ifdef _MSC_VER
929# pragma warning(pop)
930#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000931
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200932#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000933
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100934# define SHIFT (SHIFT_PRESSED)
935# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
936# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
937# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000938
939
Bram Moolenaar0f873732019-12-05 20:28:46 +0100940// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
941// We map function keys to their ANSI terminal equivalents, as produced
942// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
943// ANSI key with a value >= '\300' is nonstandard, but provided anyway
944// so that the user can have access to all SHIFT-, CTRL-, and ALT-
945// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000946
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000947static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000948{
949 WORD wVirtKey;
950 BOOL fAnsiKey;
951 int chAlone;
952 int chShift;
953 int chCtrl;
954 int chAlt;
955} VirtKeyMap[] =
956{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200957// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000958 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
959
960 { VK_F1, TRUE, ';', 'T', '^', 'h', },
961 { VK_F2, TRUE, '<', 'U', '_', 'i', },
962 { VK_F3, TRUE, '=', 'V', '`', 'j', },
963 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
964 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
965 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
966 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
967 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
968 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
969 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200970 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
971 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000972
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200973 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
974 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
975 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
976 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
977 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
978 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
979 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
980 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
981 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
982 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100983 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000984
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200985 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000986
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100987# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200988 // Most people don't have F13-F20, but what the hell...
989 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
990 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
991 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
992 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
993 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
994 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
995 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
996 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100997# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200998 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
999 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
1000 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
1001 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001002
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001003 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
1004 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
1005 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
1006 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
1007 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
1008 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
1009 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
1010 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
1011 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
1012 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001013 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001014};
1015
1016
Bram Moolenaar0f873732019-12-05 20:28:46 +01001017/*
1018 * The return code indicates key code size.
1019 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001020 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001021win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001022 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001023{
1024 UINT uMods = pker->dwControlKeyState;
1025 static int s_iIsDead = 0;
1026 static WORD awAnsiCode[2];
1027 static BYTE abKeystate[256];
1028
1029
1030 if (s_iIsDead == 2)
1031 {
K.Takata972db232022-02-04 10:45:38 +00001032 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001033 s_iIsDead = 0;
1034 return 1;
1035 }
1036
K.Takata972db232022-02-04 10:45:38 +00001037 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001038 return 1;
1039
Bram Moolenaara80faa82020-04-12 19:37:17 +02001040 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001041
Bram Moolenaar0f873732019-12-05 20:28:46 +01001042 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001043 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001044
1045 if (uMods & SHIFT_PRESSED)
1046 abKeystate[VK_SHIFT] = 0x80;
1047 if (uMods & CAPSLOCK_ON)
1048 abKeystate[VK_CAPITAL] = 1;
1049
1050 if ((uMods & ALT_GR) == ALT_GR)
1051 {
1052 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1053 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1054 }
1055
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001056 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1057 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001058
1059 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001060 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001061
1062 return s_iIsDead;
1063}
1064
Bram Moolenaar071d4272004-06-13 20:20:40 +00001065static BOOL g_fJustGotFocus = FALSE;
1066
1067/*
1068 * Decode a KEY_EVENT into one or two keystrokes
1069 */
1070 static BOOL
1071decode_key_event(
1072 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001073 WCHAR *pch,
1074 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001075 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001076 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001077{
1078 int i;
1079 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1080
1081 *pch = *pch2 = NUL;
1082 g_fJustGotFocus = FALSE;
1083
Bram Moolenaar0f873732019-12-05 20:28:46 +01001084 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001085 if (!pker->bKeyDown)
1086 return FALSE;
1087
Bram Moolenaar0f873732019-12-05 20:28:46 +01001088 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001089 switch (pker->wVirtualKeyCode)
1090 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001091 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001092 case VK_SHIFT:
1093 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001094 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001095 return FALSE;
1096
1097 default:
1098 break;
1099 }
1100
Bram Moolenaar0f873732019-12-05 20:28:46 +01001101 // special cases
K.Takata972db232022-02-04 10:45:38 +00001102 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0
1103 && pker->uChar.UnicodeChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001104 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001105 // Ctrl-6 is Ctrl-^
Bram Moolenaar071d4272004-06-13 20:20:40 +00001106 if (pker->wVirtualKeyCode == '6')
1107 {
1108 *pch = Ctrl_HAT;
1109 return TRUE;
1110 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001111 // Ctrl-2 is Ctrl-@
Bram Moolenaar071d4272004-06-13 20:20:40 +00001112 else if (pker->wVirtualKeyCode == '2')
1113 {
1114 *pch = NUL;
1115 return TRUE;
1116 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001117 // Ctrl-- is Ctrl-_
Bram Moolenaar071d4272004-06-13 20:20:40 +00001118 else if (pker->wVirtualKeyCode == 0xBD)
1119 {
1120 *pch = Ctrl__;
1121 return TRUE;
1122 }
1123 }
1124
Bram Moolenaar0f873732019-12-05 20:28:46 +01001125 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001126 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1127 {
1128 *pch = K_NUL;
1129 *pch2 = '\017';
1130 return TRUE;
1131 }
1132
K.Takataeeec2542021-06-02 13:28:16 +02001133 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001134 {
1135 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1136 {
1137 if (nModifs == 0)
1138 *pch = VirtKeyMap[i].chAlone;
1139 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1140 *pch = VirtKeyMap[i].chShift;
1141 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1142 *pch = VirtKeyMap[i].chCtrl;
1143 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1144 *pch = VirtKeyMap[i].chAlt;
1145
1146 if (*pch != 0)
1147 {
1148 if (VirtKeyMap[i].fAnsiKey)
1149 {
1150 *pch2 = *pch;
1151 *pch = K_NUL;
1152 }
1153
1154 return TRUE;
1155 }
1156 }
1157 }
1158
1159 i = win32_kbd_patch_key(pker);
1160
1161 if (i < 0)
1162 *pch = NUL;
1163 else
1164 {
K.Takata972db232022-02-04 10:45:38 +00001165 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001166
1167 if (pmodifiers != NULL)
1168 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001169 // Pass on the ALT key as a modifier, but only when not combined
1170 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001171 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1172 *pmodifiers |= MOD_MASK_ALT;
1173
Bram Moolenaar0f873732019-12-05 20:28:46 +01001174 // Pass on SHIFT only for special keys, because we don't know when
1175 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001176 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1177 *pmodifiers |= MOD_MASK_SHIFT;
1178
Bram Moolenaar0f873732019-12-05 20:28:46 +01001179 // Pass on CTRL only for non-special keys, because we don't know
1180 // when it's already included with the character. And not when
1181 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001182 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1183 && *pch >= 0x20 && *pch < 0x80)
1184 *pmodifiers |= MOD_MASK_CTRL;
1185 }
1186 }
1187
1188 return (*pch != NUL);
1189}
1190
Bram Moolenaar0f873732019-12-05 20:28:46 +01001191#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001192
1193
Bram Moolenaar071d4272004-06-13 20:20:40 +00001194/*
1195 * For the GUI the mouse handling is in gui_w32.c.
1196 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001197#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001198 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001199mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001200{
1201}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001202#else
Bram Moolenaar0f873732019-12-05 20:28:46 +01001203static int g_fMouseAvail = FALSE; // mouse present
1204static int g_fMouseActive = FALSE; // mouse enabled
1205static int g_nMouseClick = -1; // mouse status
1206static int g_xMouse; // mouse x coordinate
1207static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001208static DWORD g_cmodein = 0; // Original console input mode
1209static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001210
1211/*
1212 * Enable or disable mouse input
1213 */
1214 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001215mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001216{
1217 DWORD cmodein;
1218
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001219# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001220 if (gui.in_use)
1221 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001222# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001223 if (!g_fMouseAvail)
1224 return;
1225
1226 g_fMouseActive = on;
1227 GetConsoleMode(g_hConIn, &cmodein);
1228
1229 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001230 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001231 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001232 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1233 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001234 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001235 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001236 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001237 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1238 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001239
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001240 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001241}
1242
Bram Moolenaar157d8132018-03-06 17:09:20 +01001243
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001244# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001245/*
1246 * Called when 'balloonevalterm' changed.
1247 */
1248 void
1249mch_bevalterm_changed(void)
1250{
1251 mch_setmouse(g_fMouseActive);
1252}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001253# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001254
Bram Moolenaar071d4272004-06-13 20:20:40 +00001255/*
1256 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1257 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1258 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1259 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1260 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1261 * and we return the mouse position in g_xMouse and g_yMouse.
1262 *
1263 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1264 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1265 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1266 *
1267 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1268 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1269 *
1270 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1271 * moves, even if it stays within the same character cell. We ignore
1272 * all MOUSE_MOVED messages if the position hasn't really changed, and
1273 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1274 * we're only interested in MOUSE_DRAG).
1275 *
1276 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1277 * 2-button mouses by pressing the left & right buttons simultaneously.
1278 * In practice, it's almost impossible to click both at the same time,
1279 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1280 * in such cases, if the user is clicking quickly.
1281 */
1282 static BOOL
1283decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001284 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001285{
1286 static int s_nOldButton = -1;
1287 static int s_nOldMouseClick = -1;
1288 static int s_xOldMouse = -1;
1289 static int s_yOldMouse = -1;
1290 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001291# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001292 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001293# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001294 static int s_cClicks = 1;
1295 static BOOL s_fReleased = TRUE;
1296 static DWORD s_dwLastClickTime = 0;
1297 static BOOL s_fNextIsMiddle = FALSE;
1298
Bram Moolenaar0f873732019-12-05 20:28:46 +01001299 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001300
1301 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1302 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1303 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1304 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1305
1306 int nButton;
1307
1308 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1309 cButtons = 2;
1310
1311 if (!g_fMouseAvail || !g_fMouseActive)
1312 {
1313 g_nMouseClick = -1;
1314 return FALSE;
1315 }
1316
Bram Moolenaar0f873732019-12-05 20:28:46 +01001317 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001318 if (g_fJustGotFocus)
1319 {
1320 g_fJustGotFocus = FALSE;
1321 return FALSE;
1322 }
1323
Bram Moolenaar0f873732019-12-05 20:28:46 +01001324 // unprocessed mouse click?
Bram Moolenaar071d4272004-06-13 20:20:40 +00001325 if (g_nMouseClick != -1)
1326 return TRUE;
1327
1328 nButton = -1;
1329 g_xMouse = pmer->dwMousePosition.X;
1330 g_yMouse = pmer->dwMousePosition.Y;
1331
1332 if (pmer->dwEventFlags == MOUSE_MOVED)
1333 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001334 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1335 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001336 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1337 return FALSE;
1338 }
1339
Bram Moolenaar0f873732019-12-05 20:28:46 +01001340 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001341 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1342 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001343 nButton = MOUSE_RELEASE;
1344
Bram Moolenaar0f873732019-12-05 20:28:46 +01001345 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001346 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001347 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001348# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001349 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001350 if (p_bevalterm)
1351 nButton = MOUSE_DRAG;
1352 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001353# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001354 return FALSE;
1355 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001356
Bram Moolenaar071d4272004-06-13 20:20:40 +00001357 s_fReleased = TRUE;
1358 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001359 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001360 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001361 // on a 2-button mouse, hold down left and right buttons
1362 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001363
1364 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1365 {
1366 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1367
Bram Moolenaar0f873732019-12-05 20:28:46 +01001368 // if either left or right button only is pressed, see if the
1369 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001370 if (dwLR == LEFT || dwLR == RIGHT)
1371 {
1372 for (;;)
1373 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001374 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001375 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1376 != WAIT_OBJECT_0)
1377 break;
1378 else
1379 {
1380 DWORD cRecords = 0;
1381 INPUT_RECORD ir;
1382 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1383
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001384 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001385
1386 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1387 || !(pmer2->dwButtonState & LEFT_RIGHT))
1388 break;
1389 else
1390 {
1391 if (pmer2->dwEventFlags != MOUSE_MOVED)
1392 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001393 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001394
1395 return decode_mouse_event(pmer2);
1396 }
1397 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1398 s_yOldMouse == pmer2->dwMousePosition.Y)
1399 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001400 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001401 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001402
Bram Moolenaar0f873732019-12-05 20:28:46 +01001403 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001404 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001405
1406 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1407 break;
1408 }
1409 else
1410 break;
1411 }
1412 }
1413 }
1414 }
1415 }
1416
1417 if (s_fNextIsMiddle)
1418 {
1419 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1420 ? MOUSE_DRAG : MOUSE_MIDDLE;
1421 s_fNextIsMiddle = FALSE;
1422 }
1423 else if (cButtons == 2 &&
1424 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1425 {
1426 nButton = MOUSE_MIDDLE;
1427
1428 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1429 {
1430 s_fNextIsMiddle = TRUE;
1431 nButton = MOUSE_RELEASE;
1432 }
1433 }
1434 else if ((pmer->dwButtonState & LEFT) == LEFT)
1435 nButton = MOUSE_LEFT;
1436 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1437 nButton = MOUSE_MIDDLE;
1438 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1439 nButton = MOUSE_RIGHT;
1440
1441 if (! s_fReleased && ! s_fNextIsMiddle
1442 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1443 return FALSE;
1444
1445 s_fReleased = s_fNextIsMiddle;
1446 }
1447
1448 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1449 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001450 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001451 if (nButton != -1 && nButton != MOUSE_RELEASE)
1452 {
1453 DWORD dwCurrentTime = GetTickCount();
1454
1455 if (s_xOldMouse != g_xMouse
1456 || s_yOldMouse != g_yMouse
1457 || s_nOldButton != nButton
1458 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001459# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001460 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001461# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001462 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1463 {
1464 s_cClicks = 1;
1465 }
1466 else if (++s_cClicks > 4)
1467 {
1468 s_cClicks = 1;
1469 }
1470
1471 s_dwLastClickTime = dwCurrentTime;
1472 }
1473 }
1474 else if (pmer->dwEventFlags == MOUSE_MOVED)
1475 {
1476 if (nButton != -1 && nButton != MOUSE_RELEASE)
1477 nButton = MOUSE_DRAG;
1478
1479 s_cClicks = 1;
1480 }
1481
1482 if (nButton == -1)
1483 return FALSE;
1484
1485 if (nButton != MOUSE_RELEASE)
1486 s_nOldButton = nButton;
1487
1488 g_nMouseClick = nButton;
1489
1490 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1491 g_nMouseClick |= MOUSE_SHIFT;
1492 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1493 g_nMouseClick |= MOUSE_CTRL;
1494 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1495 g_nMouseClick |= MOUSE_ALT;
1496
1497 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1498 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1499
Bram Moolenaar0f873732019-12-05 20:28:46 +01001500 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001501 if (s_xOldMouse == g_xMouse
1502 && s_yOldMouse == g_yMouse
1503 && s_nOldMouseClick == g_nMouseClick)
1504 {
1505 g_nMouseClick = -1;
1506 return FALSE;
1507 }
1508
1509 s_xOldMouse = g_xMouse;
1510 s_yOldMouse = g_yMouse;
1511 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001512# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001513 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001514# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001515 s_nOldMouseClick = g_nMouseClick;
1516
1517 return TRUE;
1518}
1519
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001520#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001521
1522
1523#ifdef MCH_CURSOR_SHAPE
1524/*
1525 * Set the shape of the cursor.
1526 * 'thickness' can be from 1 (thin) to 99 (block)
1527 */
1528 static void
1529mch_set_cursor_shape(int thickness)
1530{
K.Takatadf5320c2022-09-01 13:20:16 +01001531 if (USE_VTP || USE_WT)
1532 {
1533 if (*T_CSI == NUL)
1534 {
1535 // If 't_SI' is not set, use the default cursor styles.
1536 if (thickness < 50)
1537 vtp_printf("\033[3 q"); // underline
1538 else
1539 vtp_printf("\033[0 q"); // default
1540 }
1541 }
1542 else
1543 {
1544 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1545 ConsoleCursorInfo.dwSize = thickness;
1546 ConsoleCursorInfo.bVisible = s_cursor_visible;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001547
K.Takatadf5320c2022-09-01 13:20:16 +01001548 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1549 if (s_cursor_visible)
1550 SetConsoleCursorPosition(g_hConOut, g_coord);
1551 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001552}
1553
1554 void
1555mch_update_cursor(void)
1556{
1557 int idx;
1558 int thickness;
1559
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001560# ifdef VIMDLL
1561 if (gui.in_use)
1562 return;
1563# endif
1564
Bram Moolenaar071d4272004-06-13 20:20:40 +00001565 /*
1566 * How the cursor is drawn depends on the current mode.
1567 */
1568 idx = get_shape_idx(FALSE);
1569
1570 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001571 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00001572 else
1573 thickness = shape_table[idx].percentage;
1574 mch_set_cursor_shape(thickness);
1575}
1576#endif
1577
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001578#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001579/*
1580 * Handle FOCUS_EVENT.
1581 */
1582 static void
1583handle_focus_event(INPUT_RECORD ir)
1584{
1585 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1586 ui_focus_change((int)g_fJustGotFocus);
1587}
1588
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001589static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1590
Bram Moolenaar071d4272004-06-13 20:20:40 +00001591/*
1592 * Wait until console input from keyboard or mouse is available,
1593 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001594 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001595 * Return TRUE if something is available FALSE if not.
1596 */
1597 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001598WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001599{
1600 DWORD dwNow = 0, dwEndTime = 0;
1601 INPUT_RECORD ir;
1602 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001603 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001604# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001605 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001606# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607
1608 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001609 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001610 dwEndTime = GetTickCount() + msec;
1611 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001612 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001613 dwEndTime = INFINITE;
1614
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001615 // We need to loop until the end of the time period, because
1616 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001617 for (;;)
1618 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001619 // Only process messages when waiting.
1620 if (msec != 0)
1621 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001622# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001623 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001624# endif
1625# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001626 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001627# endif
1628# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001629 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001630# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001631 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001632
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001633 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001634# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001635 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001636# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001637 )
1638 return TRUE;
1639
1640 if (msec > 0)
1641 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001642 // If the specified wait time has passed, return. Beware that
1643 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001644 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001645 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001646 break;
1647 }
1648 if (msec != 0)
1649 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001650 DWORD dwWaitTime = dwEndTime - dwNow;
1651
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001652 // Don't wait for more than 11 msec to avoid dropping characters,
1653 // check channel while waiting for input and handle a callback from
1654 // 'balloonexpr'.
1655 if (dwWaitTime > 11)
1656 dwWaitTime = 11;
1657
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001658# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001659 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001660 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001661# endif
1662# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001663 // When waiting very briefly don't trigger timers.
1664 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001665 {
1666 long due_time;
1667
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001668 // Trigger timers and then get the time in msec until the next
1669 // one is due. Wait up to that time.
1670 due_time = check_due_timer();
1671 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001672 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001673 // timer may have used feedkeys().
1674 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001675 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001676 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1677 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001678 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001679# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001680 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001681# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001682 // Wait for either an event on the console input or a
1683 // message in the client-server window.
1684 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1685 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001686# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001687 wait_for_single_object(g_hConIn, dwWaitTime)
1688 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001689# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001690 )
1691 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001692 }
1693
1694 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001695 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001696
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001697# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02001698 // May have to redraw if the cursor ends up in the wrong place.
1699 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01001700 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001701 {
1702 CONSOLE_SCREEN_BUFFER_INFO csbi;
1703
1704 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1705 {
1706 if (csbi.dwCursorPosition.Y != msg_row)
1707 {
matveyte08795e2021-05-07 15:00:17 +02001708 // The screen is now messed up, must redraw the command
1709 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01001710 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02001711 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001712 redrawcmd();
1713 }
1714 }
1715 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001716# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717
1718 if (cRecords > 0)
1719 {
1720 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1721 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001722# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01001723 // Windows IME sends two '\n's with only one 'ENTER'. First:
1724 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00001725 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001726 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1727 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001728 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001729 continue;
1730 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001731# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001732 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1733 NULL, FALSE))
1734 return TRUE;
1735 }
1736
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001737 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001738
1739 if (ir.EventType == FOCUS_EVENT)
1740 handle_focus_event(ir);
1741 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001742 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001743 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1744
Bram Moolenaar36698e32019-12-11 22:57:40 +01001745 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001746 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001747 if (dwSize.X != Columns || dwSize.Y != Rows)
1748 {
1749 CONSOLE_SCREEN_BUFFER_INFO csbi;
1750 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01001751 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001752 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01001753 if (dwSize.X != Columns || dwSize.Y != Rows)
1754 {
1755 ResizeConBuf(g_hConOut, dwSize);
1756 shell_resized();
1757 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001758 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001759 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001760 else if (ir.EventType == MOUSE_EVENT
1761 && decode_mouse_event(&ir.Event.MouseEvent))
1762 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001763 }
1764 else if (msec == 0)
1765 break;
1766 }
1767
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001768# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01001769 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001770 if (input_available())
1771 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001772# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001773
Bram Moolenaar071d4272004-06-13 20:20:40 +00001774 return FALSE;
1775}
1776
Bram Moolenaar071d4272004-06-13 20:20:40 +00001777/*
1778 * return non-zero if a character is available
1779 */
1780 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001781mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001782{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001783# ifdef VIMDLL
1784 if (gui.in_use)
1785 return TRUE;
1786# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001787 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001788}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001789
1790# if defined(FEAT_TERMINAL) || defined(PROTO)
1791/*
1792 * Check for any pending input or messages.
1793 */
1794 int
1795mch_check_messages(void)
1796{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001797# ifdef VIMDLL
1798 if (gui.in_use)
1799 return TRUE;
1800# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001801 return WaitForChar(0L, TRUE);
1802}
1803# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001804
1805/*
1806 * Create the console input. Used when reading stdin doesn't work.
1807 */
1808 static void
1809create_conin(void)
1810{
1811 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1812 FILE_SHARE_READ|FILE_SHARE_WRITE,
1813 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001814 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001815 did_create_conin = TRUE;
1816}
1817
1818/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001819 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001820 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001821 static WCHAR
1822tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001823{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001824 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001825
1826 for (;;)
1827 {
1828 INPUT_RECORD ir;
1829 DWORD cRecords = 0;
1830
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001831# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001832 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001833 if (input_available())
1834 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001835 if (g_nMouseClick != -1)
1836 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001837# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001838 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001839 {
1840 if (did_create_conin)
1841 read_error_exit();
1842 create_conin();
1843 continue;
1844 }
1845
1846 if (ir.EventType == KEY_EVENT)
1847 {
1848 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1849 pmodifiers, TRUE))
1850 return ch;
1851 }
1852 else if (ir.EventType == FOCUS_EVENT)
1853 handle_focus_event(ir);
1854 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1855 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001856 else if (ir.EventType == MOUSE_EVENT)
1857 {
1858 if (decode_mouse_event(&ir.Event.MouseEvent))
1859 return 0;
1860 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001861 }
1862}
Bram Moolenaar0f873732019-12-05 20:28:46 +01001863#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001864
1865
1866/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001867 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001868 * Get one or more characters from the keyboard or the mouse.
1869 * If time == 0, do not wait for characters.
1870 * If time == n, wait a short time for characters.
1871 * If time == -1, wait forever for characters.
1872 * Returns the number of characters read into buf.
1873 */
1874 int
1875mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001876 char_u *buf UNUSED,
1877 int maxlen UNUSED,
1878 long time UNUSED,
1879 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001880{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001881#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001882
1883 int len;
1884 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001885# ifdef VIMDLL
1886// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
1887# define TYPEAHEADSPACE 6
1888# else
1889# define TYPEAHEADSPACE 0
1890# endif
1891# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001892 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001893 static int typeaheadlen = 0;
1894
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001895# ifdef VIMDLL
1896 if (gui.in_use)
1897 return 0;
1898# endif
1899
Bram Moolenaar0f873732019-12-05 20:28:46 +01001900 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001901 if (typeaheadlen > 0)
1902 goto theend;
1903
Bram Moolenaar071d4272004-06-13 20:20:40 +00001904 if (time >= 0)
1905 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001906 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00001907 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001908 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001909 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00001910 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001911 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00001912
Bram Moolenaar3918c952005-03-15 22:34:55 +00001913 /*
1914 * If there is no character available within 2 seconds (default)
1915 * write the autoscript file to disk. Or cause the CursorHold event
1916 * to be triggered.
1917 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001918 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001919 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001920 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001921 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001922 buf[0] = K_SPECIAL;
1923 buf[1] = KS_EXTRA;
1924 buf[2] = (int)KE_CURSORHOLD;
1925 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001926 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001927 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001928 }
1929 }
1930
1931 /*
1932 * Try to read as many characters as there are, until the buffer is full.
1933 */
1934
Bram Moolenaar0f873732019-12-05 20:28:46 +01001935 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001936 g_fCBrkPressed = FALSE;
1937
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001938# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001939 if (fdDump)
1940 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001941# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001942
Bram Moolenaar0f873732019-12-05 20:28:46 +01001943 // Keep looping until there is something in the typeahead buffer and more
1944 // to get and still room in the buffer (up to two bytes for a char and
1945 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001946 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001947 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001948 {
1949 if (typebuf_changed(tb_change_cnt))
1950 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001951 // "buf" may be invalid now if a client put something in the
1952 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001953 typeaheadlen = 0;
1954 break;
1955 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001956 if (g_nMouseClick != -1)
1957 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001958# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001959 if (fdDump)
1960 fprintf(fdDump, "{%02x @ %d, %d}",
1961 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001962# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001963 typeahead[typeaheadlen++] = ESC + 128;
1964 typeahead[typeaheadlen++] = 'M';
1965 typeahead[typeaheadlen++] = g_nMouseClick;
1966 typeahead[typeaheadlen++] = g_xMouse + '!';
1967 typeahead[typeaheadlen++] = g_yMouse + '!';
1968 g_nMouseClick = -1;
1969 }
1970 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001971 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001972 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001973 int modifiers = 0;
1974
1975 c = tgetch(&modifiers, &ch2);
1976
1977 if (typebuf_changed(tb_change_cnt))
1978 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001979 // "buf" may be invalid now if a client put something in the
1980 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001981 typeaheadlen = 0;
1982 break;
1983 }
1984
1985 if (c == Ctrl_C && ctrl_c_interrupts)
1986 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001987# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001988 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001989# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001990 got_int = TRUE;
1991 }
1992
Bram Moolenaar071d4272004-06-13 20:20:40 +00001993 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001994 {
1995 int n = 1;
1996
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001997 if (ch2 == NUL)
1998 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001999 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002000 char_u *p;
2001 WCHAR ch[2];
2002
2003 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002004 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002005 {
2006 ch[1] = tgetch(&modifiers, &ch2);
2007 n++;
2008 }
2009 p = utf16_to_enc(ch, &n);
2010 if (p != NULL)
2011 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002012 for (i = 0, j = 0; i < n; i++)
2013 {
2014 typeahead[typeaheadlen + j++] = p[i];
2015# ifdef VIMDLL
2016 if (p[i] == CSI)
2017 {
2018 typeahead[typeaheadlen + j++] = KS_EXTRA;
2019 typeahead[typeaheadlen + j++] = KE_CSI;
2020 }
2021# endif
2022 }
2023 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002024 vim_free(p);
2025 }
2026 }
2027 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002028 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002029 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002030# ifdef VIMDLL
2031 if (c == CSI)
2032 {
2033 typeahead[typeaheadlen + 1] = KS_EXTRA;
2034 typeahead[typeaheadlen + 2] = KE_CSI;
2035 n = 3;
2036 }
2037# endif
2038 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002039 if (ch2 != NUL)
2040 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002041 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002042 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002043 switch (ch2)
2044 {
2045 case (WCHAR)'\324': // SHIFT+Insert
2046 case (WCHAR)'\325': // CTRL+Insert
2047 case (WCHAR)'\327': // SHIFT+Delete
2048 case (WCHAR)'\330': // CTRL+Delete
2049 typeahead[typeaheadlen + n] = (char_u)ch2;
2050 n++;
2051 break;
2052
2053 default:
2054 typeahead[typeaheadlen + n] = 3;
2055 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2056 n += 2;
2057 break;
2058 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002059 }
2060 else
2061 {
2062 typeahead[typeaheadlen + n] = 3;
2063 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2064 n += 2;
2065 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002066 }
2067
Bram Moolenaar0f873732019-12-05 20:28:46 +01002068 // Use the ALT key to set the 8th bit of the character
2069 // when it's one byte, the 8th bit isn't set yet and not
2070 // using a double-byte encoding (would become a lead
2071 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002072 if ((modifiers & MOD_MASK_ALT)
2073 && n == 1
2074 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002075 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002076 )
2077 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002078 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2079 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002080 modifiers &= ~MOD_MASK_ALT;
2081 }
2082
2083 if (modifiers != 0)
2084 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002085 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002086 mch_memmove(typeahead + typeaheadlen + 3,
2087 typeahead + typeaheadlen, n);
2088 typeahead[typeaheadlen++] = K_SPECIAL;
2089 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2090 typeahead[typeaheadlen++] = modifiers;
2091 }
2092
2093 typeaheadlen += n;
2094
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002095# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002096 if (fdDump)
2097 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002098# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002099 }
2100 }
2101 }
2102
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002103# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002104 if (fdDump)
2105 {
2106 fputs("]\n", fdDump);
2107 fflush(fdDump);
2108 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002109# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002110
Bram Moolenaar071d4272004-06-13 20:20:40 +00002111theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002112 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002113 len = 0;
2114 while (len < maxlen && typeaheadlen > 0)
2115 {
2116 buf[len++] = typeahead[0];
2117 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2118 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002119# ifdef FEAT_JOB_CHANNEL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002120 if (len > 0)
2121 {
2122 buf[len] = NUL;
2123 ch_log(NULL, "raw key input: \"%s\"", buf);
2124 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002125# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002126 return len;
2127
Bram Moolenaar0f873732019-12-05 20:28:46 +01002128#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002129 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002130#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002131}
2132
Bram Moolenaar82881492012-11-20 16:53:39 +01002133#ifndef PROTO
2134# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002135# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002136# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002137#endif
2138
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002139/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002140 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002141 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2142 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002143 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002144 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002145 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002146executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002147{
LemonBoy40fd7e62022-05-05 20:18:16 +01002148 int attrs = win32_getattrs((char_u *)name);
2149
2150 // The file doesn't exist or is a folder.
2151 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2152 return FALSE;
2153 // Check if the file is an AppExecLink, a special alias used by Windows
2154 // Store for its apps.
2155 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002156 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002157 char_u *res = resolve_appexeclink((char_u *)name);
2158 if (res == NULL)
2159 return FALSE;
2160 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002161 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002162 *path = res;
2163 else
2164 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002165 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002166 else if (path != NULL)
2167 *path = FullName_save((char_u *)name, FALSE);
2168 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002169}
2170
2171/*
2172 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2173 * If "use_path" is FALSE: Return TRUE if "name" exists.
2174 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2175 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2176 * the allocated memory.
2177 */
2178 static int
2179executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2180{
2181 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2182 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2183 // UTF-8.
2184 char_u buf[_MAX_PATH * 3];
2185 size_t len = STRLEN(name);
2186 size_t tmplen;
2187 char_u *p, *e, *e2;
2188 char_u *pathbuf = NULL;
2189 char_u *pathext = NULL;
2190 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002191 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002192 int noext = FALSE;
2193 int retval = FALSE;
2194
2195 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002196 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002197
2198 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002199 shname = gettail(p_sh);
2200 if (strstr((char *)shname, "sh") != NULL &&
2201 !(strstr((char *)shname, "powershell") != NULL
2202 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002203 noext = TRUE;
2204
2205 if (use_pathext)
2206 {
2207 pathext = mch_getenv("PATHEXT");
2208 if (pathext == NULL)
2209 pathext = (char_u *)".com;.exe;.bat;.cmd";
2210
2211 if (noext == FALSE)
2212 {
2213 /*
2214 * Loop over all extensions in $PATHEXT.
2215 * Check "name" ends with extension.
2216 */
2217 p = pathext;
2218 while (*p)
2219 {
2220 if (p[0] == ';'
2221 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2222 {
2223 // Skip empty or single ".".
2224 ++p;
2225 continue;
2226 }
2227 e = vim_strchr(p, ';');
2228 if (e == NULL)
2229 e = p + STRLEN(p);
2230 tmplen = e - p;
2231
2232 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2233 {
2234 noext = TRUE;
2235 break;
2236 }
2237
2238 p = e;
2239 }
2240 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002241 }
2242
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002243 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002244 if (pathext == NULL)
2245 pathext = (char_u *)".";
2246 else if (noext == TRUE)
2247 {
2248 if (pathextbuf == NULL)
2249 pathextbuf = alloc(STRLEN(pathext) + 3);
2250 if (pathextbuf == NULL)
2251 {
2252 retval = FALSE;
2253 goto theend;
2254 }
2255 STRCPY(pathextbuf, ".;");
2256 STRCAT(pathextbuf, pathext);
2257 pathext = pathextbuf;
2258 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002259
Bram Moolenaar95da1362020-05-30 18:37:55 +02002260 // Use $PATH when "use_path" is TRUE and "name" is basename.
2261 if (use_path && gettail((char_u *)name) == (char_u *)name)
2262 {
2263 p = mch_getenv("PATH");
2264 if (p != NULL)
2265 {
2266 pathbuf = alloc(STRLEN(p) + 3);
2267 if (pathbuf == NULL)
2268 {
2269 retval = FALSE;
2270 goto theend;
2271 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002272
2273 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2274 STRCPY(pathbuf, ".;");
2275 else
2276 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002277 STRCAT(pathbuf, p);
2278 }
2279 }
2280
2281 /*
2282 * Walk through all entries in $PATH to check if "name" exists there and
2283 * is an executable file.
2284 */
2285 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2286 while (*p)
2287 {
2288 if (*p == ';') // Skip empty entry
2289 {
2290 ++p;
2291 continue;
2292 }
2293 e = vim_strchr(p, ';');
2294 if (e == NULL)
2295 e = p + STRLEN(p);
2296
2297 if (e - p + len + 2 > sizeof(buf))
2298 {
2299 retval = FALSE;
2300 goto theend;
2301 }
2302 // A single "." that means current dir.
2303 if (e - p == 1 && *p == '.')
2304 STRCPY(buf, name);
2305 else
2306 {
2307 vim_strncpy(buf, p, e - p);
2308 add_pathsep(buf);
2309 STRCAT(buf, name);
2310 }
2311 tmplen = STRLEN(buf);
2312
2313 /*
2314 * Loop over all extensions in $PATHEXT.
2315 * Check "name" with extension added.
2316 */
2317 p = pathext;
2318 while (*p)
2319 {
2320 if (*p == ';')
2321 {
2322 // Skip empty entry
2323 ++p;
2324 continue;
2325 }
2326 e2 = vim_strchr(p, (int)';');
2327 if (e2 == NULL)
2328 e2 = p + STRLEN(p);
2329
2330 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2331 {
2332 // Not a single "." that means no extension is added.
2333 if (e2 - p + tmplen + 1 > sizeof(buf))
2334 {
2335 retval = FALSE;
2336 goto theend;
2337 }
2338 vim_strncpy(buf + tmplen, p, e2 - p);
2339 }
2340 if (executable_file((char *)buf, path))
2341 {
2342 retval = TRUE;
2343 goto theend;
2344 }
2345
2346 p = e2;
2347 }
2348
2349 p = e;
2350 }
2351
2352theend:
2353 free(pathextbuf);
2354 free(pathbuf);
2355 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002356}
2357
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002358#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2359 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002360/*
2361 * Bad parameter handler.
2362 *
2363 * Certain MS CRT functions will intentionally crash when passed invalid
2364 * parameters to highlight possible security holes. Setting this function as
2365 * the bad parameter handler will prevent the crash.
2366 *
2367 * In debug builds the parameters contain CRT information that might help track
2368 * down the source of a problem, but in non-debug builds the arguments are all
2369 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2370 * worth allowing these to make debugging of issues easier.
2371 */
2372 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002373bad_param_handler(const wchar_t *expression UNUSED,
2374 const wchar_t *function UNUSED,
2375 const wchar_t *file UNUSED,
2376 unsigned int line UNUSED,
2377 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002378{
2379}
2380
2381# define SET_INVALID_PARAM_HANDLER \
2382 ((void)_set_invalid_parameter_handler(bad_param_handler))
2383#else
2384# define SET_INVALID_PARAM_HANDLER
2385#endif
2386
Bram Moolenaar4f974752019-02-17 17:44:42 +01002387#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002388
2389/*
2390 * GUI version of mch_init().
2391 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002392 static void
2393mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002394{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002395# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002396 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002397# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002398
Bram Moolenaar0f873732019-12-05 20:28:46 +01002399 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002400 SET_INVALID_PARAM_HANDLER;
2401
Bram Moolenaar0f873732019-12-05 20:28:46 +01002402 // Let critical errors result in a failure, not in a dialog box. Required
2403 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002404 SetErrorMode(SEM_FAILCRITICALERRORS);
2405
Bram Moolenaar0f873732019-12-05 20:28:46 +01002406 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002407
Bram Moolenaar0f873732019-12-05 20:28:46 +01002408 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002409 Rows = 25;
2410 Columns = 80;
2411
Bram Moolenaar0f873732019-12-05 20:28:46 +01002412 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002413 {
2414 char_u vimrun_location[_MAX_PATH + 4];
2415
Bram Moolenaar0f873732019-12-05 20:28:46 +01002416 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002417 STRCPY(vimrun_location, exe_name);
2418 STRCPY(gettail(vimrun_location), "vimrun.exe");
2419 if (mch_getperm(vimrun_location) >= 0)
2420 {
2421 if (*skiptowhite(vimrun_location) != NUL)
2422 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002423 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002424 mch_memmove(vimrun_location + 1, vimrun_location,
2425 STRLEN(vimrun_location) + 1);
2426 *vimrun_location = '"';
2427 STRCPY(gettail(vimrun_location), "vimrun\" ");
2428 }
2429 else
2430 STRCPY(gettail(vimrun_location), "vimrun ");
2431
2432 vimrun_path = (char *)vim_strsave(vimrun_location);
2433 s_dont_use_vimrun = FALSE;
2434 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002435 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002436 s_dont_use_vimrun = FALSE;
2437
Bram Moolenaar0f873732019-12-05 20:28:46 +01002438 // Don't give the warning for a missing vimrun.exe right now, but only
2439 // when vimrun was supposed to be used. Don't bother people that do
2440 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002441 if (s_dont_use_vimrun)
2442 need_vimrun_warning = TRUE;
2443 }
2444
2445 /*
2446 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2447 * Otherwise the default "findstr /n" is used.
2448 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002449 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01002450 set_option_value_give_err((char_u *)"grepprg",
2451 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002452
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002453# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002454 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002455# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002456
2457 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002458}
2459
2460
Bram Moolenaar0f873732019-12-05 20:28:46 +01002461#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002462
2463#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002464
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002465# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2466# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002467
2468/*
2469 * ClearConsoleBuffer()
2470 * Description:
2471 * Clears the entire contents of the console screen buffer, using the
2472 * specified attribute.
2473 * Returns:
2474 * TRUE on success
2475 */
2476 static BOOL
2477ClearConsoleBuffer(WORD wAttribute)
2478{
2479 CONSOLE_SCREEN_BUFFER_INFO csbi;
2480 COORD coord;
2481 DWORD NumCells, dummy;
2482
2483 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2484 return FALSE;
2485
2486 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2487 coord.X = 0;
2488 coord.Y = 0;
2489 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2490 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002491 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002492 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2493 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002494 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002495
2496 return TRUE;
2497}
2498
2499/*
2500 * FitConsoleWindow()
2501 * Description:
2502 * Checks if the console window will fit within given buffer dimensions.
2503 * Also, if requested, will shrink the window to fit.
2504 * Returns:
2505 * TRUE on success
2506 */
2507 static BOOL
2508FitConsoleWindow(
2509 COORD dwBufferSize,
2510 BOOL WantAdjust)
2511{
2512 CONSOLE_SCREEN_BUFFER_INFO csbi;
2513 COORD dwWindowSize;
2514 BOOL NeedAdjust = FALSE;
2515
2516 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2517 {
2518 /*
2519 * A buffer resize will fail if the current console window does
2520 * not lie completely within that buffer. To avoid this, we might
2521 * have to move and possibly shrink the window.
2522 */
2523 if (csbi.srWindow.Right >= dwBufferSize.X)
2524 {
2525 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2526 if (dwWindowSize.X > dwBufferSize.X)
2527 dwWindowSize.X = dwBufferSize.X;
2528 csbi.srWindow.Right = dwBufferSize.X - 1;
2529 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2530 NeedAdjust = TRUE;
2531 }
2532 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2533 {
2534 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2535 if (dwWindowSize.Y > dwBufferSize.Y)
2536 dwWindowSize.Y = dwBufferSize.Y;
2537 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2538 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2539 NeedAdjust = TRUE;
2540 }
2541 if (NeedAdjust && WantAdjust)
2542 {
2543 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2544 return FALSE;
2545 }
2546 return TRUE;
2547 }
2548
2549 return FALSE;
2550}
2551
2552typedef struct ConsoleBufferStruct
2553{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002554 BOOL IsValid;
2555 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002556 PCHAR_INFO Buffer;
2557 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002558 PSMALL_RECT Regions;
2559 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002560} ConsoleBuffer;
2561
2562/*
2563 * SaveConsoleBuffer()
2564 * Description:
2565 * Saves important information about the console buffer, including the
2566 * actual buffer contents. The saved information is suitable for later
2567 * restoration by RestoreConsoleBuffer().
2568 * Returns:
2569 * TRUE if all information was saved; FALSE otherwise
2570 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2571 */
2572 static BOOL
2573SaveConsoleBuffer(
2574 ConsoleBuffer *cb)
2575{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002576 DWORD NumCells;
2577 COORD BufferCoord;
2578 SMALL_RECT ReadRegion;
2579 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002580 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002581
Bram Moolenaar071d4272004-06-13 20:20:40 +00002582 if (cb == NULL)
2583 return FALSE;
2584
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002585 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002586 {
2587 cb->IsValid = FALSE;
2588 return FALSE;
2589 }
2590 cb->IsValid = TRUE;
2591
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002592 /*
2593 * Allocate a buffer large enough to hold the entire console screen
2594 * buffer. If this ConsoleBuffer structure has already been initialized
2595 * with a buffer of the correct size, then just use that one.
2596 */
2597 if (!cb->IsValid || cb->Buffer == NULL ||
2598 cb->BufferSize.X != cb->Info.dwSize.X ||
2599 cb->BufferSize.Y != cb->Info.dwSize.Y)
2600 {
2601 cb->BufferSize.X = cb->Info.dwSize.X;
2602 cb->BufferSize.Y = cb->Info.dwSize.Y;
2603 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2604 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002605 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002606 if (cb->Buffer == NULL)
2607 return FALSE;
2608 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002609
2610 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002611 * We will now copy the console screen buffer into our buffer.
2612 * ReadConsoleOutput() seems to be limited as far as how much you
2613 * can read at a time. Empirically, this number seems to be about
2614 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2615 * in chunks until it is all copied. The chunks will all have the
2616 * same horizontal characteristics, so initialize them now. The
2617 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002618 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002619 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002620 ReadRegion.Left = 0;
2621 ReadRegion.Right = cb->Info.dwSize.X - 1;
2622 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002623
2624 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2625 if (cb->Regions == NULL || numregions != cb->NumRegions)
2626 {
2627 cb->NumRegions = numregions;
2628 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002629 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002630 if (cb->Regions == NULL)
2631 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002632 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002633 return FALSE;
2634 }
2635 }
2636
2637 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002638 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002639 /*
2640 * Read into position (0, Y) in our buffer.
2641 */
2642 BufferCoord.Y = Y;
2643 /*
2644 * Read the region whose top left corner is (0, Y) and whose bottom
2645 * right corner is (width - 1, Y + Y_incr - 1). This should define
2646 * a region of size width by Y_incr. Don't worry if this region is
2647 * too large for the remaining buffer; it will be cropped.
2648 */
2649 ReadRegion.Top = Y;
2650 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002651 if (!ReadConsoleOutputW(g_hConOut, // output handle
2652 cb->Buffer, // our buffer
2653 cb->BufferSize, // dimensions of our buffer
2654 BufferCoord, // offset in our buffer
2655 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002656 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002657 VIM_CLEAR(cb->Buffer);
2658 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002659 return FALSE;
2660 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002661 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002662 }
2663
2664 return TRUE;
2665}
2666
2667/*
2668 * RestoreConsoleBuffer()
2669 * Description:
2670 * Restores important information about the console buffer, including the
2671 * actual buffer contents, if desired. The information to restore is in
2672 * the same format used by SaveConsoleBuffer().
2673 * Returns:
2674 * TRUE on success
2675 */
2676 static BOOL
2677RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002678 ConsoleBuffer *cb,
2679 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002680{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002681 COORD BufferCoord;
2682 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002683 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002684
2685 if (cb == NULL || !cb->IsValid)
2686 return FALSE;
2687
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002688 /*
2689 * Before restoring the buffer contents, clear the current buffer, and
2690 * restore the cursor position and window information. Doing this now
2691 * prevents old buffer contents from "flashing" onto the screen.
2692 */
2693 if (RestoreScreen)
2694 ClearConsoleBuffer(cb->Info.wAttributes);
2695
2696 FitConsoleWindow(cb->Info.dwSize, TRUE);
2697 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2698 return FALSE;
2699 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2700 return FALSE;
2701
2702 if (!RestoreScreen)
2703 {
2704 /*
2705 * No need to restore the screen buffer contents, so we're done.
2706 */
2707 return TRUE;
2708 }
2709
2710 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2711 return FALSE;
2712 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2713 return FALSE;
2714
2715 /*
2716 * Restore the screen buffer contents.
2717 */
2718 if (cb->Buffer != NULL)
2719 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002720 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002721 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002722 BufferCoord.X = cb->Regions[i].Left;
2723 BufferCoord.Y = cb->Regions[i].Top;
2724 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01002725 if (!WriteConsoleOutputW(g_hConOut, // output handle
2726 cb->Buffer, // our buffer
2727 cb->BufferSize, // dimensions of our buffer
2728 BufferCoord, // offset in our buffer
2729 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02002730 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002731 }
2732 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002733
2734 return TRUE;
2735}
2736
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002737# define FEAT_RESTORE_ORIG_SCREEN
2738# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002739static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002740# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002741static ConsoleBuffer g_cbNonTermcap = { 0 };
2742static ConsoleBuffer g_cbTermcap = { 0 };
2743
Bram Moolenaar071d4272004-06-13 20:20:40 +00002744char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01002745HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00002746static HICON g_hOrigIconSmall = NULL;
2747static HICON g_hOrigIcon = NULL;
2748static HICON g_hVimIcon = NULL;
2749static BOOL g_fCanChangeIcon = FALSE;
2750
Bram Moolenaar071d4272004-06-13 20:20:40 +00002751/*
2752 * GetConsoleIcon()
2753 * Description:
2754 * Attempts to retrieve the small icon and/or the big icon currently in
2755 * use by a given window.
2756 * Returns:
2757 * TRUE on success
2758 */
2759 static BOOL
2760GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002761 HWND hWnd,
2762 HICON *phIconSmall,
2763 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002764{
2765 if (hWnd == NULL)
2766 return FALSE;
2767
2768 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002769 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2770 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002771 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002772 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2773 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002774 return TRUE;
2775}
2776
2777/*
2778 * SetConsoleIcon()
2779 * Description:
2780 * Attempts to change the small icon and/or the big icon currently in
2781 * use by a given window.
2782 * Returns:
2783 * TRUE on success
2784 */
2785 static BOOL
2786SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002787 HWND hWnd,
2788 HICON hIconSmall,
2789 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002790{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002791 if (hWnd == NULL)
2792 return FALSE;
2793
2794 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002795 SendMessage(hWnd, WM_SETICON,
2796 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002797 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002798 SendMessage(hWnd, WM_SETICON,
2799 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002800 return TRUE;
2801}
2802
2803/*
2804 * SaveConsoleTitleAndIcon()
2805 * Description:
2806 * Saves the current console window title in g_szOrigTitle, for later
2807 * restoration. Also, attempts to obtain a handle to the console window,
2808 * and use it to save the small and big icons currently in use by the
2809 * console window. This is not always possible on some versions of Windows;
2810 * nor is it possible when running Vim remotely using Telnet (since the
2811 * console window the user sees is owned by a remote process).
2812 */
2813 static void
2814SaveConsoleTitleAndIcon(void)
2815{
Bram Moolenaar0f873732019-12-05 20:28:46 +01002816 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002817 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2818 return;
2819
2820 /*
2821 * Obtain a handle to the console window using GetConsoleWindow() from
2822 * KERNEL32.DLL; we need to handle in order to change the window icon.
2823 * This function only exists on NT-based Windows, starting with Windows
2824 * 2000. On older operating systems, we can't change the window icon
2825 * anyway.
2826 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002827 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002828 if (g_hWnd == NULL)
2829 return;
2830
Bram Moolenaar0f873732019-12-05 20:28:46 +01002831 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002832 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2833 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2834 return;
2835
Bram Moolenaar0f873732019-12-05 20:28:46 +01002836 // Extract the first icon contained in the Vim executable.
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002837 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002838 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002839 if (g_hVimIcon != NULL)
2840 g_fCanChangeIcon = TRUE;
2841}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002842
2843static int g_fWindInitCalled = FALSE;
2844static int g_fTermcapMode = FALSE;
2845static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002846
2847/*
2848 * non-GUI version of mch_init().
2849 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002850 static void
2851mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002852{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002853# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002854 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002855# endif
2856# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002857 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002858# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002859
Bram Moolenaar0f873732019-12-05 20:28:46 +01002860 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002861 SET_INVALID_PARAM_HANDLER;
2862
Bram Moolenaar0f873732019-12-05 20:28:46 +01002863 // Let critical errors result in a failure, not in a dialog box. Required
2864 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002865 SetErrorMode(SEM_FAILCRITICALERRORS);
2866
Bram Moolenaar0f873732019-12-05 20:28:46 +01002867 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002868 out_flush();
2869
Bram Moolenaar0f873732019-12-05 20:28:46 +01002870 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00002871 if (read_cmd_fd == 0)
2872 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2873 else
2874 create_conin();
2875 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2876
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002877# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01002878 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002879 SaveConsoleBuffer(&g_cbOrig);
2880 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002881# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01002882 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002883 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2884 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002885# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002886 if (cterm_normal_fg_color == 0)
2887 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2888 if (cterm_normal_bg_color == 0)
2889 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2890
Bram Moolenaarbdace832019-03-02 10:13:42 +01002891 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002892 g_color_index_fg = g_attrDefault & 0xf;
2893 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2894
Bram Moolenaar0f873732019-12-05 20:28:46 +01002895 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00002896 update_tcap(g_attrCurrent);
2897
2898 GetConsoleCursorInfo(g_hConOut, &g_cci);
2899 GetConsoleMode(g_hConIn, &g_cmodein);
2900 GetConsoleMode(g_hConOut, &g_cmodeout);
2901
Bram Moolenaar071d4272004-06-13 20:20:40 +00002902 SaveConsoleTitleAndIcon();
2903 /*
2904 * Set both the small and big icons of the console window to Vim's icon.
2905 * Note that Vim presently only has one size of icon (32x32), but it
2906 * automatically gets scaled down to 16x16 when setting the small icon.
2907 */
2908 if (g_fCanChangeIcon)
2909 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002910
2911 ui_get_shellsize();
2912
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002913# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002914 fdDump = fopen("dump", "wt");
2915
2916 if (fdDump)
2917 {
2918 time_t t;
2919
2920 time(&t);
2921 fputs(ctime(&t), fdDump);
2922 fflush(fdDump);
2923 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002924# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002925
2926 g_fWindInitCalled = TRUE;
2927
Bram Moolenaar071d4272004-06-13 20:20:40 +00002928 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002929
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002930# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002931 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002932# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002933
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02002934 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002935 vtp_init();
Bram Moolenaar06b7b582020-05-30 17:49:25 +02002936 wt_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002937}
2938
2939/*
2940 * non-GUI version of mch_exit().
2941 * Shut down and exit with status `r'
2942 * Careful: mch_exit() may be called before mch_init()!
2943 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002944 static void
2945mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002946{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002947 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002948
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002949 vtp_exit();
2950
Bram Moolenaar955f1982017-02-05 15:10:51 +01002951 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002952 if (g_fWindInitCalled)
2953 settmode(TMODE_COOK);
2954
Bram Moolenaar0f873732019-12-05 20:28:46 +01002955 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00002956
2957 if (g_fWindInitCalled)
2958 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02002959 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002960 /*
2961 * Restore both the small and big icons of the console window to
2962 * what they were at startup. Don't do this when the window is
2963 * closed, Vim would hang here.
2964 */
2965 if (g_fCanChangeIcon && !g_fForceExit)
2966 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002967
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002968# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002969 if (fdDump)
2970 {
2971 time_t t;
2972
2973 time(&t);
2974 fputs(ctime(&t), fdDump);
2975 fclose(fdDump);
2976 }
2977 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002978# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002979 }
2980
2981 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02002982 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002983 SetConsoleMode(g_hConOut, g_cmodeout);
2984
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002985# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00002986 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002987# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002988
2989 exit(r);
2990}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002991#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002992
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002993 void
2994mch_init(void)
2995{
2996#ifdef VIMDLL
2997 if (gui.starting)
2998 mch_init_g();
2999 else
3000 mch_init_c();
3001#elif defined(FEAT_GUI_MSWIN)
3002 mch_init_g();
3003#else
3004 mch_init_c();
3005#endif
3006}
3007
3008 void
3009mch_exit(int r)
3010{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003011#ifdef FEAT_NETBEANS_INTG
3012 netbeans_send_disconnect();
3013#endif
3014
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003015#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003016 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003017 mch_exit_g(r);
3018 else
3019 mch_exit_c(r);
3020#elif defined(FEAT_GUI_MSWIN)
3021 mch_exit_g(r);
3022#else
3023 mch_exit_c(r);
3024#endif
3025}
3026
Bram Moolenaar071d4272004-06-13 20:20:40 +00003027/*
3028 * Do we have an interactive window?
3029 */
3030 int
3031mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003032 int argc UNUSED,
3033 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003034{
3035 get_exe_name();
3036
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003037#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003038 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003039#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003040# ifdef VIMDLL
3041 if (gui.in_use)
3042 return OK;
3043# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003044 if (isatty(1))
3045 return OK;
3046 return FAIL;
3047#endif
3048}
3049
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003050/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003051 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003052 * When "len" is > 0, also expand short to long filenames.
3053 */
3054 void
3055fname_case(
3056 char_u *name,
3057 int len)
3058{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003059 int flen;
3060 WCHAR *p;
3061 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003062
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003063 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003064 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003065 return;
3066
3067 slash_adjust(name);
3068
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003069 p = enc_to_utf16(name, NULL);
3070 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003071 return;
3072
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003073 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003074 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003075 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003076
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003077 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003078 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003079 if (len > 0 || flen >= (int)STRLEN(q))
3080 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3081 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003082 }
3083 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003084 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003085}
3086
3087
3088/*
3089 * Insert user name in s[len].
3090 */
3091 int
3092mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003093 char_u *s,
3094 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003095{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003096 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003097 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003098
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003099 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003100 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003101 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003102
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003103 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003104 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003105 vim_strncpy(s, p, len - 1);
3106 vim_free(p);
3107 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003108 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003109 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003110 s[0] = NUL;
3111 return FAIL;
3112}
3113
3114
3115/*
3116 * Insert host name in s[len].
3117 */
3118 void
3119mch_get_host_name(
3120 char_u *s,
3121 int len)
3122{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003123 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003124 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003125
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003126 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003127 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003128 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003129
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003130 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003131 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003132 vim_strncpy(s, p, len - 1);
3133 vim_free(p);
3134 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003135 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003136 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003137}
3138
3139
3140/*
3141 * return process ID
3142 */
3143 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003144mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003145{
3146 return (long)GetCurrentProcessId();
3147}
3148
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003149/*
3150 * return TRUE if process "pid" is still running
3151 */
3152 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003153mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003154{
3155 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3156 DWORD status = 0;
3157 int ret = FALSE;
3158
3159 if (hProcess == NULL)
3160 return FALSE; // might not have access
3161 if (GetExitCodeProcess(hProcess, &status) )
3162 ret = status == STILL_ACTIVE;
3163 CloseHandle(hProcess);
3164 return ret;
3165}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003166
3167/*
3168 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3169 * Return OK for success, FAIL for failure.
3170 */
3171 int
3172mch_dirname(
3173 char_u *buf,
3174 int len)
3175{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003176 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003177
Bram Moolenaar071d4272004-06-13 20:20:40 +00003178 /*
3179 * Originally this was:
3180 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3181 * But the Win32s known bug list says that getcwd() doesn't work
3182 * so use the Win32 system call instead. <Negri>
3183 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003184 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003185 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003186 WCHAR wcbuf[_MAX_PATH + 1];
3187 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003188
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003189 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003190 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003191 p = utf16_to_enc(wcbuf, NULL);
3192 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003193 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003194 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003195 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003196 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003197 }
3198 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003199 if (p == NULL)
3200 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003201
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003202 if (p != NULL)
3203 {
3204 vim_strncpy(buf, p, len - 1);
3205 vim_free(p);
3206 return OK;
3207 }
3208 }
3209 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003210}
3211
3212/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003213 * Get file permissions for "name".
3214 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003215 */
3216 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003217mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003218{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003219 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003220 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003221
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003222 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003223 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003224}
3225
3226
3227/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003228 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003229 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003230 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003231 */
3232 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003233mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003234{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003235 long n;
3236 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003237
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003238 p = enc_to_utf16(name, NULL);
3239 if (p == NULL)
3240 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003241
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003242 n = _wchmod(p, perm);
3243 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003244 if (n == -1)
3245 return FAIL;
3246
3247 win32_set_archive(name);
3248
3249 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003250}
3251
3252/*
3253 * Set hidden flag for "name".
3254 */
3255 void
3256mch_hide(char_u *name)
3257{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003258 int attrs = win32_getattrs(name);
3259 if (attrs == -1)
3260 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003261
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003262 attrs |= FILE_ATTRIBUTE_HIDDEN;
3263 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003264}
3265
3266/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003267 * Return TRUE if file "name" exists and is hidden.
3268 */
3269 int
3270mch_ishidden(char_u *name)
3271{
3272 int f = win32_getattrs(name);
3273
3274 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003275 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003276
3277 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3278}
3279
3280/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003281 * return TRUE if "name" is a directory
3282 * return FALSE if "name" is not a directory or upon error
3283 */
3284 int
3285mch_isdir(char_u *name)
3286{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003287 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003288
3289 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003290 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003291
3292 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3293}
3294
3295/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003296 * return TRUE if "name" is a directory, NOT a symlink to a directory
3297 * return FALSE if "name" is not a directory
3298 * return FALSE for error
3299 */
3300 int
3301mch_isrealdir(char_u *name)
3302{
3303 return mch_isdir(name) && !mch_is_symbolic_link(name);
3304}
3305
3306/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003307 * Create directory "name".
3308 * Return 0 on success, -1 on error.
3309 */
3310 int
3311mch_mkdir(char_u *name)
3312{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003313 WCHAR *p;
3314 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003315
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003316 p = enc_to_utf16(name, NULL);
3317 if (p == NULL)
3318 return -1;
3319 retval = _wmkdir(p);
3320 vim_free(p);
3321 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003322}
3323
3324/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003325 * Delete directory "name".
3326 * Return 0 on success, -1 on error.
3327 */
3328 int
3329mch_rmdir(char_u *name)
3330{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003331 WCHAR *p;
3332 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003333
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003334 p = enc_to_utf16(name, NULL);
3335 if (p == NULL)
3336 return -1;
3337 retval = _wrmdir(p);
3338 vim_free(p);
3339 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003340}
3341
3342/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003343 * Return TRUE if file "fname" has more than one link.
3344 */
3345 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003346mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003347{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003348 BY_HANDLE_FILE_INFORMATION info;
3349
3350 return win32_fileinfo(fname, &info) == FILEINFO_OK
3351 && info.nNumberOfLinks > 1;
3352}
3353
3354/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003355 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003356 */
3357 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003358mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003359{
3360 HANDLE hFind;
3361 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003362 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003363 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003364 WIN32_FIND_DATAW findDataW;
3365
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003366 wn = enc_to_utf16(name, NULL);
3367 if (wn == NULL)
3368 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003369
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003370 hFind = FindFirstFileW(wn, &findDataW);
3371 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003372 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003373 {
3374 fileFlags = findDataW.dwFileAttributes;
3375 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003376 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003377 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003378
3379 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003380 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3381 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003382 res = TRUE;
3383
3384 return res;
3385}
3386
3387/*
3388 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3389 * link.
3390 */
3391 int
3392mch_is_linked(char_u *fname)
3393{
3394 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3395 return TRUE;
3396 return FALSE;
3397}
3398
3399/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003400 * Get the by-handle-file-information for "fname".
3401 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003402 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003403 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3404 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3405 */
3406 int
3407win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3408{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003409 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003410 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003411 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003412
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003413 wn = enc_to_utf16(fname, NULL);
3414 if (wn == NULL)
3415 return FILEINFO_ENC_FAIL;
3416
3417 hFile = CreateFileW(wn, // file name
3418 GENERIC_READ, // access mode
3419 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3420 NULL, // security descriptor
3421 OPEN_EXISTING, // creation disposition
3422 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3423 NULL); // handle to template file
3424 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003425
3426 if (hFile != INVALID_HANDLE_VALUE)
3427 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003428 if (GetFileInformationByHandle(hFile, info) != 0)
3429 res = FILEINFO_OK;
3430 else
3431 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003432 CloseHandle(hFile);
3433 }
3434
Bram Moolenaar03f48552006-02-28 23:52:23 +00003435 return res;
3436}
3437
3438/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003439 * get file attributes for `name'
3440 * -1 : error
3441 * else FILE_ATTRIBUTE_* defined in winnt.h
3442 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003443 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003444win32_getattrs(char_u *name)
3445{
3446 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003447 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003448
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003449 p = enc_to_utf16(name, NULL);
3450 if (p == NULL)
3451 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003452
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003453 attr = GetFileAttributesW(p);
3454 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003455
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003456 return attr;
3457}
3458
3459/*
3460 * set file attributes for `name' to `attrs'
3461 *
3462 * return -1 for failure, 0 otherwise
3463 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003464 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003465win32_setattrs(char_u *name, int attrs)
3466{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003467 int res;
3468 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003469
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003470 p = enc_to_utf16(name, NULL);
3471 if (p == NULL)
3472 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003473
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003474 res = SetFileAttributesW(p, attrs);
3475 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003476
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003477 return res ? 0 : -1;
3478}
3479
3480/*
3481 * Set archive flag for "name".
3482 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003483 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003484win32_set_archive(char_u *name)
3485{
3486 int attrs = win32_getattrs(name);
3487 if (attrs == -1)
3488 return -1;
3489
3490 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3491 return win32_setattrs(name, attrs);
3492}
3493
3494/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003495 * Return TRUE if file or directory "name" is writable (not readonly).
3496 * Strange semantics of Win32: a readonly directory is writable, but you can't
3497 * delete a file. Let's say this means it is writable.
3498 */
3499 int
3500mch_writable(char_u *name)
3501{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003502 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003503
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003504 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3505 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003506}
3507
Bram Moolenaar071d4272004-06-13 20:20:40 +00003508/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003509 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003510 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003511 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3512 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003513 */
3514 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01003515mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003516{
Bram Moolenaar95da1362020-05-30 18:37:55 +02003517 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003518}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003519
3520/*
3521 * Check what "name" is:
3522 * NODE_NORMAL: file or directory (or doesn't exist)
3523 * NODE_WRITABLE: writable device, socket, fifo, etc.
3524 * NODE_OTHER: non-writable things
3525 */
3526 int
3527mch_nodetype(char_u *name)
3528{
3529 HANDLE hFile;
3530 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003531 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003532
Bram Moolenaar0f873732019-12-05 20:28:46 +01003533 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3534 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3535 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00003536 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3537 return NODE_WRITABLE;
3538
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003539 wn = enc_to_utf16(name, NULL);
3540 if (wn == NULL)
3541 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003542
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003543 hFile = CreateFileW(wn, // file name
3544 GENERIC_WRITE, // access mode
3545 0, // share mode
3546 NULL, // security descriptor
3547 OPEN_EXISTING, // creation disposition
3548 0, // file attributes
3549 NULL); // handle to template file
3550 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003551 if (hFile == INVALID_HANDLE_VALUE)
3552 return NODE_NORMAL;
3553
3554 type = GetFileType(hFile);
3555 CloseHandle(hFile);
3556 if (type == FILE_TYPE_CHAR)
3557 return NODE_WRITABLE;
3558 if (type == FILE_TYPE_DISK)
3559 return NODE_NORMAL;
3560 return NODE_OTHER;
3561}
3562
3563#ifdef HAVE_ACL
3564struct my_acl
3565{
3566 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3567 PSID pSidOwner;
3568 PSID pSidGroup;
3569 PACL pDacl;
3570 PACL pSacl;
3571};
3572#endif
3573
3574/*
3575 * Return a pointer to the ACL of file "fname" in allocated memory.
3576 * Return NULL if the ACL is not available for whatever reason.
3577 */
3578 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003579mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003580{
3581#ifndef HAVE_ACL
3582 return (vim_acl_T)NULL;
3583#else
3584 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003585 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003586
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003587 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003588 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003589 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003590 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003591
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003592 wn = enc_to_utf16(fname, NULL);
3593 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003594 {
3595 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003596 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003597 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003598
3599 // Try to retrieve the entire security descriptor.
3600 err = GetNamedSecurityInfoW(
3601 wn, // Abstract filename
3602 SE_FILE_OBJECT, // File Object
3603 OWNER_SECURITY_INFORMATION |
3604 GROUP_SECURITY_INFORMATION |
3605 DACL_SECURITY_INFORMATION |
3606 SACL_SECURITY_INFORMATION,
3607 &p->pSidOwner, // Ownership information.
3608 &p->pSidGroup, // Group membership.
3609 &p->pDacl, // Discretionary information.
3610 &p->pSacl, // For auditing purposes.
3611 &p->pSecurityDescriptor);
3612 if (err == ERROR_ACCESS_DENIED ||
3613 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003614 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003615 // Retrieve only DACL.
3616 (void)GetNamedSecurityInfoW(
3617 wn,
3618 SE_FILE_OBJECT,
3619 DACL_SECURITY_INFORMATION,
3620 NULL,
3621 NULL,
3622 &p->pDacl,
3623 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003624 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003625 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003626 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003627 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003628 mch_free_acl((vim_acl_T)p);
3629 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003630 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003631 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003632 }
3633
3634 return (vim_acl_T)p;
3635#endif
3636}
3637
Bram Moolenaar27515922013-06-29 15:36:26 +02003638#ifdef HAVE_ACL
3639/*
3640 * Check if "acl" contains inherited ACE.
3641 */
3642 static BOOL
3643is_acl_inherited(PACL acl)
3644{
3645 DWORD i;
3646 ACL_SIZE_INFORMATION acl_info;
3647 PACCESS_ALLOWED_ACE ace;
3648
3649 acl_info.AceCount = 0;
3650 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3651 for (i = 0; i < acl_info.AceCount; i++)
3652 {
3653 GetAce(acl, i, (LPVOID *)&ace);
3654 if (ace->Header.AceFlags & INHERITED_ACE)
3655 return TRUE;
3656 }
3657 return FALSE;
3658}
3659#endif
3660
Bram Moolenaar071d4272004-06-13 20:20:40 +00003661/*
3662 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3663 * Errors are ignored.
3664 * This must only be called with "acl" equal to what mch_get_acl() returned.
3665 */
3666 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003667mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003668{
3669#ifdef HAVE_ACL
3670 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003671 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003672 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003673
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003674 if (p == NULL)
3675 return;
3676
3677 wn = enc_to_utf16(fname, NULL);
3678 if (wn == NULL)
3679 return;
3680
3681 // Set security flags
3682 if (p->pSidOwner)
3683 sec_info |= OWNER_SECURITY_INFORMATION;
3684 if (p->pSidGroup)
3685 sec_info |= GROUP_SECURITY_INFORMATION;
3686 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003687 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003688 sec_info |= DACL_SECURITY_INFORMATION;
3689 // Do not inherit its parent's DACL.
3690 // If the DACL is inherited, Cygwin permissions would be changed.
3691 if (!is_acl_inherited(p->pDacl))
3692 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003693 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003694 if (p->pSacl)
3695 sec_info |= SACL_SECURITY_INFORMATION;
3696
3697 (void)SetNamedSecurityInfoW(
3698 wn, // Abstract filename
3699 SE_FILE_OBJECT, // File Object
3700 sec_info,
3701 p->pSidOwner, // Ownership information.
3702 p->pSidGroup, // Group membership.
3703 p->pDacl, // Discretionary information.
3704 p->pSacl // For auditing purposes.
3705 );
3706 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003707#endif
3708}
3709
3710 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003711mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003712{
3713#ifdef HAVE_ACL
3714 struct my_acl *p = (struct my_acl *)acl;
3715
3716 if (p != NULL)
3717 {
3718 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3719 vim_free(p);
3720 }
3721#endif
3722}
3723
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003724#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003725
3726/*
3727 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3728 */
3729 static BOOL WINAPI
3730handler_routine(
3731 DWORD dwCtrlType)
3732{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003733 INPUT_RECORD ir;
3734 DWORD out;
3735
Bram Moolenaar071d4272004-06-13 20:20:40 +00003736 switch (dwCtrlType)
3737 {
3738 case CTRL_C_EVENT:
3739 if (ctrl_c_interrupts)
3740 g_fCtrlCPressed = TRUE;
3741 return TRUE;
3742
3743 case CTRL_BREAK_EVENT:
3744 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003745 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003746 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02003747 ir.EventType = KEY_EVENT;
3748 ir.Event.KeyEvent.bKeyDown = TRUE;
3749 ir.Event.KeyEvent.wRepeatCount = 1;
3750 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3751 ir.Event.KeyEvent.wVirtualScanCode = 0;
3752 ir.Event.KeyEvent.dwControlKeyState = 0;
3753 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3754 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003755 return TRUE;
3756
Bram Moolenaar0f873732019-12-05 20:28:46 +01003757 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00003758 case CTRL_CLOSE_EVENT:
3759 case CTRL_LOGOFF_EVENT:
3760 case CTRL_SHUTDOWN_EVENT:
3761 windgoto((int)Rows - 1, 0);
3762 g_fForceExit = TRUE;
3763
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003764 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003765 (dwCtrlType == CTRL_CLOSE_EVENT
3766 ? _("close")
3767 : dwCtrlType == CTRL_LOGOFF_EVENT
3768 ? _("logoff")
3769 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003770# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00003771 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003772# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003773
Bram Moolenaar0f873732019-12-05 20:28:46 +01003774 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00003775
Bram Moolenaar0f873732019-12-05 20:28:46 +01003776 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00003777
3778 default:
3779 return FALSE;
3780 }
3781}
3782
3783
3784/*
3785 * set the tty in (raw) ? "raw" : "cooked" mode
3786 */
3787 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02003788mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003789{
3790 DWORD cmodein;
3791 DWORD cmodeout;
3792 BOOL bEnableHandler;
3793
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003794# ifdef VIMDLL
3795 if (gui.in_use)
3796 return;
3797# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003798 GetConsoleMode(g_hConIn, &cmodein);
3799 GetConsoleMode(g_hConOut, &cmodeout);
3800 if (tmode == TMODE_RAW)
3801 {
3802 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3803 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003804 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003805 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003806 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003807 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
3808 }
3809 else
3810 {
3811 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
3812 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003813 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003814# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01003815 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
3816 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003817 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003818# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003819 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003820# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003821 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003822 bEnableHandler = TRUE;
3823 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01003824 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00003825 {
3826 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3827 ENABLE_ECHO_INPUT);
3828 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3829 bEnableHandler = FALSE;
3830 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003831 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003832 SetConsoleMode(g_hConOut, cmodeout);
3833 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3834
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003835# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003836 if (fdDump)
3837 {
3838 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3839 tmode == TMODE_RAW ? "raw" :
3840 tmode == TMODE_COOK ? "cooked" : "normal",
3841 cmodein, cmodeout);
3842 fflush(fdDump);
3843 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003844# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003845}
3846
3847
3848/*
3849 * Get the size of the current window in `Rows' and `Columns'
3850 * Return OK when size could be determined, FAIL otherwise.
3851 */
3852 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003853mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003854{
3855 CONSOLE_SCREEN_BUFFER_INFO csbi;
3856
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003857# ifdef VIMDLL
3858 if (gui.in_use)
3859 return OK;
3860# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003861 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3862 {
3863 /*
3864 * For some reason, we are trying to get the screen dimensions
3865 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3866 * variables are really intended to mean the size of Vim screen
3867 * while in termcap mode.
3868 */
3869 Rows = g_cbTermcap.Info.dwSize.Y;
3870 Columns = g_cbTermcap.Info.dwSize.X;
3871 }
3872 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3873 {
3874 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3875 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3876 }
3877 else
3878 {
3879 Rows = 25;
3880 Columns = 80;
3881 }
3882 return OK;
3883}
3884
3885/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003886 * Resize console buffer to 'COORD'
3887 */
3888 static void
3889ResizeConBuf(
3890 HANDLE hConsole,
3891 COORD coordScreen)
3892{
3893 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3894 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003895# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003896 if (fdDump)
3897 {
3898 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3899 GetLastError());
3900 fflush(fdDump);
3901 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003902# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003903 }
3904}
3905
3906/*
3907 * Resize console window size to 'srWindowRect'
3908 */
3909 static void
3910ResizeWindow(
3911 HANDLE hConsole,
3912 SMALL_RECT srWindowRect)
3913{
3914 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
3915 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003916# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003917 if (fdDump)
3918 {
3919 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3920 GetLastError());
3921 fflush(fdDump);
3922 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003923# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003924 }
3925}
3926
3927/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003928 * Set a console window to `xSize' * `ySize'
3929 */
3930 static void
3931ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003932 HANDLE hConsole,
3933 int xSize,
3934 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003935{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003936 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
3937 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003938 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003939 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02003940 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003941
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003942# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003943 if (fdDump)
3944 {
3945 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3946 fflush(fdDump);
3947 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003948# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003949
Bram Moolenaar0f873732019-12-05 20:28:46 +01003950 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00003951 coordScreen = GetLargestConsoleWindowSize(hConsole);
3952
Bram Moolenaar0f873732019-12-05 20:28:46 +01003953 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00003954 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3955 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3956 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3957
3958 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3959 {
3960 int sx, sy;
3961
3962 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3963 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3964 if (sy < ySize || sx < xSize)
3965 {
3966 /*
3967 * Increasing number of lines/columns, do buffer first.
3968 * Use the maximal size in x and y direction.
3969 */
3970 if (sy < ySize)
3971 coordScreen.Y = ySize;
3972 else
3973 coordScreen.Y = sy;
3974 if (sx < xSize)
3975 coordScreen.X = xSize;
3976 else
3977 coordScreen.X = sx;
3978 SetConsoleScreenBufferSize(hConsole, coordScreen);
3979 }
3980 }
3981
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003982 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003983 coordScreen.X = xSize;
3984 coordScreen.Y = ySize;
3985
Bram Moolenaar2551c032018-08-23 22:38:31 +02003986 // In the new console call API, only the first time in reverse order
3987 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003988 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003989 ResizeWindow(hConsole, srWindowRect);
3990 ResizeConBuf(hConsole, coordScreen);
3991 }
3992 else
3993 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003994 // Workaround for a Windows 10 bug
3995 cursor.X = srWindowRect.Left;
3996 cursor.Y = srWindowRect.Top;
3997 SetConsoleCursorPosition(hConsole, cursor);
3998
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003999 ResizeConBuf(hConsole, coordScreen);
4000 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004001 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004002 }
4003}
4004
4005
4006/*
4007 * Set the console window to `Rows' * `Columns'
4008 */
4009 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004010mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004011{
4012 COORD coordScreen;
4013
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004014# ifdef VIMDLL
4015 if (gui.in_use)
4016 return;
4017# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004018 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004019 if (suppress_winsize != 0)
4020 {
4021 suppress_winsize = 2;
4022 return;
4023 }
4024
4025 if (term_console)
4026 {
4027 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4028
Bram Moolenaar0f873732019-12-05 20:28:46 +01004029 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004030 if (Rows > coordScreen.Y)
4031 Rows = coordScreen.Y;
4032 if (Columns > coordScreen.X)
4033 Columns = coordScreen.X;
4034
4035 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4036 }
4037}
4038
4039/*
4040 * Rows and/or Columns has changed.
4041 */
4042 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004043mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004044{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004045# ifdef VIMDLL
4046 if (gui.in_use)
4047 return;
4048# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004049 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4050}
4051
4052
4053/*
4054 * Called when started up, to set the winsize that was delayed.
4055 */
4056 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004057mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004058{
4059 if (suppress_winsize == 2)
4060 {
4061 suppress_winsize = 0;
4062 mch_set_shellsize();
4063 shell_resized();
4064 }
4065 suppress_winsize = 0;
4066}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004067#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004068
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004069 static BOOL
4070vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004071 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004072 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004073 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004074 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004075 PROCESS_INFORMATION *pi,
4076 LPVOID *env,
4077 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004078{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004079 BOOL ret = FALSE;
4080 WCHAR *wcmd, *wcwd = NULL;
4081
4082 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4083 if (wcmd == NULL)
4084 return FALSE;
4085 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004086 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004087 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4088 if (wcwd == NULL)
4089 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004090 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004091
4092 ret = CreateProcessW(
4093 NULL, // Executable name
4094 wcmd, // Command to execute
4095 NULL, // Process security attributes
4096 NULL, // Thread security attributes
4097 inherit_handles, // Inherit handles
4098 flags, // Creation flags
4099 env, // Environment
4100 wcwd, // Current directory
4101 (LPSTARTUPINFOW)si, // Startup information
4102 pi); // Process information
4103theend:
4104 vim_free(wcmd);
4105 vim_free(wcwd);
4106 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004107}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004108
4109
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004110 static HINSTANCE
4111vim_shell_execute(
4112 char *cmd,
4113 INT n_show_cmd)
4114{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004115 HINSTANCE ret;
4116 WCHAR *wcmd;
4117
4118 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4119 if (wcmd == NULL)
4120 return (HINSTANCE) 0;
4121
4122 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4123 vim_free(wcmd);
4124 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004125}
4126
4127
Bram Moolenaar4f974752019-02-17 17:44:42 +01004128#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004129
4130/*
4131 * Specialised version of system() for Win32 GUI mode.
4132 * This version proceeds as follows:
4133 * 1. Create a console window for use by the subprocess
4134 * 2. Run the subprocess (it gets the allocated console by default)
4135 * 3. Wait for the subprocess to terminate and get its exit code
4136 * 4. Prompt the user to press a key to close the console window
4137 */
4138 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004139mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004140{
4141 STARTUPINFO si;
4142 PROCESS_INFORMATION pi;
4143 DWORD ret = 0;
4144 HWND hwnd = GetFocus();
4145
4146 si.cb = sizeof(si);
4147 si.lpReserved = NULL;
4148 si.lpDesktop = NULL;
4149 si.lpTitle = NULL;
4150 si.dwFlags = STARTF_USESHOWWINDOW;
4151 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004152 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004153 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004154 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004155 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004156 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004157 else
4158 si.wShowWindow = SW_SHOWNORMAL;
4159 si.cbReserved2 = 0;
4160 si.lpReserved2 = NULL;
4161
Bram Moolenaar0f873732019-12-05 20:28:46 +01004162 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004163 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004164 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4165 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004166
Bram Moolenaar0f873732019-12-05 20:28:46 +01004167 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004168 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004169# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004170 int delay = 1;
4171
Bram Moolenaar0f873732019-12-05 20:28:46 +01004172 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004173 for (;;)
4174 {
4175 MSG msg;
4176
K.Takatab7057bd2022-01-21 11:37:07 +00004177 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004178 {
4179 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004180 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004181 delay = 1;
4182 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004183 }
4184 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4185 break;
4186
Bram Moolenaar0f873732019-12-05 20:28:46 +01004187 // We start waiting for a very short time and then increase it, so
4188 // that we respond quickly when the process is quick, and don't
4189 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004190 if (delay < 50)
4191 delay += 10;
4192 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004193# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004194 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004195# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004196
Bram Moolenaar0f873732019-12-05 20:28:46 +01004197 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004198 GetExitCodeProcess(pi.hProcess, &ret);
4199 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004200
Bram Moolenaar0f873732019-12-05 20:28:46 +01004201 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004202 CloseHandle(pi.hThread);
4203 CloseHandle(pi.hProcess);
4204
Bram Moolenaar0f873732019-12-05 20:28:46 +01004205 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004206 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4207
4208 return ret;
4209}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004210
4211/*
4212 * Thread launched by the gui to send the current buffer data to the
4213 * process. This way avoid to hang up vim totally if the children
4214 * process take a long time to process the lines.
4215 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004216 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004217sub_process_writer(LPVOID param)
4218{
4219 HANDLE g_hChildStd_IN_Wr = param;
4220 linenr_T lnum = curbuf->b_op_start.lnum;
4221 DWORD len = 0;
4222 DWORD l;
4223 char_u *lp = ml_get(lnum);
4224 char_u *s;
4225 int written = 0;
4226
4227 for (;;)
4228 {
4229 l = (DWORD)STRLEN(lp + written);
4230 if (l == 0)
4231 len = 0;
4232 else if (lp[written] == NL)
4233 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004234 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004235 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4236 }
4237 else
4238 {
4239 s = vim_strchr(lp + written, NL);
4240 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4241 s == NULL ? l : (DWORD)(s - (lp + written)),
4242 &len, NULL);
4243 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004244 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004245 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004246 // Finished a line, add a NL, unless this line should not have
4247 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004248 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004249 || (!curbuf->b_p_bin
4250 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004251 || (lnum != curbuf->b_no_eol_lnum
4252 && (lnum != curbuf->b_ml.ml_line_count
4253 || curbuf->b_p_eol)))
4254 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004255 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4256 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004257 }
4258
4259 ++lnum;
4260 if (lnum > curbuf->b_op_end.lnum)
4261 break;
4262
4263 lp = ml_get(lnum);
4264 written = 0;
4265 }
4266 else if (len > 0)
4267 written += len;
4268 }
4269
Bram Moolenaar0f873732019-12-05 20:28:46 +01004270 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004271 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004272 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004273}
4274
4275
Bram Moolenaar0f873732019-12-05 20:28:46 +01004276# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004277
4278/*
4279 * This function read from the children's stdout and write the
4280 * data on screen or in the buffer accordingly.
4281 */
4282 static void
4283dump_pipe(int options,
4284 HANDLE g_hChildStd_OUT_Rd,
4285 garray_T *ga,
4286 char_u buffer[],
4287 DWORD *buffer_off)
4288{
4289 DWORD availableBytes = 0;
4290 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004291 int ret;
4292 DWORD len;
4293 DWORD toRead;
4294 int repeatCount;
4295
Bram Moolenaar0f873732019-12-05 20:28:46 +01004296 // we query the pipe to see if there is any data to read
4297 // to avoid to perform a blocking read
4298 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4299 NULL, // optional buffer
4300 0, // buffer size
4301 NULL, // number of read bytes
4302 &availableBytes, // available bytes total
4303 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004304
4305 repeatCount = 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004306 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004307 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004308 {
4309 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004310 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004311 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004312 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004313
Bram Moolenaar0f873732019-12-05 20:28:46 +01004314 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004315 if (len == 0)
4316 break;
4317
4318 availableBytes -= len;
4319
4320 if (options & SHELL_READ)
4321 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004322 // Do NUL -> NL translation, append NL separated
4323 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004324 for (i = 0; i < len; ++i)
4325 {
4326 if (buffer[i] == NL)
4327 append_ga_line(ga);
4328 else if (buffer[i] == NUL)
4329 ga_append(ga, NL);
4330 else
4331 ga_append(ga, buffer[i]);
4332 }
4333 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004334 else if (has_mbyte)
4335 {
4336 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004337 int c;
4338 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004339
4340 len += *buffer_off;
4341 buffer[len] = NUL;
4342
Bram Moolenaar0f873732019-12-05 20:28:46 +01004343 // Check if the last character in buffer[] is
4344 // incomplete, keep these bytes for the next
4345 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004346 for (p = buffer; p < buffer + len; p += l)
4347 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004348 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004349 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004350 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004351 else if (MB_BYTE2LEN(*p) != l)
4352 break;
4353 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004354 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004355 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004356 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004357 if (len >= 12)
4358 ++p;
4359 else
4360 {
4361 *buffer_off = len;
4362 return;
4363 }
4364 }
4365 c = *p;
4366 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004367 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004368 if (p < buffer + len)
4369 {
4370 *p = c;
4371 *buffer_off = (DWORD)((buffer + len) - p);
4372 mch_memmove(buffer, p, *buffer_off);
4373 return;
4374 }
4375 *buffer_off = 0;
4376 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004377 else
4378 {
4379 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004380 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004381 }
4382
4383 windgoto(msg_row, msg_col);
4384 cursor_on();
4385 out_flush();
4386 }
4387}
4388
4389/*
4390 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4391 * for communication and doesn't open any new window.
4392 */
4393 static int
4394mch_system_piped(char *cmd, int options)
4395{
4396 STARTUPINFO si;
4397 PROCESS_INFORMATION pi;
4398 DWORD ret = 0;
4399
4400 HANDLE g_hChildStd_IN_Rd = NULL;
4401 HANDLE g_hChildStd_IN_Wr = NULL;
4402 HANDLE g_hChildStd_OUT_Rd = NULL;
4403 HANDLE g_hChildStd_OUT_Wr = NULL;
4404
Bram Moolenaar0f873732019-12-05 20:28:46 +01004405 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004406 DWORD len;
4407
Bram Moolenaar0f873732019-12-05 20:28:46 +01004408 // buffer used to receive keys
4409 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4410 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004411
4412 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004413 int noread_cnt = 0;
4414 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004415 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004416 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004417 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004418
4419 SECURITY_ATTRIBUTES saAttr;
4420
Bram Moolenaar0f873732019-12-05 20:28:46 +01004421 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004422 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4423 saAttr.bInheritHandle = TRUE;
4424 saAttr.lpSecurityDescriptor = NULL;
4425
4426 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004427 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004428 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004429 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004430 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004431 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004432 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004433 {
4434 CloseHandle(g_hChildStd_IN_Rd);
4435 CloseHandle(g_hChildStd_IN_Wr);
4436 CloseHandle(g_hChildStd_OUT_Rd);
4437 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004438 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004439 }
4440
4441 si.cb = sizeof(si);
4442 si.lpReserved = NULL;
4443 si.lpDesktop = NULL;
4444 si.lpTitle = NULL;
4445 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4446
Bram Moolenaar0f873732019-12-05 20:28:46 +01004447 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004448 si.hStdError = g_hChildStd_OUT_Wr;
4449 si.hStdOutput = g_hChildStd_OUT_Wr;
4450 si.hStdInput = g_hChildStd_IN_Rd;
4451 si.wShowWindow = SW_HIDE;
4452 si.cbReserved2 = 0;
4453 si.lpReserved2 = NULL;
4454
4455 if (options & SHELL_READ)
4456 ga_init2(&ga, 1, BUFLEN);
4457
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004458 if (cmd != NULL)
4459 {
4460 p = (char *)vim_strsave((char_u *)cmd);
4461 if (p != NULL)
4462 unescape_shellxquote((char_u *)p, p_sxe);
4463 else
4464 p = cmd;
4465 }
4466
Bram Moolenaar0f873732019-12-05 20:28:46 +01004467 // Now, run the command.
4468 // About "Inherit handles" being TRUE: this command can be litigious,
4469 // handle inheritance was deactivated for pending temp file, but, if we
4470 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004471 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4472 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004473
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004474 if (p != cmd)
4475 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004476
Bram Moolenaar0f873732019-12-05 20:28:46 +01004477 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004478 CloseHandle(g_hChildStd_IN_Rd);
4479 CloseHandle(g_hChildStd_OUT_Wr);
4480
4481 if (options & SHELL_WRITE)
4482 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004483 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004484 _beginthreadex(NULL, // security attributes
4485 0, // default stack size
4486 sub_process_writer, // function to be executed
4487 g_hChildStd_IN_Wr, // parameter
4488 0, // creation flag, start immediately
4489 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004490 CloseHandle(thread);
4491 g_hChildStd_IN_Wr = NULL;
4492 }
4493
Bram Moolenaar0f873732019-12-05 20:28:46 +01004494 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004495 for (;;)
4496 {
4497 MSG msg;
4498
K.Takatab7057bd2022-01-21 11:37:07 +00004499 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004500 {
4501 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004502 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004503 }
4504
Bram Moolenaar0f873732019-12-05 20:28:46 +01004505 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004506 if ((options & (SHELL_READ|SHELL_WRITE))
4507# ifdef FEAT_GUI
4508 || gui.in_use
4509# endif
4510 )
4511 {
4512 len = 0;
4513 if (!(options & SHELL_EXPAND)
4514 && ((options &
4515 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4516 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4517# ifdef FEAT_GUI
4518 || gui.in_use
4519# endif
4520 )
4521 && (ta_len > 0 || noread_cnt > 4))
4522 {
4523 if (ta_len == 0)
4524 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004525 // Get extra characters when we don't have any. Reset the
4526 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004527 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004528 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4529 }
4530 if (ta_len > 0 || len > 0)
4531 {
4532 /*
4533 * For pipes: Check for CTRL-C: send interrupt signal to
4534 * child. Check for CTRL-D: EOF, close pipe to child.
4535 */
4536 if (len == 1 && cmd != NULL)
4537 {
4538 if (ta_buf[ta_len] == Ctrl_C)
4539 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004540 // Learn what exit code is expected, for
4541 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004542 TerminateProcess(pi.hProcess, 9);
4543 }
4544 if (ta_buf[ta_len] == Ctrl_D)
4545 {
4546 CloseHandle(g_hChildStd_IN_Wr);
4547 g_hChildStd_IN_Wr = NULL;
4548 }
4549 }
4550
Bram Moolenaarf4140482020-02-15 23:06:45 +01004551 term_replace_bs_del_keycode(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004552
4553 /*
4554 * For pipes: echo the typed characters. For a pty this
4555 * does not seem to work.
4556 */
4557 for (i = ta_len; i < ta_len + len; ++i)
4558 {
4559 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4560 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004561 else if (has_mbyte)
4562 {
4563 int l = (*mb_ptr2len)(ta_buf + i);
4564
4565 msg_outtrans_len(ta_buf + i, l);
4566 i += l - 1;
4567 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004568 else
4569 msg_outtrans_len(ta_buf + i, 1);
4570 }
4571 windgoto(msg_row, msg_col);
4572 out_flush();
4573
4574 ta_len += len;
4575
4576 /*
4577 * Write the characters to the child, unless EOF has been
4578 * typed for pipes. Write one character at a time, to
4579 * avoid losing too much typeahead. When writing buffer
4580 * lines, drop the typed characters (only check for
4581 * CTRL-C).
4582 */
4583 if (options & SHELL_WRITE)
4584 ta_len = 0;
4585 else if (g_hChildStd_IN_Wr != NULL)
4586 {
4587 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4588 1, &len, NULL);
4589 // if we are typing in, we want to keep things reactive
4590 delay = 1;
4591 if (len > 0)
4592 {
4593 ta_len -= len;
4594 mch_memmove(ta_buf, ta_buf + len, ta_len);
4595 }
4596 }
4597 }
4598 }
4599 }
4600
4601 if (ta_len)
4602 ui_inchar_undo(ta_buf, ta_len);
4603
4604 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4605 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004606 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004607 break;
4608 }
4609
4610 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004611 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004612
Bram Moolenaar0f873732019-12-05 20:28:46 +01004613 // We start waiting for a very short time and then increase it, so
4614 // that we respond quickly when the process is quick, and don't
4615 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004616 if (delay < 50)
4617 delay += 10;
4618 }
4619
Bram Moolenaar0f873732019-12-05 20:28:46 +01004620 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004621 CloseHandle(g_hChildStd_OUT_Rd);
4622 if (g_hChildStd_IN_Wr != NULL)
4623 CloseHandle(g_hChildStd_IN_Wr);
4624
4625 WaitForSingleObject(pi.hProcess, INFINITE);
4626
Bram Moolenaar0f873732019-12-05 20:28:46 +01004627 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004628 GetExitCodeProcess(pi.hProcess, &ret);
4629
4630 if (options & SHELL_READ)
4631 {
4632 if (ga.ga_len > 0)
4633 {
4634 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01004635 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004636 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4637 }
4638 else
4639 curbuf->b_no_eol_lnum = 0;
4640 ga_clear(&ga);
4641 }
4642
Bram Moolenaar0f873732019-12-05 20:28:46 +01004643 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004644 CloseHandle(pi.hThread);
4645 CloseHandle(pi.hProcess);
4646
4647 return ret;
4648}
4649
4650 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004651mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004652{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004653 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004654 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004655 return mch_system_piped(cmd, options);
4656 else
4657 return mch_system_classic(cmd, options);
4658}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004659#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004660
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004661#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004662 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02004663mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004664{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004665 int ret;
4666 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004667 char_u *buf;
4668 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004669
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004670 // If the command starts and ends with double quotes, enclose the command
4671 // in parentheses.
4672 len = STRLEN(cmd);
4673 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
4674 {
4675 len += 3;
4676 buf = alloc(len);
4677 if (buf == NULL)
4678 return -1;
4679 vim_snprintf((char *)buf, len, "(%s)", cmd);
4680 wcmd = enc_to_utf16(buf, NULL);
4681 free(buf);
4682 }
4683 else
4684 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4685
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004686 if (wcmd == NULL)
4687 return -1;
4688
4689 ret = _wsystem(wcmd);
4690 vim_free(wcmd);
4691 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004692}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004693
4694#endif
4695
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004696 static int
4697mch_system(char *cmd, int options)
4698{
4699#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004700 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004701 return mch_system_g(cmd, options);
4702 else
4703 return mch_system_c(cmd, options);
4704#elif defined(FEAT_GUI_MSWIN)
4705 return mch_system_g(cmd, options);
4706#else
4707 return mch_system_c(cmd, options);
4708#endif
4709}
4710
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004711#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4712/*
4713 * Use a terminal window to run a shell command in.
4714 */
4715 static int
4716mch_call_shell_terminal(
4717 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004718 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004719{
4720 jobopt_T opt;
4721 char_u *newcmd = NULL;
4722 typval_T argvar[2];
4723 long_u cmdlen;
4724 int retval = -1;
4725 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004726 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004727 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004728 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004729
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004730 if (cmd == NULL)
4731 cmdlen = STRLEN(p_sh) + 1;
4732 else
4733 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004734 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004735 if (newcmd == NULL)
4736 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004737 if (cmd == NULL)
4738 {
4739 STRCPY(newcmd, p_sh);
4740 ch_log(NULL, "starting terminal to run a shell");
4741 }
4742 else
4743 {
4744 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4745 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4746 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004747
4748 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004749
4750 argvar[0].v_type = VAR_STRING;
4751 argvar[0].vval.v_string = newcmd;
4752 argvar[1].v_type = VAR_UNKNOWN;
4753 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004754 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004755 {
4756 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004757 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004758 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004759
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004760 job = term_getjob(buf->b_term);
4761 ++job->jv_refcount;
4762
Bram Moolenaar0f873732019-12-05 20:28:46 +01004763 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004764 aucmd_prepbuf(&aco, buf);
4765
4766 clear_oparg(&oa);
4767 while (term_use_loop())
4768 {
4769 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4770 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004771 // If terminal_loop() returns OK we got a key that is handled
4772 // in Normal model. We don't do redrawing anyway.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004773 if (terminal_loop(TRUE) == OK)
4774 normal_cmd(&oa, TRUE);
4775 }
4776 else
4777 normal_cmd(&oa, TRUE);
4778 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004779 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004780 ch_log(NULL, "system command finished");
4781
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004782 job_unref(job);
4783
Bram Moolenaar0f873732019-12-05 20:28:46 +01004784 // restore curwin/curbuf and a few other things
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004785 aucmd_restbuf(&aco);
4786
4787 wait_return(TRUE);
4788 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4789
4790 vim_free(newcmd);
4791 return retval;
4792}
4793#endif
4794
Bram Moolenaar071d4272004-06-13 20:20:40 +00004795/*
4796 * Either execute a command by calling the shell or start a new shell
4797 */
4798 int
4799mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004800 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004801 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00004802{
4803 int x = 0;
4804 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004805 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004806
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01004807#ifdef FEAT_JOB_CHANNEL
4808 ch_log(NULL, "executing shell command: %s", cmd);
4809#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004810 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02004811 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004812 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004813 if (cmd == NULL)
4814 wcscat(szShellTitle, L" :sh");
4815 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004816 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004817 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004818
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004819 if (wn != NULL)
4820 {
4821 wcscat(szShellTitle, L" - !");
4822 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02004823 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004824 wcscat(szShellTitle, wn);
4825 SetConsoleTitleW(szShellTitle);
4826 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004827 }
4828 }
4829 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004830
4831 out_flush();
4832
4833#ifdef MCH_WRITE_DUMP
4834 if (fdDump)
4835 {
4836 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4837 fflush(fdDump);
4838 }
4839#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004840#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004841 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004842 if (
4843# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004844 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004845# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004846 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004847 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4848 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004849 char_u *cmdbase = cmd;
4850
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004851 if (cmdbase != NULL)
4852 // Skip a leading quote and (.
4853 while (*cmdbase == '"' || *cmdbase == '(')
4854 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004855
4856 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01004857 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
4858 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004859 {
4860 // Use a terminal window to run the command in.
4861 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004862 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004863 return x;
4864 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004865 }
4866#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004867
4868 /*
4869 * Catch all deadly signals while running the external command, because a
4870 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4871 */
4872 signal(SIGINT, SIG_IGN);
4873#if defined(__GNUC__) && !defined(__MINGW32__)
4874 signal(SIGKILL, SIG_IGN);
4875#else
4876 signal(SIGBREAK, SIG_IGN);
4877#endif
4878 signal(SIGILL, SIG_IGN);
4879 signal(SIGFPE, SIG_IGN);
4880 signal(SIGSEGV, SIG_IGN);
4881 signal(SIGTERM, SIG_IGN);
4882 signal(SIGABRT, SIG_IGN);
4883
4884 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004885 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00004886
4887 if (cmd == NULL)
4888 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004889 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004890 }
4891 else
4892 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004893 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004894 char_u *newcmd = NULL;
4895 char_u *cmdbase = cmd;
4896 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004897
Bram Moolenaar0f873732019-12-05 20:28:46 +01004898 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004899 if (*cmdbase == '"' )
4900 ++cmdbase;
4901 if (*cmdbase == '(')
4902 ++cmdbase;
4903
Bram Moolenaar1c465442017-03-12 20:10:05 +01004904 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004905 {
4906 STARTUPINFO si;
4907 PROCESS_INFORMATION pi;
4908 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004909 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004910 char_u *p;
4911
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004912 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004913 si.cb = sizeof(si);
4914 si.lpReserved = NULL;
4915 si.lpDesktop = NULL;
4916 si.lpTitle = NULL;
4917 si.dwFlags = 0;
4918 si.cbReserved2 = 0;
4919 si.lpReserved2 = NULL;
4920
4921 cmdbase = skipwhite(cmdbase + 5);
4922 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004923 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004924 {
4925 cmdbase = skipwhite(cmdbase + 4);
4926 si.dwFlags = STARTF_USESHOWWINDOW;
4927 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004928 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004929 }
4930 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004931 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004932 {
4933 cmdbase = skipwhite(cmdbase + 2);
4934 flags = CREATE_NO_WINDOW;
4935 si.dwFlags = STARTF_USESTDHANDLES;
4936 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004937 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004938 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004939 NULL, // Security att.
4940 OPEN_EXISTING, // Open flags
4941 FILE_ATTRIBUTE_NORMAL, // File att.
4942 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004943 si.hStdOutput = si.hStdInput;
4944 si.hStdError = si.hStdInput;
4945 }
4946
Bram Moolenaar0f873732019-12-05 20:28:46 +01004947 // Remove a trailing ", ) and )" if they have a match
4948 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004949 if (cmdbase > cmd)
4950 {
4951 p = cmdbase + STRLEN(cmdbase);
4952 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4953 *--p = NUL;
4954 if (p > cmdbase && p[-1] == ')'
4955 && (*cmd =='(' || cmd[1] == '('))
4956 *--p = NUL;
4957 }
4958
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004959 newcmd = cmdbase;
4960 unescape_shellxquote(cmdbase, p_sxe);
4961
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004962 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004963 * If creating new console, arguments are passed to the
4964 * 'cmd.exe' as-is. If it's not, arguments are not treated
4965 * correctly for current 'cmd.exe'. So unescape characters in
4966 * shellxescape except '|' for avoiding to be treated as
4967 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004968 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004969 if (flags != CREATE_NEW_CONSOLE)
4970 {
4971 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004972 char_u *cmd_shell = mch_getenv("COMSPEC");
4973
4974 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004975 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004976
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004977 subcmd = vim_strsave_escaped_ext(cmdbase,
4978 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004979 if (subcmd != NULL)
4980 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004981 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004982 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004983 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004984 if (newcmd != NULL)
4985 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004986 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004987 else
4988 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004989 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004990 }
4991 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004992
4993 /*
4994 * Now, start the command as a process, so that it doesn't
4995 * inherit our handles which causes unpleasant dangling swap
4996 * files if we exit before the spawned process
4997 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004998 if (vim_create_process((char *)newcmd, FALSE, flags,
4999 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005000 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005001 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5002 > (HINSTANCE)32)
5003 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005004 else
5005 {
5006 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005007#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005008# ifdef VIMDLL
5009 if (gui.in_use)
5010# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005011 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005012#endif
5013 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005014
5015 if (newcmd != cmdbase)
5016 vim_free(newcmd);
5017
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005018 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005019 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005020 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005021 CloseHandle(si.hStdInput);
5022 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005023 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005024 CloseHandle(pi.hThread);
5025 CloseHandle(pi.hProcess);
5026 }
5027 else
5028 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005029 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005030#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005031 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005032 (!s_dont_use_vimrun && p_stmp ?
5033 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5034 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005035#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005036 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005037
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005038 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005039 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005040 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005041#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005042 if (
5043# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005044 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005045# endif
5046 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005047 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005048 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5049 "External commands will not pause after completion.\n"
5050 "See :help win32-vimrun for more information.");
5051 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005052 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5053 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005054
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005055 if (wmsg != NULL && wtitle != NULL)
5056 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5057 vim_free(wmsg);
5058 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005059 need_vimrun_warning = FALSE;
5060 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005061 if (
5062# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005063 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005064# endif
5065 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005066 // Use vimrun to execute the command. It opens a console
5067 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005068 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005069 vimrun_path,
5070 (msg_silent != 0 || (options & SHELL_DOOUT))
5071 ? "-s " : "",
5072 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005073 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005074# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005075 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005076# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005077 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005078 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005079 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5080 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005081 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005082#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005083 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005084 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005085 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005086 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005087 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005088 }
5089 }
5090
5091 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005092 {
5093 // The shell may have messed with the mode, always set it.
5094 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005095 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005096 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005097
Bram Moolenaar0f873732019-12-05 20:28:46 +01005098 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005099 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005100#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005101 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005102 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005103#endif
5104 )
5105 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005106 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005107 msg_putchar('\n');
5108 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005109 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005110
5111 signal(SIGINT, SIG_DFL);
5112#if defined(__GNUC__) && !defined(__MINGW32__)
5113 signal(SIGKILL, SIG_DFL);
5114#else
5115 signal(SIGBREAK, SIG_DFL);
5116#endif
5117 signal(SIGILL, SIG_DFL);
5118 signal(SIGFPE, SIG_DFL);
5119 signal(SIGSEGV, SIG_DFL);
5120 signal(SIGTERM, SIG_DFL);
5121 signal(SIGABRT, SIG_DFL);
5122
5123 return x;
5124}
5125
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005126#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005127 static HANDLE
5128job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005129 char_u *fname,
5130 DWORD dwDesiredAccess,
5131 DWORD dwShareMode,
5132 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5133 DWORD dwCreationDisposition,
5134 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005135{
5136 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005137 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005138
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005139 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005140 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005141 return INVALID_HANDLE_VALUE;
5142
5143 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5144 lpSecurityAttributes, dwCreationDisposition,
5145 dwFlagsAndAttributes, NULL);
5146 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005147 return h;
5148}
5149
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005150/*
5151 * Turn the dictionary "env" into a NUL separated list that can be used as the
5152 * environment argument of vim_create_process().
5153 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005154 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005155win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005156{
5157 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005158 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005159 LPVOID base = GetEnvironmentStringsW();
5160
Bram Moolenaar0f873732019-12-05 20:28:46 +01005161 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005162 if (ga_grow(gap, 1) == FAIL)
5163 return;
5164
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005165 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005166 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005167 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005168 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005169 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005170 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005171 typval_T *item = &dict_lookup(hi)->di_tv;
5172 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005173 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005174 --todo;
5175 if (wkey != NULL && wval != NULL)
5176 {
5177 size_t n;
5178 size_t lkey = wcslen(wkey);
5179 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005180
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005181 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5182 continue;
5183 for (n = 0; n < lkey; n++)
5184 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5185 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5186 for (n = 0; n < lval; n++)
5187 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5188 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5189 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005190 vim_free(wkey);
5191 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005192 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005193 }
5194 }
5195
Bram Moolenaar355757a2020-02-10 22:06:32 +01005196 if (base)
5197 {
5198 WCHAR *p = (WCHAR*) base;
5199
5200 // for last \0
5201 if (ga_grow(gap, 1) == FAIL)
5202 return;
5203
5204 while (*p != 0 || *(p + 1) != 0)
5205 {
5206 if (ga_grow(gap, 1) == OK)
5207 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5208 p++;
5209 }
5210 FreeEnvironmentStrings(base);
5211 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5212 }
5213
Bram Moolenaar493359e2018-06-12 20:25:52 +02005214# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005215 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005216# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005217 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005218 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005219# endif
5220# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005221 char_u *version = get_vim_var_str(VV_VERSION);
5222 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005223# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005224 // size of "VIM_SERVERNAME=" and value,
5225 // plus "VIM_TERMINAL=" and value,
5226 // plus two terminating NULs
5227 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005228# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005229 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005230# endif
5231# ifdef FEAT_TERMINAL
5232 + 13 + version_len + 2
5233# endif
5234 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005235
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005236 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005237 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005238# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005239 for (n = 0; n < 15; n++)
5240 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5241 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005242 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005243 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5244 (WCHAR)servername[n];
5245 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005246# endif
5247# ifdef FEAT_TERMINAL
5248 if (is_terminal)
5249 {
5250 for (n = 0; n < 13; n++)
5251 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5252 (WCHAR)"VIM_TERMINAL="[n];
5253 for (n = 0; n < version_len; n++)
5254 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5255 (WCHAR)version[n];
5256 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5257 }
5258# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005259 }
5260 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005261# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005262}
5263
Bram Moolenaarb091f302019-01-19 14:37:00 +01005264/*
5265 * Create a pair of pipes.
5266 * Return TRUE for success, FALSE for failure.
5267 */
5268 static BOOL
5269create_pipe_pair(HANDLE handles[2])
5270{
5271 static LONG s;
5272 char name[64];
5273 SECURITY_ATTRIBUTES sa;
5274
5275 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5276 GetCurrentProcessId(),
5277 InterlockedIncrement(&s));
5278
5279 // Create named pipe. Max size of named pipe is 65535.
5280 handles[1] = CreateNamedPipe(
5281 name,
5282 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5283 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005284 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005285
5286 if (handles[1] == INVALID_HANDLE_VALUE)
5287 return FALSE;
5288
5289 sa.nLength = sizeof(sa);
5290 sa.bInheritHandle = TRUE;
5291 sa.lpSecurityDescriptor = NULL;
5292
5293 handles[0] = CreateFile(name,
5294 FILE_GENERIC_READ,
5295 FILE_SHARE_READ, &sa,
5296 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5297
5298 if (handles[0] == INVALID_HANDLE_VALUE)
5299 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005300 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005301 return FALSE;
5302 }
5303
5304 return TRUE;
5305}
5306
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005307 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005308mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005309{
5310 STARTUPINFO si;
5311 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005312 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005313 SECURITY_ATTRIBUTES saAttr;
5314 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005315 HANDLE ifd[2];
5316 HANDLE ofd[2];
5317 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005318 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005319
5320 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5321 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5322 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5323 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5324 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5325 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5326 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5327
5328 if (use_out_for_err && use_null_for_out)
5329 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005330
5331 ifd[0] = INVALID_HANDLE_VALUE;
5332 ifd[1] = INVALID_HANDLE_VALUE;
5333 ofd[0] = INVALID_HANDLE_VALUE;
5334 ofd[1] = INVALID_HANDLE_VALUE;
5335 efd[0] = INVALID_HANDLE_VALUE;
5336 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005337 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005338
Bram Moolenaar14207f42016-10-27 21:13:10 +02005339 jo = CreateJobObject(NULL, NULL);
5340 if (jo == NULL)
5341 {
5342 job->jv_status = JOB_FAILED;
5343 goto failed;
5344 }
5345
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005346 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005347 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005348
Bram Moolenaar76467df2016-02-12 19:30:26 +01005349 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005350 ZeroMemory(&si, sizeof(si));
5351 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005352 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005353 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005354
Bram Moolenaard8070362016-02-15 21:56:54 +01005355 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5356 saAttr.bInheritHandle = TRUE;
5357 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005358
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005359 if (use_file_for_in)
5360 {
5361 char_u *fname = options->jo_io_name[PART_IN];
5362
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005363 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5364 FILE_SHARE_READ | FILE_SHARE_WRITE,
5365 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5366 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005367 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005368 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005369 goto failed;
5370 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005371 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005372 else if (!use_null_for_in
5373 && (!create_pipe_pair(ifd)
5374 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005375 goto failed;
5376
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005377 if (use_file_for_out)
5378 {
5379 char_u *fname = options->jo_io_name[PART_OUT];
5380
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005381 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5382 FILE_SHARE_READ | FILE_SHARE_WRITE,
5383 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5384 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005385 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005386 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005387 goto failed;
5388 }
5389 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005390 else if (!use_null_for_out &&
5391 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005392 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005393 goto failed;
5394
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005395 if (use_file_for_err)
5396 {
5397 char_u *fname = options->jo_io_name[PART_ERR];
5398
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005399 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5400 FILE_SHARE_READ | FILE_SHARE_WRITE,
5401 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5402 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005403 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005404 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005405 goto failed;
5406 }
5407 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005408 else if (!use_out_for_err && !use_null_for_err &&
5409 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005410 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005411 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005412
Bram Moolenaard8070362016-02-15 21:56:54 +01005413 si.dwFlags |= STARTF_USESTDHANDLES;
5414 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005415 si.hStdOutput = ofd[1];
5416 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5417
5418 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5419 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005420 if (options->jo_set & JO_CHANNEL)
5421 {
5422 channel = options->jo_channel;
5423 if (channel != NULL)
5424 ++channel->ch_refcount;
5425 }
5426 else
5427 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005428 if (channel == NULL)
5429 goto failed;
5430 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005431
5432 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005433 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005434 CREATE_DEFAULT_ERROR_MODE |
5435 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005436 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005437 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005438 &si, &pi,
5439 ga.ga_data,
5440 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005441 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005442 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005443 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005444 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005445 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005446
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005447 ga_clear(&ga);
5448
Bram Moolenaar14207f42016-10-27 21:13:10 +02005449 if (!AssignProcessToJobObject(jo, pi.hProcess))
5450 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005451 // if failing, switch the way to terminate
5452 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005453 CloseHandle(jo);
5454 jo = NULL;
5455 }
5456 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005457 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005458 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005459 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005460 job->jv_status = JOB_STARTED;
5461
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005462 CloseHandle(ifd[0]);
5463 CloseHandle(ofd[1]);
5464 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005465 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005466
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005467 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005468 if (channel != NULL)
5469 {
5470 channel_set_pipes(channel,
5471 use_file_for_in || use_null_for_in
5472 ? INVALID_FD : (sock_T)ifd[1],
5473 use_file_for_out || use_null_for_out
5474 ? INVALID_FD : (sock_T)ofd[0],
5475 use_out_for_err || use_file_for_err || use_null_for_err
5476 ? INVALID_FD : (sock_T)efd[0]);
5477 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005478 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005479 return;
5480
5481failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005482 CloseHandle(ifd[0]);
5483 CloseHandle(ofd[0]);
5484 CloseHandle(efd[0]);
5485 CloseHandle(ifd[1]);
5486 CloseHandle(ofd[1]);
5487 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005488 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005489 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005490}
5491
5492 char *
5493mch_job_status(job_T *job)
5494{
5495 DWORD dwExitCode = 0;
5496
Bram Moolenaar76467df2016-02-12 19:30:26 +01005497 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5498 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005499 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005500 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005501 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005502 {
5503 ch_log(job->jv_channel, "Job ended");
5504 job->jv_status = JOB_ENDED;
5505 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005506 return "dead";
5507 }
5508 return "run";
5509}
5510
Bram Moolenaar97792de2016-10-15 18:36:49 +02005511 job_T *
5512mch_detect_ended_job(job_T *job_list)
5513{
5514 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5515 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5516 job_T *job = job_list;
5517
5518 while (job != NULL)
5519 {
5520 DWORD n;
5521 DWORD result;
5522
5523 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5524 && job != NULL; job = job->jv_next)
5525 {
5526 if (job->jv_status == JOB_STARTED)
5527 {
5528 jobHandles[n] = job->jv_proc_info.hProcess;
5529 jobArray[n] = job;
5530 ++n;
5531 }
5532 }
5533 if (n == 0)
5534 continue;
5535 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5536 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5537 {
5538 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5539
5540 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5541 return wait_job;
5542 }
5543 }
5544 return NULL;
5545}
5546
Bram Moolenaarfb630902016-10-29 14:55:00 +02005547 static BOOL
5548terminate_all(HANDLE process, int code)
5549{
5550 PROCESSENTRY32 pe;
5551 HANDLE h = INVALID_HANDLE_VALUE;
5552 DWORD pid = GetProcessId(process);
5553
5554 if (pid != 0)
5555 {
5556 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5557 if (h != INVALID_HANDLE_VALUE)
5558 {
5559 pe.dwSize = sizeof(PROCESSENTRY32);
5560 if (!Process32First(h, &pe))
5561 goto theend;
5562
5563 do
5564 {
5565 if (pe.th32ParentProcessID == pid)
5566 {
5567 HANDLE ph = OpenProcess(
5568 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5569 if (ph != NULL)
5570 {
5571 terminate_all(ph, code);
5572 CloseHandle(ph);
5573 }
5574 }
5575 } while (Process32Next(h, &pe));
5576
5577 CloseHandle(h);
5578 }
5579 }
5580
5581theend:
5582 return TerminateProcess(process, code);
5583}
5584
5585/*
5586 * Send a (deadly) signal to "job".
5587 * Return FAIL if it didn't work.
5588 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005589 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005590mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005591{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005592 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005593
Bram Moolenaar923d9262016-02-25 20:56:01 +01005594 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005595 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005596 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02005597 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005598 {
5599 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5600 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00005601 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005602 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01005603 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005604 }
5605
5606 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5607 return FAIL;
5608 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005609 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5610 job->jv_proc_info.dwProcessId)
5611 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005612 FreeConsole();
5613 return ret;
5614}
5615
5616/*
5617 * Clear the data related to "job".
5618 */
5619 void
5620mch_clear_job(job_T *job)
5621{
5622 if (job->jv_status != JOB_FAILED)
5623 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005624 if (job->jv_job_object != NULL)
5625 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005626 CloseHandle(job->jv_proc_info.hProcess);
5627 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005628}
5629#endif
5630
Bram Moolenaar071d4272004-06-13 20:20:40 +00005631
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005632#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005633
5634/*
5635 * Start termcap mode
5636 */
5637 static void
5638termcap_mode_start(void)
5639{
5640 DWORD cmodein;
5641
5642 if (g_fTermcapMode)
5643 return;
5644
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005645 if (!p_rs && USE_VTP)
5646 vtp_printf("\033[?1049h");
5647
Bram Moolenaar071d4272004-06-13 20:20:40 +00005648 SaveConsoleBuffer(&g_cbNonTermcap);
5649
5650 if (g_cbTermcap.IsValid)
5651 {
5652 /*
5653 * We've been in termcap mode before. Restore certain screen
5654 * characteristics, including the buffer size and the window
5655 * size. Since we will be redrawing the screen, we don't need
5656 * to restore the actual contents of the buffer.
5657 */
5658 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005659 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005660 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5661 Rows = g_cbTermcap.Info.dwSize.Y;
5662 Columns = g_cbTermcap.Info.dwSize.X;
5663 }
5664 else
5665 {
5666 /*
5667 * This is our first time entering termcap mode. Clear the console
5668 * screen buffer, and resize the buffer to match the current window
5669 * size. We will use this as the size of our editing environment.
5670 */
5671 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005672 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005673 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5674 }
5675
Bram Moolenaar071d4272004-06-13 20:20:40 +00005676 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005677
5678 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005679 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005680 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005681 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005682 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
5683 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005684 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005685 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005686 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005687 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5688 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005689 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005690 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005691
5692 redraw_later_clear();
5693 g_fTermcapMode = TRUE;
5694}
5695
5696
5697/*
5698 * End termcap mode
5699 */
5700 static void
5701termcap_mode_end(void)
5702{
5703 DWORD cmodein;
5704 ConsoleBuffer *cb;
5705 COORD coord;
5706 DWORD dwDummy;
5707
5708 if (!g_fTermcapMode)
5709 return;
5710
5711 SaveConsoleBuffer(&g_cbTermcap);
5712
5713 GetConsoleMode(g_hConIn, &cmodein);
5714 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005715 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5716 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005717
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005718# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005719 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005720# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005721 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005722# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005723 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01005724 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005725 SetConsoleCursorInfo(g_hConOut, &g_cci);
5726
5727 if (p_rs || exiting)
5728 {
5729 /*
5730 * Clear anything that happens to be on the current line.
5731 */
5732 coord.X = 0;
5733 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5734 FillConsoleOutputCharacter(g_hConOut, ' ',
5735 cb->Info.dwSize.X, coord, &dwDummy);
5736 /*
5737 * The following is just for aesthetics. If we are exiting without
5738 * restoring the screen, then we want to have a prompt string
5739 * appear at the bottom line. However, the command interpreter
5740 * seems to always advance the cursor one line before displaying
5741 * the prompt string, which causes the screen to scroll. To
5742 * counter this, move the cursor up one line before exiting.
5743 */
5744 if (exiting && !p_rs)
5745 coord.Y--;
5746 /*
5747 * Position the cursor at the leftmost column of the desired row.
5748 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005749 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005750 }
5751
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005752 if (!p_rs && USE_VTP)
Bram Moolenaar0afdcf82020-04-01 18:29:10 +02005753 vtp_printf("\033[?1049l");
5754
Bram Moolenaar071d4272004-06-13 20:20:40 +00005755 g_fTermcapMode = FALSE;
5756}
Bram Moolenaar0f873732019-12-05 20:28:46 +01005757#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005758
5759
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005760#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005761 void
5762mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005763 char_u *s UNUSED,
5764 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005765{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005766 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00005767}
5768
5769#else
5770
5771/*
5772 * clear `n' chars, starting from `coord'
5773 */
5774 static void
5775clear_chars(
5776 COORD coord,
5777 DWORD n)
5778{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005779 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02005780 {
5781 DWORD dwDummy;
5782
5783 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5784 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
5785 &dwDummy);
5786 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005787 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005788 {
5789 set_console_color_rgb();
5790 gotoxy(coord.X + 1, coord.Y + 1);
5791 vtp_printf("\033[%dX", n);
5792 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005793}
5794
5795
5796/*
5797 * Clear the screen
5798 */
5799 static void
5800clear_screen(void)
5801{
5802 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005803
5804 if (!USE_VTP)
5805 clear_chars(g_coord, Rows * Columns);
5806 else
5807 {
5808 set_console_color_rgb();
5809 gotoxy(1, 1);
5810 vtp_printf("\033[2J");
5811 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005812}
5813
5814
5815/*
5816 * Clear to end of display
5817 */
5818 static void
5819clear_to_end_of_display(void)
5820{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005821 COORD save = g_coord;
5822
5823 if (!USE_VTP)
5824 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005825 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005826 else
5827 {
5828 set_console_color_rgb();
5829 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5830 vtp_printf("\033[0J");
5831
5832 gotoxy(save.X + 1, save.Y + 1);
5833 g_coord = save;
5834 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005835}
5836
5837
5838/*
5839 * Clear to end of line
5840 */
5841 static void
5842clear_to_end_of_line(void)
5843{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005844 COORD save = g_coord;
5845
5846 if (!USE_VTP)
5847 clear_chars(g_coord, Columns - g_coord.X);
5848 else
5849 {
5850 set_console_color_rgb();
5851 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5852 vtp_printf("\033[0K");
5853
5854 gotoxy(save.X + 1, save.Y + 1);
5855 g_coord = save;
5856 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005857}
5858
5859
5860/*
5861 * Scroll the scroll region up by `cLines' lines
5862 */
5863 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005864scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005865{
5866 COORD oldcoord = g_coord;
5867
5868 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5869 delete_lines(cLines);
5870
5871 g_coord = oldcoord;
5872}
5873
5874
5875/*
5876 * Set the scroll region
5877 */
5878 static void
5879set_scroll_region(
5880 unsigned left,
5881 unsigned top,
5882 unsigned right,
5883 unsigned bottom)
5884{
5885 if (left >= right
5886 || top >= bottom
5887 || right > (unsigned) Columns - 1
5888 || bottom > (unsigned) Rows - 1)
5889 return;
5890
5891 g_srScrollRegion.Left = left;
5892 g_srScrollRegion.Top = top;
5893 g_srScrollRegion.Right = right;
5894 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005895}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005896
Bram Moolenaar6982f422019-02-16 16:48:01 +01005897 static void
5898set_scroll_region_tb(
5899 unsigned top,
5900 unsigned bottom)
5901{
5902 if (top >= bottom || bottom > (unsigned)Rows - 1)
5903 return;
5904
5905 g_srScrollRegion.Top = top;
5906 g_srScrollRegion.Bottom = bottom;
5907}
5908
5909 static void
5910set_scroll_region_lr(
5911 unsigned left,
5912 unsigned right)
5913{
5914 if (left >= right || right > (unsigned)Columns - 1)
5915 return;
5916
5917 g_srScrollRegion.Left = left;
5918 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005919}
5920
5921
5922/*
5923 * Insert `cLines' lines at the current cursor position
5924 */
5925 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005926insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005927{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005928 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005929 COORD dest;
5930 CHAR_INFO fill;
5931
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005932 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5933
Bram Moolenaar6982f422019-02-16 16:48:01 +01005934 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005935 dest.Y = g_coord.Y + cLines;
5936
Bram Moolenaar6982f422019-02-16 16:48:01 +01005937 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005938 source.Top = g_coord.Y;
5939 source.Right = g_srScrollRegion.Right;
5940 source.Bottom = g_srScrollRegion.Bottom - cLines;
5941
Bram Moolenaar6982f422019-02-16 16:48:01 +01005942 clip.Left = g_srScrollRegion.Left;
5943 clip.Top = g_coord.Y;
5944 clip.Right = g_srScrollRegion.Right;
5945 clip.Bottom = g_srScrollRegion.Bottom;
5946
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005947 fill.Char.AsciiChar = ' ';
5948 if (!USE_VTP)
5949 fill.Attributes = g_attrCurrent;
5950 else
5951 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005952
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005953 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005954
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005955 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5956
Bram Moolenaar6982f422019-02-16 16:48:01 +01005957 // Here we have to deal with a win32 console flake: If the scroll
5958 // region looks like abc and we scroll c to a and fill with d we get
5959 // cbd... if we scroll block c one line at a time to a, we get cdd...
5960 // vim expects cdd consistently... So we have to deal with that
5961 // here... (this also occurs scrolling the same way in the other
5962 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005963
5964 if (source.Bottom < dest.Y)
5965 {
5966 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005967 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005968
Bram Moolenaar6982f422019-02-16 16:48:01 +01005969 coord.X = source.Left;
5970 for (i = clip.Top; i < dest.Y; ++i)
5971 {
5972 coord.Y = i;
5973 clear_chars(coord, source.Right - source.Left + 1);
5974 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005975 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02005976
5977 if (USE_WT)
5978 {
5979 COORD coord;
5980 int i;
5981
5982 coord.X = source.Left;
5983 for (i = source.Top; i < dest.Y; ++i)
5984 {
5985 coord.Y = i;
5986 clear_chars(coord, source.Right - source.Left + 1);
5987 }
5988 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005989}
5990
5991
5992/*
5993 * Delete `cLines' lines at the current cursor position
5994 */
5995 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005996delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005997{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005998 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005999 COORD dest;
6000 CHAR_INFO fill;
6001 int nb;
6002
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006003 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6004
Bram Moolenaar6982f422019-02-16 16:48:01 +01006005 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006006 dest.Y = g_coord.Y;
6007
Bram Moolenaar6982f422019-02-16 16:48:01 +01006008 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006009 source.Top = g_coord.Y + cLines;
6010 source.Right = g_srScrollRegion.Right;
6011 source.Bottom = g_srScrollRegion.Bottom;
6012
Bram Moolenaar6982f422019-02-16 16:48:01 +01006013 clip.Left = g_srScrollRegion.Left;
6014 clip.Top = g_coord.Y;
6015 clip.Right = g_srScrollRegion.Right;
6016 clip.Bottom = g_srScrollRegion.Bottom;
6017
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006018 fill.Char.AsciiChar = ' ';
6019 if (!USE_VTP)
6020 fill.Attributes = g_attrCurrent;
6021 else
6022 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006023
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006024 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006025
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006026 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6027
Bram Moolenaar6982f422019-02-16 16:48:01 +01006028 // Here we have to deal with a win32 console flake; See insert_lines()
6029 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006030
6031 nb = dest.Y + (source.Bottom - source.Top) + 1;
6032
6033 if (nb < source.Top)
6034 {
6035 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006036 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006037
Bram Moolenaar6982f422019-02-16 16:48:01 +01006038 coord.X = source.Left;
6039 for (i = nb; i < clip.Bottom; ++i)
6040 {
6041 coord.Y = i;
6042 clear_chars(coord, source.Right - source.Left + 1);
6043 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006044 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006045
6046 if (USE_WT)
6047 {
6048 COORD coord;
6049 int i;
6050
6051 coord.X = source.Left;
6052 for (i = nb; i <= source.Bottom; ++i)
6053 {
6054 coord.Y = i;
6055 clear_chars(coord, source.Right - source.Left + 1);
6056 }
6057 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006058}
6059
6060
6061/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006062 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006063 */
6064 static void
6065gotoxy(
6066 unsigned x,
6067 unsigned y)
6068{
6069 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6070 return;
6071
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006072 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006073 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006074 // There are reports of double-width characters not displayed
6075 // correctly. This workaround should fix it, similar to how it's done
6076 // for VTP.
6077 g_coord.X = 0;
6078 SetConsoleCursorPosition(g_hConOut, g_coord);
6079
Bram Moolenaar2313b612019-09-27 14:14:32 +02006080 // external cursor coords are 1-based; internal are 0-based
6081 g_coord.X = x - 1;
6082 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006083 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006084 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006085 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006086 {
6087 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006088 // destruction. Insider build bug. Always enabled because it's cheap
6089 // and avoids mistakes with recognizing the build.
6090 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006091
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006092 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006093
6094 g_coord.X = x - 1;
6095 g_coord.Y = y - 1;
6096 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006097}
6098
6099
6100/*
6101 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006102 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006103 */
6104 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006105textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006106{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006107 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006108
6109 SetConsoleTextAttribute(g_hConOut, wAttr);
6110}
6111
6112
6113 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006114textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006115{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006116 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006117
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006118 if (!USE_VTP)
6119 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6120 else
6121 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006122}
6123
6124
6125 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006126textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006127{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006128 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006129
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006130 if (!USE_VTP)
6131 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6132 else
6133 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006134}
6135
6136
6137/*
6138 * restore the default text attribute (whatever we started with)
6139 */
6140 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006141normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006142{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006143 if (!USE_VTP)
6144 textattr(g_attrDefault);
6145 else
6146 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006147}
6148
6149
6150static WORD g_attrPreStandout = 0;
6151
6152/*
6153 * Make the text standout, by brightening it
6154 */
6155 static void
6156standout(void)
6157{
6158 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006159
Bram Moolenaar071d4272004-06-13 20:20:40 +00006160 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6161}
6162
6163
6164/*
6165 * Turn off standout mode
6166 */
6167 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006168standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006169{
6170 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006171 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006172
6173 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006174}
6175
6176
6177/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006178 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006179 */
6180 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006181mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006182{
6183 char_u *p;
6184 int n;
6185
6186 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6187 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006188 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006189# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006190 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006191# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006192 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006193 {
6194 p = T_ME + 2;
6195 n = getdigits(&p);
6196 if (*p == 'm' && n > 0)
6197 {
6198 cterm_normal_fg_color = (n & 0xf) + 1;
6199 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6200 }
6201 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006202# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006203 cterm_normal_fg_gui_color = INVALCOLOR;
6204 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006205# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006206}
6207
6208
6209/*
6210 * visual bell: flash the screen
6211 */
6212 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006213visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006214{
6215 COORD coordOrigin = {0, 0};
6216 WORD attrFlash = ~g_attrCurrent & 0xff;
6217
6218 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006219 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006220
6221 if (oldattrs == NULL)
6222 return;
6223 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6224 coordOrigin, &dwDummy);
6225 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6226 coordOrigin, &dwDummy);
6227
Bram Moolenaar0f873732019-12-05 20:28:46 +01006228 Sleep(15); // wait for 15 msec
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006229 if (!USE_VTP)
6230 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006231 coordOrigin, &dwDummy);
6232 vim_free(oldattrs);
6233}
6234
6235
6236/*
6237 * Make the cursor visible or invisible
6238 */
6239 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006240cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006241{
6242 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006243
6244 if (USE_VTP)
6245 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6246
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006247# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006248 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006249# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006250}
6251
6252
6253/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006254 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006255 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006256 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006257 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006258write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006259 char_u *pchBuf,
6260 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006261{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006262 COORD coord = g_coord;
6263 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006264 DWORD n, cchwritten;
6265 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006266 static WCHAR *unicodebuf = NULL;
6267 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006268 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006269 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006270 static WCHAR *utf8spbuf = NULL;
6271 static int utf8splength;
6272 static DWORD utf8spcells;
6273 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006274
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006275 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006276 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006277 utf8usingbuf = &unicodebuf;
6278 do
6279 {
6280 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6281 unicodebuf, unibuflen);
6282 if (length && length <= unibuflen)
6283 break;
6284 vim_free(unicodebuf);
6285 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6286 unibuflen = unibuflen ? 0 : length;
6287 } while(1);
6288 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006289 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006290 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6291 {
6292 if (utf8usingbuf != &utf8spbuf)
6293 {
6294 if (utf8spbuf == NULL)
6295 {
6296 cells = mb_string2cells((char_u *)" ", 1);
6297 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6298 utf8spbuf = LALLOC_MULT(WCHAR, length);
6299 if (utf8spbuf != NULL)
6300 {
6301 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6302 utf8usingbuf = &utf8spbuf;
6303 utf8splength = length;
6304 utf8spcells = cells;
6305 }
6306 }
6307 else
6308 {
6309 utf8usingbuf = &utf8spbuf;
6310 length = utf8splength;
6311 cells = utf8spcells;
6312 }
6313 }
6314 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006315
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006316 if (!USE_VTP)
6317 {
6318 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6319 coord, &written);
6320 // When writing fails or didn't write a single character, pretend one
6321 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006322 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006323 coord, &cchwritten) == 0
6324 || cchwritten == 0 || cchwritten == (DWORD)-1)
6325 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006326 }
6327 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006328 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006329 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006330 NULL) == 0 || cchwritten == 0)
6331 cchwritten = 1;
6332 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006333
K.Takata135e1522022-01-29 15:27:58 +00006334 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006335 {
6336 written = cbToWrite;
6337 g_coord.X += (SHORT)cells;
6338 }
6339 else
6340 {
6341 char_u *p = pchBuf;
6342 for (n = 0; n < cchwritten; n++)
6343 MB_CPTR_ADV(p);
6344 written = p - pchBuf;
6345 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006346 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006347
6348 while (g_coord.X > g_srScrollRegion.Right)
6349 {
6350 g_coord.X -= (SHORT) Columns;
6351 if (g_coord.Y < g_srScrollRegion.Bottom)
6352 g_coord.Y++;
6353 }
6354
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006355 // Cursor under VTP is always in the correct position, no need to reset.
6356 if (!USE_VTP)
6357 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006358
6359 return written;
6360}
6361
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006362 static char_u *
6363get_seq(
6364 int *args,
6365 int *count,
6366 char_u *head)
6367{
6368 int argc;
6369 char_u *p;
6370
6371 if (head == NULL || *head != '\033')
6372 return NULL;
6373
6374 argc = 0;
6375 p = head;
6376 ++p;
6377 do
6378 {
6379 ++p;
6380 args[argc] = getdigits(&p);
6381 argc += (argc < 15) ? 1 : 0;
6382 } while (*p == ';');
6383 *count = argc;
6384
6385 return p;
6386}
6387
6388 static char_u *
6389get_sgr(
6390 int *args,
6391 int *count,
6392 char_u *head)
6393{
6394 char_u *p = get_seq(args, count, head);
6395
6396 return (p && *p == 'm') ? ++p : NULL;
6397}
6398
6399/*
6400 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6401 */
6402 static char_u *
6403sgrn2(
6404 char_u *head,
6405 int n)
6406{
6407 int argc;
6408 int args[16];
6409 char_u *p = get_sgr(args, &argc, head);
6410
6411 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6412}
6413
6414/*
6415 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6416 */
6417 static char_u *
6418sgrnc(
6419 char_u *head,
6420 int n)
6421{
6422 int argc;
6423 int args[16];
6424 char_u *p = get_sgr(args, &argc, head);
6425
6426 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6427 ? p : NULL;
6428}
6429
6430 static char_u *
6431skipblank(char_u *q)
6432{
6433 char_u *p = q;
6434
6435 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6436 ++p;
6437 return p;
6438}
6439
6440/*
6441 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6442 * NULL.
6443 */
6444 static char_u *
6445sgrn2c(
6446 char_u *head,
6447 int n)
6448{
6449 char_u *p = sgrn2(head, n);
6450
6451 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6452}
6453
6454/*
6455 * If there is only a newline between the sequence immediately following it,
6456 * a pointer to the character following the newline is returned.
6457 * Otherwise NULL.
6458 */
6459 static char_u *
6460sgrn2cn(
6461 char_u *head,
6462 int n)
6463{
6464 char_u *p = sgrn2(head, n);
6465
6466 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6467}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006468
6469/*
6470 * mch_write(): write the output buffer to the screen, translating ESC
6471 * sequences into calls to console output routines.
6472 */
6473 void
6474mch_write(
6475 char_u *s,
6476 int len)
6477{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006478 char_u *end = s + len;
6479
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006480# ifdef VIMDLL
6481 if (gui.in_use)
6482 return;
6483# endif
6484
Bram Moolenaar071d4272004-06-13 20:20:40 +00006485 if (!term_console)
6486 {
6487 write(1, s, (unsigned)len);
6488 return;
6489 }
6490
Bram Moolenaar0f873732019-12-05 20:28:46 +01006491 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00006492 while (len--)
6493 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006494 int prefix = -1;
6495 char_u ch;
6496
6497 // While processing a sequence, on rare occasions it seems that another
6498 // sequence may be inserted asynchronously.
6499 if (len < 0)
6500 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006501 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006502 return;
6503 }
6504
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006505 while (s + ++prefix < end)
6506 {
6507 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006508 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6509 && ch != '\a' && ch != '\033'))
6510 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006511 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006512
6513 if (p_wd)
6514 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006515 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006516 if (prefix != 0)
6517 prefix = 1;
6518 }
6519
6520 if (prefix != 0)
6521 {
6522 DWORD nWritten;
6523
6524 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006525# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006526 if (fdDump)
6527 {
6528 fputc('>', fdDump);
6529 fwrite(s, sizeof(char_u), nWritten, fdDump);
6530 fputs("<\n", fdDump);
6531 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006532# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006533 len -= (nWritten - 1);
6534 s += nWritten;
6535 }
6536 else if (s[0] == '\n')
6537 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006538 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00006539 if (g_coord.Y == g_srScrollRegion.Bottom)
6540 {
6541 scroll(1);
6542 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6543 }
6544 else
6545 {
6546 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6547 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006548# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006549 if (fdDump)
6550 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006551# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006552 s++;
6553 }
6554 else if (s[0] == '\r')
6555 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006556 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00006557 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006558# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006559 if (fdDump)
6560 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006561# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006562 s++;
6563 }
6564 else if (s[0] == '\b')
6565 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006566 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00006567 if (g_coord.X > g_srScrollRegion.Left)
6568 g_coord.X--;
6569 else if (g_coord.Y > g_srScrollRegion.Top)
6570 {
6571 g_coord.X = g_srScrollRegion.Right;
6572 g_coord.Y--;
6573 }
6574 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006575# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006576 if (fdDump)
6577 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006578# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006579 s++;
6580 }
6581 else if (s[0] == '\a')
6582 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006583 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00006584 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006585# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006586 if (fdDump)
6587 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006588# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006589 s++;
6590 }
6591 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6592 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006593# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006594 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006595# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006596 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006597 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006598 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006599
6600 switch (s[2])
6601 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006602 case '0': case '1': case '2': case '3': case '4':
6603 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006604 if (*(p = get_seq(args, &argc, s)) != 'm')
6605 goto notsgr;
6606
6607 p = s;
6608
6609 // Handling frequent optional sequences. Output to the screen
6610 // takes too long, so do not output as much as possible.
6611
6612 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
6613 // resetFG,FG,BG are omitted.
6614 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006615 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006616 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
6617 len = len + 1 - (int)(p - s);
6618 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006619 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006620 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006621
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006622 // If FG,BG,BG,FG of SGR are connected, the first FG can be
6623 // omitted.
6624 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
6625 p = sp;
6626
6627 // If FG,BG,FG,BG of SGR are connected, the first FG can be
6628 // omitted.
6629 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
6630 p = sp;
6631
6632 // If BG,BG of SGR are connected, the first BG can be omitted.
6633 if (sgrn2((sp = sgrn2(p, 48)), 48))
6634 p = sp;
6635
6636 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01006637 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006638 if (sgrn2((sp = sgrnc(p, 39)), 38))
6639 p = sp;
6640
6641 p = get_seq(args, &argc, p);
6642
6643notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006644 arg1 = args[0];
6645 arg2 = args[1];
6646 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006647 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006648 if (argc == 1 && args[0] == 0)
6649 normvideo();
6650 else if (argc == 1)
6651 {
6652 if (USE_VTP)
6653 textcolor((WORD) arg1);
6654 else
6655 textattr((WORD) arg1);
6656 }
6657 else if (USE_VTP)
6658 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006659 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006660 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006661 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006662 gotoxy(arg2, arg1);
6663 }
6664 else if (argc == 2 && *p == 'r')
6665 {
6666 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6667 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006668 else if (argc == 2 && *p == 'R')
6669 {
6670 set_scroll_region_tb(arg1, arg2);
6671 }
6672 else if (argc == 2 && *p == 'V')
6673 {
6674 set_scroll_region_lr(arg1, arg2);
6675 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006676 else if (argc == 1 && *p == 'A')
6677 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006678 gotoxy(g_coord.X + 1,
6679 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6680 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006681 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006682 {
6683 textbackground((WORD) arg1);
6684 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006685 else if (argc == 1 && *p == 'C')
6686 {
6687 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6688 g_coord.Y + 1);
6689 }
6690 else if (argc == 1 && *p == 'f')
6691 {
6692 textcolor((WORD) arg1);
6693 }
6694 else if (argc == 1 && *p == 'H')
6695 {
6696 gotoxy(1, arg1);
6697 }
6698 else if (argc == 1 && *p == 'L')
6699 {
6700 insert_lines(arg1);
6701 }
6702 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006703 {
6704 delete_lines(arg1);
6705 }
6706
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006707 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006708 s = p + 1;
6709 break;
6710
Bram Moolenaar071d4272004-06-13 20:20:40 +00006711 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006712 gotoxy(g_coord.X + 1,
6713 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6714 goto got3;
6715
6716 case 'B':
6717 visual_bell();
6718 goto got3;
6719
6720 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006721 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6722 g_coord.Y + 1);
6723 goto got3;
6724
6725 case 'E':
6726 termcap_mode_end();
6727 goto got3;
6728
6729 case 'F':
6730 standout();
6731 goto got3;
6732
6733 case 'f':
6734 standend();
6735 goto got3;
6736
6737 case 'H':
6738 gotoxy(1, 1);
6739 goto got3;
6740
6741 case 'j':
6742 clear_to_end_of_display();
6743 goto got3;
6744
6745 case 'J':
6746 clear_screen();
6747 goto got3;
6748
6749 case 'K':
6750 clear_to_end_of_line();
6751 goto got3;
6752
6753 case 'L':
6754 insert_lines(1);
6755 goto got3;
6756
6757 case 'M':
6758 delete_lines(1);
6759 goto got3;
6760
6761 case 'S':
6762 termcap_mode_start();
6763 goto got3;
6764
6765 case 'V':
6766 cursor_visible(TRUE);
6767 goto got3;
6768
6769 case 'v':
6770 cursor_visible(FALSE);
6771 goto got3;
6772
6773 got3:
6774 s += 3;
6775 len -= 2;
6776 }
6777
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006778# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006779 if (fdDump)
6780 {
6781 fputs("ESC | ", fdDump);
6782 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6783 fputc('\n', fdDump);
6784 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006785# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006786 }
K.Takatadf5320c2022-09-01 13:20:16 +01006787 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
6788 {
6789 int l = 2;
6790
6791 if (isdigit(s[l]))
6792 l++;
6793 if (s[l] == ' ' && s[l + 1] == 'q')
6794 {
6795 // DECSCUSR (cursor style) sequences
6796 if (USE_VTP || USE_WT)
6797 vtp_printf("%.*s", l + 2, s); // Pass through
6798 s += l + 2;
6799 len -= l + 1;
6800 }
6801 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006802 else
6803 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006804 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00006805 DWORD nWritten;
6806
6807 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006808# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006809 if (fdDump)
6810 {
6811 fputc('>', fdDump);
6812 fwrite(s, sizeof(char_u), nWritten, fdDump);
6813 fputs("<\n", fdDump);
6814 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006815# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006816
6817 len -= (nWritten - 1);
6818 s += nWritten;
6819 }
6820 }
6821
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006822# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006823 if (fdDump)
6824 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006825# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006826}
6827
Bram Moolenaar0f873732019-12-05 20:28:46 +01006828#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006829
6830
6831/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006832 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006833 */
6834 void
6835mch_delay(
6836 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02006837 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006838{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006839#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006840 Sleep((int)msec); // never wait for input
6841#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006842# ifdef VIMDLL
6843 if (gui.in_use)
6844 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006845 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006846 return;
6847 }
6848# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02006849 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006850# ifdef FEAT_MZSCHEME
6851 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6852 {
6853 int towait = p_mzq;
6854
Bram Moolenaar0f873732019-12-05 20:28:46 +01006855 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006856 while (msec > 0)
6857 {
6858 mzvim_check_threads();
6859 if (msec < towait)
6860 towait = msec;
6861 Sleep(towait);
6862 msec -= towait;
6863 }
6864 }
6865 else
6866# endif
6867 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006868 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006869 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006870#endif
6871}
6872
6873
6874/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006875 * This version of remove is not scared by a readonly (backup) file.
6876 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006877 * Return 0 for success, -1 for failure.
6878 */
6879 int
6880mch_remove(char_u *name)
6881{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006882 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006883 int n;
6884
Bram Moolenaar203258c2016-01-17 22:15:16 +01006885 /*
6886 * On Windows, deleting a directory's symbolic link is done by
6887 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6888 */
6889 if (mch_isdir(name) && mch_is_symbolic_link(name))
6890 return mch_rmdir(name);
6891
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006892 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6893
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006894 wn = enc_to_utf16(name, NULL);
6895 if (wn == NULL)
6896 return -1;
6897
6898 n = DeleteFileW(wn) ? 0 : -1;
6899 vim_free(wn);
6900 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006901}
6902
6903
6904/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006905 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006906 */
6907 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006908mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006909{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006910#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
6911# ifdef VIMDLL
6912 if (!gui.in_use)
6913# endif
6914 if (g_fCtrlCPressed || g_fCBrkPressed)
6915 {
6916 ctrl_break_was_pressed = g_fCBrkPressed;
6917 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6918 got_int = TRUE;
6919 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006920#endif
6921}
6922
Bram Moolenaar0f873732019-12-05 20:28:46 +01006923// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01006924#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006925
6926/*
6927 * How much main memory in KiB that can be used by VIM.
6928 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006929 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006930mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006931{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006932 MEMORYSTATUSEX ms;
6933
Bram Moolenaar0f873732019-12-05 20:28:46 +01006934 // Need to use GlobalMemoryStatusEx() when there is more memory than
6935 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006936 ms.dwLength = sizeof(MEMORYSTATUSEX);
6937 GlobalMemoryStatusEx(&ms);
6938 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006939 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006940 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006941 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006942 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006943 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006944 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006945 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006946 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006947 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01006948 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006949 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006950}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006951
Bram Moolenaar071d4272004-06-13 20:20:40 +00006952/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006953 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00006954 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6955 * file whose short file name is "FOO.BAR" (its long file name will
6956 * be correct: "foo.bar~"). Because a file can be accessed by
6957 * either its SFN or its LFN, "foo.bar" has effectively been
6958 * renamed to "foo.bar", which is not at all what was wanted. This
6959 * seems to happen only when renaming files with three-character
6960 * extensions by appending a suffix that does not include ".".
6961 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6962 *
6963 * There is another problem, which isn't really a bug but isn't right either:
6964 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6965 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6966 * service pack 6. Doesn't seem to happen on Windows 98.
6967 *
6968 * Like rename(), returns 0 upon success, non-zero upon failure.
6969 * Should probably set errno appropriately when errors occur.
6970 */
6971 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006972mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006973{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006974 WCHAR *p;
6975 int i;
6976 WCHAR szTempFile[_MAX_PATH + 1];
6977 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006978 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006979
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006980 // No need to play tricks unless the file name contains a "~" as the
6981 // seventh character.
6982 p = wold;
6983 for (i = 0; wold[i] != NUL; ++i)
6984 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6985 && wold[i + 1] != 0)
6986 p = wold + i + 1;
6987 if ((int)(wold + i - p) < 8 || p[6] != '~')
6988 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006989
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006990 // Get base path of new file name. Undocumented feature: If pszNewFile is
6991 // a directory, no error is returned and pszFilePart will be NULL.
6992 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006993 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006994 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006995
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006996 // Get (and create) a unique temporary file name in directory of new file
6997 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006998 return -2;
6999
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007000 // blow the temp file away
7001 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007002 return -3;
7003
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007004 // rename old file to the temp file
7005 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007006 return -4;
7007
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007008 // now create an empty file called pszOldFile; this prevents the operating
7009 // system using pszOldFile as an alias (SFN) if we're renaming within the
7010 // same directory. For example, we're editing a file called
7011 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7012 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7013 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7014 // cause all sorts of problems later in buf_write(). So, we create an
7015 // empty file called filena~1.txt and the system will have to find some
7016 // other SFN for filena~1.txt~, such as filena~2.txt
7017 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007018 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7019 return -5;
7020 if (!CloseHandle(hf))
7021 return -6;
7022
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007023 // rename the temp file to the new file
7024 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007025 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007026 // Renaming failed. Rename the file back to its old name, so that it
7027 // looks like nothing happened.
7028 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007029 return -7;
7030 }
7031
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007032 // Seems to be left around on Novell filesystems
7033 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007034
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007035 // finally, remove the empty old file
7036 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007037 return -8;
7038
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007039 return 0;
7040}
7041
7042
7043/*
7044 * Converts the filenames to UTF-16, then call mch_wrename().
7045 * Like rename(), returns 0 upon success, non-zero upon failure.
7046 */
7047 int
7048mch_rename(
7049 const char *pszOldFile,
7050 const char *pszNewFile)
7051{
7052 WCHAR *wold = NULL;
7053 WCHAR *wnew = NULL;
7054 int retval = -1;
7055
7056 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7057 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7058 if (wold != NULL && wnew != NULL)
7059 retval = mch_wrename(wold, wnew);
7060 vim_free(wold);
7061 vim_free(wnew);
7062 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007063}
7064
7065/*
7066 * Get the default shell for the current hardware platform
7067 */
7068 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007069default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007070{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007071 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007072}
7073
7074/*
7075 * mch_access() extends access() to do more detailed check on network drives.
7076 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7077 */
7078 int
7079mch_access(char *n, int p)
7080{
7081 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007082 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007083 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007084
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007085 wn = enc_to_utf16((char_u *)n, NULL);
7086 if (wn == NULL)
7087 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007088
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007089 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007090 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007091 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007092
7093 if (p & R_OK)
7094 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007095 // Read check is performed by seeing if we can do a find file on
7096 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007097 int i;
7098 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007099
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007100 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7101 TempNameW[i] = wn[i];
7102 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7103 TempNameW[i++] = '\\';
7104 TempNameW[i++] = '*';
7105 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007106
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007107 hFile = FindFirstFileW(TempNameW, &d);
7108 if (hFile == INVALID_HANDLE_VALUE)
7109 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007110 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007111 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007112 }
7113
7114 if (p & W_OK)
7115 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007116 // Trying to create a temporary file in the directory should catch
7117 // directories on read-only network shares. However, in
7118 // directories whose ACL allows writes but denies deletes will end
7119 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007120 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7121 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007122 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007123 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007124 }
7125 }
7126 else
7127 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007128 // Don't consider a file read-only if another process has opened it.
7129 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7130
Bram Moolenaar0f873732019-12-05 20:28:46 +01007131 // Trying to open the file for the required access does ACL, read-only
7132 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007133 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7134 | ((p & R_OK) ? GENERIC_READ : 0);
7135
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007136 hFile = CreateFileW(wn, access_mode, share_mode,
7137 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007138 if (hFile == INVALID_HANDLE_VALUE)
7139 goto getout;
7140 CloseHandle(hFile);
7141 }
7142
Bram Moolenaar0f873732019-12-05 20:28:46 +01007143 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007144getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007145 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007146 return retval;
7147}
7148
Bram Moolenaar071d4272004-06-13 20:20:40 +00007149/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007150 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007151 */
7152 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007153mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007154{
7155 WCHAR *wn;
7156 int f;
7157
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007158 wn = enc_to_utf16((char_u *)name, NULL);
7159 if (wn == NULL)
7160 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007161
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007162 f = _wopen(wn, flags, mode);
7163 vim_free(wn);
7164 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007165}
7166
7167/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007168 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007169 */
7170 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007171mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007172{
7173 WCHAR *wn, *wm;
7174 FILE *f = NULL;
7175
Bram Moolenaara12a1612019-01-24 16:39:02 +01007176#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007177 // Work around an annoying assertion in the Microsoft debug CRT
7178 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007179 char newMode = mode[strlen(mode) - 1];
7180 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007181
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007182 _get_fmode(&oldMode);
7183 if (newMode == 't')
7184 _set_fmode(_O_TEXT);
7185 else if (newMode == 'b')
7186 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007187#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007188 wn = enc_to_utf16((char_u *)name, NULL);
7189 wm = enc_to_utf16((char_u *)mode, NULL);
7190 if (wn != NULL && wm != NULL)
7191 f = _wfopen(wn, wm);
7192 vim_free(wn);
7193 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007194
Bram Moolenaara12a1612019-01-24 16:39:02 +01007195#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007196 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007197#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007198 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007199}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007200
Bram Moolenaar071d4272004-06-13 20:20:40 +00007201/*
7202 * SUB STREAM (aka info stream) handling:
7203 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007204 * NTFS can have sub streams for each file. The normal contents of a file is
7205 * stored in the main stream, and extra contents (author information, title and
7206 * so on) can be stored in a sub stream. After Windows 2000, the user can
7207 * access and store this information in sub streams via an explorer's property
7208 * menu item in the right click menu. This information in sub streams was lost
7209 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007210 *
7211 * Incomplete explanation:
7212 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7213 * More useful info and an example:
7214 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7215 */
7216
7217/*
7218 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7219 * and write to stream "substream" of file "to".
7220 * Errors are ignored.
7221 */
7222 static void
7223copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7224{
7225 HANDLE hTo;
7226 WCHAR *to_name;
7227
7228 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7229 wcscpy(to_name, to);
7230 wcscat(to_name, substream);
7231
7232 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7233 FILE_ATTRIBUTE_NORMAL, NULL);
7234 if (hTo != INVALID_HANDLE_VALUE)
7235 {
7236 long done;
7237 DWORD todo;
7238 DWORD readcnt, written;
7239 char buf[4096];
7240
Bram Moolenaar0f873732019-12-05 20:28:46 +01007241 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007242 for (done = 0; done < len; done += written)
7243 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007244 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007245 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7246 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007247 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7248 FALSE, FALSE, context)
7249 || readcnt != todo
7250 || !WriteFile(hTo, buf, todo, &written, NULL)
7251 || written != todo)
7252 break;
7253 }
7254 CloseHandle(hTo);
7255 }
7256
7257 free(to_name);
7258}
7259
7260/*
7261 * Copy info streams from file "from" to file "to".
7262 */
7263 static void
7264copy_infostreams(char_u *from, char_u *to)
7265{
7266 WCHAR *fromw;
7267 WCHAR *tow;
7268 HANDLE sh;
7269 WIN32_STREAM_ID sid;
7270 int headersize;
7271 WCHAR streamname[_MAX_PATH];
7272 DWORD readcount;
7273 void *context = NULL;
7274 DWORD lo, hi;
7275 int len;
7276
Bram Moolenaar0f873732019-12-05 20:28:46 +01007277 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007278 fromw = enc_to_utf16(from, NULL);
7279 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007280 if (fromw != NULL && tow != NULL)
7281 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007282 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007283 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7284 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7285 if (sh != INVALID_HANDLE_VALUE)
7286 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007287 // Use BackupRead() to find the info streams. Repeat until we
7288 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007289 for (;;)
7290 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007291 // Get the header to find the length of the stream name. If
7292 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007293 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007294 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007295 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7296 &readcount, FALSE, FALSE, &context)
7297 || readcount == 0)
7298 break;
7299
Bram Moolenaar0f873732019-12-05 20:28:46 +01007300 // We only deal with streams that have a name. The normal
7301 // file data appears to be without a name, even though docs
7302 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007303 if (sid.dwStreamNameSize > 0)
7304 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007305 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007306 if (!BackupRead(sh, (LPBYTE)streamname,
7307 sid.dwStreamNameSize,
7308 &readcount, FALSE, FALSE, &context))
7309 break;
7310
Bram Moolenaar0f873732019-12-05 20:28:46 +01007311 // Copy an info stream with a name ":anything:$DATA".
7312 // Skip "::$DATA", it has no stream name (examples suggest
7313 // it might be used for the normal file contents).
7314 // Note that BackupRead() counts bytes, but the name is in
7315 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007316 len = readcount / sizeof(WCHAR);
7317 streamname[len] = 0;
7318 if (len > 7 && wcsicmp(streamname + len - 6,
7319 L":$DATA") == 0)
7320 {
7321 streamname[len - 6] = 0;
7322 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007323 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007324 }
7325 }
7326
Bram Moolenaar0f873732019-12-05 20:28:46 +01007327 // Advance to the next stream. We might try seeking too far,
7328 // but BackupSeek() doesn't skip over stream borders, thus
7329 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007330 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007331 &lo, &hi, &context);
7332 }
7333
Bram Moolenaar0f873732019-12-05 20:28:46 +01007334 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007335 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7336
7337 CloseHandle(sh);
7338 }
7339 }
7340 vim_free(fromw);
7341 vim_free(tow);
7342}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007343
7344/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007345 * ntdll.dll definitions
7346 */
7347#define FileEaInformation 7
7348#ifndef STATUS_SUCCESS
7349# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7350#endif
7351
7352typedef struct _FILE_FULL_EA_INFORMATION_ {
7353 ULONG NextEntryOffset;
7354 UCHAR Flags;
7355 UCHAR EaNameLength;
7356 USHORT EaValueLength;
7357 CHAR EaName[1];
7358} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7359
7360typedef struct _FILE_EA_INFORMATION_ {
7361 ULONG EaSize;
7362} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7363
Paul Ollis65745772022-06-05 16:55:54 +01007364#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007365typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7366 PHANDLE FileHandle,
7367 ACCESS_MASK DesiredAccess,
7368 POBJECT_ATTRIBUTES ObjectAttributes,
7369 PIO_STATUS_BLOCK IoStatusBlock,
7370 ULONG ShareAccess,
7371 ULONG OpenOptions);
7372typedef NTSTATUS (NTAPI *PfnNtClose)(
7373 HANDLE Handle);
7374typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007375 HANDLE FileHandle,
7376 PIO_STATUS_BLOCK IoStatusBlock,
7377 PVOID Buffer,
7378 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007379typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7380 HANDLE FileHandle,
7381 PIO_STATUS_BLOCK IoStatusBlock,
7382 PVOID Buffer,
7383 ULONG Length,
7384 BOOLEAN ReturnSingleEntry,
7385 PVOID EaList,
7386 ULONG EaListLength,
7387 PULONG EaIndex,
7388 BOOLEAN RestartScan);
7389typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007390 HANDLE FileHandle,
7391 PIO_STATUS_BLOCK IoStatusBlock,
7392 PVOID FileInformation,
7393 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007394 FILE_INFORMATION_CLASS FileInformationClass);
7395typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7396 PUNICODE_STRING DestinationString,
7397 PCWSTR SourceString);
7398
7399PfnNtOpenFile pNtOpenFile = NULL;
7400PfnNtClose pNtClose = NULL;
7401PfnNtSetEaFile pNtSetEaFile = NULL;
7402PfnNtQueryEaFile pNtQueryEaFile = NULL;
7403PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7404PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01007405#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007406
7407/*
7408 * Load ntdll.dll functions.
7409 */
7410 static BOOL
7411load_ntdll(void)
7412{
7413 static int loaded = -1;
7414
7415 if (loaded == -1)
7416 {
7417 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7418 if (hNtdll != NULL)
7419 {
7420 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7421 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7422 pNtSetEaFile = (PfnNtSetEaFile)
7423 GetProcAddress(hNtdll, "NtSetEaFile");
7424 pNtQueryEaFile = (PfnNtQueryEaFile)
7425 GetProcAddress(hNtdll, "NtQueryEaFile");
7426 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7427 GetProcAddress(hNtdll, "NtQueryInformationFile");
7428 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7429 GetProcAddress(hNtdll, "RtlInitUnicodeString");
7430 }
7431 if (pNtOpenFile == NULL
7432 || pNtClose == NULL
7433 || pNtSetEaFile == NULL
7434 || pNtQueryEaFile == NULL
7435 || pNtQueryInformationFile == NULL
7436 || pRtlInitUnicodeString == NULL)
7437 loaded = FALSE;
7438 else
7439 loaded = TRUE;
7440 }
7441 return (BOOL) loaded;
7442}
7443
7444/*
7445 * Copy extended attributes (EA) from file "from" to file "to".
7446 */
7447 static void
7448copy_extattr(char_u *from, char_u *to)
7449{
7450 char_u *fromf = NULL;
7451 char_u *tof = NULL;
7452 WCHAR *fromw = NULL;
7453 WCHAR *tow = NULL;
7454 UNICODE_STRING u;
7455 HANDLE h;
7456 OBJECT_ATTRIBUTES oa;
7457 IO_STATUS_BLOCK iosb;
7458 FILE_EA_INFORMATION_ eainfo = {0};
7459 void *ea = NULL;
7460
7461 if (!load_ntdll())
7462 return;
7463
7464 // Convert the file names to the fully qualified object names.
7465 fromf = alloc(STRLEN(from) + 5);
7466 tof = alloc(STRLEN(to) + 5);
7467 if (fromf == NULL || tof == NULL)
7468 goto theend;
7469 STRCPY(fromf, "\\??\\");
7470 STRCAT(fromf, from);
7471 STRCPY(tof, "\\??\\");
7472 STRCAT(tof, to);
7473
7474 // Convert the names to wide characters.
7475 fromw = enc_to_utf16(fromf, NULL);
7476 tow = enc_to_utf16(tof, NULL);
7477 if (fromw == NULL || tow == NULL)
7478 goto theend;
7479
7480 // Get the EA.
7481 pRtlInitUnicodeString(&u, fromw);
7482 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7483 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7484 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7485 goto theend;
7486 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7487 FileEaInformation);
7488 if (eainfo.EaSize != 0)
7489 {
7490 ea = alloc(eainfo.EaSize);
7491 if (ea != NULL)
7492 {
7493 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7494 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7495 {
7496 vim_free(ea);
7497 ea = NULL;
7498 }
7499 }
7500 }
7501 pNtClose(h);
7502
7503 // Set the EA.
7504 if (ea != NULL)
7505 {
7506 pRtlInitUnicodeString(&u, tow);
7507 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7508 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7509 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7510 goto theend;
7511
7512 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
7513 pNtClose(h);
7514 }
7515
7516theend:
7517 vim_free(fromf);
7518 vim_free(tof);
7519 vim_free(fromw);
7520 vim_free(tow);
7521 vim_free(ea);
7522}
7523
7524/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007525 * Copy file attributes from file "from" to file "to".
7526 * For Windows NT and later we copy info streams.
7527 * Always returns zero, errors are ignored.
7528 */
7529 int
7530mch_copy_file_attribute(char_u *from, char_u *to)
7531{
Bram Moolenaar0f873732019-12-05 20:28:46 +01007532 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007533 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007534 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007535 return 0;
7536}
7537
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007538
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007539/*
K.Takatadc73b4b2021-06-08 18:32:36 +02007540 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007541 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007542static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007543static LPWSTR *ArglistW = NULL;
7544static int global_argc = 0;
7545static char **global_argv;
7546
Bram Moolenaar0f873732019-12-05 20:28:46 +01007547static int used_file_argc = 0; // last argument in global_argv[] used
7548 // for the argument list.
7549static int *used_file_indexes = NULL; // indexes in global_argv[] for
7550 // command line arguments added to
7551 // the argument list
7552static int used_file_count = 0; // nr of entries in used_file_indexes
7553static int used_file_literal = FALSE; // take file names literally
7554static int used_file_full_path = FALSE; // file name was full path
7555static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007556static int used_alist_count = 0;
7557
7558
7559/*
7560 * Get the command line arguments. Unicode version.
7561 * Returns argc. Zero when something fails.
7562 */
7563 int
7564get_cmd_argsW(char ***argvp)
7565{
7566 char **argv = NULL;
7567 int argc = 0;
7568 int i;
7569
Bram Moolenaar14993322014-09-09 12:25:33 +02007570 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007571 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7572 if (ArglistW != NULL)
7573 {
7574 argv = malloc((nArgsW + 1) * sizeof(char *));
7575 if (argv != NULL)
7576 {
7577 argc = nArgsW;
7578 argv[argc] = NULL;
7579 for (i = 0; i < argc; ++i)
7580 {
7581 int len;
7582
K.Takatadc73b4b2021-06-08 18:32:36 +02007583 // Convert each Unicode argument to UTF-8.
7584 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007585 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007586 (LPSTR *)&argv[i], &len, 0, 0);
7587 if (argv[i] == NULL)
7588 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007589 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007590 while (i > 0)
7591 free(argv[--i]);
7592 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007593 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007594 argc = 0;
7595 }
7596 }
7597 }
7598 }
7599
7600 global_argc = argc;
7601 global_argv = argv;
7602 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007603 {
7604 if (used_file_indexes != NULL)
7605 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007606 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007607 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007608
7609 if (argvp != NULL)
7610 *argvp = argv;
7611 return argc;
7612}
7613
7614 void
7615free_cmd_argsW(void)
7616{
7617 if (ArglistW != NULL)
7618 {
7619 GlobalFree(ArglistW);
7620 ArglistW = NULL;
7621 }
7622}
7623
7624/*
7625 * Remember "name" is an argument that was added to the argument list.
7626 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7627 * is called.
7628 */
7629 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007630used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007631{
7632 int i;
7633
7634 if (used_file_indexes == NULL)
7635 return;
7636 for (i = used_file_argc + 1; i < global_argc; ++i)
7637 if (STRCMP(global_argv[i], name) == 0)
7638 {
7639 used_file_argc = i;
7640 used_file_indexes[used_file_count++] = i;
7641 break;
7642 }
7643 used_file_literal = literal;
7644 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007645 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007646}
7647
7648/*
7649 * Remember the length of the argument list as it was. If it changes then we
7650 * leave it alone when 'encoding' is set.
7651 */
7652 void
7653set_alist_count(void)
7654{
7655 used_alist_count = GARGCOUNT;
7656}
7657
7658/*
7659 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02007660 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007661 * and convert them to 'encoding'.
7662 */
7663 void
7664fix_arg_enc(void)
7665{
7666 int i;
7667 int idx;
7668 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007669 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007670
Bram Moolenaar0f873732019-12-05 20:28:46 +01007671 // Safety checks:
7672 // - if argument count differs between the wide and non-wide argument
7673 // list, something must be wrong.
7674 // - the file name arguments must have been located.
7675 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007676 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007677 || ArglistW == NULL
7678 || used_file_indexes == NULL
7679 || used_file_count == 0
7680 || used_alist_count != GARGCOUNT)
7681 return;
7682
Bram Moolenaar0f873732019-12-05 20:28:46 +01007683 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007684 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007685 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007686 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00007687 for (i = 0; i < GARGCOUNT; ++i)
7688 fnum_list[i] = GARGLIST[i].ae_fnum;
7689
Bram Moolenaar0f873732019-12-05 20:28:46 +01007690 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007691 alist_clear(&global_alist);
7692 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007693 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007694
7695 for (i = 0; i < used_file_count; ++i)
7696 {
7697 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007698 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007699 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007700 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007701 int literal = used_file_literal;
7702
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007703#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01007704 // When using diff mode may need to concatenate file name to
7705 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007706 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7707 && !mch_isdir(alist_name(&GARGLIST[0])))
7708 {
7709 char_u *r;
7710
7711 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7712 if (r != NULL)
7713 {
7714 vim_free(str);
7715 str = r;
7716 }
7717 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007718#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01007719 // Re-use the old buffer by renaming it. When not using literal
7720 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00007721 if (used_file_literal)
7722 buf_set_name(fnum_list[i], str);
7723
Bram Moolenaar0f873732019-12-05 20:28:46 +01007724 // Check backtick literal. backtick literal is already expanded in
7725 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007726 if (literal == FALSE)
7727 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007728 size_t len = STRLEN(str);
7729
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007730 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7731 literal = TRUE;
7732 }
7733 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007734 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007735 }
7736
7737 if (!used_file_literal)
7738 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007739 // Now expand wildcards in the arguments.
7740 // Temporarily add '(' and ')' to 'isfname'. These are valid
7741 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00007742 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01007743 // Also, unset wildignore to not be influenced by this option.
7744 // The arguments specified in command-line should be kept even if
7745 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00007746 // Use :legacy so that it also works when in Vim9 script.
7747 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
7748 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007749 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00007750 do_cmdline_cmd(
7751 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
7752 do_cmdline_cmd(
7753 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007754 }
7755
Bram Moolenaar0f873732019-12-05 20:28:46 +01007756 // If wildcard expansion failed, we are editing the first file of the
7757 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007758 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7759 {
7760 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00007761 if (GARGCOUNT == 1 && used_file_full_path
7762 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
7763 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007764 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007765
7766 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007767}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007768
7769 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007770mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007771{
7772 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007773 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007774
Bram Moolenaar964b3742019-05-24 18:54:09 +02007775 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007776 if (envbuf == NULL)
7777 return -1;
7778
7779 sprintf((char *)envbuf, "%s=%s", var, value);
7780
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007781 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007782
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007783 vim_free(envbuf);
7784 if (p == NULL)
7785 return -1;
7786 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007787#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007788 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007789#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007790 // Unlike Un*x systems, we can free the string for _wputenv().
7791 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007792
7793 return 0;
7794}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007795
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007796/*
7797 * Support for 256 colors and 24-bit colors was added in Windows 10
7798 * version 1703 (Creators update).
7799 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007800#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7801
7802/*
7803 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02007804 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007805 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007806#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007807
7808/*
7809 * ConPTY differences between versions, need different logic.
7810 * version 1903 (May 2019 update).
7811 */
7812#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
7813
7814/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007815 * version 1909 (November 2019 update).
7816 */
7817#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
7818
7819/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007820 * Stay ahead of the next update, and when it's done, fix this.
7821 * version ? (2020 update, temporarily use the build number of insider preview)
7822 */
7823#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
7824
7825/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02007826 * Confirm until this version. Also the logic changes.
7827 * insider preview.
7828 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02007829#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007830
7831/*
7832 * Not stable now.
7833 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007834#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007835
7836 static void
7837vtp_flag_init(void)
7838{
7839 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007840#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007841 DWORD mode;
7842 HANDLE out;
7843
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007844# ifdef VIMDLL
7845 if (!gui.in_use)
7846# endif
7847 {
7848 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007849
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007850 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7851 GetConsoleMode(out, &mode);
7852 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7853 if (SetConsoleMode(out, mode) == 0)
7854 vtp_working = 0;
7855 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007856#endif
7857
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007858 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007859 conpty_working = 1;
7860 if (ver >= CONPTY_STABLE_BUILD)
7861 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007862
Bram Moolenaar57da6982019-09-13 22:30:11 +02007863 if (ver <= CONPTY_INSIDER_BUILD)
7864 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007865 if (ver <= CONPTY_1909_BUILD)
7866 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02007867 if (ver <= CONPTY_1903_BUILD)
7868 conpty_type = 2;
7869 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
7870 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007871
7872 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
7873 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007874}
7875
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007876#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007877
7878 static void
7879vtp_init(void)
7880{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007881 HMODULE hKerneldll;
7882 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007883# ifdef FEAT_TERMGUICOLORS
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01007884 COLORREF fg;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007885# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007886
Bram Moolenaar0f873732019-12-05 20:28:46 +01007887 // Use functions supported from Vista
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007888 hKerneldll = GetModuleHandle("kernel32.dll");
7889 if (hKerneldll != NULL)
7890 {
7891 pGetConsoleScreenBufferInfoEx =
7892 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7893 hKerneldll, "GetConsoleScreenBufferInfoEx");
7894 pSetConsoleScreenBufferInfoEx =
7895 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7896 hKerneldll, "SetConsoleScreenBufferInfoEx");
7897 if (pGetConsoleScreenBufferInfoEx != NULL
7898 && pSetConsoleScreenBufferInfoEx != NULL)
7899 has_csbiex = TRUE;
7900 }
7901
7902 csbi.cbSize = sizeof(csbi);
7903 if (has_csbiex)
7904 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007905 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7906 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
Bram Moolenaardf543822020-01-30 11:53:59 +01007907 store_console_bg_rgb = save_console_bg_rgb;
7908 store_console_fg_rgb = save_console_fg_rgb;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007909
7910# ifdef FEAT_TERMGUICOLORS
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01007911 if (!USE_WT)
7912 {
7913 COLORREF bg;
7914 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7915 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7916 default_console_color_bg = bg;
7917 }
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007918 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007919 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007920 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007921# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007922
7923 set_console_color_rgb();
7924}
7925
7926 static void
7927vtp_exit(void)
7928{
Bram Moolenaardf543822020-01-30 11:53:59 +01007929 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007930}
7931
Bram Moolenaar06b7b582020-05-30 17:49:25 +02007932 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007933vtp_printf(
7934 char *format,
7935 ...)
7936{
7937 char_u buf[100];
7938 va_list list;
7939 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007940 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007941
7942 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007943 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007944 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007945 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007946 return (int)result;
7947}
7948
7949 static void
7950vtp_sgr_bulk(
7951 int arg)
7952{
7953 int args[1];
7954
7955 args[0] = arg;
7956 vtp_sgr_bulks(1, args);
7957}
7958
K.Takata6e1d31e2022-02-03 13:05:32 +00007959# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007960 if ((*p-- = "0123456789"[(n = x % 10)]) \
7961 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
7962 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
7963
K.Takata6e1d31e2022-02-03 13:05:32 +00007964# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007965 case x: \
7966 FAST256(newargs[x - 1]);
7967
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007968 static void
7969vtp_sgr_bulks(
7970 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007971 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007972{
K.Takata6e1d31e2022-02-03 13:05:32 +00007973# define MAXSGR 16
7974# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007975 char_u buf[SGRBUFSIZE];
7976 char_u *p;
7977 int in, out;
7978 int newargs[16];
7979 static int sgrfgr = -1, sgrfgg, sgrfgb;
7980 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007981
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007982 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007983 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007984 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01007985 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007986 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007987 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007988
7989 in = out = 0;
7990 while (in < argc)
7991 {
7992 int s = args[in];
7993 int copylen = 1;
7994
7995 if (s == 38)
7996 {
7997 if (argc - in >= 5 && args[in + 1] == 2)
7998 {
7999 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8000 && sgrfgb == args[in + 4])
8001 {
8002 in += 5;
8003 copylen = 0;
8004 }
8005 else
8006 {
8007 sgrfgr = args[in + 2];
8008 sgrfgg = args[in + 3];
8009 sgrfgb = args[in + 4];
8010 copylen = 5;
8011 }
8012 }
8013 else if (argc - in >= 3 && args[in + 1] == 5)
8014 {
8015 sgrfgr = -1;
8016 copylen = 3;
8017 }
8018 }
8019 else if (s == 48)
8020 {
8021 if (argc - in >= 5 && args[in + 1] == 2)
8022 {
8023 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8024 && sgrbgb == args[in + 4])
8025 {
8026 in += 5;
8027 copylen = 0;
8028 }
8029 else
8030 {
8031 sgrbgr = args[in + 2];
8032 sgrbgg = args[in + 3];
8033 sgrbgb = args[in + 4];
8034 copylen = 5;
8035 }
8036 }
8037 else if (argc - in >= 3 && args[in + 1] == 5)
8038 {
8039 sgrbgr = -1;
8040 copylen = 3;
8041 }
8042 }
8043 else if (30 <= s && s <= 39)
8044 sgrfgr = -1;
8045 else if (90 <= s && s <= 97)
8046 sgrfgr = -1;
8047 else if (40 <= s && s <= 49)
8048 sgrbgr = -1;
8049 else if (100 <= s && s <= 107)
8050 sgrbgr = -1;
8051 else if (s == 0)
8052 sgrfgr = sgrbgr = -1;
8053
8054 while (copylen--)
8055 newargs[out++] = args[in++];
8056 }
8057
8058 p = &buf[sizeof(buf) - 1];
8059 *p-- = 'm';
8060
8061 switch (out)
8062 {
8063 int n, m;
8064 DWORD r;
8065
8066 FAST256CASE(16);
8067 *p-- = ';';
8068 FAST256CASE(15);
8069 *p-- = ';';
8070 FAST256CASE(14);
8071 *p-- = ';';
8072 FAST256CASE(13);
8073 *p-- = ';';
8074 FAST256CASE(12);
8075 *p-- = ';';
8076 FAST256CASE(11);
8077 *p-- = ';';
8078 FAST256CASE(10);
8079 *p-- = ';';
8080 FAST256CASE(9);
8081 *p-- = ';';
8082 FAST256CASE(8);
8083 *p-- = ';';
8084 FAST256CASE(7);
8085 *p-- = ';';
8086 FAST256CASE(6);
8087 *p-- = ';';
8088 FAST256CASE(5);
8089 *p-- = ';';
8090 FAST256CASE(4);
8091 *p-- = ';';
8092 FAST256CASE(3);
8093 *p-- = ';';
8094 FAST256CASE(2);
8095 *p-- = ';';
8096 FAST256CASE(1);
8097 *p-- = '[';
8098 *p = '\033';
8099 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8100 default:
8101 break;
8102 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008103}
8104
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008105 static void
8106wt_init(void)
8107{
8108 wt_working = (mch_getenv("WT_SESSION") != NULL);
8109}
8110
8111 int
8112use_wt(void)
8113{
8114 return USE_WT;
8115}
8116
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008117# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008118 static int
8119ctermtoxterm(
8120 int cterm)
8121{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008122 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008123
8124 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8125 return (((int)r << 16) | ((int)g << 8) | (int)b);
8126}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008127# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008128
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008129 static void
8130set_console_color_rgb(void)
8131{
8132# ifdef FEAT_TERMGUICOLORS
8133 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008134 guicolor_T fg, bg;
8135 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008136
8137 if (!USE_VTP)
8138 return;
8139
Bram Moolenaara050b942019-12-02 21:35:31 +01008140 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8141
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008142 if (USE_WT)
8143 {
8144 term_fg_rgb_color(fg);
8145 term_bg_rgb_color(bg);
8146 return;
8147 }
8148
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008149 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8150 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8151
8152 csbi.cbSize = sizeof(csbi);
8153 if (has_csbiex)
8154 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8155
8156 csbi.cbSize = sizeof(csbi);
8157 csbi.srWindow.Right += 1;
8158 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008159 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8160 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008161 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8162 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008163 if (has_csbiex)
8164 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8165# endif
8166}
8167
Bram Moolenaara050b942019-12-02 21:35:31 +01008168# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8169 void
8170get_default_console_color(
8171 int *cterm_fg,
8172 int *cterm_bg,
8173 guicolor_T *gui_fg,
8174 guicolor_T *gui_bg)
8175{
8176 int id;
8177 guicolor_T guifg = INVALCOLOR;
8178 guicolor_T guibg = INVALCOLOR;
8179 int ctermfg = 0;
8180 int ctermbg = 0;
8181
8182 id = syn_name2id((char_u *)"Normal");
8183 if (id > 0 && p_tgc)
8184 syn_id2colors(id, &guifg, &guibg);
8185 if (guifg == INVALCOLOR)
8186 {
8187 ctermfg = -1;
8188 if (id > 0)
8189 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8190 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
8191 : default_console_color_fg;
8192 cterm_normal_fg_gui_color = guifg;
8193 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8194 }
8195 if (guibg == INVALCOLOR)
8196 {
8197 ctermbg = -1;
8198 if (id > 0)
8199 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
K.Takatae53a0d42022-09-05 21:45:11 +01008200 if (USE_WT)
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008201 {
8202 cterm_normal_bg_gui_color = guibg =
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01008203 ctermbg != -1 ? ctermtoxterm(ctermbg) : INVALCOLOR;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008204 if (ctermbg < 0)
8205 ctermbg = 0;
8206 }
K.Takatae53a0d42022-09-05 21:45:11 +01008207 else
8208 {
8209 guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8210 : default_console_color_bg;
8211 cterm_normal_bg_gui_color = guibg;
8212 ctermbg = ctermbg < 0 ? 0 : ctermbg;
8213 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008214 }
8215
8216 *cterm_fg = ctermfg;
8217 *cterm_bg = ctermbg;
8218 *gui_fg = guifg;
8219 *gui_bg = guibg;
8220}
8221# endif
8222
Bram Moolenaardf543822020-01-30 11:53:59 +01008223/*
8224 * Set the console colors to the original colors or the last set colors.
8225 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008226 static void
8227reset_console_color_rgb(void)
8228{
8229# ifdef FEAT_TERMGUICOLORS
8230 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8231
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008232 if (USE_WT)
8233 return;
8234
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008235 csbi.cbSize = sizeof(csbi);
8236 if (has_csbiex)
8237 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8238
8239 csbi.cbSize = sizeof(csbi);
8240 csbi.srWindow.Right += 1;
8241 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008242 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8243 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
8244 if (has_csbiex)
8245 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8246# endif
8247}
8248
8249/*
8250 * Set the console colors to the original colors.
8251 */
8252 static void
8253restore_console_color_rgb(void)
8254{
8255# ifdef FEAT_TERMGUICOLORS
8256 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8257
8258 csbi.cbSize = sizeof(csbi);
8259 if (has_csbiex)
8260 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8261
8262 csbi.cbSize = sizeof(csbi);
8263 csbi.srWindow.Right += 1;
8264 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008265 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8266 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008267 if (has_csbiex)
8268 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8269# endif
8270}
8271
8272 void
8273control_console_color_rgb(void)
8274{
8275 if (USE_VTP)
8276 set_console_color_rgb();
8277 else
8278 reset_console_color_rgb();
8279}
8280
8281 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008282use_vtp(void)
8283{
8284 return USE_VTP;
8285}
8286
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008287 int
8288is_term_win32(void)
8289{
8290 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8291}
8292
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008293 int
8294has_vtp_working(void)
8295{
8296 return vtp_working;
8297}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008298
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008299#endif
8300
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008301 int
8302has_conpty_working(void)
8303{
8304 return conpty_working;
8305}
8306
8307 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008308get_conpty_type(void)
8309{
8310 return conpty_type;
8311}
8312
8313 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008314is_conpty_stable(void)
8315{
8316 return conpty_stable;
8317}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008318
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008319 int
8320get_conpty_fix_type(void)
8321{
8322 return conpty_fix_type;
8323}
8324
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008325#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008326 void
8327resize_console_buf(void)
8328{
8329 CONSOLE_SCREEN_BUFFER_INFO csbi;
8330 COORD coord;
8331 SMALL_RECT newsize;
8332
8333 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8334 {
8335 coord.X = SRWIDTH(csbi.srWindow);
8336 coord.Y = SRHEIGHT(csbi.srWindow);
8337 SetConsoleScreenBufferSize(g_hConOut, coord);
8338
8339 newsize.Left = 0;
8340 newsize.Top = 0;
8341 newsize.Right = coord.X - 1;
8342 newsize.Bottom = coord.Y - 1;
8343 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8344
8345 SetConsoleScreenBufferSize(g_hConOut, coord);
8346 }
8347}
8348#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008349
8350 char *
8351GetWin32Error(void)
8352{
K.Takatad68b2fc2022-02-12 11:18:37 +00008353 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008354 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008355
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008356 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8357 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008358 if (oldmsg != NULL)
8359 LocalFree(oldmsg);
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008360 if (msg != NULL)
8361 {
8362 // remove trailing \r\n
8363 char *pcrlf = strstr(msg, "\r\n");
8364 if (pcrlf != NULL)
8365 *pcrlf = '\0';
K.Takatad68b2fc2022-02-12 11:18:37 +00008366 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008367 }
8368 return msg;
8369}
Paul Ollis65745772022-06-05 16:55:54 +01008370
8371#if defined(FEAT_RELTIME) || defined(PROTO)
8372static HANDLE timer_handle;
8373static int timer_active = FALSE;
8374
8375/*
8376 * Calls to start_timeout alternate the return value pointer between the two
8377 * entries in timeout_flags. If the previously active timeout is very close to
8378 * expiring when start_timeout() is called then a race condition means that the
8379 * set_flag() function may still be invoked after the previous timer is
8380 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8381 * timeouts.
8382 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008383static sig_atomic_t timeout_flags[2];
8384static int timeout_flag_idx = 0;
8385static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01008386
8387
8388 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01008389set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01008390{
8391 int *timeout_flag = (int *)param;
8392
8393 *timeout_flag = TRUE;
8394}
8395
8396/*
8397 * Stop any active timeout.
8398 */
8399 void
8400stop_timeout(void)
8401{
8402 if (timer_active)
8403 {
8404 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
8405 timer_active = FALSE;
8406 if (!ret && GetLastError() != ERROR_IO_PENDING)
8407 {
8408 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
8409 }
8410 }
8411 *timeout_flag = FALSE;
8412}
8413
8414/*
8415 * Start the timeout timer.
8416 *
8417 * The period is defined in milliseconds.
8418 *
8419 * The return value is a pointer to a flag that is initialised to 0. If the
8420 * timeout expires, the flag is set to 1. This will only return pointers to
8421 * static memory; i.e. any pointer returned by this function may always be
8422 * safely dereferenced.
8423 *
8424 * This function is not expected to fail, but if it does it still returns a
8425 * valid flag pointer; the flag will remain stuck at zero.
8426 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008427 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01008428start_timeout(long msec)
8429{
Paul Ollis65745772022-06-05 16:55:54 +01008430 BOOL ret;
8431
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008432 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01008433
8434 stop_timeout();
8435 ret = CreateTimerQueueTimer(
8436 &timer_handle, NULL, set_flag, timeout_flag,
8437 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
8438 if (!ret)
8439 {
8440 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
8441 }
8442 else
8443 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008444 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01008445 timer_active = TRUE;
8446 *timeout_flag = FALSE;
8447 }
8448 return timeout_flag;
8449}
8450#endif