blob: 7224fadef59a0271c61e8f058bc3f5d100f7ed67 [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;
103typedef int COLORREF;
104typedef int CONSOLE_CURSOR_INFO;
105typedef int COORD;
106typedef int DWORD;
107typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100108typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000109typedef int HDC;
110typedef int HFONT;
111typedef int HICON;
112typedef int HINSTANCE;
113typedef int HWND;
114typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200115typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000116typedef int KEY_EVENT_RECORD;
117typedef int LOGFONT;
118typedef int LPBOOL;
119typedef int LPCTSTR;
120typedef int LPDWORD;
121typedef int LPSTR;
122typedef int LPTSTR;
123typedef int LPVOID;
124typedef int MOUSE_EVENT_RECORD;
125typedef int PACL;
126typedef int PDWORD;
127typedef int PHANDLE;
128typedef int PRINTDLG;
129typedef int PSECURITY_DESCRIPTOR;
130typedef int PSID;
131typedef int SECURITY_INFORMATION;
132typedef int SHORT;
133typedef int SMALL_RECT;
134typedef int TEXTMETRIC;
135typedef int TOKEN_INFORMATION_CLASS;
136typedef int TRUSTEE;
137typedef int WORD;
138typedef int WCHAR;
139typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100140typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200141typedef int SE_OBJECT_TYPE;
142typedef int PSNSECINFO;
143typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100144typedef int STARTUPINFO;
145typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200146typedef int LPSECURITY_ATTRIBUTES;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100147# define __stdcall // empty
Bram Moolenaar071d4272004-06-13 20:20:40 +0000148#endif
149
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200150#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100151// Win32 Console handles for input and output
Bram Moolenaar071d4272004-06-13 20:20:40 +0000152static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
153static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
154
Bram Moolenaar0f873732019-12-05 20:28:46 +0100155// Win32 Screen buffer,coordinate,console I/O information
Bram Moolenaar071d4272004-06-13 20:20:40 +0000156static SMALL_RECT g_srScrollRegion;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100157static COORD g_coord; // 0-based, but external coords are 1-based
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158
Bram Moolenaar0f873732019-12-05 20:28:46 +0100159// The attribute of the screen when the editor was started
160static WORD g_attrDefault = 7; // lightgray text on black background
Bram Moolenaar071d4272004-06-13 20:20:40 +0000161static WORD g_attrCurrent;
162
Bram Moolenaar0f873732019-12-05 20:28:46 +0100163static int g_fCBrkPressed = FALSE; // set by ctrl-break interrupt
164static int g_fCtrlCPressed = FALSE; // set when ctrl-C or ctrl-break detected
165static int g_fForceExit = FALSE; // set when forcefully exiting
Bram Moolenaar071d4272004-06-13 20:20:40 +0000166
Bram Moolenaar071d4272004-06-13 20:20:40 +0000167static void scroll(unsigned cLines);
168static void set_scroll_region(unsigned left, unsigned top,
169 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100170static void set_scroll_region_tb(unsigned top, unsigned bottom);
171static void set_scroll_region_lr(unsigned left, unsigned right);
172static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000173static void delete_lines(unsigned cLines);
174static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000175static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000176static int s_cursor_visible = TRUE;
177static int did_create_conin = FALSE;
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200178#endif
179#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000180static int s_dont_use_vimrun = TRUE;
181static int need_vimrun_warning = FALSE;
182static char *vimrun_path = "vimrun ";
183#endif
184
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200185static int win32_getattrs(char_u *name);
186static int win32_setattrs(char_u *name, int attrs);
187static int win32_set_archive(char_u *name);
188
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100189static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200190static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100191static int conpty_stable = 0;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +0200192static int conpty_fix_type = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100193static void vtp_flag_init();
194
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200195#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100196static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100197static void vtp_init();
198static void vtp_exit();
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100199static void vtp_sgr_bulk(int arg);
200static void vtp_sgr_bulks(int argc, int *argv);
201
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200202static int wt_working = 0;
203static void wt_init();
204
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100205static guicolor_T save_console_bg_rgb;
206static guicolor_T save_console_fg_rgb;
Bram Moolenaardf543822020-01-30 11:53:59 +0100207static guicolor_T store_console_bg_rgb;
208static guicolor_T store_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100209
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200210static int g_color_index_bg = 0;
211static int g_color_index_fg = 7;
212
213# ifdef FEAT_TERMGUICOLORS
214static int default_console_color_bg = 0x000000; // black
215static int default_console_color_fg = 0xc0c0c0; // white
216# endif
217
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100218# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200219# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200220# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100221# else
222# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200223# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100224# endif
225
226static void set_console_color_rgb(void);
227static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100228static void restore_console_color_rgb(void);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100229#endif
230
Bram Moolenaar0f873732019-12-05 20:28:46 +0100231// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100232#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
233# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
234#endif
235
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200236#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100237static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000238#endif
239
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200240static char_u *exe_path = NULL;
241
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100242static BOOL win8_or_later = FALSE;
243
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200244#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100245// Dynamic loading for portability
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100246typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
247{
248 ULONG cbSize;
249 COORD dwSize;
250 COORD dwCursorPosition;
251 WORD wAttributes;
252 SMALL_RECT srWindow;
253 COORD dwMaximumWindowSize;
254 WORD wPopupAttributes;
255 BOOL bFullscreenSupported;
256 COLORREF ColorTable[16];
257} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
258typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
259static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
260typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
261static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
262static BOOL has_csbiex = FALSE;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100263#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100264
265/*
266 * Get version number including build number
267 */
268typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100269#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100270 (((major) << 24) | ((minor) << 16) | (build))
271
272 static DWORD
273get_build_number(void)
274{
275 OSVERSIONINFOW osver = {sizeof(OSVERSIONINFOW)};
276 HMODULE hNtdll;
277 PfnRtlGetVersion pRtlGetVersion;
278 DWORD ver = MAKE_VER(0, 0, 0);
279
280 hNtdll = GetModuleHandle("ntdll.dll");
281 if (hNtdll != NULL)
282 {
283 pRtlGetVersion =
284 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
285 pRtlGetVersion(&osver);
286 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
287 min(osver.dwMinorVersion, 255),
288 min(osver.dwBuildNumber, 32767));
289 }
290 return ver;
291}
292
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200293#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200294 static BOOL
295is_ambiwidth_event(
296 INPUT_RECORD *ir)
297{
298 return ir->EventType == KEY_EVENT
299 && ir->Event.KeyEvent.bKeyDown
300 && ir->Event.KeyEvent.wRepeatCount == 1
301 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
302 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000303 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200304 && ir->Event.KeyEvent.dwControlKeyState == 2;
305}
306
307 static void
308make_ambiwidth_event(
309 INPUT_RECORD *down,
310 INPUT_RECORD *up)
311{
312 down->Event.KeyEvent.wVirtualKeyCode = 0;
313 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000314 down->Event.KeyEvent.uChar.UnicodeChar
315 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200316 down->Event.KeyEvent.dwControlKeyState = 0;
317}
318
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100319/*
320 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100321 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100322 */
323 static BOOL
324read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100325 HANDLE hInput,
326 INPUT_RECORD *lpBuffer,
327 DWORD nLength,
328 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100329{
330 enum
331 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100332 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100333 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100334 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100335 static DWORD s_dwIndex = 0;
336 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100337 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100338 int head;
339 int tail;
340 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200341 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100342
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200343 if (nLength == -2)
344 return (s_dwMax > 0) ? TRUE : FALSE;
345
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100346 if (!win8_or_later)
347 {
348 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200349 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
350 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100351 }
352
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100353 if (s_dwMax == 0)
354 {
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200355 if (!USE_WT && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200356 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200357 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
358 if (dwEvents == 0 && nLength == -1)
359 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
360 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100361 s_dwIndex = 0;
362 s_dwMax = dwEvents;
363 if (dwEvents == 0)
364 {
365 *lpEvents = 0;
366 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100367 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100368
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200369 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
370 if (is_ambiwidth_event(&s_irCache[i]))
371 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
372
Bram Moolenaardd415a62014-02-05 14:02:27 +0100373 if (s_dwMax > 1)
374 {
375 head = 0;
376 tail = s_dwMax - 1;
377 while (head != tail)
378 {
379 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
380 && s_irCache[head + 1].EventType
381 == WINDOW_BUFFER_SIZE_EVENT)
382 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100383 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100384 for (i = head; i < tail; ++i)
385 s_irCache[i] = s_irCache[i + 1];
386 --tail;
387 continue;
388 }
389 head++;
390 }
391 s_dwMax = tail + 1;
392 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100393 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100394
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200395 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
396 {
397 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
398 {
399 s_irPseudo = s_irCache[s_dwIndex];
400 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
401 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
402 *lpBuffer = s_irPseudo;
403 *lpEvents = 1;
404 return TRUE;
405 }
406 }
407
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100408 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200409 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100410 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100411 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100412 return TRUE;
413}
414
415/*
416 * Version of PeekConsoleInput() that works with IME.
417 */
418 static BOOL
419peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100420 HANDLE hInput,
421 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200422 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100423 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100424{
K.Takata135e1522022-01-29 15:27:58 +0000425 return read_console_input(hInput, lpBuffer, (DWORD)-1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100426}
427
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100428# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200429 static DWORD
430msg_wait_for_multiple_objects(
431 DWORD nCount,
432 LPHANDLE pHandles,
433 BOOL fWaitAll,
434 DWORD dwMilliseconds,
435 DWORD dwWakeMask)
436{
K.Takata135e1522022-01-29 15:27:58 +0000437 if (read_console_input(NULL, NULL, (DWORD)-2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200438 return WAIT_OBJECT_0;
439 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
440 dwMilliseconds, dwWakeMask);
441}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100442# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200443
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100444# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200445 static DWORD
446wait_for_single_object(
447 HANDLE hHandle,
448 DWORD dwMilliseconds)
449{
K.Takata54119102022-02-03 13:33:03 +0000450 if (read_console_input(NULL, NULL, (DWORD)-2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200451 return WAIT_OBJECT_0;
452 return WaitForSingleObject(hHandle, dwMilliseconds);
453}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100454# endif
455#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200456
Bram Moolenaar071d4272004-06-13 20:20:40 +0000457 static void
458get_exe_name(void)
459{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100460 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
461 // as the maximum length that works (plus a NUL byte).
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100462#define MAX_ENV_PATH_LEN 8192
463 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200464 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000465
466 if (exe_name == NULL)
467 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100468 // store the name of the executable, may be used for $VIM
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100469 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000470 if (*temp != NUL)
471 exe_name = FullName_save((char_u *)temp, FALSE);
472 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000473
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200474 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000475 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200476 exe_path = vim_strnsave(exe_name, gettail_sep(exe_name) - exe_name);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200477 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000478 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100479 // Append our starting directory to $PATH, so that when doing
480 // "!xxd" it's found in our starting directory. Needed because
481 // SearchPath() also looks there.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200482 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100483 if (p == NULL
484 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200485 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100486 if (p == NULL || *p == NUL)
487 temp[0] = NUL;
488 else
489 {
490 STRCPY(temp, p);
491 STRCAT(temp, ";");
492 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200493 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100494 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200495 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000496 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000497 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000498}
499
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200500/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100501 * Unescape characters in "p" that appear in "escaped".
502 */
503 static void
504unescape_shellxquote(char_u *p, char_u *escaped)
505{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100506 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100507 int n;
508
509 while (*p != NUL)
510 {
511 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
512 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100513 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100514 p += n;
515 l -= n;
516 }
517}
518
519/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200520 * Load library "name".
521 */
522 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000523vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200524{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200525 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200526
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200527 // No need to load any library when registering OLE.
528 if (found_register_arg)
529 return dll;
530
Bram Moolenaar0f873732019-12-05 20:28:46 +0100531 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
532 // vimLoadLib() recursively, which causes a stack overflow.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200533 if (exe_path == NULL)
534 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200535 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200536 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200537 WCHAR old_dirw[MAXPATHL];
538
539 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
540 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100541 // Change directory to where the executable is, both to make
542 // sure we find a .dll there and to avoid looking for a .dll
543 // in the current directory.
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100544 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200545 dll = LoadLibrary(name);
546 SetCurrentDirectoryW(old_dirw);
547 return dll;
548 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200549 }
550 return dll;
551}
552
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200553#if defined(VIMDLL) || defined(PROTO)
554/*
555 * Check if the current executable file is for the GUI subsystem.
556 */
557 int
558mch_is_gui_executable(void)
559{
560 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
561 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
562 PIMAGE_NT_HEADERS pPE;
563
564 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
565 return FALSE;
566 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
567 if (pPE->Signature != IMAGE_NT_SIGNATURE)
568 return FALSE;
569 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
570 return TRUE;
571 return FALSE;
572}
573#endif
574
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000575#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
576 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100577/*
578 * Get related information about 'funcname' which is imported by 'hInst'.
579 * If 'info' is 0, return the function address.
580 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000581 * If 'info' is 2, hook the function with 'ptr', and return the original
582 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100583 */
584 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000585get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
586 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100587{
588 PBYTE pImage = (PBYTE)hInst;
589 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
590 PIMAGE_NT_HEADERS pPE;
591 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100592 PIMAGE_THUNK_DATA pIAT; // Import Address Table
593 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100594 PIMAGE_IMPORT_BY_NAME pImpName;
595
596 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
597 return NULL;
598 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
599 if (pPE->Signature != IMAGE_NT_SIGNATURE)
600 return NULL;
601 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
602 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
603 .VirtualAddress);
604 for (; pImpDesc->FirstThunk; ++pImpDesc)
605 {
606 if (!pImpDesc->OriginalFirstThunk)
607 continue;
608 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
609 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
610 for (; pIAT->u1.Function; ++pIAT, ++pINT)
611 {
612 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
613 continue;
614 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
615 + (UINT_PTR)(pINT->u1.AddressOfData));
616 if (strcmp((char *)pImpName->Name, funcname) == 0)
617 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000618 void *original;
619 DWORD old, new = PAGE_READWRITE;
620
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100621 switch (info)
622 {
623 case 0:
624 return (void *)pIAT->u1.Function;
625 case 1:
626 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000627 case 2:
628 original = (void *)pIAT->u1.Function;
629 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
630 new, &old);
631 pIAT->u1.Function = (UINT_PTR)ptr;
632 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
633 old, &new);
634 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100635 default:
636 return NULL;
637 }
638 }
639 }
640 }
641 return NULL;
642}
643
644/*
645 * Get the module handle which 'funcname' in 'hInst' is imported from.
646 */
647 HINSTANCE
648find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
649{
650 char *modulename;
651
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000652 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100653 if (modulename != NULL)
654 return GetModuleHandleA(modulename);
655 return NULL;
656}
657
658/*
659 * Get the address of 'funcname' which is imported by 'hInst' DLL.
660 */
661 void *
662get_dll_import_func(HINSTANCE hInst, const char *funcname)
663{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000664 return get_imported_func_info(hInst, funcname, 0, NULL);
665}
666
667/*
668 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
669 * and return the original function address.
670 */
671 void *
672hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
673{
674 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100675}
676#endif
677
Bram Moolenaar071d4272004-06-13 20:20:40 +0000678#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
679# ifndef GETTEXT_DLL
680# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200681# define GETTEXT_DLL_ALT1 "libintl-8.dll"
682# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000683# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100684// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000685static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200686static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000687static char *null_libintl_textdomain(const char *);
688static char *null_libintl_bindtextdomain(const char *, const char *);
689static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100690static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000691
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200692static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000693char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200694char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
695 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000696char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
697char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000698 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000699char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
700 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100701int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000702
703 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100704dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000705{
706 int i;
707 static struct
708 {
709 char *name;
710 FARPROC *ptr;
711 } libintl_entry[] =
712 {
713 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200714 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000715 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
716 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
717 {NULL, NULL}
718 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100719 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000720
Bram Moolenaar7554c542018-10-06 15:03:15 +0200721 // No need to initialize twice.
722 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000723 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200724 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100725 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100726# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100727 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200728 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100729# endif
730# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200731 if (!hLibintlDLL)
732 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100733# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100734 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000735 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200736 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000737 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200738 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000739 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200740 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000741 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200742 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000743 }
744 for (i = 0; libintl_entry[i].name != NULL
745 && libintl_entry[i].ptr != NULL; ++i)
746 {
K.Takata54119102022-02-03 13:33:03 +0000747 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000748 libintl_entry[i].name)) == NULL)
749 {
750 dyn_libintl_end();
751 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000752 {
753 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000754 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000755 verbose_leave();
756 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000757 return 0;
758 }
759 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000760
Bram Moolenaar0f873732019-12-05 20:28:46 +0100761 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000762 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000763 "bind_textdomain_codeset");
764 if (dyn_libintl_bind_textdomain_codeset == NULL)
765 dyn_libintl_bind_textdomain_codeset =
766 null_libintl_bind_textdomain_codeset;
767
Bram Moolenaar0f873732019-12-05 20:28:46 +0100768 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100769 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
770 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100771 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100772 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
773 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100774
Bram Moolenaar071d4272004-06-13 20:20:40 +0000775 return 1;
776}
777
778 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100779dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000780{
781 if (hLibintlDLL)
782 FreeLibrary(hLibintlDLL);
783 hLibintlDLL = NULL;
784 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200785 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000786 dyn_libintl_textdomain = null_libintl_textdomain;
787 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000788 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100789 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000790}
791
792 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000793null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000794{
795 return (char*)msgid;
796}
797
798 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200799null_libintl_ngettext(
800 const char *msgid,
801 const char *msgid_plural,
802 unsigned long n)
803{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200804 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200805}
806
Bram Moolenaaree695f72016-08-03 22:08:45 +0200807 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100808null_libintl_bindtextdomain(
809 const char *domainname UNUSED,
810 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000811{
812 return NULL;
813}
814
815 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100816null_libintl_bind_textdomain_codeset(
817 const char *domainname UNUSED,
818 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000819{
820 return NULL;
821}
822
823 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100824null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000825{
826 return NULL;
827}
828
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200829 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100830null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100831{
832 return 0;
833}
834
Bram Moolenaar0f873732019-12-05 20:28:46 +0100835#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000836
Bram Moolenaar0f873732019-12-05 20:28:46 +0100837// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000838
839#ifndef VER_PLATFORM_WIN32_WINDOWS
840# define VER_PLATFORM_WIN32_WINDOWS 1
841#endif
842
Bram Moolenaar071d4272004-06-13 20:20:40 +0000843#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100844# ifndef PROTO
845# include <aclapi.h>
846# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200847# ifndef PROTECTED_DACL_SECURITY_INFORMATION
848# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
849# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000850#endif
851
Bram Moolenaar27515922013-06-29 15:36:26 +0200852#ifdef HAVE_ACL
853/*
854 * Enables or disables the specified privilege.
855 */
856 static BOOL
857win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
858{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100859 BOOL bResult;
860 LUID luid;
861 HANDLE hToken;
862 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200863
864 if (!OpenProcessToken(GetCurrentProcess(),
865 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
866 return FALSE;
867
868 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
869 {
870 CloseHandle(hToken);
871 return FALSE;
872 }
873
Bram Moolenaar45500912014-07-09 20:51:07 +0200874 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200875 tokenPrivileges.Privileges[0].Luid = luid;
876 tokenPrivileges.Privileges[0].Attributes = bEnable ?
877 SE_PRIVILEGE_ENABLED : 0;
878
879 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
880 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
881
882 CloseHandle(hToken);
883
884 return bResult && GetLastError() == ERROR_SUCCESS;
885}
886#endif
887
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100888#ifdef _MSC_VER
889// Suppress the deprecation warning for using GetVersionEx().
890// It is needed for implementing "windowsversion()".
891# pragma warning(push)
892# pragma warning(disable: 4996)
893#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000894/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200895 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000896 */
897 void
898PlatformId(void)
899{
900 static int done = FALSE;
901
902 if (!done)
903 {
904 OSVERSIONINFO ovi;
905
906 ovi.dwOSVersionInfoSize = sizeof(ovi);
907 GetVersionEx(&ovi);
908
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200909#ifdef FEAT_EVAL
Bram Moolenaar0c1e3742019-12-27 13:49:24 +0100910 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
911 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200912#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100913 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
914 || ovi.dwMajorVersion > 6)
915 win8_or_later = TRUE;
916
Bram Moolenaar071d4272004-06-13 20:20:40 +0000917#ifdef HAVE_ACL
Bram Moolenaar0f873732019-12-05 20:28:46 +0100918 // Enable privilege for getting or setting SACLs.
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200919 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000920#endif
921 done = TRUE;
922 }
923}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100924#ifdef _MSC_VER
925# pragma warning(pop)
926#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000927
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200928#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000929
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100930# define SHIFT (SHIFT_PRESSED)
931# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
932# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
933# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000934
935
Bram Moolenaar0f873732019-12-05 20:28:46 +0100936// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
937// We map function keys to their ANSI terminal equivalents, as produced
938// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
939// ANSI key with a value >= '\300' is nonstandard, but provided anyway
940// so that the user can have access to all SHIFT-, CTRL-, and ALT-
941// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000942
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000943static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000944{
945 WORD wVirtKey;
946 BOOL fAnsiKey;
947 int chAlone;
948 int chShift;
949 int chCtrl;
950 int chAlt;
951} VirtKeyMap[] =
952{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200953// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000954 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
955
956 { VK_F1, TRUE, ';', 'T', '^', 'h', },
957 { VK_F2, TRUE, '<', 'U', '_', 'i', },
958 { VK_F3, TRUE, '=', 'V', '`', 'j', },
959 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
960 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
961 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
962 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
963 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
964 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
965 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200966 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
967 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000968
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200969 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
970 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
971 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
972 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
973 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
974 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
975 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
976 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
977 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
978 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100979 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000980
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200981 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000982
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100983# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200984 // Most people don't have F13-F20, but what the hell...
985 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
986 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
987 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
988 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
989 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
990 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
991 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
992 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100993# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200994 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
995 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
996 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
997 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000998
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200999 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
1000 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
1001 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
1002 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
1003 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
1004 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
1005 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
1006 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
1007 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
1008 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001009 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001010};
1011
1012
Bram Moolenaar0f873732019-12-05 20:28:46 +01001013/*
1014 * The return code indicates key code size.
1015 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001016 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001017win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001018 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001019{
1020 UINT uMods = pker->dwControlKeyState;
1021 static int s_iIsDead = 0;
1022 static WORD awAnsiCode[2];
1023 static BYTE abKeystate[256];
1024
1025
1026 if (s_iIsDead == 2)
1027 {
K.Takata972db232022-02-04 10:45:38 +00001028 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001029 s_iIsDead = 0;
1030 return 1;
1031 }
1032
K.Takata972db232022-02-04 10:45:38 +00001033 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001034 return 1;
1035
Bram Moolenaara80faa82020-04-12 19:37:17 +02001036 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001037
Bram Moolenaar0f873732019-12-05 20:28:46 +01001038 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001039 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001040
1041 if (uMods & SHIFT_PRESSED)
1042 abKeystate[VK_SHIFT] = 0x80;
1043 if (uMods & CAPSLOCK_ON)
1044 abKeystate[VK_CAPITAL] = 1;
1045
1046 if ((uMods & ALT_GR) == ALT_GR)
1047 {
1048 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1049 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1050 }
1051
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001052 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1053 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001054
1055 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001056 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001057
1058 return s_iIsDead;
1059}
1060
Bram Moolenaar071d4272004-06-13 20:20:40 +00001061static BOOL g_fJustGotFocus = FALSE;
1062
1063/*
1064 * Decode a KEY_EVENT into one or two keystrokes
1065 */
1066 static BOOL
1067decode_key_event(
1068 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001069 WCHAR *pch,
1070 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001071 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001072 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001073{
1074 int i;
1075 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1076
1077 *pch = *pch2 = NUL;
1078 g_fJustGotFocus = FALSE;
1079
Bram Moolenaar0f873732019-12-05 20:28:46 +01001080 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001081 if (!pker->bKeyDown)
1082 return FALSE;
1083
Bram Moolenaar0f873732019-12-05 20:28:46 +01001084 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001085 switch (pker->wVirtualKeyCode)
1086 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001087 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001088 case VK_SHIFT:
1089 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001090 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001091 return FALSE;
1092
1093 default:
1094 break;
1095 }
1096
Bram Moolenaar0f873732019-12-05 20:28:46 +01001097 // special cases
K.Takata972db232022-02-04 10:45:38 +00001098 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0
1099 && pker->uChar.UnicodeChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001100 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001101 // Ctrl-6 is Ctrl-^
Bram Moolenaar071d4272004-06-13 20:20:40 +00001102 if (pker->wVirtualKeyCode == '6')
1103 {
1104 *pch = Ctrl_HAT;
1105 return TRUE;
1106 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001107 // Ctrl-2 is Ctrl-@
Bram Moolenaar071d4272004-06-13 20:20:40 +00001108 else if (pker->wVirtualKeyCode == '2')
1109 {
1110 *pch = NUL;
1111 return TRUE;
1112 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001113 // Ctrl-- is Ctrl-_
Bram Moolenaar071d4272004-06-13 20:20:40 +00001114 else if (pker->wVirtualKeyCode == 0xBD)
1115 {
1116 *pch = Ctrl__;
1117 return TRUE;
1118 }
1119 }
1120
Bram Moolenaar0f873732019-12-05 20:28:46 +01001121 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001122 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1123 {
1124 *pch = K_NUL;
1125 *pch2 = '\017';
1126 return TRUE;
1127 }
1128
K.Takataeeec2542021-06-02 13:28:16 +02001129 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001130 {
1131 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1132 {
1133 if (nModifs == 0)
1134 *pch = VirtKeyMap[i].chAlone;
1135 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1136 *pch = VirtKeyMap[i].chShift;
1137 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1138 *pch = VirtKeyMap[i].chCtrl;
1139 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1140 *pch = VirtKeyMap[i].chAlt;
1141
1142 if (*pch != 0)
1143 {
1144 if (VirtKeyMap[i].fAnsiKey)
1145 {
1146 *pch2 = *pch;
1147 *pch = K_NUL;
1148 }
1149
1150 return TRUE;
1151 }
1152 }
1153 }
1154
1155 i = win32_kbd_patch_key(pker);
1156
1157 if (i < 0)
1158 *pch = NUL;
1159 else
1160 {
K.Takata972db232022-02-04 10:45:38 +00001161 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001162
1163 if (pmodifiers != NULL)
1164 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001165 // Pass on the ALT key as a modifier, but only when not combined
1166 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001167 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1168 *pmodifiers |= MOD_MASK_ALT;
1169
Bram Moolenaar0f873732019-12-05 20:28:46 +01001170 // Pass on SHIFT only for special keys, because we don't know when
1171 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001172 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1173 *pmodifiers |= MOD_MASK_SHIFT;
1174
Bram Moolenaar0f873732019-12-05 20:28:46 +01001175 // Pass on CTRL only for non-special keys, because we don't know
1176 // when it's already included with the character. And not when
1177 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001178 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1179 && *pch >= 0x20 && *pch < 0x80)
1180 *pmodifiers |= MOD_MASK_CTRL;
1181 }
1182 }
1183
1184 return (*pch != NUL);
1185}
1186
Bram Moolenaar0f873732019-12-05 20:28:46 +01001187#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001188
1189
Bram Moolenaar071d4272004-06-13 20:20:40 +00001190/*
1191 * For the GUI the mouse handling is in gui_w32.c.
1192 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001193#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001194 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001195mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001196{
1197}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001198#else
Bram Moolenaar0f873732019-12-05 20:28:46 +01001199static int g_fMouseAvail = FALSE; // mouse present
1200static int g_fMouseActive = FALSE; // mouse enabled
1201static int g_nMouseClick = -1; // mouse status
1202static int g_xMouse; // mouse x coordinate
1203static int g_yMouse; // mouse y coordinate
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001204static DWORD g_cmodein = 0; // Original console input mode
1205static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001206
1207/*
1208 * Enable or disable mouse input
1209 */
1210 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001211mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001212{
1213 DWORD cmodein;
1214
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001215# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001216 if (gui.in_use)
1217 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001218# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001219 if (!g_fMouseAvail)
1220 return;
1221
1222 g_fMouseActive = on;
1223 GetConsoleMode(g_hConIn, &cmodein);
1224
1225 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001226 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001227 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001228 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1229 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001230 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001231 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001232 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001233 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1234 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001235
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001236 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001237}
1238
Bram Moolenaar157d8132018-03-06 17:09:20 +01001239
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001240# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001241/*
1242 * Called when 'balloonevalterm' changed.
1243 */
1244 void
1245mch_bevalterm_changed(void)
1246{
1247 mch_setmouse(g_fMouseActive);
1248}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001249# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001250
Bram Moolenaar071d4272004-06-13 20:20:40 +00001251/*
1252 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1253 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1254 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1255 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1256 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1257 * and we return the mouse position in g_xMouse and g_yMouse.
1258 *
1259 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1260 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1261 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1262 *
1263 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1264 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1265 *
1266 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1267 * moves, even if it stays within the same character cell. We ignore
1268 * all MOUSE_MOVED messages if the position hasn't really changed, and
1269 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1270 * we're only interested in MOUSE_DRAG).
1271 *
1272 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1273 * 2-button mouses by pressing the left & right buttons simultaneously.
1274 * In practice, it's almost impossible to click both at the same time,
1275 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1276 * in such cases, if the user is clicking quickly.
1277 */
1278 static BOOL
1279decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001280 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001281{
1282 static int s_nOldButton = -1;
1283 static int s_nOldMouseClick = -1;
1284 static int s_xOldMouse = -1;
1285 static int s_yOldMouse = -1;
1286 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001287# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001288 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001289# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001290 static int s_cClicks = 1;
1291 static BOOL s_fReleased = TRUE;
1292 static DWORD s_dwLastClickTime = 0;
1293 static BOOL s_fNextIsMiddle = FALSE;
1294
Bram Moolenaar0f873732019-12-05 20:28:46 +01001295 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001296
1297 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1298 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1299 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1300 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1301
1302 int nButton;
1303
1304 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1305 cButtons = 2;
1306
1307 if (!g_fMouseAvail || !g_fMouseActive)
1308 {
1309 g_nMouseClick = -1;
1310 return FALSE;
1311 }
1312
Bram Moolenaar0f873732019-12-05 20:28:46 +01001313 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001314 if (g_fJustGotFocus)
1315 {
1316 g_fJustGotFocus = FALSE;
1317 return FALSE;
1318 }
1319
Bram Moolenaar0f873732019-12-05 20:28:46 +01001320 // unprocessed mouse click?
Bram Moolenaar071d4272004-06-13 20:20:40 +00001321 if (g_nMouseClick != -1)
1322 return TRUE;
1323
1324 nButton = -1;
1325 g_xMouse = pmer->dwMousePosition.X;
1326 g_yMouse = pmer->dwMousePosition.Y;
1327
1328 if (pmer->dwEventFlags == MOUSE_MOVED)
1329 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001330 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1331 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001332 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1333 return FALSE;
1334 }
1335
Bram Moolenaar0f873732019-12-05 20:28:46 +01001336 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001337 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1338 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001339 nButton = MOUSE_RELEASE;
1340
Bram Moolenaar0f873732019-12-05 20:28:46 +01001341 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001342 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001343 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001344# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001345 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001346 if (p_bevalterm)
1347 nButton = MOUSE_DRAG;
1348 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001349# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001350 return FALSE;
1351 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001352
Bram Moolenaar071d4272004-06-13 20:20:40 +00001353 s_fReleased = TRUE;
1354 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001355 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001356 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001357 // on a 2-button mouse, hold down left and right buttons
1358 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001359
1360 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1361 {
1362 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1363
Bram Moolenaar0f873732019-12-05 20:28:46 +01001364 // if either left or right button only is pressed, see if the
1365 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001366 if (dwLR == LEFT || dwLR == RIGHT)
1367 {
1368 for (;;)
1369 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001370 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001371 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1372 != WAIT_OBJECT_0)
1373 break;
1374 else
1375 {
1376 DWORD cRecords = 0;
1377 INPUT_RECORD ir;
1378 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1379
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001380 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001381
1382 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1383 || !(pmer2->dwButtonState & LEFT_RIGHT))
1384 break;
1385 else
1386 {
1387 if (pmer2->dwEventFlags != MOUSE_MOVED)
1388 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001389 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001390
1391 return decode_mouse_event(pmer2);
1392 }
1393 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1394 s_yOldMouse == pmer2->dwMousePosition.Y)
1395 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001396 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001397 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001398
Bram Moolenaar0f873732019-12-05 20:28:46 +01001399 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001400 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001401
1402 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1403 break;
1404 }
1405 else
1406 break;
1407 }
1408 }
1409 }
1410 }
1411 }
1412
1413 if (s_fNextIsMiddle)
1414 {
1415 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1416 ? MOUSE_DRAG : MOUSE_MIDDLE;
1417 s_fNextIsMiddle = FALSE;
1418 }
1419 else if (cButtons == 2 &&
1420 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1421 {
1422 nButton = MOUSE_MIDDLE;
1423
1424 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1425 {
1426 s_fNextIsMiddle = TRUE;
1427 nButton = MOUSE_RELEASE;
1428 }
1429 }
1430 else if ((pmer->dwButtonState & LEFT) == LEFT)
1431 nButton = MOUSE_LEFT;
1432 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1433 nButton = MOUSE_MIDDLE;
1434 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1435 nButton = MOUSE_RIGHT;
1436
1437 if (! s_fReleased && ! s_fNextIsMiddle
1438 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1439 return FALSE;
1440
1441 s_fReleased = s_fNextIsMiddle;
1442 }
1443
1444 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1445 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001446 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001447 if (nButton != -1 && nButton != MOUSE_RELEASE)
1448 {
1449 DWORD dwCurrentTime = GetTickCount();
1450
1451 if (s_xOldMouse != g_xMouse
1452 || s_yOldMouse != g_yMouse
1453 || s_nOldButton != nButton
1454 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001455# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001456 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001457# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001458 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1459 {
1460 s_cClicks = 1;
1461 }
1462 else if (++s_cClicks > 4)
1463 {
1464 s_cClicks = 1;
1465 }
1466
1467 s_dwLastClickTime = dwCurrentTime;
1468 }
1469 }
1470 else if (pmer->dwEventFlags == MOUSE_MOVED)
1471 {
1472 if (nButton != -1 && nButton != MOUSE_RELEASE)
1473 nButton = MOUSE_DRAG;
1474
1475 s_cClicks = 1;
1476 }
1477
1478 if (nButton == -1)
1479 return FALSE;
1480
1481 if (nButton != MOUSE_RELEASE)
1482 s_nOldButton = nButton;
1483
1484 g_nMouseClick = nButton;
1485
1486 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1487 g_nMouseClick |= MOUSE_SHIFT;
1488 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1489 g_nMouseClick |= MOUSE_CTRL;
1490 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1491 g_nMouseClick |= MOUSE_ALT;
1492
1493 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1494 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1495
Bram Moolenaar0f873732019-12-05 20:28:46 +01001496 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001497 if (s_xOldMouse == g_xMouse
1498 && s_yOldMouse == g_yMouse
1499 && s_nOldMouseClick == g_nMouseClick)
1500 {
1501 g_nMouseClick = -1;
1502 return FALSE;
1503 }
1504
1505 s_xOldMouse = g_xMouse;
1506 s_yOldMouse = g_yMouse;
1507 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001508# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001509 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001510# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001511 s_nOldMouseClick = g_nMouseClick;
1512
1513 return TRUE;
1514}
1515
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001516#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001517
1518
1519#ifdef MCH_CURSOR_SHAPE
1520/*
1521 * Set the shape of the cursor.
1522 * 'thickness' can be from 1 (thin) to 99 (block)
1523 */
1524 static void
1525mch_set_cursor_shape(int thickness)
1526{
1527 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1528 ConsoleCursorInfo.dwSize = thickness;
1529 ConsoleCursorInfo.bVisible = s_cursor_visible;
1530
1531 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1532 if (s_cursor_visible)
1533 SetConsoleCursorPosition(g_hConOut, g_coord);
1534}
1535
1536 void
1537mch_update_cursor(void)
1538{
1539 int idx;
1540 int thickness;
1541
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001542# ifdef VIMDLL
1543 if (gui.in_use)
1544 return;
1545# endif
1546
Bram Moolenaar071d4272004-06-13 20:20:40 +00001547 /*
1548 * How the cursor is drawn depends on the current mode.
1549 */
1550 idx = get_shape_idx(FALSE);
1551
1552 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001553 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00001554 else
1555 thickness = shape_table[idx].percentage;
1556 mch_set_cursor_shape(thickness);
1557}
1558#endif
1559
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001560#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001561/*
1562 * Handle FOCUS_EVENT.
1563 */
1564 static void
1565handle_focus_event(INPUT_RECORD ir)
1566{
1567 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1568 ui_focus_change((int)g_fJustGotFocus);
1569}
1570
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001571static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1572
Bram Moolenaar071d4272004-06-13 20:20:40 +00001573/*
1574 * Wait until console input from keyboard or mouse is available,
1575 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001576 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001577 * Return TRUE if something is available FALSE if not.
1578 */
1579 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001580WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001581{
1582 DWORD dwNow = 0, dwEndTime = 0;
1583 INPUT_RECORD ir;
1584 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001585 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001586# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001587 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001588# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001589
1590 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001591 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001592 dwEndTime = GetTickCount() + msec;
1593 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001594 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001595 dwEndTime = INFINITE;
1596
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001597 // We need to loop until the end of the time period, because
1598 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001599 for (;;)
1600 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001601 // Only process messages when waiting.
1602 if (msec != 0)
1603 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001604# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001605 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001606# endif
1607# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001608 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001609# endif
1610# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001611 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001612# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001613 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001614
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001615 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001616# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001617 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001618# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001619 )
1620 return TRUE;
1621
1622 if (msec > 0)
1623 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001624 // If the specified wait time has passed, return. Beware that
1625 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001626 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001627 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001628 break;
1629 }
1630 if (msec != 0)
1631 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001632 DWORD dwWaitTime = dwEndTime - dwNow;
1633
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001634 // Don't wait for more than 11 msec to avoid dropping characters,
1635 // check channel while waiting for input and handle a callback from
1636 // 'balloonexpr'.
1637 if (dwWaitTime > 11)
1638 dwWaitTime = 11;
1639
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001640# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001641 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001642 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001643# endif
1644# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001645 // When waiting very briefly don't trigger timers.
1646 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001647 {
1648 long due_time;
1649
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001650 // Trigger timers and then get the time in msec until the next
1651 // one is due. Wait up to that time.
1652 due_time = check_due_timer();
1653 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001654 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001655 // timer may have used feedkeys().
1656 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001657 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001658 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1659 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001660 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001661# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001662 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001663# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001664 // Wait for either an event on the console input or a
1665 // message in the client-server window.
1666 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1667 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001668# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001669 wait_for_single_object(g_hConIn, dwWaitTime)
1670 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001671# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001672 )
1673 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001674 }
1675
1676 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001677 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001678
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001679# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02001680 // May have to redraw if the cursor ends up in the wrong place.
1681 // Only when not peeking.
1682 if (State & CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001683 {
1684 CONSOLE_SCREEN_BUFFER_INFO csbi;
1685
1686 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1687 {
1688 if (csbi.dwCursorPosition.Y != msg_row)
1689 {
matveyte08795e2021-05-07 15:00:17 +02001690 // The screen is now messed up, must redraw the command
1691 // line and later all the windows.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001692 redraw_all_later(CLEAR);
matveyte08795e2021-05-07 15:00:17 +02001693 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001694 redrawcmd();
1695 }
1696 }
1697 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001698# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001699
1700 if (cRecords > 0)
1701 {
1702 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1703 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001704# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01001705 // Windows IME sends two '\n's with only one 'ENTER'. First:
1706 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00001707 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001708 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1709 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001710 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001711 continue;
1712 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001713# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001714 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1715 NULL, FALSE))
1716 return TRUE;
1717 }
1718
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001719 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001720
1721 if (ir.EventType == FOCUS_EVENT)
1722 handle_focus_event(ir);
1723 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001724 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001725 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1726
Bram Moolenaar36698e32019-12-11 22:57:40 +01001727 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001728 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001729 if (dwSize.X != Columns || dwSize.Y != Rows)
1730 {
1731 CONSOLE_SCREEN_BUFFER_INFO csbi;
1732 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01001733 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001734 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01001735 if (dwSize.X != Columns || dwSize.Y != Rows)
1736 {
1737 ResizeConBuf(g_hConOut, dwSize);
1738 shell_resized();
1739 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001740 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001741 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001742 else if (ir.EventType == MOUSE_EVENT
1743 && decode_mouse_event(&ir.Event.MouseEvent))
1744 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001745 }
1746 else if (msec == 0)
1747 break;
1748 }
1749
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001750# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01001751 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001752 if (input_available())
1753 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001754# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001755
Bram Moolenaar071d4272004-06-13 20:20:40 +00001756 return FALSE;
1757}
1758
Bram Moolenaar071d4272004-06-13 20:20:40 +00001759/*
1760 * return non-zero if a character is available
1761 */
1762 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001763mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001764{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001765# ifdef VIMDLL
1766 if (gui.in_use)
1767 return TRUE;
1768# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001769 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001770}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001771
1772# if defined(FEAT_TERMINAL) || defined(PROTO)
1773/*
1774 * Check for any pending input or messages.
1775 */
1776 int
1777mch_check_messages(void)
1778{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001779# ifdef VIMDLL
1780 if (gui.in_use)
1781 return TRUE;
1782# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001783 return WaitForChar(0L, TRUE);
1784}
1785# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001786
1787/*
1788 * Create the console input. Used when reading stdin doesn't work.
1789 */
1790 static void
1791create_conin(void)
1792{
1793 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1794 FILE_SHARE_READ|FILE_SHARE_WRITE,
1795 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001796 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001797 did_create_conin = TRUE;
1798}
1799
1800/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001801 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001802 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001803 static WCHAR
1804tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001805{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001806 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001807
1808 for (;;)
1809 {
1810 INPUT_RECORD ir;
1811 DWORD cRecords = 0;
1812
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001813# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001814 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001815 if (input_available())
1816 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001817 if (g_nMouseClick != -1)
1818 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001819# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001820 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001821 {
1822 if (did_create_conin)
1823 read_error_exit();
1824 create_conin();
1825 continue;
1826 }
1827
1828 if (ir.EventType == KEY_EVENT)
1829 {
1830 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1831 pmodifiers, TRUE))
1832 return ch;
1833 }
1834 else if (ir.EventType == FOCUS_EVENT)
1835 handle_focus_event(ir);
1836 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1837 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001838 else if (ir.EventType == MOUSE_EVENT)
1839 {
1840 if (decode_mouse_event(&ir.Event.MouseEvent))
1841 return 0;
1842 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001843 }
1844}
Bram Moolenaar0f873732019-12-05 20:28:46 +01001845#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001846
1847
1848/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001849 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001850 * Get one or more characters from the keyboard or the mouse.
1851 * If time == 0, do not wait for characters.
1852 * If time == n, wait a short time for characters.
1853 * If time == -1, wait forever for characters.
1854 * Returns the number of characters read into buf.
1855 */
1856 int
1857mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001858 char_u *buf UNUSED,
1859 int maxlen UNUSED,
1860 long time UNUSED,
1861 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001862{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001863#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001864
1865 int len;
1866 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001867# ifdef VIMDLL
1868// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
1869# define TYPEAHEADSPACE 6
1870# else
1871# define TYPEAHEADSPACE 0
1872# endif
1873# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001874 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001875 static int typeaheadlen = 0;
1876
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001877# ifdef VIMDLL
1878 if (gui.in_use)
1879 return 0;
1880# endif
1881
Bram Moolenaar0f873732019-12-05 20:28:46 +01001882 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001883 if (typeaheadlen > 0)
1884 goto theend;
1885
Bram Moolenaar071d4272004-06-13 20:20:40 +00001886 if (time >= 0)
1887 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001888 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00001889 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001890 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001891 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00001892 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001893 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00001894
Bram Moolenaar3918c952005-03-15 22:34:55 +00001895 /*
1896 * If there is no character available within 2 seconds (default)
1897 * write the autoscript file to disk. Or cause the CursorHold event
1898 * to be triggered.
1899 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001900 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001901 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001902 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001903 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001904 buf[0] = K_SPECIAL;
1905 buf[1] = KS_EXTRA;
1906 buf[2] = (int)KE_CURSORHOLD;
1907 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001908 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001909 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001910 }
1911 }
1912
1913 /*
1914 * Try to read as many characters as there are, until the buffer is full.
1915 */
1916
Bram Moolenaar0f873732019-12-05 20:28:46 +01001917 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001918 g_fCBrkPressed = FALSE;
1919
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001920# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001921 if (fdDump)
1922 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001923# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001924
Bram Moolenaar0f873732019-12-05 20:28:46 +01001925 // Keep looping until there is something in the typeahead buffer and more
1926 // to get and still room in the buffer (up to two bytes for a char and
1927 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001928 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001929 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001930 {
1931 if (typebuf_changed(tb_change_cnt))
1932 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001933 // "buf" may be invalid now if a client put something in the
1934 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001935 typeaheadlen = 0;
1936 break;
1937 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001938 if (g_nMouseClick != -1)
1939 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001940# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001941 if (fdDump)
1942 fprintf(fdDump, "{%02x @ %d, %d}",
1943 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001944# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001945 typeahead[typeaheadlen++] = ESC + 128;
1946 typeahead[typeaheadlen++] = 'M';
1947 typeahead[typeaheadlen++] = g_nMouseClick;
1948 typeahead[typeaheadlen++] = g_xMouse + '!';
1949 typeahead[typeaheadlen++] = g_yMouse + '!';
1950 g_nMouseClick = -1;
1951 }
1952 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001953 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001954 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001955 int modifiers = 0;
1956
1957 c = tgetch(&modifiers, &ch2);
1958
1959 if (typebuf_changed(tb_change_cnt))
1960 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001961 // "buf" may be invalid now if a client put something in the
1962 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001963 typeaheadlen = 0;
1964 break;
1965 }
1966
1967 if (c == Ctrl_C && ctrl_c_interrupts)
1968 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001969# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001970 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001971# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001972 got_int = TRUE;
1973 }
1974
Bram Moolenaar071d4272004-06-13 20:20:40 +00001975 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001976 {
1977 int n = 1;
1978
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001979 if (ch2 == NUL)
1980 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001981 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001982 char_u *p;
1983 WCHAR ch[2];
1984
1985 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01001986 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001987 {
1988 ch[1] = tgetch(&modifiers, &ch2);
1989 n++;
1990 }
1991 p = utf16_to_enc(ch, &n);
1992 if (p != NULL)
1993 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001994 for (i = 0, j = 0; i < n; i++)
1995 {
1996 typeahead[typeaheadlen + j++] = p[i];
1997# ifdef VIMDLL
1998 if (p[i] == CSI)
1999 {
2000 typeahead[typeaheadlen + j++] = KS_EXTRA;
2001 typeahead[typeaheadlen + j++] = KE_CSI;
2002 }
2003# endif
2004 }
2005 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002006 vim_free(p);
2007 }
2008 }
2009 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002010 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002011 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002012# ifdef VIMDLL
2013 if (c == CSI)
2014 {
2015 typeahead[typeaheadlen + 1] = KS_EXTRA;
2016 typeahead[typeaheadlen + 2] = KE_CSI;
2017 n = 3;
2018 }
2019# endif
2020 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002021 if (ch2 != NUL)
2022 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002023 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002024 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002025 switch (ch2)
2026 {
2027 case (WCHAR)'\324': // SHIFT+Insert
2028 case (WCHAR)'\325': // CTRL+Insert
2029 case (WCHAR)'\327': // SHIFT+Delete
2030 case (WCHAR)'\330': // CTRL+Delete
2031 typeahead[typeaheadlen + n] = (char_u)ch2;
2032 n++;
2033 break;
2034
2035 default:
2036 typeahead[typeaheadlen + n] = 3;
2037 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2038 n += 2;
2039 break;
2040 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002041 }
2042 else
2043 {
2044 typeahead[typeaheadlen + n] = 3;
2045 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2046 n += 2;
2047 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002048 }
2049
Bram Moolenaar0f873732019-12-05 20:28:46 +01002050 // Use the ALT key to set the 8th bit of the character
2051 // when it's one byte, the 8th bit isn't set yet and not
2052 // using a double-byte encoding (would become a lead
2053 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002054 if ((modifiers & MOD_MASK_ALT)
2055 && n == 1
2056 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002058 )
2059 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002060 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2061 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002062 modifiers &= ~MOD_MASK_ALT;
2063 }
2064
2065 if (modifiers != 0)
2066 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002067 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002068 mch_memmove(typeahead + typeaheadlen + 3,
2069 typeahead + typeaheadlen, n);
2070 typeahead[typeaheadlen++] = K_SPECIAL;
2071 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2072 typeahead[typeaheadlen++] = modifiers;
2073 }
2074
2075 typeaheadlen += n;
2076
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002077# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002078 if (fdDump)
2079 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002080# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002081 }
2082 }
2083 }
2084
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002085# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002086 if (fdDump)
2087 {
2088 fputs("]\n", fdDump);
2089 fflush(fdDump);
2090 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002091# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002092
Bram Moolenaar071d4272004-06-13 20:20:40 +00002093theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002094 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002095 len = 0;
2096 while (len < maxlen && typeaheadlen > 0)
2097 {
2098 buf[len++] = typeahead[0];
2099 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2100 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002101# ifdef FEAT_JOB_CHANNEL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002102 if (len > 0)
2103 {
2104 buf[len] = NUL;
2105 ch_log(NULL, "raw key input: \"%s\"", buf);
2106 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002107# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002108 return len;
2109
Bram Moolenaar0f873732019-12-05 20:28:46 +01002110#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002111 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002112#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002113}
2114
Bram Moolenaar82881492012-11-20 16:53:39 +01002115#ifndef PROTO
2116# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002117# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002118# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002119#endif
2120
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002121/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002122 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002123 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2124 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002125 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002126 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002127 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002128executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002129{
LemonBoy40fd7e62022-05-05 20:18:16 +01002130 int attrs = win32_getattrs((char_u *)name);
2131
2132 // The file doesn't exist or is a folder.
2133 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2134 return FALSE;
2135 // Check if the file is an AppExecLink, a special alias used by Windows
2136 // Store for its apps.
2137 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002138 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002139 char_u *res = resolve_appexeclink((char_u *)name);
2140 if (res == NULL)
2141 return FALSE;
2142 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002143 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002144 *path = res;
2145 else
2146 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002147 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002148 else if (path != NULL)
2149 *path = FullName_save((char_u *)name, FALSE);
2150 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002151}
2152
2153/*
2154 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2155 * If "use_path" is FALSE: Return TRUE if "name" exists.
2156 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2157 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2158 * the allocated memory.
2159 */
2160 static int
2161executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2162{
2163 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2164 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2165 // UTF-8.
2166 char_u buf[_MAX_PATH * 3];
2167 size_t len = STRLEN(name);
2168 size_t tmplen;
2169 char_u *p, *e, *e2;
2170 char_u *pathbuf = NULL;
2171 char_u *pathext = NULL;
2172 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002173 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002174 int noext = FALSE;
2175 int retval = FALSE;
2176
2177 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002178 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002179
2180 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002181 shname = gettail(p_sh);
2182 if (strstr((char *)shname, "sh") != NULL &&
2183 !(strstr((char *)shname, "powershell") != NULL
2184 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002185 noext = TRUE;
2186
2187 if (use_pathext)
2188 {
2189 pathext = mch_getenv("PATHEXT");
2190 if (pathext == NULL)
2191 pathext = (char_u *)".com;.exe;.bat;.cmd";
2192
2193 if (noext == FALSE)
2194 {
2195 /*
2196 * Loop over all extensions in $PATHEXT.
2197 * Check "name" ends with extension.
2198 */
2199 p = pathext;
2200 while (*p)
2201 {
2202 if (p[0] == ';'
2203 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2204 {
2205 // Skip empty or single ".".
2206 ++p;
2207 continue;
2208 }
2209 e = vim_strchr(p, ';');
2210 if (e == NULL)
2211 e = p + STRLEN(p);
2212 tmplen = e - p;
2213
2214 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2215 {
2216 noext = TRUE;
2217 break;
2218 }
2219
2220 p = e;
2221 }
2222 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002223 }
2224
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002225 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002226 if (pathext == NULL)
2227 pathext = (char_u *)".";
2228 else if (noext == TRUE)
2229 {
2230 if (pathextbuf == NULL)
2231 pathextbuf = alloc(STRLEN(pathext) + 3);
2232 if (pathextbuf == NULL)
2233 {
2234 retval = FALSE;
2235 goto theend;
2236 }
2237 STRCPY(pathextbuf, ".;");
2238 STRCAT(pathextbuf, pathext);
2239 pathext = pathextbuf;
2240 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002241
Bram Moolenaar95da1362020-05-30 18:37:55 +02002242 // Use $PATH when "use_path" is TRUE and "name" is basename.
2243 if (use_path && gettail((char_u *)name) == (char_u *)name)
2244 {
2245 p = mch_getenv("PATH");
2246 if (p != NULL)
2247 {
2248 pathbuf = alloc(STRLEN(p) + 3);
2249 if (pathbuf == NULL)
2250 {
2251 retval = FALSE;
2252 goto theend;
2253 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002254
2255 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2256 STRCPY(pathbuf, ".;");
2257 else
2258 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002259 STRCAT(pathbuf, p);
2260 }
2261 }
2262
2263 /*
2264 * Walk through all entries in $PATH to check if "name" exists there and
2265 * is an executable file.
2266 */
2267 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2268 while (*p)
2269 {
2270 if (*p == ';') // Skip empty entry
2271 {
2272 ++p;
2273 continue;
2274 }
2275 e = vim_strchr(p, ';');
2276 if (e == NULL)
2277 e = p + STRLEN(p);
2278
2279 if (e - p + len + 2 > sizeof(buf))
2280 {
2281 retval = FALSE;
2282 goto theend;
2283 }
2284 // A single "." that means current dir.
2285 if (e - p == 1 && *p == '.')
2286 STRCPY(buf, name);
2287 else
2288 {
2289 vim_strncpy(buf, p, e - p);
2290 add_pathsep(buf);
2291 STRCAT(buf, name);
2292 }
2293 tmplen = STRLEN(buf);
2294
2295 /*
2296 * Loop over all extensions in $PATHEXT.
2297 * Check "name" with extension added.
2298 */
2299 p = pathext;
2300 while (*p)
2301 {
2302 if (*p == ';')
2303 {
2304 // Skip empty entry
2305 ++p;
2306 continue;
2307 }
2308 e2 = vim_strchr(p, (int)';');
2309 if (e2 == NULL)
2310 e2 = p + STRLEN(p);
2311
2312 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2313 {
2314 // Not a single "." that means no extension is added.
2315 if (e2 - p + tmplen + 1 > sizeof(buf))
2316 {
2317 retval = FALSE;
2318 goto theend;
2319 }
2320 vim_strncpy(buf + tmplen, p, e2 - p);
2321 }
2322 if (executable_file((char *)buf, path))
2323 {
2324 retval = TRUE;
2325 goto theend;
2326 }
2327
2328 p = e2;
2329 }
2330
2331 p = e;
2332 }
2333
2334theend:
2335 free(pathextbuf);
2336 free(pathbuf);
2337 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002338}
2339
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002340#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2341 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002342/*
2343 * Bad parameter handler.
2344 *
2345 * Certain MS CRT functions will intentionally crash when passed invalid
2346 * parameters to highlight possible security holes. Setting this function as
2347 * the bad parameter handler will prevent the crash.
2348 *
2349 * In debug builds the parameters contain CRT information that might help track
2350 * down the source of a problem, but in non-debug builds the arguments are all
2351 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2352 * worth allowing these to make debugging of issues easier.
2353 */
2354 static void
2355bad_param_handler(const wchar_t *expression,
2356 const wchar_t *function,
2357 const wchar_t *file,
2358 unsigned int line,
2359 uintptr_t pReserved)
2360{
2361}
2362
2363# define SET_INVALID_PARAM_HANDLER \
2364 ((void)_set_invalid_parameter_handler(bad_param_handler))
2365#else
2366# define SET_INVALID_PARAM_HANDLER
2367#endif
2368
Bram Moolenaar4f974752019-02-17 17:44:42 +01002369#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002370
2371/*
2372 * GUI version of mch_init().
2373 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002374 static void
2375mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002376{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002377# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002378 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002379# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002380
Bram Moolenaar0f873732019-12-05 20:28:46 +01002381 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002382 SET_INVALID_PARAM_HANDLER;
2383
Bram Moolenaar0f873732019-12-05 20:28:46 +01002384 // Let critical errors result in a failure, not in a dialog box. Required
2385 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002386 SetErrorMode(SEM_FAILCRITICALERRORS);
2387
Bram Moolenaar0f873732019-12-05 20:28:46 +01002388 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002389
Bram Moolenaar0f873732019-12-05 20:28:46 +01002390 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002391 Rows = 25;
2392 Columns = 80;
2393
Bram Moolenaar0f873732019-12-05 20:28:46 +01002394 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002395 {
2396 char_u vimrun_location[_MAX_PATH + 4];
2397
Bram Moolenaar0f873732019-12-05 20:28:46 +01002398 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002399 STRCPY(vimrun_location, exe_name);
2400 STRCPY(gettail(vimrun_location), "vimrun.exe");
2401 if (mch_getperm(vimrun_location) >= 0)
2402 {
2403 if (*skiptowhite(vimrun_location) != NUL)
2404 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002405 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002406 mch_memmove(vimrun_location + 1, vimrun_location,
2407 STRLEN(vimrun_location) + 1);
2408 *vimrun_location = '"';
2409 STRCPY(gettail(vimrun_location), "vimrun\" ");
2410 }
2411 else
2412 STRCPY(gettail(vimrun_location), "vimrun ");
2413
2414 vimrun_path = (char *)vim_strsave(vimrun_location);
2415 s_dont_use_vimrun = FALSE;
2416 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002417 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002418 s_dont_use_vimrun = FALSE;
2419
Bram Moolenaar0f873732019-12-05 20:28:46 +01002420 // Don't give the warning for a missing vimrun.exe right now, but only
2421 // when vimrun was supposed to be used. Don't bother people that do
2422 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002423 if (s_dont_use_vimrun)
2424 need_vimrun_warning = TRUE;
2425 }
2426
2427 /*
2428 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2429 * Otherwise the default "findstr /n" is used.
2430 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002431 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01002432 set_option_value_give_err((char_u *)"grepprg",
2433 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002434
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002435# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002436 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002437# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002438
2439 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002440}
2441
2442
Bram Moolenaar0f873732019-12-05 20:28:46 +01002443#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002444
2445#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002446
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002447# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2448# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002449
2450/*
2451 * ClearConsoleBuffer()
2452 * Description:
2453 * Clears the entire contents of the console screen buffer, using the
2454 * specified attribute.
2455 * Returns:
2456 * TRUE on success
2457 */
2458 static BOOL
2459ClearConsoleBuffer(WORD wAttribute)
2460{
2461 CONSOLE_SCREEN_BUFFER_INFO csbi;
2462 COORD coord;
2463 DWORD NumCells, dummy;
2464
2465 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2466 return FALSE;
2467
2468 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2469 coord.X = 0;
2470 coord.Y = 0;
2471 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2472 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002473 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002474 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2475 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002476 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002477
2478 return TRUE;
2479}
2480
2481/*
2482 * FitConsoleWindow()
2483 * Description:
2484 * Checks if the console window will fit within given buffer dimensions.
2485 * Also, if requested, will shrink the window to fit.
2486 * Returns:
2487 * TRUE on success
2488 */
2489 static BOOL
2490FitConsoleWindow(
2491 COORD dwBufferSize,
2492 BOOL WantAdjust)
2493{
2494 CONSOLE_SCREEN_BUFFER_INFO csbi;
2495 COORD dwWindowSize;
2496 BOOL NeedAdjust = FALSE;
2497
2498 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2499 {
2500 /*
2501 * A buffer resize will fail if the current console window does
2502 * not lie completely within that buffer. To avoid this, we might
2503 * have to move and possibly shrink the window.
2504 */
2505 if (csbi.srWindow.Right >= dwBufferSize.X)
2506 {
2507 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2508 if (dwWindowSize.X > dwBufferSize.X)
2509 dwWindowSize.X = dwBufferSize.X;
2510 csbi.srWindow.Right = dwBufferSize.X - 1;
2511 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2512 NeedAdjust = TRUE;
2513 }
2514 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2515 {
2516 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2517 if (dwWindowSize.Y > dwBufferSize.Y)
2518 dwWindowSize.Y = dwBufferSize.Y;
2519 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2520 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2521 NeedAdjust = TRUE;
2522 }
2523 if (NeedAdjust && WantAdjust)
2524 {
2525 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2526 return FALSE;
2527 }
2528 return TRUE;
2529 }
2530
2531 return FALSE;
2532}
2533
2534typedef struct ConsoleBufferStruct
2535{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002536 BOOL IsValid;
2537 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002538 PCHAR_INFO Buffer;
2539 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002540 PSMALL_RECT Regions;
2541 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002542} ConsoleBuffer;
2543
2544/*
2545 * SaveConsoleBuffer()
2546 * Description:
2547 * Saves important information about the console buffer, including the
2548 * actual buffer contents. The saved information is suitable for later
2549 * restoration by RestoreConsoleBuffer().
2550 * Returns:
2551 * TRUE if all information was saved; FALSE otherwise
2552 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2553 */
2554 static BOOL
2555SaveConsoleBuffer(
2556 ConsoleBuffer *cb)
2557{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002558 DWORD NumCells;
2559 COORD BufferCoord;
2560 SMALL_RECT ReadRegion;
2561 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002562 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002563
Bram Moolenaar071d4272004-06-13 20:20:40 +00002564 if (cb == NULL)
2565 return FALSE;
2566
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002567 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002568 {
2569 cb->IsValid = FALSE;
2570 return FALSE;
2571 }
2572 cb->IsValid = TRUE;
2573
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002574 /*
2575 * Allocate a buffer large enough to hold the entire console screen
2576 * buffer. If this ConsoleBuffer structure has already been initialized
2577 * with a buffer of the correct size, then just use that one.
2578 */
2579 if (!cb->IsValid || cb->Buffer == NULL ||
2580 cb->BufferSize.X != cb->Info.dwSize.X ||
2581 cb->BufferSize.Y != cb->Info.dwSize.Y)
2582 {
2583 cb->BufferSize.X = cb->Info.dwSize.X;
2584 cb->BufferSize.Y = cb->Info.dwSize.Y;
2585 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2586 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002587 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002588 if (cb->Buffer == NULL)
2589 return FALSE;
2590 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002591
2592 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002593 * We will now copy the console screen buffer into our buffer.
2594 * ReadConsoleOutput() seems to be limited as far as how much you
2595 * can read at a time. Empirically, this number seems to be about
2596 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2597 * in chunks until it is all copied. The chunks will all have the
2598 * same horizontal characteristics, so initialize them now. The
2599 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002600 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002601 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002602 ReadRegion.Left = 0;
2603 ReadRegion.Right = cb->Info.dwSize.X - 1;
2604 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002605
2606 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2607 if (cb->Regions == NULL || numregions != cb->NumRegions)
2608 {
2609 cb->NumRegions = numregions;
2610 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002611 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002612 if (cb->Regions == NULL)
2613 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002614 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002615 return FALSE;
2616 }
2617 }
2618
2619 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002620 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002621 /*
2622 * Read into position (0, Y) in our buffer.
2623 */
2624 BufferCoord.Y = Y;
2625 /*
2626 * Read the region whose top left corner is (0, Y) and whose bottom
2627 * right corner is (width - 1, Y + Y_incr - 1). This should define
2628 * a region of size width by Y_incr. Don't worry if this region is
2629 * too large for the remaining buffer; it will be cropped.
2630 */
2631 ReadRegion.Top = Y;
2632 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002633 if (!ReadConsoleOutputW(g_hConOut, // output handle
2634 cb->Buffer, // our buffer
2635 cb->BufferSize, // dimensions of our buffer
2636 BufferCoord, // offset in our buffer
2637 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002638 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002639 VIM_CLEAR(cb->Buffer);
2640 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002641 return FALSE;
2642 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002643 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002644 }
2645
2646 return TRUE;
2647}
2648
2649/*
2650 * RestoreConsoleBuffer()
2651 * Description:
2652 * Restores important information about the console buffer, including the
2653 * actual buffer contents, if desired. The information to restore is in
2654 * the same format used by SaveConsoleBuffer().
2655 * Returns:
2656 * TRUE on success
2657 */
2658 static BOOL
2659RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002660 ConsoleBuffer *cb,
2661 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002662{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002663 COORD BufferCoord;
2664 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002665 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002666
2667 if (cb == NULL || !cb->IsValid)
2668 return FALSE;
2669
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002670 /*
2671 * Before restoring the buffer contents, clear the current buffer, and
2672 * restore the cursor position and window information. Doing this now
2673 * prevents old buffer contents from "flashing" onto the screen.
2674 */
2675 if (RestoreScreen)
2676 ClearConsoleBuffer(cb->Info.wAttributes);
2677
2678 FitConsoleWindow(cb->Info.dwSize, TRUE);
2679 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2680 return FALSE;
2681 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2682 return FALSE;
2683
2684 if (!RestoreScreen)
2685 {
2686 /*
2687 * No need to restore the screen buffer contents, so we're done.
2688 */
2689 return TRUE;
2690 }
2691
2692 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2693 return FALSE;
2694 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2695 return FALSE;
2696
2697 /*
2698 * Restore the screen buffer contents.
2699 */
2700 if (cb->Buffer != NULL)
2701 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002702 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002703 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002704 BufferCoord.X = cb->Regions[i].Left;
2705 BufferCoord.Y = cb->Regions[i].Top;
2706 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01002707 if (!WriteConsoleOutputW(g_hConOut, // output handle
2708 cb->Buffer, // our buffer
2709 cb->BufferSize, // dimensions of our buffer
2710 BufferCoord, // offset in our buffer
2711 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02002712 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002713 }
2714 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002715
2716 return TRUE;
2717}
2718
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002719# define FEAT_RESTORE_ORIG_SCREEN
2720# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002721static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002722# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002723static ConsoleBuffer g_cbNonTermcap = { 0 };
2724static ConsoleBuffer g_cbTermcap = { 0 };
2725
Bram Moolenaar071d4272004-06-13 20:20:40 +00002726char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01002727HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00002728static HICON g_hOrigIconSmall = NULL;
2729static HICON g_hOrigIcon = NULL;
2730static HICON g_hVimIcon = NULL;
2731static BOOL g_fCanChangeIcon = FALSE;
2732
Bram Moolenaar071d4272004-06-13 20:20:40 +00002733/*
2734 * GetConsoleIcon()
2735 * Description:
2736 * Attempts to retrieve the small icon and/or the big icon currently in
2737 * use by a given window.
2738 * Returns:
2739 * TRUE on success
2740 */
2741 static BOOL
2742GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002743 HWND hWnd,
2744 HICON *phIconSmall,
2745 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002746{
2747 if (hWnd == NULL)
2748 return FALSE;
2749
2750 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002751 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2752 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002753 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002754 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2755 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002756 return TRUE;
2757}
2758
2759/*
2760 * SetConsoleIcon()
2761 * Description:
2762 * Attempts to change the small icon and/or the big icon currently in
2763 * use by a given window.
2764 * Returns:
2765 * TRUE on success
2766 */
2767 static BOOL
2768SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002769 HWND hWnd,
2770 HICON hIconSmall,
2771 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002772{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002773 if (hWnd == NULL)
2774 return FALSE;
2775
2776 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002777 SendMessage(hWnd, WM_SETICON,
2778 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002779 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002780 SendMessage(hWnd, WM_SETICON,
2781 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002782 return TRUE;
2783}
2784
2785/*
2786 * SaveConsoleTitleAndIcon()
2787 * Description:
2788 * Saves the current console window title in g_szOrigTitle, for later
2789 * restoration. Also, attempts to obtain a handle to the console window,
2790 * and use it to save the small and big icons currently in use by the
2791 * console window. This is not always possible on some versions of Windows;
2792 * nor is it possible when running Vim remotely using Telnet (since the
2793 * console window the user sees is owned by a remote process).
2794 */
2795 static void
2796SaveConsoleTitleAndIcon(void)
2797{
Bram Moolenaar0f873732019-12-05 20:28:46 +01002798 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002799 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2800 return;
2801
2802 /*
2803 * Obtain a handle to the console window using GetConsoleWindow() from
2804 * KERNEL32.DLL; we need to handle in order to change the window icon.
2805 * This function only exists on NT-based Windows, starting with Windows
2806 * 2000. On older operating systems, we can't change the window icon
2807 * anyway.
2808 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002809 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002810 if (g_hWnd == NULL)
2811 return;
2812
Bram Moolenaar0f873732019-12-05 20:28:46 +01002813 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002814 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2815 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2816 return;
2817
Bram Moolenaar0f873732019-12-05 20:28:46 +01002818 // Extract the first icon contained in the Vim executable.
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002819 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002820 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002821 if (g_hVimIcon != NULL)
2822 g_fCanChangeIcon = TRUE;
2823}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002824
2825static int g_fWindInitCalled = FALSE;
2826static int g_fTermcapMode = FALSE;
2827static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002828
2829/*
2830 * non-GUI version of mch_init().
2831 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002832 static void
2833mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002834{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002835# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002836 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002837# endif
2838# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002839 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002840# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002841
Bram Moolenaar0f873732019-12-05 20:28:46 +01002842 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002843 SET_INVALID_PARAM_HANDLER;
2844
Bram Moolenaar0f873732019-12-05 20:28:46 +01002845 // Let critical errors result in a failure, not in a dialog box. Required
2846 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002847 SetErrorMode(SEM_FAILCRITICALERRORS);
2848
Bram Moolenaar0f873732019-12-05 20:28:46 +01002849 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002850 out_flush();
2851
Bram Moolenaar0f873732019-12-05 20:28:46 +01002852 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00002853 if (read_cmd_fd == 0)
2854 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2855 else
2856 create_conin();
2857 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2858
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002859# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01002860 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002861 SaveConsoleBuffer(&g_cbOrig);
2862 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002863# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01002864 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002865 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2866 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002867# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002868 if (cterm_normal_fg_color == 0)
2869 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2870 if (cterm_normal_bg_color == 0)
2871 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2872
Bram Moolenaarbdace832019-03-02 10:13:42 +01002873 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002874 g_color_index_fg = g_attrDefault & 0xf;
2875 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2876
Bram Moolenaar0f873732019-12-05 20:28:46 +01002877 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00002878 update_tcap(g_attrCurrent);
2879
2880 GetConsoleCursorInfo(g_hConOut, &g_cci);
2881 GetConsoleMode(g_hConIn, &g_cmodein);
2882 GetConsoleMode(g_hConOut, &g_cmodeout);
2883
Bram Moolenaar071d4272004-06-13 20:20:40 +00002884 SaveConsoleTitleAndIcon();
2885 /*
2886 * Set both the small and big icons of the console window to Vim's icon.
2887 * Note that Vim presently only has one size of icon (32x32), but it
2888 * automatically gets scaled down to 16x16 when setting the small icon.
2889 */
2890 if (g_fCanChangeIcon)
2891 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002892
2893 ui_get_shellsize();
2894
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002895# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002896 fdDump = fopen("dump", "wt");
2897
2898 if (fdDump)
2899 {
2900 time_t t;
2901
2902 time(&t);
2903 fputs(ctime(&t), fdDump);
2904 fflush(fdDump);
2905 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002906# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002907
2908 g_fWindInitCalled = TRUE;
2909
Bram Moolenaar071d4272004-06-13 20:20:40 +00002910 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002911
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002912# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002913 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002914# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002915
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02002916 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002917 vtp_init();
Bram Moolenaar06b7b582020-05-30 17:49:25 +02002918 wt_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002919}
2920
2921/*
2922 * non-GUI version of mch_exit().
2923 * Shut down and exit with status `r'
2924 * Careful: mch_exit() may be called before mch_init()!
2925 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002926 static void
2927mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002928{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002929 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002930
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002931 vtp_exit();
2932
Bram Moolenaar955f1982017-02-05 15:10:51 +01002933 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002934 if (g_fWindInitCalled)
2935 settmode(TMODE_COOK);
2936
Bram Moolenaar0f873732019-12-05 20:28:46 +01002937 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00002938
2939 if (g_fWindInitCalled)
2940 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02002941 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002942 /*
2943 * Restore both the small and big icons of the console window to
2944 * what they were at startup. Don't do this when the window is
2945 * closed, Vim would hang here.
2946 */
2947 if (g_fCanChangeIcon && !g_fForceExit)
2948 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002949
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002950# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002951 if (fdDump)
2952 {
2953 time_t t;
2954
2955 time(&t);
2956 fputs(ctime(&t), fdDump);
2957 fclose(fdDump);
2958 }
2959 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002960# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002961 }
2962
2963 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02002964 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002965 SetConsoleMode(g_hConOut, g_cmodeout);
2966
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002967# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00002968 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002969# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002970
2971 exit(r);
2972}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002973#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002974
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002975 void
2976mch_init(void)
2977{
2978#ifdef VIMDLL
2979 if (gui.starting)
2980 mch_init_g();
2981 else
2982 mch_init_c();
2983#elif defined(FEAT_GUI_MSWIN)
2984 mch_init_g();
2985#else
2986 mch_init_c();
2987#endif
2988}
2989
2990 void
2991mch_exit(int r)
2992{
Bram Moolenaar173d8412020-04-19 14:02:26 +02002993#ifdef FEAT_NETBEANS_INTG
2994 netbeans_send_disconnect();
2995#endif
2996
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002997#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02002998 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002999 mch_exit_g(r);
3000 else
3001 mch_exit_c(r);
3002#elif defined(FEAT_GUI_MSWIN)
3003 mch_exit_g(r);
3004#else
3005 mch_exit_c(r);
3006#endif
3007}
3008
Bram Moolenaar071d4272004-06-13 20:20:40 +00003009/*
3010 * Do we have an interactive window?
3011 */
3012 int
3013mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003014 int argc UNUSED,
3015 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003016{
3017 get_exe_name();
3018
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003019#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003020 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003021#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003022# ifdef VIMDLL
3023 if (gui.in_use)
3024 return OK;
3025# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003026 if (isatty(1))
3027 return OK;
3028 return FAIL;
3029#endif
3030}
3031
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003032/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003033 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003034 * When "len" is > 0, also expand short to long filenames.
3035 */
3036 void
3037fname_case(
3038 char_u *name,
3039 int len)
3040{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003041 int flen;
3042 WCHAR *p;
3043 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003044
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003045 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003046 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003047 return;
3048
3049 slash_adjust(name);
3050
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003051 p = enc_to_utf16(name, NULL);
3052 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003053 return;
3054
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003055 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003056 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003057 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003058
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003059 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003060 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003061 if (len > 0 || flen >= (int)STRLEN(q))
3062 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3063 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003064 }
3065 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003066 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003067}
3068
3069
3070/*
3071 * Insert user name in s[len].
3072 */
3073 int
3074mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003075 char_u *s,
3076 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003077{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003078 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003079 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003080
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003081 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003082 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003083 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003084
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003085 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003086 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003087 vim_strncpy(s, p, len - 1);
3088 vim_free(p);
3089 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003090 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003091 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003092 s[0] = NUL;
3093 return FAIL;
3094}
3095
3096
3097/*
3098 * Insert host name in s[len].
3099 */
3100 void
3101mch_get_host_name(
3102 char_u *s,
3103 int len)
3104{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003105 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003106 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003107
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003108 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003109 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003110 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003111
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003112 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003113 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003114 vim_strncpy(s, p, len - 1);
3115 vim_free(p);
3116 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003117 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003118 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003119}
3120
3121
3122/*
3123 * return process ID
3124 */
3125 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003126mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003127{
3128 return (long)GetCurrentProcessId();
3129}
3130
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003131/*
3132 * return TRUE if process "pid" is still running
3133 */
3134 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003135mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003136{
3137 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3138 DWORD status = 0;
3139 int ret = FALSE;
3140
3141 if (hProcess == NULL)
3142 return FALSE; // might not have access
3143 if (GetExitCodeProcess(hProcess, &status) )
3144 ret = status == STILL_ACTIVE;
3145 CloseHandle(hProcess);
3146 return ret;
3147}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003148
3149/*
3150 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3151 * Return OK for success, FAIL for failure.
3152 */
3153 int
3154mch_dirname(
3155 char_u *buf,
3156 int len)
3157{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003158 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003159
Bram Moolenaar071d4272004-06-13 20:20:40 +00003160 /*
3161 * Originally this was:
3162 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3163 * But the Win32s known bug list says that getcwd() doesn't work
3164 * so use the Win32 system call instead. <Negri>
3165 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003166 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003167 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003168 WCHAR wcbuf[_MAX_PATH + 1];
3169 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003170
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003171 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003172 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003173 p = utf16_to_enc(wcbuf, NULL);
3174 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003175 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003176 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003177 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003178 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003179 }
3180 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003181 if (p == NULL)
3182 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003183
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003184 if (p != NULL)
3185 {
3186 vim_strncpy(buf, p, len - 1);
3187 vim_free(p);
3188 return OK;
3189 }
3190 }
3191 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003192}
3193
3194/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003195 * Get file permissions for "name".
3196 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003197 */
3198 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003199mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003200{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003201 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003202 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003203
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003204 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003205 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003206}
3207
3208
3209/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003210 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003211 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003212 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003213 */
3214 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003215mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003216{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003217 long n;
3218 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003219
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003220 p = enc_to_utf16(name, NULL);
3221 if (p == NULL)
3222 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003223
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003224 n = _wchmod(p, perm);
3225 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003226 if (n == -1)
3227 return FAIL;
3228
3229 win32_set_archive(name);
3230
3231 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003232}
3233
3234/*
3235 * Set hidden flag for "name".
3236 */
3237 void
3238mch_hide(char_u *name)
3239{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003240 int attrs = win32_getattrs(name);
3241 if (attrs == -1)
3242 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003243
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003244 attrs |= FILE_ATTRIBUTE_HIDDEN;
3245 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003246}
3247
3248/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003249 * Return TRUE if file "name" exists and is hidden.
3250 */
3251 int
3252mch_ishidden(char_u *name)
3253{
3254 int f = win32_getattrs(name);
3255
3256 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003257 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003258
3259 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3260}
3261
3262/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003263 * return TRUE if "name" is a directory
3264 * return FALSE if "name" is not a directory or upon error
3265 */
3266 int
3267mch_isdir(char_u *name)
3268{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003269 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003270
3271 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003272 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003273
3274 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3275}
3276
3277/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003278 * return TRUE if "name" is a directory, NOT a symlink to a directory
3279 * return FALSE if "name" is not a directory
3280 * return FALSE for error
3281 */
3282 int
3283mch_isrealdir(char_u *name)
3284{
3285 return mch_isdir(name) && !mch_is_symbolic_link(name);
3286}
3287
3288/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003289 * Create directory "name".
3290 * Return 0 on success, -1 on error.
3291 */
3292 int
3293mch_mkdir(char_u *name)
3294{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003295 WCHAR *p;
3296 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003297
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003298 p = enc_to_utf16(name, NULL);
3299 if (p == NULL)
3300 return -1;
3301 retval = _wmkdir(p);
3302 vim_free(p);
3303 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003304}
3305
3306/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003307 * Delete directory "name".
3308 * Return 0 on success, -1 on error.
3309 */
3310 int
3311mch_rmdir(char_u *name)
3312{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003313 WCHAR *p;
3314 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003315
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003316 p = enc_to_utf16(name, NULL);
3317 if (p == NULL)
3318 return -1;
3319 retval = _wrmdir(p);
3320 vim_free(p);
3321 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003322}
3323
3324/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003325 * Return TRUE if file "fname" has more than one link.
3326 */
3327 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003328mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003329{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003330 BY_HANDLE_FILE_INFORMATION info;
3331
3332 return win32_fileinfo(fname, &info) == FILEINFO_OK
3333 && info.nNumberOfLinks > 1;
3334}
3335
3336/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003337 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003338 */
3339 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003340mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003341{
3342 HANDLE hFind;
3343 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003344 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003345 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003346 WIN32_FIND_DATAW findDataW;
3347
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003348 wn = enc_to_utf16(name, NULL);
3349 if (wn == NULL)
3350 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003351
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003352 hFind = FindFirstFileW(wn, &findDataW);
3353 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003354 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003355 {
3356 fileFlags = findDataW.dwFileAttributes;
3357 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003358 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003359 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003360
3361 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003362 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3363 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003364 res = TRUE;
3365
3366 return res;
3367}
3368
3369/*
3370 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3371 * link.
3372 */
3373 int
3374mch_is_linked(char_u *fname)
3375{
3376 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3377 return TRUE;
3378 return FALSE;
3379}
3380
3381/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003382 * Get the by-handle-file-information for "fname".
3383 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003384 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003385 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3386 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3387 */
3388 int
3389win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3390{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003391 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003392 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003393 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003394
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003395 wn = enc_to_utf16(fname, NULL);
3396 if (wn == NULL)
3397 return FILEINFO_ENC_FAIL;
3398
3399 hFile = CreateFileW(wn, // file name
3400 GENERIC_READ, // access mode
3401 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3402 NULL, // security descriptor
3403 OPEN_EXISTING, // creation disposition
3404 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3405 NULL); // handle to template file
3406 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003407
3408 if (hFile != INVALID_HANDLE_VALUE)
3409 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003410 if (GetFileInformationByHandle(hFile, info) != 0)
3411 res = FILEINFO_OK;
3412 else
3413 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003414 CloseHandle(hFile);
3415 }
3416
Bram Moolenaar03f48552006-02-28 23:52:23 +00003417 return res;
3418}
3419
3420/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003421 * get file attributes for `name'
3422 * -1 : error
3423 * else FILE_ATTRIBUTE_* defined in winnt.h
3424 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003425 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003426win32_getattrs(char_u *name)
3427{
3428 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003429 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003430
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003431 p = enc_to_utf16(name, NULL);
3432 if (p == NULL)
3433 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003434
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003435 attr = GetFileAttributesW(p);
3436 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003437
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003438 return attr;
3439}
3440
3441/*
3442 * set file attributes for `name' to `attrs'
3443 *
3444 * return -1 for failure, 0 otherwise
3445 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003446 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003447win32_setattrs(char_u *name, int attrs)
3448{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003449 int res;
3450 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003451
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003452 p = enc_to_utf16(name, NULL);
3453 if (p == NULL)
3454 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003455
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003456 res = SetFileAttributesW(p, attrs);
3457 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003458
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003459 return res ? 0 : -1;
3460}
3461
3462/*
3463 * Set archive flag for "name".
3464 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003465 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003466win32_set_archive(char_u *name)
3467{
3468 int attrs = win32_getattrs(name);
3469 if (attrs == -1)
3470 return -1;
3471
3472 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3473 return win32_setattrs(name, attrs);
3474}
3475
3476/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003477 * Return TRUE if file or directory "name" is writable (not readonly).
3478 * Strange semantics of Win32: a readonly directory is writable, but you can't
3479 * delete a file. Let's say this means it is writable.
3480 */
3481 int
3482mch_writable(char_u *name)
3483{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003484 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003485
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003486 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3487 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003488}
3489
Bram Moolenaar071d4272004-06-13 20:20:40 +00003490/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003491 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003492 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003493 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3494 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003495 */
3496 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003497mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003498{
Bram Moolenaar95da1362020-05-30 18:37:55 +02003499 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003500}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003501
3502/*
3503 * Check what "name" is:
3504 * NODE_NORMAL: file or directory (or doesn't exist)
3505 * NODE_WRITABLE: writable device, socket, fifo, etc.
3506 * NODE_OTHER: non-writable things
3507 */
3508 int
3509mch_nodetype(char_u *name)
3510{
3511 HANDLE hFile;
3512 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003513 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003514
Bram Moolenaar0f873732019-12-05 20:28:46 +01003515 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3516 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3517 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00003518 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3519 return NODE_WRITABLE;
3520
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003521 wn = enc_to_utf16(name, NULL);
3522 if (wn == NULL)
3523 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003524
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003525 hFile = CreateFileW(wn, // file name
3526 GENERIC_WRITE, // access mode
3527 0, // share mode
3528 NULL, // security descriptor
3529 OPEN_EXISTING, // creation disposition
3530 0, // file attributes
3531 NULL); // handle to template file
3532 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003533 if (hFile == INVALID_HANDLE_VALUE)
3534 return NODE_NORMAL;
3535
3536 type = GetFileType(hFile);
3537 CloseHandle(hFile);
3538 if (type == FILE_TYPE_CHAR)
3539 return NODE_WRITABLE;
3540 if (type == FILE_TYPE_DISK)
3541 return NODE_NORMAL;
3542 return NODE_OTHER;
3543}
3544
3545#ifdef HAVE_ACL
3546struct my_acl
3547{
3548 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3549 PSID pSidOwner;
3550 PSID pSidGroup;
3551 PACL pDacl;
3552 PACL pSacl;
3553};
3554#endif
3555
3556/*
3557 * Return a pointer to the ACL of file "fname" in allocated memory.
3558 * Return NULL if the ACL is not available for whatever reason.
3559 */
3560 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003561mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003562{
3563#ifndef HAVE_ACL
3564 return (vim_acl_T)NULL;
3565#else
3566 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003567 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003568
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003569 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003570 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003571 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003572 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003573
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003574 wn = enc_to_utf16(fname, NULL);
3575 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003576 {
3577 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003578 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003579 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003580
3581 // Try to retrieve the entire security descriptor.
3582 err = GetNamedSecurityInfoW(
3583 wn, // Abstract filename
3584 SE_FILE_OBJECT, // File Object
3585 OWNER_SECURITY_INFORMATION |
3586 GROUP_SECURITY_INFORMATION |
3587 DACL_SECURITY_INFORMATION |
3588 SACL_SECURITY_INFORMATION,
3589 &p->pSidOwner, // Ownership information.
3590 &p->pSidGroup, // Group membership.
3591 &p->pDacl, // Discretionary information.
3592 &p->pSacl, // For auditing purposes.
3593 &p->pSecurityDescriptor);
3594 if (err == ERROR_ACCESS_DENIED ||
3595 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003596 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003597 // Retrieve only DACL.
3598 (void)GetNamedSecurityInfoW(
3599 wn,
3600 SE_FILE_OBJECT,
3601 DACL_SECURITY_INFORMATION,
3602 NULL,
3603 NULL,
3604 &p->pDacl,
3605 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003606 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003607 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003608 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003609 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003610 mch_free_acl((vim_acl_T)p);
3611 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003612 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003613 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003614 }
3615
3616 return (vim_acl_T)p;
3617#endif
3618}
3619
Bram Moolenaar27515922013-06-29 15:36:26 +02003620#ifdef HAVE_ACL
3621/*
3622 * Check if "acl" contains inherited ACE.
3623 */
3624 static BOOL
3625is_acl_inherited(PACL acl)
3626{
3627 DWORD i;
3628 ACL_SIZE_INFORMATION acl_info;
3629 PACCESS_ALLOWED_ACE ace;
3630
3631 acl_info.AceCount = 0;
3632 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3633 for (i = 0; i < acl_info.AceCount; i++)
3634 {
3635 GetAce(acl, i, (LPVOID *)&ace);
3636 if (ace->Header.AceFlags & INHERITED_ACE)
3637 return TRUE;
3638 }
3639 return FALSE;
3640}
3641#endif
3642
Bram Moolenaar071d4272004-06-13 20:20:40 +00003643/*
3644 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3645 * Errors are ignored.
3646 * This must only be called with "acl" equal to what mch_get_acl() returned.
3647 */
3648 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003649mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003650{
3651#ifdef HAVE_ACL
3652 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003653 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003654 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003655
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003656 if (p == NULL)
3657 return;
3658
3659 wn = enc_to_utf16(fname, NULL);
3660 if (wn == NULL)
3661 return;
3662
3663 // Set security flags
3664 if (p->pSidOwner)
3665 sec_info |= OWNER_SECURITY_INFORMATION;
3666 if (p->pSidGroup)
3667 sec_info |= GROUP_SECURITY_INFORMATION;
3668 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003669 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003670 sec_info |= DACL_SECURITY_INFORMATION;
3671 // Do not inherit its parent's DACL.
3672 // If the DACL is inherited, Cygwin permissions would be changed.
3673 if (!is_acl_inherited(p->pDacl))
3674 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003675 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003676 if (p->pSacl)
3677 sec_info |= SACL_SECURITY_INFORMATION;
3678
3679 (void)SetNamedSecurityInfoW(
3680 wn, // Abstract filename
3681 SE_FILE_OBJECT, // File Object
3682 sec_info,
3683 p->pSidOwner, // Ownership information.
3684 p->pSidGroup, // Group membership.
3685 p->pDacl, // Discretionary information.
3686 p->pSacl // For auditing purposes.
3687 );
3688 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003689#endif
3690}
3691
3692 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003693mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003694{
3695#ifdef HAVE_ACL
3696 struct my_acl *p = (struct my_acl *)acl;
3697
3698 if (p != NULL)
3699 {
3700 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3701 vim_free(p);
3702 }
3703#endif
3704}
3705
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003706#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003707
3708/*
3709 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3710 */
3711 static BOOL WINAPI
3712handler_routine(
3713 DWORD dwCtrlType)
3714{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003715 INPUT_RECORD ir;
3716 DWORD out;
3717
Bram Moolenaar071d4272004-06-13 20:20:40 +00003718 switch (dwCtrlType)
3719 {
3720 case CTRL_C_EVENT:
3721 if (ctrl_c_interrupts)
3722 g_fCtrlCPressed = TRUE;
3723 return TRUE;
3724
3725 case CTRL_BREAK_EVENT:
3726 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003727 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003728 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02003729 ir.EventType = KEY_EVENT;
3730 ir.Event.KeyEvent.bKeyDown = TRUE;
3731 ir.Event.KeyEvent.wRepeatCount = 1;
3732 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3733 ir.Event.KeyEvent.wVirtualScanCode = 0;
3734 ir.Event.KeyEvent.dwControlKeyState = 0;
3735 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3736 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003737 return TRUE;
3738
Bram Moolenaar0f873732019-12-05 20:28:46 +01003739 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00003740 case CTRL_CLOSE_EVENT:
3741 case CTRL_LOGOFF_EVENT:
3742 case CTRL_SHUTDOWN_EVENT:
3743 windgoto((int)Rows - 1, 0);
3744 g_fForceExit = TRUE;
3745
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003746 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003747 (dwCtrlType == CTRL_CLOSE_EVENT
3748 ? _("close")
3749 : dwCtrlType == CTRL_LOGOFF_EVENT
3750 ? _("logoff")
3751 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003752# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00003753 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003754# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003755
Bram Moolenaar0f873732019-12-05 20:28:46 +01003756 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00003757
Bram Moolenaar0f873732019-12-05 20:28:46 +01003758 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00003759
3760 default:
3761 return FALSE;
3762 }
3763}
3764
3765
3766/*
3767 * set the tty in (raw) ? "raw" : "cooked" mode
3768 */
3769 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02003770mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003771{
3772 DWORD cmodein;
3773 DWORD cmodeout;
3774 BOOL bEnableHandler;
3775
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003776# ifdef VIMDLL
3777 if (gui.in_use)
3778 return;
3779# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003780 GetConsoleMode(g_hConIn, &cmodein);
3781 GetConsoleMode(g_hConOut, &cmodeout);
3782 if (tmode == TMODE_RAW)
3783 {
3784 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3785 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003786 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003787 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003788 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003789 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
3790 }
3791 else
3792 {
3793 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
3794 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003795 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003796# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01003797 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
3798 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003799 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003800# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003801 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003802# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003803 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003804 bEnableHandler = TRUE;
3805 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01003806 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00003807 {
3808 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3809 ENABLE_ECHO_INPUT);
3810 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3811 bEnableHandler = FALSE;
3812 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003813 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003814 SetConsoleMode(g_hConOut, cmodeout);
3815 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3816
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003817# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003818 if (fdDump)
3819 {
3820 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3821 tmode == TMODE_RAW ? "raw" :
3822 tmode == TMODE_COOK ? "cooked" : "normal",
3823 cmodein, cmodeout);
3824 fflush(fdDump);
3825 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003826# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003827}
3828
3829
3830/*
3831 * Get the size of the current window in `Rows' and `Columns'
3832 * Return OK when size could be determined, FAIL otherwise.
3833 */
3834 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003835mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003836{
3837 CONSOLE_SCREEN_BUFFER_INFO csbi;
3838
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003839# ifdef VIMDLL
3840 if (gui.in_use)
3841 return OK;
3842# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003843 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3844 {
3845 /*
3846 * For some reason, we are trying to get the screen dimensions
3847 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3848 * variables are really intended to mean the size of Vim screen
3849 * while in termcap mode.
3850 */
3851 Rows = g_cbTermcap.Info.dwSize.Y;
3852 Columns = g_cbTermcap.Info.dwSize.X;
3853 }
3854 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3855 {
3856 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3857 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3858 }
3859 else
3860 {
3861 Rows = 25;
3862 Columns = 80;
3863 }
3864 return OK;
3865}
3866
3867/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003868 * Resize console buffer to 'COORD'
3869 */
3870 static void
3871ResizeConBuf(
3872 HANDLE hConsole,
3873 COORD coordScreen)
3874{
3875 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3876 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003877# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003878 if (fdDump)
3879 {
3880 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3881 GetLastError());
3882 fflush(fdDump);
3883 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003884# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003885 }
3886}
3887
3888/*
3889 * Resize console window size to 'srWindowRect'
3890 */
3891 static void
3892ResizeWindow(
3893 HANDLE hConsole,
3894 SMALL_RECT srWindowRect)
3895{
3896 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
3897 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003898# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003899 if (fdDump)
3900 {
3901 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3902 GetLastError());
3903 fflush(fdDump);
3904 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003905# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003906 }
3907}
3908
3909/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003910 * Set a console window to `xSize' * `ySize'
3911 */
3912 static void
3913ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003914 HANDLE hConsole,
3915 int xSize,
3916 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003917{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003918 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
3919 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003920 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003921 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02003922 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003923
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003924# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003925 if (fdDump)
3926 {
3927 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3928 fflush(fdDump);
3929 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003930# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003931
Bram Moolenaar0f873732019-12-05 20:28:46 +01003932 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00003933 coordScreen = GetLargestConsoleWindowSize(hConsole);
3934
Bram Moolenaar0f873732019-12-05 20:28:46 +01003935 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00003936 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3937 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3938 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3939
3940 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3941 {
3942 int sx, sy;
3943
3944 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3945 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3946 if (sy < ySize || sx < xSize)
3947 {
3948 /*
3949 * Increasing number of lines/columns, do buffer first.
3950 * Use the maximal size in x and y direction.
3951 */
3952 if (sy < ySize)
3953 coordScreen.Y = ySize;
3954 else
3955 coordScreen.Y = sy;
3956 if (sx < xSize)
3957 coordScreen.X = xSize;
3958 else
3959 coordScreen.X = sx;
3960 SetConsoleScreenBufferSize(hConsole, coordScreen);
3961 }
3962 }
3963
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003964 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003965 coordScreen.X = xSize;
3966 coordScreen.Y = ySize;
3967
Bram Moolenaar2551c032018-08-23 22:38:31 +02003968 // In the new console call API, only the first time in reverse order
3969 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003970 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003971 ResizeWindow(hConsole, srWindowRect);
3972 ResizeConBuf(hConsole, coordScreen);
3973 }
3974 else
3975 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003976 // Workaround for a Windows 10 bug
3977 cursor.X = srWindowRect.Left;
3978 cursor.Y = srWindowRect.Top;
3979 SetConsoleCursorPosition(hConsole, cursor);
3980
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003981 ResizeConBuf(hConsole, coordScreen);
3982 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02003983 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003984 }
3985}
3986
3987
3988/*
3989 * Set the console window to `Rows' * `Columns'
3990 */
3991 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003992mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003993{
3994 COORD coordScreen;
3995
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003996# ifdef VIMDLL
3997 if (gui.in_use)
3998 return;
3999# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004000 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004001 if (suppress_winsize != 0)
4002 {
4003 suppress_winsize = 2;
4004 return;
4005 }
4006
4007 if (term_console)
4008 {
4009 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4010
Bram Moolenaar0f873732019-12-05 20:28:46 +01004011 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004012 if (Rows > coordScreen.Y)
4013 Rows = coordScreen.Y;
4014 if (Columns > coordScreen.X)
4015 Columns = coordScreen.X;
4016
4017 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4018 }
4019}
4020
4021/*
4022 * Rows and/or Columns has changed.
4023 */
4024 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004025mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004026{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004027# ifdef VIMDLL
4028 if (gui.in_use)
4029 return;
4030# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004031 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4032}
4033
4034
4035/*
4036 * Called when started up, to set the winsize that was delayed.
4037 */
4038 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004039mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004040{
4041 if (suppress_winsize == 2)
4042 {
4043 suppress_winsize = 0;
4044 mch_set_shellsize();
4045 shell_resized();
4046 }
4047 suppress_winsize = 0;
4048}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004049#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004050
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004051 static BOOL
4052vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004053 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004054 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004055 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004056 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004057 PROCESS_INFORMATION *pi,
4058 LPVOID *env,
4059 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004060{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004061 BOOL ret = FALSE;
4062 WCHAR *wcmd, *wcwd = NULL;
4063
4064 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4065 if (wcmd == NULL)
4066 return FALSE;
4067 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004068 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004069 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4070 if (wcwd == NULL)
4071 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004072 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004073
4074 ret = CreateProcessW(
4075 NULL, // Executable name
4076 wcmd, // Command to execute
4077 NULL, // Process security attributes
4078 NULL, // Thread security attributes
4079 inherit_handles, // Inherit handles
4080 flags, // Creation flags
4081 env, // Environment
4082 wcwd, // Current directory
4083 (LPSTARTUPINFOW)si, // Startup information
4084 pi); // Process information
4085theend:
4086 vim_free(wcmd);
4087 vim_free(wcwd);
4088 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004089}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004090
4091
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004092 static HINSTANCE
4093vim_shell_execute(
4094 char *cmd,
4095 INT n_show_cmd)
4096{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004097 HINSTANCE ret;
4098 WCHAR *wcmd;
4099
4100 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4101 if (wcmd == NULL)
4102 return (HINSTANCE) 0;
4103
4104 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4105 vim_free(wcmd);
4106 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004107}
4108
4109
Bram Moolenaar4f974752019-02-17 17:44:42 +01004110#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004111
4112/*
4113 * Specialised version of system() for Win32 GUI mode.
4114 * This version proceeds as follows:
4115 * 1. Create a console window for use by the subprocess
4116 * 2. Run the subprocess (it gets the allocated console by default)
4117 * 3. Wait for the subprocess to terminate and get its exit code
4118 * 4. Prompt the user to press a key to close the console window
4119 */
4120 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004121mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004122{
4123 STARTUPINFO si;
4124 PROCESS_INFORMATION pi;
4125 DWORD ret = 0;
4126 HWND hwnd = GetFocus();
4127
4128 si.cb = sizeof(si);
4129 si.lpReserved = NULL;
4130 si.lpDesktop = NULL;
4131 si.lpTitle = NULL;
4132 si.dwFlags = STARTF_USESHOWWINDOW;
4133 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004134 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004135 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004136 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004137 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004138 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004139 else
4140 si.wShowWindow = SW_SHOWNORMAL;
4141 si.cbReserved2 = 0;
4142 si.lpReserved2 = NULL;
4143
Bram Moolenaar0f873732019-12-05 20:28:46 +01004144 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004145 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004146 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4147 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004148
Bram Moolenaar0f873732019-12-05 20:28:46 +01004149 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004150 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004151# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004152 int delay = 1;
4153
Bram Moolenaar0f873732019-12-05 20:28:46 +01004154 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004155 for (;;)
4156 {
4157 MSG msg;
4158
K.Takatab7057bd2022-01-21 11:37:07 +00004159 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004160 {
4161 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004162 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004163 delay = 1;
4164 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004165 }
4166 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4167 break;
4168
Bram Moolenaar0f873732019-12-05 20:28:46 +01004169 // We start waiting for a very short time and then increase it, so
4170 // that we respond quickly when the process is quick, and don't
4171 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004172 if (delay < 50)
4173 delay += 10;
4174 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004175# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004176 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004177# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004178
Bram Moolenaar0f873732019-12-05 20:28:46 +01004179 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004180 GetExitCodeProcess(pi.hProcess, &ret);
4181 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004182
Bram Moolenaar0f873732019-12-05 20:28:46 +01004183 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004184 CloseHandle(pi.hThread);
4185 CloseHandle(pi.hProcess);
4186
Bram Moolenaar0f873732019-12-05 20:28:46 +01004187 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004188 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4189
4190 return ret;
4191}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004192
4193/*
4194 * Thread launched by the gui to send the current buffer data to the
4195 * process. This way avoid to hang up vim totally if the children
4196 * process take a long time to process the lines.
4197 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004198 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004199sub_process_writer(LPVOID param)
4200{
4201 HANDLE g_hChildStd_IN_Wr = param;
4202 linenr_T lnum = curbuf->b_op_start.lnum;
4203 DWORD len = 0;
4204 DWORD l;
4205 char_u *lp = ml_get(lnum);
4206 char_u *s;
4207 int written = 0;
4208
4209 for (;;)
4210 {
4211 l = (DWORD)STRLEN(lp + written);
4212 if (l == 0)
4213 len = 0;
4214 else if (lp[written] == NL)
4215 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004216 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004217 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4218 }
4219 else
4220 {
4221 s = vim_strchr(lp + written, NL);
4222 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4223 s == NULL ? l : (DWORD)(s - (lp + written)),
4224 &len, NULL);
4225 }
4226 if (len == (int)l)
4227 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004228 // Finished a line, add a NL, unless this line should not have
4229 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004230 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004231 || (!curbuf->b_p_bin
4232 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004233 || (lnum != curbuf->b_no_eol_lnum
4234 && (lnum != curbuf->b_ml.ml_line_count
4235 || curbuf->b_p_eol)))
4236 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004237 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4238 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004239 }
4240
4241 ++lnum;
4242 if (lnum > curbuf->b_op_end.lnum)
4243 break;
4244
4245 lp = ml_get(lnum);
4246 written = 0;
4247 }
4248 else if (len > 0)
4249 written += len;
4250 }
4251
Bram Moolenaar0f873732019-12-05 20:28:46 +01004252 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004253 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004254 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004255}
4256
4257
Bram Moolenaar0f873732019-12-05 20:28:46 +01004258# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004259
4260/*
4261 * This function read from the children's stdout and write the
4262 * data on screen or in the buffer accordingly.
4263 */
4264 static void
4265dump_pipe(int options,
4266 HANDLE g_hChildStd_OUT_Rd,
4267 garray_T *ga,
4268 char_u buffer[],
4269 DWORD *buffer_off)
4270{
4271 DWORD availableBytes = 0;
4272 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004273 int ret;
4274 DWORD len;
4275 DWORD toRead;
4276 int repeatCount;
4277
Bram Moolenaar0f873732019-12-05 20:28:46 +01004278 // we query the pipe to see if there is any data to read
4279 // to avoid to perform a blocking read
4280 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4281 NULL, // optional buffer
4282 0, // buffer size
4283 NULL, // number of read bytes
4284 &availableBytes, // available bytes total
4285 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004286
4287 repeatCount = 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004288 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004289 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004290 {
4291 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004292 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004293 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004294 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004295
Bram Moolenaar0f873732019-12-05 20:28:46 +01004296 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004297 if (len == 0)
4298 break;
4299
4300 availableBytes -= len;
4301
4302 if (options & SHELL_READ)
4303 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004304 // Do NUL -> NL translation, append NL separated
4305 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004306 for (i = 0; i < len; ++i)
4307 {
4308 if (buffer[i] == NL)
4309 append_ga_line(ga);
4310 else if (buffer[i] == NUL)
4311 ga_append(ga, NL);
4312 else
4313 ga_append(ga, buffer[i]);
4314 }
4315 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004316 else if (has_mbyte)
4317 {
4318 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004319 int c;
4320 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004321
4322 len += *buffer_off;
4323 buffer[len] = NUL;
4324
Bram Moolenaar0f873732019-12-05 20:28:46 +01004325 // Check if the last character in buffer[] is
4326 // incomplete, keep these bytes for the next
4327 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004328 for (p = buffer; p < buffer + len; p += l)
4329 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004330 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004331 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004332 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004333 else if (MB_BYTE2LEN(*p) != l)
4334 break;
4335 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004336 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004337 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004338 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004339 if (len >= 12)
4340 ++p;
4341 else
4342 {
4343 *buffer_off = len;
4344 return;
4345 }
4346 }
4347 c = *p;
4348 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004349 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004350 if (p < buffer + len)
4351 {
4352 *p = c;
4353 *buffer_off = (DWORD)((buffer + len) - p);
4354 mch_memmove(buffer, p, *buffer_off);
4355 return;
4356 }
4357 *buffer_off = 0;
4358 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004359 else
4360 {
4361 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004362 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004363 }
4364
4365 windgoto(msg_row, msg_col);
4366 cursor_on();
4367 out_flush();
4368 }
4369}
4370
4371/*
4372 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4373 * for communication and doesn't open any new window.
4374 */
4375 static int
4376mch_system_piped(char *cmd, int options)
4377{
4378 STARTUPINFO si;
4379 PROCESS_INFORMATION pi;
4380 DWORD ret = 0;
4381
4382 HANDLE g_hChildStd_IN_Rd = NULL;
4383 HANDLE g_hChildStd_IN_Wr = NULL;
4384 HANDLE g_hChildStd_OUT_Rd = NULL;
4385 HANDLE g_hChildStd_OUT_Wr = NULL;
4386
Bram Moolenaar0f873732019-12-05 20:28:46 +01004387 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004388 DWORD len;
4389
Bram Moolenaar0f873732019-12-05 20:28:46 +01004390 // buffer used to receive keys
4391 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4392 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004393
4394 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004395 int noread_cnt = 0;
4396 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004397 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004398 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004399 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004400
4401 SECURITY_ATTRIBUTES saAttr;
4402
Bram Moolenaar0f873732019-12-05 20:28:46 +01004403 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004404 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4405 saAttr.bInheritHandle = TRUE;
4406 saAttr.lpSecurityDescriptor = NULL;
4407
4408 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004409 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004410 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004411 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004412 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004413 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004414 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004415 {
4416 CloseHandle(g_hChildStd_IN_Rd);
4417 CloseHandle(g_hChildStd_IN_Wr);
4418 CloseHandle(g_hChildStd_OUT_Rd);
4419 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004420 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004421 }
4422
4423 si.cb = sizeof(si);
4424 si.lpReserved = NULL;
4425 si.lpDesktop = NULL;
4426 si.lpTitle = NULL;
4427 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4428
Bram Moolenaar0f873732019-12-05 20:28:46 +01004429 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004430 si.hStdError = g_hChildStd_OUT_Wr;
4431 si.hStdOutput = g_hChildStd_OUT_Wr;
4432 si.hStdInput = g_hChildStd_IN_Rd;
4433 si.wShowWindow = SW_HIDE;
4434 si.cbReserved2 = 0;
4435 si.lpReserved2 = NULL;
4436
4437 if (options & SHELL_READ)
4438 ga_init2(&ga, 1, BUFLEN);
4439
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004440 if (cmd != NULL)
4441 {
4442 p = (char *)vim_strsave((char_u *)cmd);
4443 if (p != NULL)
4444 unescape_shellxquote((char_u *)p, p_sxe);
4445 else
4446 p = cmd;
4447 }
4448
Bram Moolenaar0f873732019-12-05 20:28:46 +01004449 // Now, run the command.
4450 // About "Inherit handles" being TRUE: this command can be litigious,
4451 // handle inheritance was deactivated for pending temp file, but, if we
4452 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004453 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4454 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004455
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004456 if (p != cmd)
4457 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004458
Bram Moolenaar0f873732019-12-05 20:28:46 +01004459 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004460 CloseHandle(g_hChildStd_IN_Rd);
4461 CloseHandle(g_hChildStd_OUT_Wr);
4462
4463 if (options & SHELL_WRITE)
4464 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004465 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004466 _beginthreadex(NULL, // security attributes
4467 0, // default stack size
4468 sub_process_writer, // function to be executed
4469 g_hChildStd_IN_Wr, // parameter
4470 0, // creation flag, start immediately
4471 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004472 CloseHandle(thread);
4473 g_hChildStd_IN_Wr = NULL;
4474 }
4475
Bram Moolenaar0f873732019-12-05 20:28:46 +01004476 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004477 for (;;)
4478 {
4479 MSG msg;
4480
K.Takatab7057bd2022-01-21 11:37:07 +00004481 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004482 {
4483 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004484 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004485 }
4486
Bram Moolenaar0f873732019-12-05 20:28:46 +01004487 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004488 if ((options & (SHELL_READ|SHELL_WRITE))
4489# ifdef FEAT_GUI
4490 || gui.in_use
4491# endif
4492 )
4493 {
4494 len = 0;
4495 if (!(options & SHELL_EXPAND)
4496 && ((options &
4497 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4498 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4499# ifdef FEAT_GUI
4500 || gui.in_use
4501# endif
4502 )
4503 && (ta_len > 0 || noread_cnt > 4))
4504 {
4505 if (ta_len == 0)
4506 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004507 // Get extra characters when we don't have any. Reset the
4508 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004509 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004510 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4511 }
4512 if (ta_len > 0 || len > 0)
4513 {
4514 /*
4515 * For pipes: Check for CTRL-C: send interrupt signal to
4516 * child. Check for CTRL-D: EOF, close pipe to child.
4517 */
4518 if (len == 1 && cmd != NULL)
4519 {
4520 if (ta_buf[ta_len] == Ctrl_C)
4521 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004522 // Learn what exit code is expected, for
4523 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004524 TerminateProcess(pi.hProcess, 9);
4525 }
4526 if (ta_buf[ta_len] == Ctrl_D)
4527 {
4528 CloseHandle(g_hChildStd_IN_Wr);
4529 g_hChildStd_IN_Wr = NULL;
4530 }
4531 }
4532
Bram Moolenaarf4140482020-02-15 23:06:45 +01004533 term_replace_bs_del_keycode(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004534
4535 /*
4536 * For pipes: echo the typed characters. For a pty this
4537 * does not seem to work.
4538 */
4539 for (i = ta_len; i < ta_len + len; ++i)
4540 {
4541 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4542 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004543 else if (has_mbyte)
4544 {
4545 int l = (*mb_ptr2len)(ta_buf + i);
4546
4547 msg_outtrans_len(ta_buf + i, l);
4548 i += l - 1;
4549 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004550 else
4551 msg_outtrans_len(ta_buf + i, 1);
4552 }
4553 windgoto(msg_row, msg_col);
4554 out_flush();
4555
4556 ta_len += len;
4557
4558 /*
4559 * Write the characters to the child, unless EOF has been
4560 * typed for pipes. Write one character at a time, to
4561 * avoid losing too much typeahead. When writing buffer
4562 * lines, drop the typed characters (only check for
4563 * CTRL-C).
4564 */
4565 if (options & SHELL_WRITE)
4566 ta_len = 0;
4567 else if (g_hChildStd_IN_Wr != NULL)
4568 {
4569 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4570 1, &len, NULL);
4571 // if we are typing in, we want to keep things reactive
4572 delay = 1;
4573 if (len > 0)
4574 {
4575 ta_len -= len;
4576 mch_memmove(ta_buf, ta_buf + len, ta_len);
4577 }
4578 }
4579 }
4580 }
4581 }
4582
4583 if (ta_len)
4584 ui_inchar_undo(ta_buf, ta_len);
4585
4586 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4587 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004588 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004589 break;
4590 }
4591
4592 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004593 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004594
Bram Moolenaar0f873732019-12-05 20:28:46 +01004595 // We start waiting for a very short time and then increase it, so
4596 // that we respond quickly when the process is quick, and don't
4597 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004598 if (delay < 50)
4599 delay += 10;
4600 }
4601
Bram Moolenaar0f873732019-12-05 20:28:46 +01004602 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004603 CloseHandle(g_hChildStd_OUT_Rd);
4604 if (g_hChildStd_IN_Wr != NULL)
4605 CloseHandle(g_hChildStd_IN_Wr);
4606
4607 WaitForSingleObject(pi.hProcess, INFINITE);
4608
Bram Moolenaar0f873732019-12-05 20:28:46 +01004609 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004610 GetExitCodeProcess(pi.hProcess, &ret);
4611
4612 if (options & SHELL_READ)
4613 {
4614 if (ga.ga_len > 0)
4615 {
4616 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01004617 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004618 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4619 }
4620 else
4621 curbuf->b_no_eol_lnum = 0;
4622 ga_clear(&ga);
4623 }
4624
Bram Moolenaar0f873732019-12-05 20:28:46 +01004625 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004626 CloseHandle(pi.hThread);
4627 CloseHandle(pi.hProcess);
4628
4629 return ret;
4630}
4631
4632 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004633mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004634{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004635 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004636 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004637 return mch_system_piped(cmd, options);
4638 else
4639 return mch_system_classic(cmd, options);
4640}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004641#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004642
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004643#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004644 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02004645mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004646{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004647 int ret;
4648 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004649 char_u *buf;
4650 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004651
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004652 // If the command starts and ends with double quotes, enclose the command
4653 // in parentheses.
4654 len = STRLEN(cmd);
4655 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
4656 {
4657 len += 3;
4658 buf = alloc(len);
4659 if (buf == NULL)
4660 return -1;
4661 vim_snprintf((char *)buf, len, "(%s)", cmd);
4662 wcmd = enc_to_utf16(buf, NULL);
4663 free(buf);
4664 }
4665 else
4666 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4667
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004668 if (wcmd == NULL)
4669 return -1;
4670
4671 ret = _wsystem(wcmd);
4672 vim_free(wcmd);
4673 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004674}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004675
4676#endif
4677
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004678 static int
4679mch_system(char *cmd, int options)
4680{
4681#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004682 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004683 return mch_system_g(cmd, options);
4684 else
4685 return mch_system_c(cmd, options);
4686#elif defined(FEAT_GUI_MSWIN)
4687 return mch_system_g(cmd, options);
4688#else
4689 return mch_system_c(cmd, options);
4690#endif
4691}
4692
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004693#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4694/*
4695 * Use a terminal window to run a shell command in.
4696 */
4697 static int
4698mch_call_shell_terminal(
4699 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004700 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004701{
4702 jobopt_T opt;
4703 char_u *newcmd = NULL;
4704 typval_T argvar[2];
4705 long_u cmdlen;
4706 int retval = -1;
4707 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004708 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004709 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004710 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004711
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004712 if (cmd == NULL)
4713 cmdlen = STRLEN(p_sh) + 1;
4714 else
4715 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004716 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004717 if (newcmd == NULL)
4718 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004719 if (cmd == NULL)
4720 {
4721 STRCPY(newcmd, p_sh);
4722 ch_log(NULL, "starting terminal to run a shell");
4723 }
4724 else
4725 {
4726 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4727 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4728 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004729
4730 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004731
4732 argvar[0].v_type = VAR_STRING;
4733 argvar[0].vval.v_string = newcmd;
4734 argvar[1].v_type = VAR_UNKNOWN;
4735 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004736 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004737 {
4738 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004739 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004740 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004741
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004742 job = term_getjob(buf->b_term);
4743 ++job->jv_refcount;
4744
Bram Moolenaar0f873732019-12-05 20:28:46 +01004745 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004746 aucmd_prepbuf(&aco, buf);
4747
4748 clear_oparg(&oa);
4749 while (term_use_loop())
4750 {
4751 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4752 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004753 // If terminal_loop() returns OK we got a key that is handled
4754 // in Normal model. We don't do redrawing anyway.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004755 if (terminal_loop(TRUE) == OK)
4756 normal_cmd(&oa, TRUE);
4757 }
4758 else
4759 normal_cmd(&oa, TRUE);
4760 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004761 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004762 ch_log(NULL, "system command finished");
4763
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004764 job_unref(job);
4765
Bram Moolenaar0f873732019-12-05 20:28:46 +01004766 // restore curwin/curbuf and a few other things
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004767 aucmd_restbuf(&aco);
4768
4769 wait_return(TRUE);
4770 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4771
4772 vim_free(newcmd);
4773 return retval;
4774}
4775#endif
4776
Bram Moolenaar071d4272004-06-13 20:20:40 +00004777/*
4778 * Either execute a command by calling the shell or start a new shell
4779 */
4780 int
4781mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004782 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004783 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00004784{
4785 int x = 0;
4786 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004787 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004788
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01004789#ifdef FEAT_JOB_CHANNEL
4790 ch_log(NULL, "executing shell command: %s", cmd);
4791#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004792 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02004793 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004794 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004795 if (cmd == NULL)
4796 wcscat(szShellTitle, L" :sh");
4797 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004798 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004799 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004800
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004801 if (wn != NULL)
4802 {
4803 wcscat(szShellTitle, L" - !");
4804 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02004805 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004806 wcscat(szShellTitle, wn);
4807 SetConsoleTitleW(szShellTitle);
4808 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004809 }
4810 }
4811 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004812
4813 out_flush();
4814
4815#ifdef MCH_WRITE_DUMP
4816 if (fdDump)
4817 {
4818 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4819 fflush(fdDump);
4820 }
4821#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004822#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004823 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004824 if (
4825# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004826 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004827# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004828 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004829 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4830 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004831 char_u *cmdbase = cmd;
4832
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004833 if (cmdbase != NULL)
4834 // Skip a leading quote and (.
4835 while (*cmdbase == '"' || *cmdbase == '(')
4836 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004837
4838 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01004839 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
4840 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004841 {
4842 // Use a terminal window to run the command in.
4843 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004844 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004845 return x;
4846 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004847 }
4848#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004849
4850 /*
4851 * Catch all deadly signals while running the external command, because a
4852 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4853 */
4854 signal(SIGINT, SIG_IGN);
4855#if defined(__GNUC__) && !defined(__MINGW32__)
4856 signal(SIGKILL, SIG_IGN);
4857#else
4858 signal(SIGBREAK, SIG_IGN);
4859#endif
4860 signal(SIGILL, SIG_IGN);
4861 signal(SIGFPE, SIG_IGN);
4862 signal(SIGSEGV, SIG_IGN);
4863 signal(SIGTERM, SIG_IGN);
4864 signal(SIGABRT, SIG_IGN);
4865
4866 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004867 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00004868
4869 if (cmd == NULL)
4870 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004871 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004872 }
4873 else
4874 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004875 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004876 char_u *newcmd = NULL;
4877 char_u *cmdbase = cmd;
4878 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004879
Bram Moolenaar0f873732019-12-05 20:28:46 +01004880 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004881 if (*cmdbase == '"' )
4882 ++cmdbase;
4883 if (*cmdbase == '(')
4884 ++cmdbase;
4885
Bram Moolenaar1c465442017-03-12 20:10:05 +01004886 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004887 {
4888 STARTUPINFO si;
4889 PROCESS_INFORMATION pi;
4890 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004891 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004892 char_u *p;
4893
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004894 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004895 si.cb = sizeof(si);
4896 si.lpReserved = NULL;
4897 si.lpDesktop = NULL;
4898 si.lpTitle = NULL;
4899 si.dwFlags = 0;
4900 si.cbReserved2 = 0;
4901 si.lpReserved2 = NULL;
4902
4903 cmdbase = skipwhite(cmdbase + 5);
4904 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004905 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004906 {
4907 cmdbase = skipwhite(cmdbase + 4);
4908 si.dwFlags = STARTF_USESHOWWINDOW;
4909 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004910 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004911 }
4912 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004913 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004914 {
4915 cmdbase = skipwhite(cmdbase + 2);
4916 flags = CREATE_NO_WINDOW;
4917 si.dwFlags = STARTF_USESTDHANDLES;
4918 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004919 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004920 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004921 NULL, // Security att.
4922 OPEN_EXISTING, // Open flags
4923 FILE_ATTRIBUTE_NORMAL, // File att.
4924 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004925 si.hStdOutput = si.hStdInput;
4926 si.hStdError = si.hStdInput;
4927 }
4928
Bram Moolenaar0f873732019-12-05 20:28:46 +01004929 // Remove a trailing ", ) and )" if they have a match
4930 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004931 if (cmdbase > cmd)
4932 {
4933 p = cmdbase + STRLEN(cmdbase);
4934 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4935 *--p = NUL;
4936 if (p > cmdbase && p[-1] == ')'
4937 && (*cmd =='(' || cmd[1] == '('))
4938 *--p = NUL;
4939 }
4940
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004941 newcmd = cmdbase;
4942 unescape_shellxquote(cmdbase, p_sxe);
4943
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004944 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004945 * If creating new console, arguments are passed to the
4946 * 'cmd.exe' as-is. If it's not, arguments are not treated
4947 * correctly for current 'cmd.exe'. So unescape characters in
4948 * shellxescape except '|' for avoiding to be treated as
4949 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004950 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004951 if (flags != CREATE_NEW_CONSOLE)
4952 {
4953 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004954 char_u *cmd_shell = mch_getenv("COMSPEC");
4955
4956 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004957 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004958
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004959 subcmd = vim_strsave_escaped_ext(cmdbase,
4960 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004961 if (subcmd != NULL)
4962 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004963 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004964 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004965 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004966 if (newcmd != NULL)
4967 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004968 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004969 else
4970 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004971 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004972 }
4973 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004974
4975 /*
4976 * Now, start the command as a process, so that it doesn't
4977 * inherit our handles which causes unpleasant dangling swap
4978 * files if we exit before the spawned process
4979 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004980 if (vim_create_process((char *)newcmd, FALSE, flags,
4981 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004982 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004983 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4984 > (HINSTANCE)32)
4985 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004986 else
4987 {
4988 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01004989#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004990# ifdef VIMDLL
4991 if (gui.in_use)
4992# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00004993 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004994#endif
4995 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004996
4997 if (newcmd != cmdbase)
4998 vim_free(newcmd);
4999
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005000 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005001 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005002 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005003 CloseHandle(si.hStdInput);
5004 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005005 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005006 CloseHandle(pi.hThread);
5007 CloseHandle(pi.hProcess);
5008 }
5009 else
5010 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005011 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005012#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005013 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005014 (!s_dont_use_vimrun && p_stmp ?
5015 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5016 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005017#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005018 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005019
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005020 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005021 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005022 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005023#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005024 if (
5025# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005026 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005027# endif
5028 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005029 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005030 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5031 "External commands will not pause after completion.\n"
5032 "See :help win32-vimrun for more information.");
5033 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005034 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5035 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005036
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005037 if (wmsg != NULL && wtitle != NULL)
5038 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5039 vim_free(wmsg);
5040 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005041 need_vimrun_warning = FALSE;
5042 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005043 if (
5044# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005045 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005046# endif
5047 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005048 // Use vimrun to execute the command. It opens a console
5049 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005050 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005051 vimrun_path,
5052 (msg_silent != 0 || (options & SHELL_DOOUT))
5053 ? "-s " : "",
5054 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005055 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005056# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005057 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005058# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005059 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005060 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005061 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5062 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005063 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005064#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005065 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005066 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005067 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005068 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005069 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005070 }
5071 }
5072
5073 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005074 {
5075 // The shell may have messed with the mode, always set it.
5076 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005077 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005078 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005079
Bram Moolenaar0f873732019-12-05 20:28:46 +01005080 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005081 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005082#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005083 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005084 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005085#endif
5086 )
5087 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005088 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005089 msg_putchar('\n');
5090 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005091 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005092
5093 signal(SIGINT, SIG_DFL);
5094#if defined(__GNUC__) && !defined(__MINGW32__)
5095 signal(SIGKILL, SIG_DFL);
5096#else
5097 signal(SIGBREAK, SIG_DFL);
5098#endif
5099 signal(SIGILL, SIG_DFL);
5100 signal(SIGFPE, SIG_DFL);
5101 signal(SIGSEGV, SIG_DFL);
5102 signal(SIGTERM, SIG_DFL);
5103 signal(SIGABRT, SIG_DFL);
5104
5105 return x;
5106}
5107
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005108#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005109 static HANDLE
5110job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005111 char_u *fname,
5112 DWORD dwDesiredAccess,
5113 DWORD dwShareMode,
5114 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5115 DWORD dwCreationDisposition,
5116 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005117{
5118 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005119 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005120
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005121 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005122 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005123 return INVALID_HANDLE_VALUE;
5124
5125 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5126 lpSecurityAttributes, dwCreationDisposition,
5127 dwFlagsAndAttributes, NULL);
5128 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005129 return h;
5130}
5131
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005132/*
5133 * Turn the dictionary "env" into a NUL separated list that can be used as the
5134 * environment argument of vim_create_process().
5135 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005136 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005137win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005138{
5139 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005140 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005141 LPVOID base = GetEnvironmentStringsW();
5142
Bram Moolenaar0f873732019-12-05 20:28:46 +01005143 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005144 if (ga_grow(gap, 1) == FAIL)
5145 return;
5146
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005147 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005148 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005149 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005150 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005151 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005152 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005153 typval_T *item = &dict_lookup(hi)->di_tv;
5154 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005155 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005156 --todo;
5157 if (wkey != NULL && wval != NULL)
5158 {
5159 size_t n;
5160 size_t lkey = wcslen(wkey);
5161 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005162
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005163 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5164 continue;
5165 for (n = 0; n < lkey; n++)
5166 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5167 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5168 for (n = 0; n < lval; n++)
5169 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5170 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5171 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005172 vim_free(wkey);
5173 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005174 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005175 }
5176 }
5177
Bram Moolenaar355757a2020-02-10 22:06:32 +01005178 if (base)
5179 {
5180 WCHAR *p = (WCHAR*) base;
5181
5182 // for last \0
5183 if (ga_grow(gap, 1) == FAIL)
5184 return;
5185
5186 while (*p != 0 || *(p + 1) != 0)
5187 {
5188 if (ga_grow(gap, 1) == OK)
5189 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5190 p++;
5191 }
5192 FreeEnvironmentStrings(base);
5193 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5194 }
5195
Bram Moolenaar493359e2018-06-12 20:25:52 +02005196# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005197 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005198# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005199 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005200 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005201# endif
5202# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005203 char_u *version = get_vim_var_str(VV_VERSION);
5204 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005205# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005206 // size of "VIM_SERVERNAME=" and value,
5207 // plus "VIM_TERMINAL=" and value,
5208 // plus two terminating NULs
5209 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005210# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005211 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005212# endif
5213# ifdef FEAT_TERMINAL
5214 + 13 + version_len + 2
5215# endif
5216 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005217
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005218 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005219 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005220# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005221 for (n = 0; n < 15; n++)
5222 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5223 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005224 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005225 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5226 (WCHAR)servername[n];
5227 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005228# endif
5229# ifdef FEAT_TERMINAL
5230 if (is_terminal)
5231 {
5232 for (n = 0; n < 13; n++)
5233 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5234 (WCHAR)"VIM_TERMINAL="[n];
5235 for (n = 0; n < version_len; n++)
5236 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5237 (WCHAR)version[n];
5238 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5239 }
5240# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005241 }
5242 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005243# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005244}
5245
Bram Moolenaarb091f302019-01-19 14:37:00 +01005246/*
5247 * Create a pair of pipes.
5248 * Return TRUE for success, FALSE for failure.
5249 */
5250 static BOOL
5251create_pipe_pair(HANDLE handles[2])
5252{
5253 static LONG s;
5254 char name[64];
5255 SECURITY_ATTRIBUTES sa;
5256
5257 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5258 GetCurrentProcessId(),
5259 InterlockedIncrement(&s));
5260
5261 // Create named pipe. Max size of named pipe is 65535.
5262 handles[1] = CreateNamedPipe(
5263 name,
5264 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5265 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005266 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005267
5268 if (handles[1] == INVALID_HANDLE_VALUE)
5269 return FALSE;
5270
5271 sa.nLength = sizeof(sa);
5272 sa.bInheritHandle = TRUE;
5273 sa.lpSecurityDescriptor = NULL;
5274
5275 handles[0] = CreateFile(name,
5276 FILE_GENERIC_READ,
5277 FILE_SHARE_READ, &sa,
5278 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5279
5280 if (handles[0] == INVALID_HANDLE_VALUE)
5281 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005282 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005283 return FALSE;
5284 }
5285
5286 return TRUE;
5287}
5288
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005289 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005290mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005291{
5292 STARTUPINFO si;
5293 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005294 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005295 SECURITY_ATTRIBUTES saAttr;
5296 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005297 HANDLE ifd[2];
5298 HANDLE ofd[2];
5299 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005300 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005301
5302 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5303 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5304 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5305 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5306 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5307 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5308 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5309
5310 if (use_out_for_err && use_null_for_out)
5311 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005312
5313 ifd[0] = INVALID_HANDLE_VALUE;
5314 ifd[1] = INVALID_HANDLE_VALUE;
5315 ofd[0] = INVALID_HANDLE_VALUE;
5316 ofd[1] = INVALID_HANDLE_VALUE;
5317 efd[0] = INVALID_HANDLE_VALUE;
5318 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005319 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005320
Bram Moolenaar14207f42016-10-27 21:13:10 +02005321 jo = CreateJobObject(NULL, NULL);
5322 if (jo == NULL)
5323 {
5324 job->jv_status = JOB_FAILED;
5325 goto failed;
5326 }
5327
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005328 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005329 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005330
Bram Moolenaar76467df2016-02-12 19:30:26 +01005331 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005332 ZeroMemory(&si, sizeof(si));
5333 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005334 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005335 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005336
Bram Moolenaard8070362016-02-15 21:56:54 +01005337 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5338 saAttr.bInheritHandle = TRUE;
5339 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005340
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005341 if (use_file_for_in)
5342 {
5343 char_u *fname = options->jo_io_name[PART_IN];
5344
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005345 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5346 FILE_SHARE_READ | FILE_SHARE_WRITE,
5347 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5348 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005349 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005350 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005351 goto failed;
5352 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005353 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005354 else if (!use_null_for_in
5355 && (!create_pipe_pair(ifd)
5356 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005357 goto failed;
5358
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005359 if (use_file_for_out)
5360 {
5361 char_u *fname = options->jo_io_name[PART_OUT];
5362
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005363 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5364 FILE_SHARE_READ | FILE_SHARE_WRITE,
5365 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5366 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005367 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005368 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005369 goto failed;
5370 }
5371 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005372 else if (!use_null_for_out &&
5373 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005374 || !SetHandleInformation(ofd[0], 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_err)
5378 {
5379 char_u *fname = options->jo_io_name[PART_ERR];
5380
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005381 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5382 FILE_SHARE_READ | FILE_SHARE_WRITE,
5383 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5384 if (efd[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_out_for_err && !use_null_for_err &&
5391 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005392 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005393 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005394
Bram Moolenaard8070362016-02-15 21:56:54 +01005395 si.dwFlags |= STARTF_USESTDHANDLES;
5396 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005397 si.hStdOutput = ofd[1];
5398 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5399
5400 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5401 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005402 if (options->jo_set & JO_CHANNEL)
5403 {
5404 channel = options->jo_channel;
5405 if (channel != NULL)
5406 ++channel->ch_refcount;
5407 }
5408 else
5409 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005410 if (channel == NULL)
5411 goto failed;
5412 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005413
5414 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005415 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005416 CREATE_DEFAULT_ERROR_MODE |
5417 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005418 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005419 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005420 &si, &pi,
5421 ga.ga_data,
5422 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005423 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005424 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005425 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005426 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005427 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005428
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005429 ga_clear(&ga);
5430
Bram Moolenaar14207f42016-10-27 21:13:10 +02005431 if (!AssignProcessToJobObject(jo, pi.hProcess))
5432 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005433 // if failing, switch the way to terminate
5434 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005435 CloseHandle(jo);
5436 jo = NULL;
5437 }
5438 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005439 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005440 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005441 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005442 job->jv_status = JOB_STARTED;
5443
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005444 CloseHandle(ifd[0]);
5445 CloseHandle(ofd[1]);
5446 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005447 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005448
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005449 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005450 if (channel != NULL)
5451 {
5452 channel_set_pipes(channel,
5453 use_file_for_in || use_null_for_in
5454 ? INVALID_FD : (sock_T)ifd[1],
5455 use_file_for_out || use_null_for_out
5456 ? INVALID_FD : (sock_T)ofd[0],
5457 use_out_for_err || use_file_for_err || use_null_for_err
5458 ? INVALID_FD : (sock_T)efd[0]);
5459 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005460 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005461 return;
5462
5463failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005464 CloseHandle(ifd[0]);
5465 CloseHandle(ofd[0]);
5466 CloseHandle(efd[0]);
5467 CloseHandle(ifd[1]);
5468 CloseHandle(ofd[1]);
5469 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005470 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005471 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005472}
5473
5474 char *
5475mch_job_status(job_T *job)
5476{
5477 DWORD dwExitCode = 0;
5478
Bram Moolenaar76467df2016-02-12 19:30:26 +01005479 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5480 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005481 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005482 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005483 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005484 {
5485 ch_log(job->jv_channel, "Job ended");
5486 job->jv_status = JOB_ENDED;
5487 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005488 return "dead";
5489 }
5490 return "run";
5491}
5492
Bram Moolenaar97792de2016-10-15 18:36:49 +02005493 job_T *
5494mch_detect_ended_job(job_T *job_list)
5495{
5496 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5497 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5498 job_T *job = job_list;
5499
5500 while (job != NULL)
5501 {
5502 DWORD n;
5503 DWORD result;
5504
5505 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5506 && job != NULL; job = job->jv_next)
5507 {
5508 if (job->jv_status == JOB_STARTED)
5509 {
5510 jobHandles[n] = job->jv_proc_info.hProcess;
5511 jobArray[n] = job;
5512 ++n;
5513 }
5514 }
5515 if (n == 0)
5516 continue;
5517 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5518 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5519 {
5520 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5521
5522 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5523 return wait_job;
5524 }
5525 }
5526 return NULL;
5527}
5528
Bram Moolenaarfb630902016-10-29 14:55:00 +02005529 static BOOL
5530terminate_all(HANDLE process, int code)
5531{
5532 PROCESSENTRY32 pe;
5533 HANDLE h = INVALID_HANDLE_VALUE;
5534 DWORD pid = GetProcessId(process);
5535
5536 if (pid != 0)
5537 {
5538 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5539 if (h != INVALID_HANDLE_VALUE)
5540 {
5541 pe.dwSize = sizeof(PROCESSENTRY32);
5542 if (!Process32First(h, &pe))
5543 goto theend;
5544
5545 do
5546 {
5547 if (pe.th32ParentProcessID == pid)
5548 {
5549 HANDLE ph = OpenProcess(
5550 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5551 if (ph != NULL)
5552 {
5553 terminate_all(ph, code);
5554 CloseHandle(ph);
5555 }
5556 }
5557 } while (Process32Next(h, &pe));
5558
5559 CloseHandle(h);
5560 }
5561 }
5562
5563theend:
5564 return TerminateProcess(process, code);
5565}
5566
5567/*
5568 * Send a (deadly) signal to "job".
5569 * Return FAIL if it didn't work.
5570 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005571 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005572mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005573{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005574 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005575
Bram Moolenaar923d9262016-02-25 20:56:01 +01005576 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005577 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005578 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02005579 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005580 {
5581 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5582 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00005583 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005584 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01005585 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005586 }
5587
5588 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5589 return FAIL;
5590 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005591 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5592 job->jv_proc_info.dwProcessId)
5593 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005594 FreeConsole();
5595 return ret;
5596}
5597
5598/*
5599 * Clear the data related to "job".
5600 */
5601 void
5602mch_clear_job(job_T *job)
5603{
5604 if (job->jv_status != JOB_FAILED)
5605 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005606 if (job->jv_job_object != NULL)
5607 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005608 CloseHandle(job->jv_proc_info.hProcess);
5609 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005610}
5611#endif
5612
Bram Moolenaar071d4272004-06-13 20:20:40 +00005613
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005614#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005615
5616/*
5617 * Start termcap mode
5618 */
5619 static void
5620termcap_mode_start(void)
5621{
5622 DWORD cmodein;
5623
5624 if (g_fTermcapMode)
5625 return;
5626
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005627 if (!p_rs && USE_VTP)
5628 vtp_printf("\033[?1049h");
5629
Bram Moolenaar071d4272004-06-13 20:20:40 +00005630 SaveConsoleBuffer(&g_cbNonTermcap);
5631
5632 if (g_cbTermcap.IsValid)
5633 {
5634 /*
5635 * We've been in termcap mode before. Restore certain screen
5636 * characteristics, including the buffer size and the window
5637 * size. Since we will be redrawing the screen, we don't need
5638 * to restore the actual contents of the buffer.
5639 */
5640 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005641 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005642 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5643 Rows = g_cbTermcap.Info.dwSize.Y;
5644 Columns = g_cbTermcap.Info.dwSize.X;
5645 }
5646 else
5647 {
5648 /*
5649 * This is our first time entering termcap mode. Clear the console
5650 * screen buffer, and resize the buffer to match the current window
5651 * size. We will use this as the size of our editing environment.
5652 */
5653 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005654 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005655 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5656 }
5657
Bram Moolenaar071d4272004-06-13 20:20:40 +00005658 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005659
5660 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005661 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005662 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005663 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005664 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
5665 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005666 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005667 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005668 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005669 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5670 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005671 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005672 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005673
5674 redraw_later_clear();
5675 g_fTermcapMode = TRUE;
5676}
5677
5678
5679/*
5680 * End termcap mode
5681 */
5682 static void
5683termcap_mode_end(void)
5684{
5685 DWORD cmodein;
5686 ConsoleBuffer *cb;
5687 COORD coord;
5688 DWORD dwDummy;
5689
5690 if (!g_fTermcapMode)
5691 return;
5692
5693 SaveConsoleBuffer(&g_cbTermcap);
5694
5695 GetConsoleMode(g_hConIn, &cmodein);
5696 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005697 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5698 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005699
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005700# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005701 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005702# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005703 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005704# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005705 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01005706 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005707 SetConsoleCursorInfo(g_hConOut, &g_cci);
5708
5709 if (p_rs || exiting)
5710 {
5711 /*
5712 * Clear anything that happens to be on the current line.
5713 */
5714 coord.X = 0;
5715 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5716 FillConsoleOutputCharacter(g_hConOut, ' ',
5717 cb->Info.dwSize.X, coord, &dwDummy);
5718 /*
5719 * The following is just for aesthetics. If we are exiting without
5720 * restoring the screen, then we want to have a prompt string
5721 * appear at the bottom line. However, the command interpreter
5722 * seems to always advance the cursor one line before displaying
5723 * the prompt string, which causes the screen to scroll. To
5724 * counter this, move the cursor up one line before exiting.
5725 */
5726 if (exiting && !p_rs)
5727 coord.Y--;
5728 /*
5729 * Position the cursor at the leftmost column of the desired row.
5730 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005731 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005732 }
5733
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005734 if (!p_rs && USE_VTP)
Bram Moolenaar0afdcf82020-04-01 18:29:10 +02005735 vtp_printf("\033[?1049l");
5736
Bram Moolenaar071d4272004-06-13 20:20:40 +00005737 g_fTermcapMode = FALSE;
5738}
Bram Moolenaar0f873732019-12-05 20:28:46 +01005739#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005740
5741
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005742#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005743 void
5744mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005745 char_u *s UNUSED,
5746 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005747{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005748 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00005749}
5750
5751#else
5752
5753/*
5754 * clear `n' chars, starting from `coord'
5755 */
5756 static void
5757clear_chars(
5758 COORD coord,
5759 DWORD n)
5760{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005761 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02005762 {
5763 DWORD dwDummy;
5764
5765 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5766 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
5767 &dwDummy);
5768 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005769 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005770 {
5771 set_console_color_rgb();
5772 gotoxy(coord.X + 1, coord.Y + 1);
5773 vtp_printf("\033[%dX", n);
5774 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005775}
5776
5777
5778/*
5779 * Clear the screen
5780 */
5781 static void
5782clear_screen(void)
5783{
5784 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005785
5786 if (!USE_VTP)
5787 clear_chars(g_coord, Rows * Columns);
5788 else
5789 {
5790 set_console_color_rgb();
5791 gotoxy(1, 1);
5792 vtp_printf("\033[2J");
5793 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005794}
5795
5796
5797/*
5798 * Clear to end of display
5799 */
5800 static void
5801clear_to_end_of_display(void)
5802{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005803 COORD save = g_coord;
5804
5805 if (!USE_VTP)
5806 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005807 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005808 else
5809 {
5810 set_console_color_rgb();
5811 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5812 vtp_printf("\033[0J");
5813
5814 gotoxy(save.X + 1, save.Y + 1);
5815 g_coord = save;
5816 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005817}
5818
5819
5820/*
5821 * Clear to end of line
5822 */
5823 static void
5824clear_to_end_of_line(void)
5825{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005826 COORD save = g_coord;
5827
5828 if (!USE_VTP)
5829 clear_chars(g_coord, Columns - g_coord.X);
5830 else
5831 {
5832 set_console_color_rgb();
5833 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5834 vtp_printf("\033[0K");
5835
5836 gotoxy(save.X + 1, save.Y + 1);
5837 g_coord = save;
5838 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005839}
5840
5841
5842/*
5843 * Scroll the scroll region up by `cLines' lines
5844 */
5845 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005846scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005847{
5848 COORD oldcoord = g_coord;
5849
5850 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5851 delete_lines(cLines);
5852
5853 g_coord = oldcoord;
5854}
5855
5856
5857/*
5858 * Set the scroll region
5859 */
5860 static void
5861set_scroll_region(
5862 unsigned left,
5863 unsigned top,
5864 unsigned right,
5865 unsigned bottom)
5866{
5867 if (left >= right
5868 || top >= bottom
5869 || right > (unsigned) Columns - 1
5870 || bottom > (unsigned) Rows - 1)
5871 return;
5872
5873 g_srScrollRegion.Left = left;
5874 g_srScrollRegion.Top = top;
5875 g_srScrollRegion.Right = right;
5876 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005877}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005878
Bram Moolenaar6982f422019-02-16 16:48:01 +01005879 static void
5880set_scroll_region_tb(
5881 unsigned top,
5882 unsigned bottom)
5883{
5884 if (top >= bottom || bottom > (unsigned)Rows - 1)
5885 return;
5886
5887 g_srScrollRegion.Top = top;
5888 g_srScrollRegion.Bottom = bottom;
5889}
5890
5891 static void
5892set_scroll_region_lr(
5893 unsigned left,
5894 unsigned right)
5895{
5896 if (left >= right || right > (unsigned)Columns - 1)
5897 return;
5898
5899 g_srScrollRegion.Left = left;
5900 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005901}
5902
5903
5904/*
5905 * Insert `cLines' lines at the current cursor position
5906 */
5907 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005908insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005909{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005910 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005911 COORD dest;
5912 CHAR_INFO fill;
5913
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005914 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5915
Bram Moolenaar6982f422019-02-16 16:48:01 +01005916 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005917 dest.Y = g_coord.Y + cLines;
5918
Bram Moolenaar6982f422019-02-16 16:48:01 +01005919 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005920 source.Top = g_coord.Y;
5921 source.Right = g_srScrollRegion.Right;
5922 source.Bottom = g_srScrollRegion.Bottom - cLines;
5923
Bram Moolenaar6982f422019-02-16 16:48:01 +01005924 clip.Left = g_srScrollRegion.Left;
5925 clip.Top = g_coord.Y;
5926 clip.Right = g_srScrollRegion.Right;
5927 clip.Bottom = g_srScrollRegion.Bottom;
5928
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005929 fill.Char.AsciiChar = ' ';
5930 if (!USE_VTP)
5931 fill.Attributes = g_attrCurrent;
5932 else
5933 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005934
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005935 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005936
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005937 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5938
Bram Moolenaar6982f422019-02-16 16:48:01 +01005939 // Here we have to deal with a win32 console flake: If the scroll
5940 // region looks like abc and we scroll c to a and fill with d we get
5941 // cbd... if we scroll block c one line at a time to a, we get cdd...
5942 // vim expects cdd consistently... So we have to deal with that
5943 // here... (this also occurs scrolling the same way in the other
5944 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005945
5946 if (source.Bottom < dest.Y)
5947 {
5948 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005949 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005950
Bram Moolenaar6982f422019-02-16 16:48:01 +01005951 coord.X = source.Left;
5952 for (i = clip.Top; i < dest.Y; ++i)
5953 {
5954 coord.Y = i;
5955 clear_chars(coord, source.Right - source.Left + 1);
5956 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005957 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02005958
5959 if (USE_WT)
5960 {
5961 COORD coord;
5962 int i;
5963
5964 coord.X = source.Left;
5965 for (i = source.Top; i < dest.Y; ++i)
5966 {
5967 coord.Y = i;
5968 clear_chars(coord, source.Right - source.Left + 1);
5969 }
5970 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005971}
5972
5973
5974/*
5975 * Delete `cLines' lines at the current cursor position
5976 */
5977 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005978delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005979{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005980 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005981 COORD dest;
5982 CHAR_INFO fill;
5983 int nb;
5984
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005985 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5986
Bram Moolenaar6982f422019-02-16 16:48:01 +01005987 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005988 dest.Y = g_coord.Y;
5989
Bram Moolenaar6982f422019-02-16 16:48:01 +01005990 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005991 source.Top = g_coord.Y + cLines;
5992 source.Right = g_srScrollRegion.Right;
5993 source.Bottom = g_srScrollRegion.Bottom;
5994
Bram Moolenaar6982f422019-02-16 16:48:01 +01005995 clip.Left = g_srScrollRegion.Left;
5996 clip.Top = g_coord.Y;
5997 clip.Right = g_srScrollRegion.Right;
5998 clip.Bottom = g_srScrollRegion.Bottom;
5999
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006000 fill.Char.AsciiChar = ' ';
6001 if (!USE_VTP)
6002 fill.Attributes = g_attrCurrent;
6003 else
6004 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006005
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006006 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006007
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006008 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6009
Bram Moolenaar6982f422019-02-16 16:48:01 +01006010 // Here we have to deal with a win32 console flake; See insert_lines()
6011 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006012
6013 nb = dest.Y + (source.Bottom - source.Top) + 1;
6014
6015 if (nb < source.Top)
6016 {
6017 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006018 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006019
Bram Moolenaar6982f422019-02-16 16:48:01 +01006020 coord.X = source.Left;
6021 for (i = nb; i < clip.Bottom; ++i)
6022 {
6023 coord.Y = i;
6024 clear_chars(coord, source.Right - source.Left + 1);
6025 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006026 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006027
6028 if (USE_WT)
6029 {
6030 COORD coord;
6031 int i;
6032
6033 coord.X = source.Left;
6034 for (i = nb; i <= source.Bottom; ++i)
6035 {
6036 coord.Y = i;
6037 clear_chars(coord, source.Right - source.Left + 1);
6038 }
6039 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006040}
6041
6042
6043/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006044 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006045 */
6046 static void
6047gotoxy(
6048 unsigned x,
6049 unsigned y)
6050{
6051 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6052 return;
6053
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006054 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006055 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006056 // There are reports of double-width characters not displayed
6057 // correctly. This workaround should fix it, similar to how it's done
6058 // for VTP.
6059 g_coord.X = 0;
6060 SetConsoleCursorPosition(g_hConOut, g_coord);
6061
Bram Moolenaar2313b612019-09-27 14:14:32 +02006062 // external cursor coords are 1-based; internal are 0-based
6063 g_coord.X = x - 1;
6064 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006065 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006066 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006067 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006068 {
6069 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006070 // destruction. Insider build bug. Always enabled because it's cheap
6071 // and avoids mistakes with recognizing the build.
6072 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006073
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006074 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006075
6076 g_coord.X = x - 1;
6077 g_coord.Y = y - 1;
6078 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006079}
6080
6081
6082/*
6083 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006084 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006085 */
6086 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006087textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006088{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006089 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006090
6091 SetConsoleTextAttribute(g_hConOut, wAttr);
6092}
6093
6094
6095 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006096textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006097{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006098 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006099
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006100 if (!USE_VTP)
6101 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6102 else
6103 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006104}
6105
6106
6107 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006108textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006109{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006110 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006111
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006112 if (!USE_VTP)
6113 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6114 else
6115 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006116}
6117
6118
6119/*
6120 * restore the default text attribute (whatever we started with)
6121 */
6122 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006123normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006124{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006125 if (!USE_VTP)
6126 textattr(g_attrDefault);
6127 else
6128 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006129}
6130
6131
6132static WORD g_attrPreStandout = 0;
6133
6134/*
6135 * Make the text standout, by brightening it
6136 */
6137 static void
6138standout(void)
6139{
6140 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006141
Bram Moolenaar071d4272004-06-13 20:20:40 +00006142 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6143}
6144
6145
6146/*
6147 * Turn off standout mode
6148 */
6149 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006150standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006151{
6152 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006153 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006154
6155 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006156}
6157
6158
6159/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006160 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006161 */
6162 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006163mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006164{
6165 char_u *p;
6166 int n;
6167
6168 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6169 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006170 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006171# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006172 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006173# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006174 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006175 {
6176 p = T_ME + 2;
6177 n = getdigits(&p);
6178 if (*p == 'm' && n > 0)
6179 {
6180 cterm_normal_fg_color = (n & 0xf) + 1;
6181 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6182 }
6183 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006184# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006185 cterm_normal_fg_gui_color = INVALCOLOR;
6186 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006187# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006188}
6189
6190
6191/*
6192 * visual bell: flash the screen
6193 */
6194 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006195visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006196{
6197 COORD coordOrigin = {0, 0};
6198 WORD attrFlash = ~g_attrCurrent & 0xff;
6199
6200 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006201 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006202
6203 if (oldattrs == NULL)
6204 return;
6205 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6206 coordOrigin, &dwDummy);
6207 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6208 coordOrigin, &dwDummy);
6209
Bram Moolenaar0f873732019-12-05 20:28:46 +01006210 Sleep(15); // wait for 15 msec
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006211 if (!USE_VTP)
6212 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006213 coordOrigin, &dwDummy);
6214 vim_free(oldattrs);
6215}
6216
6217
6218/*
6219 * Make the cursor visible or invisible
6220 */
6221 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006222cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006223{
6224 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006225
6226 if (USE_VTP)
6227 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6228
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006229# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006230 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006231# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006232}
6233
6234
6235/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006236 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006237 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006238 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006239 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006240write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006241 char_u *pchBuf,
6242 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006243{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006244 COORD coord = g_coord;
6245 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006246 DWORD n, cchwritten;
6247 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006248 static WCHAR *unicodebuf = NULL;
6249 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006250 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006251 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006252 static WCHAR *utf8spbuf = NULL;
6253 static int utf8splength;
6254 static DWORD utf8spcells;
6255 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006256
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006257 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006258 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006259 utf8usingbuf = &unicodebuf;
6260 do
6261 {
6262 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6263 unicodebuf, unibuflen);
6264 if (length && length <= unibuflen)
6265 break;
6266 vim_free(unicodebuf);
6267 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6268 unibuflen = unibuflen ? 0 : length;
6269 } while(1);
6270 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006271 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006272 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6273 {
6274 if (utf8usingbuf != &utf8spbuf)
6275 {
6276 if (utf8spbuf == NULL)
6277 {
6278 cells = mb_string2cells((char_u *)" ", 1);
6279 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6280 utf8spbuf = LALLOC_MULT(WCHAR, length);
6281 if (utf8spbuf != NULL)
6282 {
6283 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6284 utf8usingbuf = &utf8spbuf;
6285 utf8splength = length;
6286 utf8spcells = cells;
6287 }
6288 }
6289 else
6290 {
6291 utf8usingbuf = &utf8spbuf;
6292 length = utf8splength;
6293 cells = utf8spcells;
6294 }
6295 }
6296 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006297
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006298 if (!USE_VTP)
6299 {
6300 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6301 coord, &written);
6302 // When writing fails or didn't write a single character, pretend one
6303 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006304 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006305 coord, &cchwritten) == 0
6306 || cchwritten == 0 || cchwritten == (DWORD)-1)
6307 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006308 }
6309 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006310 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006311 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006312 NULL) == 0 || cchwritten == 0)
6313 cchwritten = 1;
6314 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006315
K.Takata135e1522022-01-29 15:27:58 +00006316 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006317 {
6318 written = cbToWrite;
6319 g_coord.X += (SHORT)cells;
6320 }
6321 else
6322 {
6323 char_u *p = pchBuf;
6324 for (n = 0; n < cchwritten; n++)
6325 MB_CPTR_ADV(p);
6326 written = p - pchBuf;
6327 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006328 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006329
6330 while (g_coord.X > g_srScrollRegion.Right)
6331 {
6332 g_coord.X -= (SHORT) Columns;
6333 if (g_coord.Y < g_srScrollRegion.Bottom)
6334 g_coord.Y++;
6335 }
6336
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006337 // Cursor under VTP is always in the correct position, no need to reset.
6338 if (!USE_VTP)
6339 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006340
6341 return written;
6342}
6343
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006344 static char_u *
6345get_seq(
6346 int *args,
6347 int *count,
6348 char_u *head)
6349{
6350 int argc;
6351 char_u *p;
6352
6353 if (head == NULL || *head != '\033')
6354 return NULL;
6355
6356 argc = 0;
6357 p = head;
6358 ++p;
6359 do
6360 {
6361 ++p;
6362 args[argc] = getdigits(&p);
6363 argc += (argc < 15) ? 1 : 0;
6364 } while (*p == ';');
6365 *count = argc;
6366
6367 return p;
6368}
6369
6370 static char_u *
6371get_sgr(
6372 int *args,
6373 int *count,
6374 char_u *head)
6375{
6376 char_u *p = get_seq(args, count, head);
6377
6378 return (p && *p == 'm') ? ++p : NULL;
6379}
6380
6381/*
6382 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6383 */
6384 static char_u *
6385sgrn2(
6386 char_u *head,
6387 int n)
6388{
6389 int argc;
6390 int args[16];
6391 char_u *p = get_sgr(args, &argc, head);
6392
6393 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6394}
6395
6396/*
6397 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6398 */
6399 static char_u *
6400sgrnc(
6401 char_u *head,
6402 int n)
6403{
6404 int argc;
6405 int args[16];
6406 char_u *p = get_sgr(args, &argc, head);
6407
6408 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6409 ? p : NULL;
6410}
6411
6412 static char_u *
6413skipblank(char_u *q)
6414{
6415 char_u *p = q;
6416
6417 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6418 ++p;
6419 return p;
6420}
6421
6422/*
6423 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6424 * NULL.
6425 */
6426 static char_u *
6427sgrn2c(
6428 char_u *head,
6429 int n)
6430{
6431 char_u *p = sgrn2(head, n);
6432
6433 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6434}
6435
6436/*
6437 * If there is only a newline between the sequence immediately following it,
6438 * a pointer to the character following the newline is returned.
6439 * Otherwise NULL.
6440 */
6441 static char_u *
6442sgrn2cn(
6443 char_u *head,
6444 int n)
6445{
6446 char_u *p = sgrn2(head, n);
6447
6448 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6449}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006450
6451/*
6452 * mch_write(): write the output buffer to the screen, translating ESC
6453 * sequences into calls to console output routines.
6454 */
6455 void
6456mch_write(
6457 char_u *s,
6458 int len)
6459{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006460 char_u *end = s + len;
6461
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006462# ifdef VIMDLL
6463 if (gui.in_use)
6464 return;
6465# endif
6466
Bram Moolenaar071d4272004-06-13 20:20:40 +00006467 if (!term_console)
6468 {
6469 write(1, s, (unsigned)len);
6470 return;
6471 }
6472
Bram Moolenaar0f873732019-12-05 20:28:46 +01006473 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00006474 while (len--)
6475 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006476 int prefix = -1;
6477 char_u ch;
6478
6479 // While processing a sequence, on rare occasions it seems that another
6480 // sequence may be inserted asynchronously.
6481 if (len < 0)
6482 {
6483 redraw_all_later(CLEAR);
6484 return;
6485 }
6486
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006487 while (s + ++prefix < end)
6488 {
6489 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006490 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6491 && ch != '\a' && ch != '\033'))
6492 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006493 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006494
6495 if (p_wd)
6496 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006497 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006498 if (prefix != 0)
6499 prefix = 1;
6500 }
6501
6502 if (prefix != 0)
6503 {
6504 DWORD nWritten;
6505
6506 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006507# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006508 if (fdDump)
6509 {
6510 fputc('>', fdDump);
6511 fwrite(s, sizeof(char_u), nWritten, fdDump);
6512 fputs("<\n", fdDump);
6513 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006514# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006515 len -= (nWritten - 1);
6516 s += nWritten;
6517 }
6518 else if (s[0] == '\n')
6519 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006520 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00006521 if (g_coord.Y == g_srScrollRegion.Bottom)
6522 {
6523 scroll(1);
6524 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6525 }
6526 else
6527 {
6528 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6529 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006530# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006531 if (fdDump)
6532 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006533# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006534 s++;
6535 }
6536 else if (s[0] == '\r')
6537 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006538 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00006539 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006540# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006541 if (fdDump)
6542 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006543# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006544 s++;
6545 }
6546 else if (s[0] == '\b')
6547 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006548 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00006549 if (g_coord.X > g_srScrollRegion.Left)
6550 g_coord.X--;
6551 else if (g_coord.Y > g_srScrollRegion.Top)
6552 {
6553 g_coord.X = g_srScrollRegion.Right;
6554 g_coord.Y--;
6555 }
6556 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006557# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006558 if (fdDump)
6559 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006560# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006561 s++;
6562 }
6563 else if (s[0] == '\a')
6564 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006565 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00006566 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006567# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006568 if (fdDump)
6569 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006570# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006571 s++;
6572 }
6573 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6574 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006575# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006576 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006577# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006578 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006579 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006580 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006581
6582 switch (s[2])
6583 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006584 case '0': case '1': case '2': case '3': case '4':
6585 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006586 if (*(p = get_seq(args, &argc, s)) != 'm')
6587 goto notsgr;
6588
6589 p = s;
6590
6591 // Handling frequent optional sequences. Output to the screen
6592 // takes too long, so do not output as much as possible.
6593
6594 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
6595 // resetFG,FG,BG are omitted.
6596 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006597 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006598 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
6599 len = len + 1 - (int)(p - s);
6600 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006601 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006602 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006603
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006604 // If FG,BG,BG,FG of SGR are connected, the first FG can be
6605 // omitted.
6606 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
6607 p = sp;
6608
6609 // If FG,BG,FG,BG of SGR are connected, the first FG can be
6610 // omitted.
6611 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
6612 p = sp;
6613
6614 // If BG,BG of SGR are connected, the first BG can be omitted.
6615 if (sgrn2((sp = sgrn2(p, 48)), 48))
6616 p = sp;
6617
6618 // If restoreFG and FG are connected, the restoreFG can be
6619 // omitted.
6620 if (sgrn2((sp = sgrnc(p, 39)), 38))
6621 p = sp;
6622
6623 p = get_seq(args, &argc, p);
6624
6625notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006626 arg1 = args[0];
6627 arg2 = args[1];
6628 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006629 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006630 if (argc == 1 && args[0] == 0)
6631 normvideo();
6632 else if (argc == 1)
6633 {
6634 if (USE_VTP)
6635 textcolor((WORD) arg1);
6636 else
6637 textattr((WORD) arg1);
6638 }
6639 else if (USE_VTP)
6640 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006641 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006642 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006643 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006644 gotoxy(arg2, arg1);
6645 }
6646 else if (argc == 2 && *p == 'r')
6647 {
6648 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6649 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006650 else if (argc == 2 && *p == 'R')
6651 {
6652 set_scroll_region_tb(arg1, arg2);
6653 }
6654 else if (argc == 2 && *p == 'V')
6655 {
6656 set_scroll_region_lr(arg1, arg2);
6657 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006658 else if (argc == 1 && *p == 'A')
6659 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006660 gotoxy(g_coord.X + 1,
6661 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6662 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006663 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006664 {
6665 textbackground((WORD) arg1);
6666 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006667 else if (argc == 1 && *p == 'C')
6668 {
6669 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6670 g_coord.Y + 1);
6671 }
6672 else if (argc == 1 && *p == 'f')
6673 {
6674 textcolor((WORD) arg1);
6675 }
6676 else if (argc == 1 && *p == 'H')
6677 {
6678 gotoxy(1, arg1);
6679 }
6680 else if (argc == 1 && *p == 'L')
6681 {
6682 insert_lines(arg1);
6683 }
6684 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006685 {
6686 delete_lines(arg1);
6687 }
6688
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006689 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006690 s = p + 1;
6691 break;
6692
Bram Moolenaar071d4272004-06-13 20:20:40 +00006693 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006694 gotoxy(g_coord.X + 1,
6695 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6696 goto got3;
6697
6698 case 'B':
6699 visual_bell();
6700 goto got3;
6701
6702 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006703 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6704 g_coord.Y + 1);
6705 goto got3;
6706
6707 case 'E':
6708 termcap_mode_end();
6709 goto got3;
6710
6711 case 'F':
6712 standout();
6713 goto got3;
6714
6715 case 'f':
6716 standend();
6717 goto got3;
6718
6719 case 'H':
6720 gotoxy(1, 1);
6721 goto got3;
6722
6723 case 'j':
6724 clear_to_end_of_display();
6725 goto got3;
6726
6727 case 'J':
6728 clear_screen();
6729 goto got3;
6730
6731 case 'K':
6732 clear_to_end_of_line();
6733 goto got3;
6734
6735 case 'L':
6736 insert_lines(1);
6737 goto got3;
6738
6739 case 'M':
6740 delete_lines(1);
6741 goto got3;
6742
6743 case 'S':
6744 termcap_mode_start();
6745 goto got3;
6746
6747 case 'V':
6748 cursor_visible(TRUE);
6749 goto got3;
6750
6751 case 'v':
6752 cursor_visible(FALSE);
6753 goto got3;
6754
6755 got3:
6756 s += 3;
6757 len -= 2;
6758 }
6759
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006760# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006761 if (fdDump)
6762 {
6763 fputs("ESC | ", fdDump);
6764 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6765 fputc('\n', fdDump);
6766 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006767# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006768 }
6769 else
6770 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006771 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00006772 DWORD nWritten;
6773
6774 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006775# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006776 if (fdDump)
6777 {
6778 fputc('>', fdDump);
6779 fwrite(s, sizeof(char_u), nWritten, fdDump);
6780 fputs("<\n", fdDump);
6781 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006782# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006783
6784 len -= (nWritten - 1);
6785 s += nWritten;
6786 }
6787 }
6788
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006789# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006790 if (fdDump)
6791 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006792# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006793}
6794
Bram Moolenaar0f873732019-12-05 20:28:46 +01006795#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006796
6797
6798/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006799 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006800 */
6801 void
6802mch_delay(
6803 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02006804 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006805{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006806#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006807 Sleep((int)msec); // never wait for input
6808#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006809# ifdef VIMDLL
6810 if (gui.in_use)
6811 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006812 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006813 return;
6814 }
6815# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02006816 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006817# ifdef FEAT_MZSCHEME
6818 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6819 {
6820 int towait = p_mzq;
6821
Bram Moolenaar0f873732019-12-05 20:28:46 +01006822 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006823 while (msec > 0)
6824 {
6825 mzvim_check_threads();
6826 if (msec < towait)
6827 towait = msec;
6828 Sleep(towait);
6829 msec -= towait;
6830 }
6831 }
6832 else
6833# endif
6834 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006835 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006836 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006837#endif
6838}
6839
6840
6841/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006842 * This version of remove is not scared by a readonly (backup) file.
6843 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006844 * Return 0 for success, -1 for failure.
6845 */
6846 int
6847mch_remove(char_u *name)
6848{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006849 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006850 int n;
6851
Bram Moolenaar203258c2016-01-17 22:15:16 +01006852 /*
6853 * On Windows, deleting a directory's symbolic link is done by
6854 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6855 */
6856 if (mch_isdir(name) && mch_is_symbolic_link(name))
6857 return mch_rmdir(name);
6858
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006859 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6860
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006861 wn = enc_to_utf16(name, NULL);
6862 if (wn == NULL)
6863 return -1;
6864
6865 n = DeleteFileW(wn) ? 0 : -1;
6866 vim_free(wn);
6867 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006868}
6869
6870
6871/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006872 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006873 */
6874 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006875mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006876{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006877#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
6878# ifdef VIMDLL
6879 if (!gui.in_use)
6880# endif
6881 if (g_fCtrlCPressed || g_fCBrkPressed)
6882 {
6883 ctrl_break_was_pressed = g_fCBrkPressed;
6884 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6885 got_int = TRUE;
6886 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006887#endif
6888}
6889
Bram Moolenaar0f873732019-12-05 20:28:46 +01006890// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01006891#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006892
6893/*
6894 * How much main memory in KiB that can be used by VIM.
6895 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006896 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006897mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006898{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006899 MEMORYSTATUSEX ms;
6900
Bram Moolenaar0f873732019-12-05 20:28:46 +01006901 // Need to use GlobalMemoryStatusEx() when there is more memory than
6902 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006903 ms.dwLength = sizeof(MEMORYSTATUSEX);
6904 GlobalMemoryStatusEx(&ms);
6905 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006906 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006907 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006908 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006909 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006910 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006911 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006912 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006913 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006914 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01006915 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006916 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006917}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006918
Bram Moolenaar071d4272004-06-13 20:20:40 +00006919/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006920 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00006921 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6922 * file whose short file name is "FOO.BAR" (its long file name will
6923 * be correct: "foo.bar~"). Because a file can be accessed by
6924 * either its SFN or its LFN, "foo.bar" has effectively been
6925 * renamed to "foo.bar", which is not at all what was wanted. This
6926 * seems to happen only when renaming files with three-character
6927 * extensions by appending a suffix that does not include ".".
6928 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6929 *
6930 * There is another problem, which isn't really a bug but isn't right either:
6931 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6932 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6933 * service pack 6. Doesn't seem to happen on Windows 98.
6934 *
6935 * Like rename(), returns 0 upon success, non-zero upon failure.
6936 * Should probably set errno appropriately when errors occur.
6937 */
6938 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006939mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006940{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006941 WCHAR *p;
6942 int i;
6943 WCHAR szTempFile[_MAX_PATH + 1];
6944 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006945 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006946
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006947 // No need to play tricks unless the file name contains a "~" as the
6948 // seventh character.
6949 p = wold;
6950 for (i = 0; wold[i] != NUL; ++i)
6951 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6952 && wold[i + 1] != 0)
6953 p = wold + i + 1;
6954 if ((int)(wold + i - p) < 8 || p[6] != '~')
6955 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006956
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006957 // Get base path of new file name. Undocumented feature: If pszNewFile is
6958 // a directory, no error is returned and pszFilePart will be NULL.
6959 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006960 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006961 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006962
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006963 // Get (and create) a unique temporary file name in directory of new file
6964 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006965 return -2;
6966
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006967 // blow the temp file away
6968 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006969 return -3;
6970
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006971 // rename old file to the temp file
6972 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006973 return -4;
6974
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006975 // now create an empty file called pszOldFile; this prevents the operating
6976 // system using pszOldFile as an alias (SFN) if we're renaming within the
6977 // same directory. For example, we're editing a file called
6978 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6979 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
6980 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
6981 // cause all sorts of problems later in buf_write(). So, we create an
6982 // empty file called filena~1.txt and the system will have to find some
6983 // other SFN for filena~1.txt~, such as filena~2.txt
6984 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006985 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6986 return -5;
6987 if (!CloseHandle(hf))
6988 return -6;
6989
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006990 // rename the temp file to the new file
6991 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006992 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006993 // Renaming failed. Rename the file back to its old name, so that it
6994 // looks like nothing happened.
6995 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006996 return -7;
6997 }
6998
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006999 // Seems to be left around on Novell filesystems
7000 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007001
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007002 // finally, remove the empty old file
7003 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007004 return -8;
7005
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007006 return 0;
7007}
7008
7009
7010/*
7011 * Converts the filenames to UTF-16, then call mch_wrename().
7012 * Like rename(), returns 0 upon success, non-zero upon failure.
7013 */
7014 int
7015mch_rename(
7016 const char *pszOldFile,
7017 const char *pszNewFile)
7018{
7019 WCHAR *wold = NULL;
7020 WCHAR *wnew = NULL;
7021 int retval = -1;
7022
7023 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7024 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7025 if (wold != NULL && wnew != NULL)
7026 retval = mch_wrename(wold, wnew);
7027 vim_free(wold);
7028 vim_free(wnew);
7029 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007030}
7031
7032/*
7033 * Get the default shell for the current hardware platform
7034 */
7035 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007036default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007037{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007038 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007039}
7040
7041/*
7042 * mch_access() extends access() to do more detailed check on network drives.
7043 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7044 */
7045 int
7046mch_access(char *n, int p)
7047{
7048 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007049 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007050 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007051
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007052 wn = enc_to_utf16((char_u *)n, NULL);
7053 if (wn == NULL)
7054 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007055
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007056 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007057 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007058 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007059
7060 if (p & R_OK)
7061 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007062 // Read check is performed by seeing if we can do a find file on
7063 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007064 int i;
7065 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007066
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007067 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7068 TempNameW[i] = wn[i];
7069 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7070 TempNameW[i++] = '\\';
7071 TempNameW[i++] = '*';
7072 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007073
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007074 hFile = FindFirstFileW(TempNameW, &d);
7075 if (hFile == INVALID_HANDLE_VALUE)
7076 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007077 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007078 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007079 }
7080
7081 if (p & W_OK)
7082 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007083 // Trying to create a temporary file in the directory should catch
7084 // directories on read-only network shares. However, in
7085 // directories whose ACL allows writes but denies deletes will end
7086 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007087 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7088 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007089 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007090 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007091 }
7092 }
7093 else
7094 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007095 // Don't consider a file read-only if another process has opened it.
7096 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7097
Bram Moolenaar0f873732019-12-05 20:28:46 +01007098 // Trying to open the file for the required access does ACL, read-only
7099 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007100 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7101 | ((p & R_OK) ? GENERIC_READ : 0);
7102
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007103 hFile = CreateFileW(wn, access_mode, share_mode,
7104 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007105 if (hFile == INVALID_HANDLE_VALUE)
7106 goto getout;
7107 CloseHandle(hFile);
7108 }
7109
Bram Moolenaar0f873732019-12-05 20:28:46 +01007110 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007111getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007112 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007113 return retval;
7114}
7115
Bram Moolenaar071d4272004-06-13 20:20:40 +00007116/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007117 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007118 */
7119 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007120mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007121{
7122 WCHAR *wn;
7123 int f;
7124
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007125 wn = enc_to_utf16((char_u *)name, NULL);
7126 if (wn == NULL)
7127 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007128
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007129 f = _wopen(wn, flags, mode);
7130 vim_free(wn);
7131 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007132}
7133
7134/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007135 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007136 */
7137 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007138mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007139{
7140 WCHAR *wn, *wm;
7141 FILE *f = NULL;
7142
Bram Moolenaara12a1612019-01-24 16:39:02 +01007143#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007144 // Work around an annoying assertion in the Microsoft debug CRT
7145 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007146 char newMode = mode[strlen(mode) - 1];
7147 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007148
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007149 _get_fmode(&oldMode);
7150 if (newMode == 't')
7151 _set_fmode(_O_TEXT);
7152 else if (newMode == 'b')
7153 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007154#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007155 wn = enc_to_utf16((char_u *)name, NULL);
7156 wm = enc_to_utf16((char_u *)mode, NULL);
7157 if (wn != NULL && wm != NULL)
7158 f = _wfopen(wn, wm);
7159 vim_free(wn);
7160 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007161
Bram Moolenaara12a1612019-01-24 16:39:02 +01007162#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007163 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007164#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007165 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007166}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007167
Bram Moolenaar071d4272004-06-13 20:20:40 +00007168/*
7169 * SUB STREAM (aka info stream) handling:
7170 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007171 * NTFS can have sub streams for each file. The normal contents of a file is
7172 * stored in the main stream, and extra contents (author information, title and
7173 * so on) can be stored in a sub stream. After Windows 2000, the user can
7174 * access and store this information in sub streams via an explorer's property
7175 * menu item in the right click menu. This information in sub streams was lost
7176 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007177 *
7178 * Incomplete explanation:
7179 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7180 * More useful info and an example:
7181 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7182 */
7183
7184/*
7185 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7186 * and write to stream "substream" of file "to".
7187 * Errors are ignored.
7188 */
7189 static void
7190copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7191{
7192 HANDLE hTo;
7193 WCHAR *to_name;
7194
7195 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7196 wcscpy(to_name, to);
7197 wcscat(to_name, substream);
7198
7199 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7200 FILE_ATTRIBUTE_NORMAL, NULL);
7201 if (hTo != INVALID_HANDLE_VALUE)
7202 {
7203 long done;
7204 DWORD todo;
7205 DWORD readcnt, written;
7206 char buf[4096];
7207
Bram Moolenaar0f873732019-12-05 20:28:46 +01007208 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007209 for (done = 0; done < len; done += written)
7210 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007211 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007212 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7213 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007214 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7215 FALSE, FALSE, context)
7216 || readcnt != todo
7217 || !WriteFile(hTo, buf, todo, &written, NULL)
7218 || written != todo)
7219 break;
7220 }
7221 CloseHandle(hTo);
7222 }
7223
7224 free(to_name);
7225}
7226
7227/*
7228 * Copy info streams from file "from" to file "to".
7229 */
7230 static void
7231copy_infostreams(char_u *from, char_u *to)
7232{
7233 WCHAR *fromw;
7234 WCHAR *tow;
7235 HANDLE sh;
7236 WIN32_STREAM_ID sid;
7237 int headersize;
7238 WCHAR streamname[_MAX_PATH];
7239 DWORD readcount;
7240 void *context = NULL;
7241 DWORD lo, hi;
7242 int len;
7243
Bram Moolenaar0f873732019-12-05 20:28:46 +01007244 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007245 fromw = enc_to_utf16(from, NULL);
7246 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007247 if (fromw != NULL && tow != NULL)
7248 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007249 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007250 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7251 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7252 if (sh != INVALID_HANDLE_VALUE)
7253 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007254 // Use BackupRead() to find the info streams. Repeat until we
7255 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007256 for (;;)
7257 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007258 // Get the header to find the length of the stream name. If
7259 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007260 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007261 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007262 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7263 &readcount, FALSE, FALSE, &context)
7264 || readcount == 0)
7265 break;
7266
Bram Moolenaar0f873732019-12-05 20:28:46 +01007267 // We only deal with streams that have a name. The normal
7268 // file data appears to be without a name, even though docs
7269 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007270 if (sid.dwStreamNameSize > 0)
7271 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007272 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007273 if (!BackupRead(sh, (LPBYTE)streamname,
7274 sid.dwStreamNameSize,
7275 &readcount, FALSE, FALSE, &context))
7276 break;
7277
Bram Moolenaar0f873732019-12-05 20:28:46 +01007278 // Copy an info stream with a name ":anything:$DATA".
7279 // Skip "::$DATA", it has no stream name (examples suggest
7280 // it might be used for the normal file contents).
7281 // Note that BackupRead() counts bytes, but the name is in
7282 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007283 len = readcount / sizeof(WCHAR);
7284 streamname[len] = 0;
7285 if (len > 7 && wcsicmp(streamname + len - 6,
7286 L":$DATA") == 0)
7287 {
7288 streamname[len - 6] = 0;
7289 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007290 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007291 }
7292 }
7293
Bram Moolenaar0f873732019-12-05 20:28:46 +01007294 // Advance to the next stream. We might try seeking too far,
7295 // but BackupSeek() doesn't skip over stream borders, thus
7296 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007297 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007298 &lo, &hi, &context);
7299 }
7300
Bram Moolenaar0f873732019-12-05 20:28:46 +01007301 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007302 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7303
7304 CloseHandle(sh);
7305 }
7306 }
7307 vim_free(fromw);
7308 vim_free(tow);
7309}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007310
7311/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007312 * ntdll.dll definitions
7313 */
7314#define FileEaInformation 7
7315#ifndef STATUS_SUCCESS
7316# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7317#endif
7318
7319typedef struct _FILE_FULL_EA_INFORMATION_ {
7320 ULONG NextEntryOffset;
7321 UCHAR Flags;
7322 UCHAR EaNameLength;
7323 USHORT EaValueLength;
7324 CHAR EaName[1];
7325} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7326
7327typedef struct _FILE_EA_INFORMATION_ {
7328 ULONG EaSize;
7329} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7330
7331typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7332 PHANDLE FileHandle,
7333 ACCESS_MASK DesiredAccess,
7334 POBJECT_ATTRIBUTES ObjectAttributes,
7335 PIO_STATUS_BLOCK IoStatusBlock,
7336 ULONG ShareAccess,
7337 ULONG OpenOptions);
7338typedef NTSTATUS (NTAPI *PfnNtClose)(
7339 HANDLE Handle);
7340typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
7341 HANDLE FileHandle,
7342 PIO_STATUS_BLOCK IoStatusBlock,
7343 PVOID Buffer,
7344 ULONG Length);
7345typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7346 HANDLE FileHandle,
7347 PIO_STATUS_BLOCK IoStatusBlock,
7348 PVOID Buffer,
7349 ULONG Length,
7350 BOOLEAN ReturnSingleEntry,
7351 PVOID EaList,
7352 ULONG EaListLength,
7353 PULONG EaIndex,
7354 BOOLEAN RestartScan);
7355typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
7356 HANDLE FileHandle,
7357 PIO_STATUS_BLOCK IoStatusBlock,
7358 PVOID FileInformation,
7359 ULONG Length,
7360 FILE_INFORMATION_CLASS FileInformationClass);
7361typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7362 PUNICODE_STRING DestinationString,
7363 PCWSTR SourceString);
7364
7365PfnNtOpenFile pNtOpenFile = NULL;
7366PfnNtClose pNtClose = NULL;
7367PfnNtSetEaFile pNtSetEaFile = NULL;
7368PfnNtQueryEaFile pNtQueryEaFile = NULL;
7369PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7370PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
7371
7372/*
7373 * Load ntdll.dll functions.
7374 */
7375 static BOOL
7376load_ntdll(void)
7377{
7378 static int loaded = -1;
7379
7380 if (loaded == -1)
7381 {
7382 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7383 if (hNtdll != NULL)
7384 {
7385 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7386 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7387 pNtSetEaFile = (PfnNtSetEaFile)
7388 GetProcAddress(hNtdll, "NtSetEaFile");
7389 pNtQueryEaFile = (PfnNtQueryEaFile)
7390 GetProcAddress(hNtdll, "NtQueryEaFile");
7391 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7392 GetProcAddress(hNtdll, "NtQueryInformationFile");
7393 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7394 GetProcAddress(hNtdll, "RtlInitUnicodeString");
7395 }
7396 if (pNtOpenFile == NULL
7397 || pNtClose == NULL
7398 || pNtSetEaFile == NULL
7399 || pNtQueryEaFile == NULL
7400 || pNtQueryInformationFile == NULL
7401 || pRtlInitUnicodeString == NULL)
7402 loaded = FALSE;
7403 else
7404 loaded = TRUE;
7405 }
7406 return (BOOL) loaded;
7407}
7408
7409/*
7410 * Copy extended attributes (EA) from file "from" to file "to".
7411 */
7412 static void
7413copy_extattr(char_u *from, char_u *to)
7414{
7415 char_u *fromf = NULL;
7416 char_u *tof = NULL;
7417 WCHAR *fromw = NULL;
7418 WCHAR *tow = NULL;
7419 UNICODE_STRING u;
7420 HANDLE h;
7421 OBJECT_ATTRIBUTES oa;
7422 IO_STATUS_BLOCK iosb;
7423 FILE_EA_INFORMATION_ eainfo = {0};
7424 void *ea = NULL;
7425
7426 if (!load_ntdll())
7427 return;
7428
7429 // Convert the file names to the fully qualified object names.
7430 fromf = alloc(STRLEN(from) + 5);
7431 tof = alloc(STRLEN(to) + 5);
7432 if (fromf == NULL || tof == NULL)
7433 goto theend;
7434 STRCPY(fromf, "\\??\\");
7435 STRCAT(fromf, from);
7436 STRCPY(tof, "\\??\\");
7437 STRCAT(tof, to);
7438
7439 // Convert the names to wide characters.
7440 fromw = enc_to_utf16(fromf, NULL);
7441 tow = enc_to_utf16(tof, NULL);
7442 if (fromw == NULL || tow == NULL)
7443 goto theend;
7444
7445 // Get the EA.
7446 pRtlInitUnicodeString(&u, fromw);
7447 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7448 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7449 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7450 goto theend;
7451 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7452 FileEaInformation);
7453 if (eainfo.EaSize != 0)
7454 {
7455 ea = alloc(eainfo.EaSize);
7456 if (ea != NULL)
7457 {
7458 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7459 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7460 {
7461 vim_free(ea);
7462 ea = NULL;
7463 }
7464 }
7465 }
7466 pNtClose(h);
7467
7468 // Set the EA.
7469 if (ea != NULL)
7470 {
7471 pRtlInitUnicodeString(&u, tow);
7472 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7473 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7474 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7475 goto theend;
7476
7477 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
7478 pNtClose(h);
7479 }
7480
7481theend:
7482 vim_free(fromf);
7483 vim_free(tof);
7484 vim_free(fromw);
7485 vim_free(tow);
7486 vim_free(ea);
7487}
7488
7489/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007490 * Copy file attributes from file "from" to file "to".
7491 * For Windows NT and later we copy info streams.
7492 * Always returns zero, errors are ignored.
7493 */
7494 int
7495mch_copy_file_attribute(char_u *from, char_u *to)
7496{
Bram Moolenaar0f873732019-12-05 20:28:46 +01007497 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007498 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007499 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007500 return 0;
7501}
7502
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007503
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007504/*
K.Takatadc73b4b2021-06-08 18:32:36 +02007505 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007506 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007507static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007508static LPWSTR *ArglistW = NULL;
7509static int global_argc = 0;
7510static char **global_argv;
7511
Bram Moolenaar0f873732019-12-05 20:28:46 +01007512static int used_file_argc = 0; // last argument in global_argv[] used
7513 // for the argument list.
7514static int *used_file_indexes = NULL; // indexes in global_argv[] for
7515 // command line arguments added to
7516 // the argument list
7517static int used_file_count = 0; // nr of entries in used_file_indexes
7518static int used_file_literal = FALSE; // take file names literally
7519static int used_file_full_path = FALSE; // file name was full path
7520static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007521static int used_alist_count = 0;
7522
7523
7524/*
7525 * Get the command line arguments. Unicode version.
7526 * Returns argc. Zero when something fails.
7527 */
7528 int
7529get_cmd_argsW(char ***argvp)
7530{
7531 char **argv = NULL;
7532 int argc = 0;
7533 int i;
7534
Bram Moolenaar14993322014-09-09 12:25:33 +02007535 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007536 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7537 if (ArglistW != NULL)
7538 {
7539 argv = malloc((nArgsW + 1) * sizeof(char *));
7540 if (argv != NULL)
7541 {
7542 argc = nArgsW;
7543 argv[argc] = NULL;
7544 for (i = 0; i < argc; ++i)
7545 {
7546 int len;
7547
K.Takatadc73b4b2021-06-08 18:32:36 +02007548 // Convert each Unicode argument to UTF-8.
7549 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007550 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007551 (LPSTR *)&argv[i], &len, 0, 0);
7552 if (argv[i] == NULL)
7553 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007554 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007555 while (i > 0)
7556 free(argv[--i]);
7557 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007558 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007559 argc = 0;
7560 }
7561 }
7562 }
7563 }
7564
7565 global_argc = argc;
7566 global_argv = argv;
7567 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007568 {
7569 if (used_file_indexes != NULL)
7570 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007571 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007572 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007573
7574 if (argvp != NULL)
7575 *argvp = argv;
7576 return argc;
7577}
7578
7579 void
7580free_cmd_argsW(void)
7581{
7582 if (ArglistW != NULL)
7583 {
7584 GlobalFree(ArglistW);
7585 ArglistW = NULL;
7586 }
7587}
7588
7589/*
7590 * Remember "name" is an argument that was added to the argument list.
7591 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7592 * is called.
7593 */
7594 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007595used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007596{
7597 int i;
7598
7599 if (used_file_indexes == NULL)
7600 return;
7601 for (i = used_file_argc + 1; i < global_argc; ++i)
7602 if (STRCMP(global_argv[i], name) == 0)
7603 {
7604 used_file_argc = i;
7605 used_file_indexes[used_file_count++] = i;
7606 break;
7607 }
7608 used_file_literal = literal;
7609 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007610 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007611}
7612
7613/*
7614 * Remember the length of the argument list as it was. If it changes then we
7615 * leave it alone when 'encoding' is set.
7616 */
7617 void
7618set_alist_count(void)
7619{
7620 used_alist_count = GARGCOUNT;
7621}
7622
7623/*
7624 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02007625 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007626 * and convert them to 'encoding'.
7627 */
7628 void
7629fix_arg_enc(void)
7630{
7631 int i;
7632 int idx;
7633 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007634 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007635
Bram Moolenaar0f873732019-12-05 20:28:46 +01007636 // Safety checks:
7637 // - if argument count differs between the wide and non-wide argument
7638 // list, something must be wrong.
7639 // - the file name arguments must have been located.
7640 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007641 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007642 || ArglistW == NULL
7643 || used_file_indexes == NULL
7644 || used_file_count == 0
7645 || used_alist_count != GARGCOUNT)
7646 return;
7647
Bram Moolenaar0f873732019-12-05 20:28:46 +01007648 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007649 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007650 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007651 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00007652 for (i = 0; i < GARGCOUNT; ++i)
7653 fnum_list[i] = GARGLIST[i].ae_fnum;
7654
Bram Moolenaar0f873732019-12-05 20:28:46 +01007655 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007656 alist_clear(&global_alist);
7657 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007658 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007659
7660 for (i = 0; i < used_file_count; ++i)
7661 {
7662 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007663 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007664 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007665 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007666 int literal = used_file_literal;
7667
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007668#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01007669 // When using diff mode may need to concatenate file name to
7670 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007671 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7672 && !mch_isdir(alist_name(&GARGLIST[0])))
7673 {
7674 char_u *r;
7675
7676 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7677 if (r != NULL)
7678 {
7679 vim_free(str);
7680 str = r;
7681 }
7682 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007683#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01007684 // Re-use the old buffer by renaming it. When not using literal
7685 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00007686 if (used_file_literal)
7687 buf_set_name(fnum_list[i], str);
7688
Bram Moolenaar0f873732019-12-05 20:28:46 +01007689 // Check backtick literal. backtick literal is already expanded in
7690 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007691 if (literal == FALSE)
7692 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007693 size_t len = STRLEN(str);
7694
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007695 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7696 literal = TRUE;
7697 }
7698 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007699 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007700 }
7701
7702 if (!used_file_literal)
7703 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007704 // Now expand wildcards in the arguments.
7705 // Temporarily add '(' and ')' to 'isfname'. These are valid
7706 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00007707 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01007708 // Also, unset wildignore to not be influenced by this option.
7709 // The arguments specified in command-line should be kept even if
7710 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00007711 // Use :legacy so that it also works when in Vim9 script.
7712 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
7713 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007714 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00007715 do_cmdline_cmd(
7716 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
7717 do_cmdline_cmd(
7718 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007719 }
7720
Bram Moolenaar0f873732019-12-05 20:28:46 +01007721 // If wildcard expansion failed, we are editing the first file of the
7722 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007723 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7724 {
7725 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00007726 if (GARGCOUNT == 1 && used_file_full_path
7727 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
7728 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007729 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007730
7731 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007732}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007733
7734 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007735mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007736{
7737 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007738 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007739
Bram Moolenaar964b3742019-05-24 18:54:09 +02007740 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007741 if (envbuf == NULL)
7742 return -1;
7743
7744 sprintf((char *)envbuf, "%s=%s", var, value);
7745
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007746 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007747
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007748 vim_free(envbuf);
7749 if (p == NULL)
7750 return -1;
7751 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007752#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007753 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007754#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007755 // Unlike Un*x systems, we can free the string for _wputenv().
7756 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007757
7758 return 0;
7759}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007760
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007761/*
7762 * Support for 256 colors and 24-bit colors was added in Windows 10
7763 * version 1703 (Creators update).
7764 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007765#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7766
7767/*
7768 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02007769 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007770 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007771#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007772
7773/*
7774 * ConPTY differences between versions, need different logic.
7775 * version 1903 (May 2019 update).
7776 */
7777#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
7778
7779/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007780 * version 1909 (November 2019 update).
7781 */
7782#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
7783
7784/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007785 * Stay ahead of the next update, and when it's done, fix this.
7786 * version ? (2020 update, temporarily use the build number of insider preview)
7787 */
7788#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
7789
7790/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02007791 * Confirm until this version. Also the logic changes.
7792 * insider preview.
7793 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02007794#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007795
7796/*
7797 * Not stable now.
7798 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007799#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007800
7801 static void
7802vtp_flag_init(void)
7803{
7804 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007805#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007806 DWORD mode;
7807 HANDLE out;
7808
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007809# ifdef VIMDLL
7810 if (!gui.in_use)
7811# endif
7812 {
7813 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007814
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007815 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7816 GetConsoleMode(out, &mode);
7817 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7818 if (SetConsoleMode(out, mode) == 0)
7819 vtp_working = 0;
7820 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007821#endif
7822
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007823 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007824 conpty_working = 1;
7825 if (ver >= CONPTY_STABLE_BUILD)
7826 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007827
Bram Moolenaar57da6982019-09-13 22:30:11 +02007828 if (ver <= CONPTY_INSIDER_BUILD)
7829 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007830 if (ver <= CONPTY_1909_BUILD)
7831 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02007832 if (ver <= CONPTY_1903_BUILD)
7833 conpty_type = 2;
7834 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
7835 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007836
7837 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
7838 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007839}
7840
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007841#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007842
7843 static void
7844vtp_init(void)
7845{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007846 HMODULE hKerneldll;
7847 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007848# ifdef FEAT_TERMGUICOLORS
7849 COLORREF fg, bg;
7850# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007851
Bram Moolenaar0f873732019-12-05 20:28:46 +01007852 // Use functions supported from Vista
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007853 hKerneldll = GetModuleHandle("kernel32.dll");
7854 if (hKerneldll != NULL)
7855 {
7856 pGetConsoleScreenBufferInfoEx =
7857 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7858 hKerneldll, "GetConsoleScreenBufferInfoEx");
7859 pSetConsoleScreenBufferInfoEx =
7860 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7861 hKerneldll, "SetConsoleScreenBufferInfoEx");
7862 if (pGetConsoleScreenBufferInfoEx != NULL
7863 && pSetConsoleScreenBufferInfoEx != NULL)
7864 has_csbiex = TRUE;
7865 }
7866
7867 csbi.cbSize = sizeof(csbi);
7868 if (has_csbiex)
7869 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007870 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7871 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
Bram Moolenaardf543822020-01-30 11:53:59 +01007872 store_console_bg_rgb = save_console_bg_rgb;
7873 store_console_fg_rgb = save_console_fg_rgb;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007874
7875# ifdef FEAT_TERMGUICOLORS
7876 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7877 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7878 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7879 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7880 default_console_color_bg = bg;
7881 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007882# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007883
7884 set_console_color_rgb();
7885}
7886
7887 static void
7888vtp_exit(void)
7889{
Bram Moolenaardf543822020-01-30 11:53:59 +01007890 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007891}
7892
Bram Moolenaar06b7b582020-05-30 17:49:25 +02007893 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007894vtp_printf(
7895 char *format,
7896 ...)
7897{
7898 char_u buf[100];
7899 va_list list;
7900 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007901 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007902
7903 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007904 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007905 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007906 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007907 return (int)result;
7908}
7909
7910 static void
7911vtp_sgr_bulk(
7912 int arg)
7913{
7914 int args[1];
7915
7916 args[0] = arg;
7917 vtp_sgr_bulks(1, args);
7918}
7919
K.Takata6e1d31e2022-02-03 13:05:32 +00007920# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007921 if ((*p-- = "0123456789"[(n = x % 10)]) \
7922 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
7923 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
7924
K.Takata6e1d31e2022-02-03 13:05:32 +00007925# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007926 case x: \
7927 FAST256(newargs[x - 1]);
7928
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007929 static void
7930vtp_sgr_bulks(
7931 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007932 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007933{
K.Takata6e1d31e2022-02-03 13:05:32 +00007934# define MAXSGR 16
7935# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007936 char_u buf[SGRBUFSIZE];
7937 char_u *p;
7938 int in, out;
7939 int newargs[16];
7940 static int sgrfgr = -1, sgrfgg, sgrfgb;
7941 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007942
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007943 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007944 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007945 sgrfgr = sgrbgr = -1;
7946 vtp_printf("033[m");
7947 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007948 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007949
7950 in = out = 0;
7951 while (in < argc)
7952 {
7953 int s = args[in];
7954 int copylen = 1;
7955
7956 if (s == 38)
7957 {
7958 if (argc - in >= 5 && args[in + 1] == 2)
7959 {
7960 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
7961 && sgrfgb == args[in + 4])
7962 {
7963 in += 5;
7964 copylen = 0;
7965 }
7966 else
7967 {
7968 sgrfgr = args[in + 2];
7969 sgrfgg = args[in + 3];
7970 sgrfgb = args[in + 4];
7971 copylen = 5;
7972 }
7973 }
7974 else if (argc - in >= 3 && args[in + 1] == 5)
7975 {
7976 sgrfgr = -1;
7977 copylen = 3;
7978 }
7979 }
7980 else if (s == 48)
7981 {
7982 if (argc - in >= 5 && args[in + 1] == 2)
7983 {
7984 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
7985 && sgrbgb == args[in + 4])
7986 {
7987 in += 5;
7988 copylen = 0;
7989 }
7990 else
7991 {
7992 sgrbgr = args[in + 2];
7993 sgrbgg = args[in + 3];
7994 sgrbgb = args[in + 4];
7995 copylen = 5;
7996 }
7997 }
7998 else if (argc - in >= 3 && args[in + 1] == 5)
7999 {
8000 sgrbgr = -1;
8001 copylen = 3;
8002 }
8003 }
8004 else if (30 <= s && s <= 39)
8005 sgrfgr = -1;
8006 else if (90 <= s && s <= 97)
8007 sgrfgr = -1;
8008 else if (40 <= s && s <= 49)
8009 sgrbgr = -1;
8010 else if (100 <= s && s <= 107)
8011 sgrbgr = -1;
8012 else if (s == 0)
8013 sgrfgr = sgrbgr = -1;
8014
8015 while (copylen--)
8016 newargs[out++] = args[in++];
8017 }
8018
8019 p = &buf[sizeof(buf) - 1];
8020 *p-- = 'm';
8021
8022 switch (out)
8023 {
8024 int n, m;
8025 DWORD r;
8026
8027 FAST256CASE(16);
8028 *p-- = ';';
8029 FAST256CASE(15);
8030 *p-- = ';';
8031 FAST256CASE(14);
8032 *p-- = ';';
8033 FAST256CASE(13);
8034 *p-- = ';';
8035 FAST256CASE(12);
8036 *p-- = ';';
8037 FAST256CASE(11);
8038 *p-- = ';';
8039 FAST256CASE(10);
8040 *p-- = ';';
8041 FAST256CASE(9);
8042 *p-- = ';';
8043 FAST256CASE(8);
8044 *p-- = ';';
8045 FAST256CASE(7);
8046 *p-- = ';';
8047 FAST256CASE(6);
8048 *p-- = ';';
8049 FAST256CASE(5);
8050 *p-- = ';';
8051 FAST256CASE(4);
8052 *p-- = ';';
8053 FAST256CASE(3);
8054 *p-- = ';';
8055 FAST256CASE(2);
8056 *p-- = ';';
8057 FAST256CASE(1);
8058 *p-- = '[';
8059 *p = '\033';
8060 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8061 default:
8062 break;
8063 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008064}
8065
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008066 static void
8067wt_init(void)
8068{
8069 wt_working = (mch_getenv("WT_SESSION") != NULL);
8070}
8071
8072 int
8073use_wt(void)
8074{
8075 return USE_WT;
8076}
8077
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008078# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008079 static int
8080ctermtoxterm(
8081 int cterm)
8082{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008083 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008084
8085 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8086 return (((int)r << 16) | ((int)g << 8) | (int)b);
8087}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008088# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008089
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008090 static void
8091set_console_color_rgb(void)
8092{
8093# ifdef FEAT_TERMGUICOLORS
8094 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008095 guicolor_T fg, bg;
8096 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008097
8098 if (!USE_VTP)
8099 return;
8100
Bram Moolenaara050b942019-12-02 21:35:31 +01008101 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8102
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008103 if (USE_WT)
8104 {
8105 term_fg_rgb_color(fg);
8106 term_bg_rgb_color(bg);
8107 return;
8108 }
8109
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008110 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8111 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8112
8113 csbi.cbSize = sizeof(csbi);
8114 if (has_csbiex)
8115 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8116
8117 csbi.cbSize = sizeof(csbi);
8118 csbi.srWindow.Right += 1;
8119 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008120 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8121 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008122 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8123 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008124 if (has_csbiex)
8125 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8126# endif
8127}
8128
Bram Moolenaara050b942019-12-02 21:35:31 +01008129# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8130 void
8131get_default_console_color(
8132 int *cterm_fg,
8133 int *cterm_bg,
8134 guicolor_T *gui_fg,
8135 guicolor_T *gui_bg)
8136{
8137 int id;
8138 guicolor_T guifg = INVALCOLOR;
8139 guicolor_T guibg = INVALCOLOR;
8140 int ctermfg = 0;
8141 int ctermbg = 0;
8142
8143 id = syn_name2id((char_u *)"Normal");
8144 if (id > 0 && p_tgc)
8145 syn_id2colors(id, &guifg, &guibg);
8146 if (guifg == INVALCOLOR)
8147 {
8148 ctermfg = -1;
8149 if (id > 0)
8150 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8151 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
8152 : default_console_color_fg;
8153 cterm_normal_fg_gui_color = guifg;
8154 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8155 }
8156 if (guibg == INVALCOLOR)
8157 {
8158 ctermbg = -1;
8159 if (id > 0)
8160 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8161 guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8162 : default_console_color_bg;
8163 cterm_normal_bg_gui_color = guibg;
8164 ctermbg = ctermbg < 0 ? 0 : ctermbg;
8165 }
8166
8167 *cterm_fg = ctermfg;
8168 *cterm_bg = ctermbg;
8169 *gui_fg = guifg;
8170 *gui_bg = guibg;
8171}
8172# endif
8173
Bram Moolenaardf543822020-01-30 11:53:59 +01008174/*
8175 * Set the console colors to the original colors or the last set colors.
8176 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008177 static void
8178reset_console_color_rgb(void)
8179{
8180# ifdef FEAT_TERMGUICOLORS
8181 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8182
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008183 if (USE_WT)
8184 return;
8185
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008186 csbi.cbSize = sizeof(csbi);
8187 if (has_csbiex)
8188 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8189
8190 csbi.cbSize = sizeof(csbi);
8191 csbi.srWindow.Right += 1;
8192 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008193 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8194 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
8195 if (has_csbiex)
8196 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8197# endif
8198}
8199
8200/*
8201 * Set the console colors to the original colors.
8202 */
8203 static void
8204restore_console_color_rgb(void)
8205{
8206# ifdef FEAT_TERMGUICOLORS
8207 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8208
8209 csbi.cbSize = sizeof(csbi);
8210 if (has_csbiex)
8211 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8212
8213 csbi.cbSize = sizeof(csbi);
8214 csbi.srWindow.Right += 1;
8215 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008216 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8217 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008218 if (has_csbiex)
8219 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8220# endif
8221}
8222
8223 void
8224control_console_color_rgb(void)
8225{
8226 if (USE_VTP)
8227 set_console_color_rgb();
8228 else
8229 reset_console_color_rgb();
8230}
8231
8232 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008233use_vtp(void)
8234{
8235 return USE_VTP;
8236}
8237
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008238 int
8239is_term_win32(void)
8240{
8241 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8242}
8243
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008244 int
8245has_vtp_working(void)
8246{
8247 return vtp_working;
8248}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008249
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008250#endif
8251
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008252 int
8253has_conpty_working(void)
8254{
8255 return conpty_working;
8256}
8257
8258 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008259get_conpty_type(void)
8260{
8261 return conpty_type;
8262}
8263
8264 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008265is_conpty_stable(void)
8266{
8267 return conpty_stable;
8268}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008269
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008270 int
8271get_conpty_fix_type(void)
8272{
8273 return conpty_fix_type;
8274}
8275
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008276#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008277 void
8278resize_console_buf(void)
8279{
8280 CONSOLE_SCREEN_BUFFER_INFO csbi;
8281 COORD coord;
8282 SMALL_RECT newsize;
8283
8284 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8285 {
8286 coord.X = SRWIDTH(csbi.srWindow);
8287 coord.Y = SRHEIGHT(csbi.srWindow);
8288 SetConsoleScreenBufferSize(g_hConOut, coord);
8289
8290 newsize.Left = 0;
8291 newsize.Top = 0;
8292 newsize.Right = coord.X - 1;
8293 newsize.Bottom = coord.Y - 1;
8294 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8295
8296 SetConsoleScreenBufferSize(g_hConOut, coord);
8297 }
8298}
8299#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008300
8301 char *
8302GetWin32Error(void)
8303{
K.Takatad68b2fc2022-02-12 11:18:37 +00008304 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008305 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008306
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008307 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8308 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008309 if (oldmsg != NULL)
8310 LocalFree(oldmsg);
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008311 if (msg != NULL)
8312 {
8313 // remove trailing \r\n
8314 char *pcrlf = strstr(msg, "\r\n");
8315 if (pcrlf != NULL)
8316 *pcrlf = '\0';
K.Takatad68b2fc2022-02-12 11:18:37 +00008317 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008318 }
8319 return msg;
8320}