blob: 7cb45d557ce2c5f6c7e35fc2d47707ec9a8990bf [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
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200214static int default_console_color_fg = 0xc0c0c0; // white
215# endif
216
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100217# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200218# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200219# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100220# else
221# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200222# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100223# endif
224
225static void set_console_color_rgb(void);
226static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100227static void restore_console_color_rgb(void);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100228#endif
229
Bram Moolenaar0f873732019-12-05 20:28:46 +0100230// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100231#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
232# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
233#endif
234
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200235#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100236static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000237#endif
238
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200239static char_u *exe_path = NULL;
240
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100241static BOOL win8_or_later = FALSE;
242
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200243#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100244// Dynamic loading for portability
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100245typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
246{
247 ULONG cbSize;
248 COORD dwSize;
249 COORD dwCursorPosition;
250 WORD wAttributes;
251 SMALL_RECT srWindow;
252 COORD dwMaximumWindowSize;
253 WORD wPopupAttributes;
254 BOOL bFullscreenSupported;
255 COLORREF ColorTable[16];
256} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
257typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
258static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
259typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
260static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
261static BOOL has_csbiex = FALSE;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100262#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100263
264/*
265 * Get version number including build number
266 */
267typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100268#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100269 (((major) << 24) | ((minor) << 16) | (build))
270
271 static DWORD
272get_build_number(void)
273{
274 OSVERSIONINFOW osver = {sizeof(OSVERSIONINFOW)};
275 HMODULE hNtdll;
276 PfnRtlGetVersion pRtlGetVersion;
277 DWORD ver = MAKE_VER(0, 0, 0);
278
279 hNtdll = GetModuleHandle("ntdll.dll");
280 if (hNtdll != NULL)
281 {
282 pRtlGetVersion =
283 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
284 pRtlGetVersion(&osver);
285 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
286 min(osver.dwMinorVersion, 255),
287 min(osver.dwBuildNumber, 32767));
288 }
289 return ver;
290}
291
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200292#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200293 static BOOL
294is_ambiwidth_event(
295 INPUT_RECORD *ir)
296{
297 return ir->EventType == KEY_EVENT
298 && ir->Event.KeyEvent.bKeyDown
299 && ir->Event.KeyEvent.wRepeatCount == 1
300 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
301 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000302 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200303 && ir->Event.KeyEvent.dwControlKeyState == 2;
304}
305
306 static void
307make_ambiwidth_event(
308 INPUT_RECORD *down,
309 INPUT_RECORD *up)
310{
311 down->Event.KeyEvent.wVirtualKeyCode = 0;
312 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000313 down->Event.KeyEvent.uChar.UnicodeChar
314 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200315 down->Event.KeyEvent.dwControlKeyState = 0;
316}
317
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100318/*
319 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100320 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100321 */
322 static BOOL
323read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100324 HANDLE hInput,
325 INPUT_RECORD *lpBuffer,
326 DWORD nLength,
327 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100328{
329 enum
330 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100331 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100332 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100333 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100334 static DWORD s_dwIndex = 0;
335 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100336 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100337 int head;
338 int tail;
339 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200340 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100341
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200342 if (nLength == -2)
343 return (s_dwMax > 0) ? TRUE : FALSE;
344
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100345 if (!win8_or_later)
346 {
347 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200348 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
349 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100350 }
351
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100352 if (s_dwMax == 0)
353 {
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200354 if (!USE_WT && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200355 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200356 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
357 if (dwEvents == 0 && nLength == -1)
358 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
359 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100360 s_dwIndex = 0;
361 s_dwMax = dwEvents;
362 if (dwEvents == 0)
363 {
364 *lpEvents = 0;
365 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100366 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100367
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200368 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
369 if (is_ambiwidth_event(&s_irCache[i]))
370 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
371
Bram Moolenaardd415a62014-02-05 14:02:27 +0100372 if (s_dwMax > 1)
373 {
374 head = 0;
375 tail = s_dwMax - 1;
376 while (head != tail)
377 {
378 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
379 && s_irCache[head + 1].EventType
380 == WINDOW_BUFFER_SIZE_EVENT)
381 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100382 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100383 for (i = head; i < tail; ++i)
384 s_irCache[i] = s_irCache[i + 1];
385 --tail;
386 continue;
387 }
388 head++;
389 }
390 s_dwMax = tail + 1;
391 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100392 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100393
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200394 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
395 {
396 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
397 {
398 s_irPseudo = s_irCache[s_dwIndex];
399 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
400 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
401 *lpBuffer = s_irPseudo;
402 *lpEvents = 1;
403 return TRUE;
404 }
405 }
406
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100407 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200408 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100409 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100410 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100411 return TRUE;
412}
413
414/*
415 * Version of PeekConsoleInput() that works with IME.
416 */
417 static BOOL
418peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100419 HANDLE hInput,
420 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200421 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100422 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100423{
K.Takata135e1522022-01-29 15:27:58 +0000424 return read_console_input(hInput, lpBuffer, (DWORD)-1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100425}
426
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100427# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200428 static DWORD
429msg_wait_for_multiple_objects(
430 DWORD nCount,
431 LPHANDLE pHandles,
432 BOOL fWaitAll,
433 DWORD dwMilliseconds,
434 DWORD dwWakeMask)
435{
K.Takata135e1522022-01-29 15:27:58 +0000436 if (read_console_input(NULL, NULL, (DWORD)-2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200437 return WAIT_OBJECT_0;
438 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
439 dwMilliseconds, dwWakeMask);
440}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100441# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200442
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100443# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200444 static DWORD
445wait_for_single_object(
446 HANDLE hHandle,
447 DWORD dwMilliseconds)
448{
K.Takata54119102022-02-03 13:33:03 +0000449 if (read_console_input(NULL, NULL, (DWORD)-2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200450 return WAIT_OBJECT_0;
451 return WaitForSingleObject(hHandle, dwMilliseconds);
452}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100453# endif
454#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200455
Bram Moolenaar071d4272004-06-13 20:20:40 +0000456 static void
457get_exe_name(void)
458{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100459 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
460 // as the maximum length that works (plus a NUL byte).
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100461#define MAX_ENV_PATH_LEN 8192
462 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200463 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000464
465 if (exe_name == NULL)
466 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100467 // store the name of the executable, may be used for $VIM
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100468 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000469 if (*temp != NUL)
470 exe_name = FullName_save((char_u *)temp, FALSE);
471 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000472
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200473 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000474 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200475 exe_path = vim_strnsave(exe_name, gettail_sep(exe_name) - exe_name);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200476 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000477 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100478 // Append our starting directory to $PATH, so that when doing
479 // "!xxd" it's found in our starting directory. Needed because
480 // SearchPath() also looks there.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200481 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100482 if (p == NULL
483 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200484 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100485 if (p == NULL || *p == NUL)
486 temp[0] = NUL;
487 else
488 {
489 STRCPY(temp, p);
490 STRCAT(temp, ";");
491 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200492 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100493 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200494 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000495 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000496 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000497}
498
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200499/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100500 * Unescape characters in "p" that appear in "escaped".
501 */
502 static void
503unescape_shellxquote(char_u *p, char_u *escaped)
504{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100505 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100506 int n;
507
508 while (*p != NUL)
509 {
510 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
511 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100512 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100513 p += n;
514 l -= n;
515 }
516}
517
518/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200519 * Load library "name".
520 */
521 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000522vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200523{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200524 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200525
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200526 // No need to load any library when registering OLE.
527 if (found_register_arg)
528 return dll;
529
Bram Moolenaar0f873732019-12-05 20:28:46 +0100530 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
531 // vimLoadLib() recursively, which causes a stack overflow.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200532 if (exe_path == NULL)
533 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200534 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200535 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200536 WCHAR old_dirw[MAXPATHL];
537
538 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
539 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100540 // Change directory to where the executable is, both to make
541 // sure we find a .dll there and to avoid looking for a .dll
542 // in the current directory.
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100543 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200544 dll = LoadLibrary(name);
545 SetCurrentDirectoryW(old_dirw);
546 return dll;
547 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200548 }
549 return dll;
550}
551
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200552#if defined(VIMDLL) || defined(PROTO)
553/*
554 * Check if the current executable file is for the GUI subsystem.
555 */
556 int
557mch_is_gui_executable(void)
558{
559 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
560 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
561 PIMAGE_NT_HEADERS pPE;
562
563 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
564 return FALSE;
565 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
566 if (pPE->Signature != IMAGE_NT_SIGNATURE)
567 return FALSE;
568 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
569 return TRUE;
570 return FALSE;
571}
572#endif
573
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000574#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
575 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100576/*
577 * Get related information about 'funcname' which is imported by 'hInst'.
578 * If 'info' is 0, return the function address.
579 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000580 * If 'info' is 2, hook the function with 'ptr', and return the original
581 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100582 */
583 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000584get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
585 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100586{
587 PBYTE pImage = (PBYTE)hInst;
588 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
589 PIMAGE_NT_HEADERS pPE;
590 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100591 PIMAGE_THUNK_DATA pIAT; // Import Address Table
592 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100593 PIMAGE_IMPORT_BY_NAME pImpName;
594
595 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
596 return NULL;
597 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
598 if (pPE->Signature != IMAGE_NT_SIGNATURE)
599 return NULL;
600 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
601 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
602 .VirtualAddress);
603 for (; pImpDesc->FirstThunk; ++pImpDesc)
604 {
605 if (!pImpDesc->OriginalFirstThunk)
606 continue;
607 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
608 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
609 for (; pIAT->u1.Function; ++pIAT, ++pINT)
610 {
611 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
612 continue;
613 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
614 + (UINT_PTR)(pINT->u1.AddressOfData));
615 if (strcmp((char *)pImpName->Name, funcname) == 0)
616 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000617 void *original;
618 DWORD old, new = PAGE_READWRITE;
619
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100620 switch (info)
621 {
622 case 0:
623 return (void *)pIAT->u1.Function;
624 case 1:
625 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000626 case 2:
627 original = (void *)pIAT->u1.Function;
628 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
629 new, &old);
630 pIAT->u1.Function = (UINT_PTR)ptr;
631 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
632 old, &new);
633 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100634 default:
635 return NULL;
636 }
637 }
638 }
639 }
640 return NULL;
641}
642
643/*
644 * Get the module handle which 'funcname' in 'hInst' is imported from.
645 */
646 HINSTANCE
647find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
648{
649 char *modulename;
650
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000651 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100652 if (modulename != NULL)
653 return GetModuleHandleA(modulename);
654 return NULL;
655}
656
657/*
658 * Get the address of 'funcname' which is imported by 'hInst' DLL.
659 */
660 void *
661get_dll_import_func(HINSTANCE hInst, const char *funcname)
662{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000663 return get_imported_func_info(hInst, funcname, 0, NULL);
664}
665
666/*
667 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
668 * and return the original function address.
669 */
670 void *
671hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
672{
673 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100674}
675#endif
676
Bram Moolenaar071d4272004-06-13 20:20:40 +0000677#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
678# ifndef GETTEXT_DLL
679# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200680# define GETTEXT_DLL_ALT1 "libintl-8.dll"
681# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000682# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100683// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000684static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200685static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000686static char *null_libintl_textdomain(const char *);
687static char *null_libintl_bindtextdomain(const char *, const char *);
688static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100689static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000690
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200691static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000692char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200693char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
694 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000695char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
696char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000697 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000698char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
699 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100700int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000701
702 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100703dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000704{
705 int i;
706 static struct
707 {
708 char *name;
709 FARPROC *ptr;
710 } libintl_entry[] =
711 {
712 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200713 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000714 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
715 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
716 {NULL, NULL}
717 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100718 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000719
Bram Moolenaar7554c542018-10-06 15:03:15 +0200720 // No need to initialize twice.
721 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000722 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200723 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100724 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100725# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100726 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200727 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100728# endif
729# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200730 if (!hLibintlDLL)
731 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100732# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100733 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000734 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200735 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000736 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200737 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000738 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200739 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000740 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200741 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000742 }
743 for (i = 0; libintl_entry[i].name != NULL
744 && libintl_entry[i].ptr != NULL; ++i)
745 {
K.Takata54119102022-02-03 13:33:03 +0000746 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000747 libintl_entry[i].name)) == NULL)
748 {
749 dyn_libintl_end();
750 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000751 {
752 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000753 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000754 verbose_leave();
755 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000756 return 0;
757 }
758 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000759
Bram Moolenaar0f873732019-12-05 20:28:46 +0100760 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000761 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000762 "bind_textdomain_codeset");
763 if (dyn_libintl_bind_textdomain_codeset == NULL)
764 dyn_libintl_bind_textdomain_codeset =
765 null_libintl_bind_textdomain_codeset;
766
Bram Moolenaar0f873732019-12-05 20:28:46 +0100767 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100768 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
769 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100770 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100771 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
772 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100773
Bram Moolenaar071d4272004-06-13 20:20:40 +0000774 return 1;
775}
776
777 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100778dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000779{
780 if (hLibintlDLL)
781 FreeLibrary(hLibintlDLL);
782 hLibintlDLL = NULL;
783 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200784 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000785 dyn_libintl_textdomain = null_libintl_textdomain;
786 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000787 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100788 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000789}
790
791 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000792null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000793{
794 return (char*)msgid;
795}
796
797 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200798null_libintl_ngettext(
799 const char *msgid,
800 const char *msgid_plural,
801 unsigned long n)
802{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200803 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200804}
805
Bram Moolenaaree695f72016-08-03 22:08:45 +0200806 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100807null_libintl_bindtextdomain(
808 const char *domainname UNUSED,
809 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000810{
811 return NULL;
812}
813
814 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100815null_libintl_bind_textdomain_codeset(
816 const char *domainname UNUSED,
817 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000818{
819 return NULL;
820}
821
822 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100823null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000824{
825 return NULL;
826}
827
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200828 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100829null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100830{
831 return 0;
832}
833
Bram Moolenaar0f873732019-12-05 20:28:46 +0100834#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000835
Bram Moolenaar0f873732019-12-05 20:28:46 +0100836// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000837
838#ifndef VER_PLATFORM_WIN32_WINDOWS
839# define VER_PLATFORM_WIN32_WINDOWS 1
840#endif
841
Bram Moolenaar071d4272004-06-13 20:20:40 +0000842#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100843# ifndef PROTO
844# include <aclapi.h>
845# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200846# ifndef PROTECTED_DACL_SECURITY_INFORMATION
847# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
848# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000849#endif
850
Bram Moolenaar27515922013-06-29 15:36:26 +0200851#ifdef HAVE_ACL
852/*
853 * Enables or disables the specified privilege.
854 */
855 static BOOL
856win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
857{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100858 BOOL bResult;
859 LUID luid;
860 HANDLE hToken;
861 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200862
863 if (!OpenProcessToken(GetCurrentProcess(),
864 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
865 return FALSE;
866
867 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
868 {
869 CloseHandle(hToken);
870 return FALSE;
871 }
872
Bram Moolenaar45500912014-07-09 20:51:07 +0200873 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200874 tokenPrivileges.Privileges[0].Luid = luid;
875 tokenPrivileges.Privileges[0].Attributes = bEnable ?
876 SE_PRIVILEGE_ENABLED : 0;
877
878 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
879 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
880
881 CloseHandle(hToken);
882
883 return bResult && GetLastError() == ERROR_SUCCESS;
884}
885#endif
886
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100887#ifdef _MSC_VER
888// Suppress the deprecation warning for using GetVersionEx().
889// It is needed for implementing "windowsversion()".
890# pragma warning(push)
891# pragma warning(disable: 4996)
892#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000893/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200894 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000895 */
896 void
897PlatformId(void)
898{
899 static int done = FALSE;
900
901 if (!done)
902 {
903 OSVERSIONINFO ovi;
904
905 ovi.dwOSVersionInfoSize = sizeof(ovi);
906 GetVersionEx(&ovi);
907
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200908#ifdef FEAT_EVAL
Bram Moolenaar0c1e3742019-12-27 13:49:24 +0100909 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
910 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200911#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100912 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
913 || ovi.dwMajorVersion > 6)
914 win8_or_later = TRUE;
915
Bram Moolenaar071d4272004-06-13 20:20:40 +0000916#ifdef HAVE_ACL
Bram Moolenaar0f873732019-12-05 20:28:46 +0100917 // Enable privilege for getting or setting SACLs.
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200918 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000919#endif
920 done = TRUE;
921 }
922}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100923#ifdef _MSC_VER
924# pragma warning(pop)
925#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000926
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200927#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000928
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100929# define SHIFT (SHIFT_PRESSED)
930# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
931# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
932# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000933
934
Bram Moolenaar0f873732019-12-05 20:28:46 +0100935// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
936// We map function keys to their ANSI terminal equivalents, as produced
937// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
938// ANSI key with a value >= '\300' is nonstandard, but provided anyway
939// so that the user can have access to all SHIFT-, CTRL-, and ALT-
940// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000941
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000942static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000943{
944 WORD wVirtKey;
945 BOOL fAnsiKey;
946 int chAlone;
947 int chShift;
948 int chCtrl;
949 int chAlt;
950} VirtKeyMap[] =
951{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200952// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000953 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
954
955 { VK_F1, TRUE, ';', 'T', '^', 'h', },
956 { VK_F2, TRUE, '<', 'U', '_', 'i', },
957 { VK_F3, TRUE, '=', 'V', '`', 'j', },
958 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
959 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
960 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
961 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
962 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
963 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
964 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200965 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
966 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000967
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200968 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
969 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
970 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
971 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
972 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
973 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
974 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
975 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
976 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
977 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100978 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000979
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200980 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000981
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100982# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200983 // Most people don't have F13-F20, but what the hell...
984 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
985 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
986 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
987 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
988 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
989 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
990 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
991 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100992# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200993 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
994 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
995 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
996 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000997
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200998 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
999 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
1000 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
1001 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
1002 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
1003 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
1004 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
1005 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
1006 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
1007 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001008 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001009};
1010
1011
Bram Moolenaar0f873732019-12-05 20:28:46 +01001012/*
1013 * The return code indicates key code size.
1014 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001015 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001016win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001017 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001018{
1019 UINT uMods = pker->dwControlKeyState;
1020 static int s_iIsDead = 0;
1021 static WORD awAnsiCode[2];
1022 static BYTE abKeystate[256];
1023
1024
1025 if (s_iIsDead == 2)
1026 {
K.Takata972db232022-02-04 10:45:38 +00001027 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001028 s_iIsDead = 0;
1029 return 1;
1030 }
1031
K.Takata972db232022-02-04 10:45:38 +00001032 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001033 return 1;
1034
Bram Moolenaara80faa82020-04-12 19:37:17 +02001035 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001036
Bram Moolenaar0f873732019-12-05 20:28:46 +01001037 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001038 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001039
1040 if (uMods & SHIFT_PRESSED)
1041 abKeystate[VK_SHIFT] = 0x80;
1042 if (uMods & CAPSLOCK_ON)
1043 abKeystate[VK_CAPITAL] = 1;
1044
1045 if ((uMods & ALT_GR) == ALT_GR)
1046 {
1047 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1048 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1049 }
1050
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001051 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1052 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001053
1054 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001055 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001056
1057 return s_iIsDead;
1058}
1059
Bram Moolenaar071d4272004-06-13 20:20:40 +00001060static BOOL g_fJustGotFocus = FALSE;
1061
1062/*
1063 * Decode a KEY_EVENT into one or two keystrokes
1064 */
1065 static BOOL
1066decode_key_event(
1067 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001068 WCHAR *pch,
1069 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001070 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001071 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001072{
1073 int i;
1074 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1075
1076 *pch = *pch2 = NUL;
1077 g_fJustGotFocus = FALSE;
1078
Bram Moolenaar0f873732019-12-05 20:28:46 +01001079 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001080 if (!pker->bKeyDown)
1081 return FALSE;
1082
Bram Moolenaar0f873732019-12-05 20:28:46 +01001083 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001084 switch (pker->wVirtualKeyCode)
1085 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001086 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001087 case VK_SHIFT:
1088 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001089 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001090 return FALSE;
1091
1092 default:
1093 break;
1094 }
1095
Bram Moolenaar0f873732019-12-05 20:28:46 +01001096 // special cases
K.Takata972db232022-02-04 10:45:38 +00001097 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0
1098 && pker->uChar.UnicodeChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001099 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001100 // Ctrl-6 is Ctrl-^
Bram Moolenaar071d4272004-06-13 20:20:40 +00001101 if (pker->wVirtualKeyCode == '6')
1102 {
1103 *pch = Ctrl_HAT;
1104 return TRUE;
1105 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001106 // Ctrl-2 is Ctrl-@
Bram Moolenaar071d4272004-06-13 20:20:40 +00001107 else if (pker->wVirtualKeyCode == '2')
1108 {
1109 *pch = NUL;
1110 return TRUE;
1111 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001112 // Ctrl-- is Ctrl-_
Bram Moolenaar071d4272004-06-13 20:20:40 +00001113 else if (pker->wVirtualKeyCode == 0xBD)
1114 {
1115 *pch = Ctrl__;
1116 return TRUE;
1117 }
1118 }
1119
Bram Moolenaar0f873732019-12-05 20:28:46 +01001120 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001121 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1122 {
1123 *pch = K_NUL;
1124 *pch2 = '\017';
1125 return TRUE;
1126 }
1127
K.Takataeeec2542021-06-02 13:28:16 +02001128 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001129 {
1130 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1131 {
1132 if (nModifs == 0)
1133 *pch = VirtKeyMap[i].chAlone;
1134 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1135 *pch = VirtKeyMap[i].chShift;
1136 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1137 *pch = VirtKeyMap[i].chCtrl;
1138 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1139 *pch = VirtKeyMap[i].chAlt;
1140
1141 if (*pch != 0)
1142 {
1143 if (VirtKeyMap[i].fAnsiKey)
1144 {
1145 *pch2 = *pch;
1146 *pch = K_NUL;
1147 }
1148
1149 return TRUE;
1150 }
1151 }
1152 }
1153
1154 i = win32_kbd_patch_key(pker);
1155
1156 if (i < 0)
1157 *pch = NUL;
1158 else
1159 {
K.Takata972db232022-02-04 10:45:38 +00001160 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001161
1162 if (pmodifiers != NULL)
1163 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001164 // Pass on the ALT key as a modifier, but only when not combined
1165 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001166 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1167 *pmodifiers |= MOD_MASK_ALT;
1168
Bram Moolenaar0f873732019-12-05 20:28:46 +01001169 // Pass on SHIFT only for special keys, because we don't know when
1170 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001171 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1172 *pmodifiers |= MOD_MASK_SHIFT;
1173
Bram Moolenaar0f873732019-12-05 20:28:46 +01001174 // Pass on CTRL only for non-special keys, because we don't know
1175 // when it's already included with the character. And not when
1176 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001177 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1178 && *pch >= 0x20 && *pch < 0x80)
1179 *pmodifiers |= MOD_MASK_CTRL;
1180 }
1181 }
1182
1183 return (*pch != NUL);
1184}
1185
Bram Moolenaar0f873732019-12-05 20:28:46 +01001186#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001187
1188
Bram Moolenaar071d4272004-06-13 20:20:40 +00001189/*
1190 * For the GUI the mouse handling is in gui_w32.c.
1191 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001192#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001193 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001194mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001195{
1196}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001197#else
Bram Moolenaar0f873732019-12-05 20:28:46 +01001198static int g_fMouseAvail = FALSE; // mouse present
1199static int g_fMouseActive = FALSE; // mouse enabled
1200static int g_nMouseClick = -1; // mouse status
1201static int g_xMouse; // mouse x coordinate
1202static int g_yMouse; // mouse y coordinate
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001203static DWORD g_cmodein = 0; // Original console input mode
1204static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001205
1206/*
1207 * Enable or disable mouse input
1208 */
1209 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001210mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001211{
1212 DWORD cmodein;
1213
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001214# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001215 if (gui.in_use)
1216 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001217# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001218 if (!g_fMouseAvail)
1219 return;
1220
1221 g_fMouseActive = on;
1222 GetConsoleMode(g_hConIn, &cmodein);
1223
1224 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001225 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001226 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001227 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1228 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001229 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001230 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001231 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001232 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1233 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001234
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001235 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001236}
1237
Bram Moolenaar157d8132018-03-06 17:09:20 +01001238
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001239# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001240/*
1241 * Called when 'balloonevalterm' changed.
1242 */
1243 void
1244mch_bevalterm_changed(void)
1245{
1246 mch_setmouse(g_fMouseActive);
1247}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001248# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001249
Bram Moolenaar071d4272004-06-13 20:20:40 +00001250/*
1251 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1252 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1253 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1254 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1255 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1256 * and we return the mouse position in g_xMouse and g_yMouse.
1257 *
1258 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1259 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1260 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1261 *
1262 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1263 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1264 *
1265 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1266 * moves, even if it stays within the same character cell. We ignore
1267 * all MOUSE_MOVED messages if the position hasn't really changed, and
1268 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1269 * we're only interested in MOUSE_DRAG).
1270 *
1271 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1272 * 2-button mouses by pressing the left & right buttons simultaneously.
1273 * In practice, it's almost impossible to click both at the same time,
1274 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1275 * in such cases, if the user is clicking quickly.
1276 */
1277 static BOOL
1278decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001279 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001280{
1281 static int s_nOldButton = -1;
1282 static int s_nOldMouseClick = -1;
1283 static int s_xOldMouse = -1;
1284 static int s_yOldMouse = -1;
1285 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001286# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001287 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001288# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001289 static int s_cClicks = 1;
1290 static BOOL s_fReleased = TRUE;
1291 static DWORD s_dwLastClickTime = 0;
1292 static BOOL s_fNextIsMiddle = FALSE;
1293
Bram Moolenaar0f873732019-12-05 20:28:46 +01001294 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001295
1296 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1297 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1298 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1299 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1300
1301 int nButton;
1302
1303 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1304 cButtons = 2;
1305
1306 if (!g_fMouseAvail || !g_fMouseActive)
1307 {
1308 g_nMouseClick = -1;
1309 return FALSE;
1310 }
1311
Bram Moolenaar0f873732019-12-05 20:28:46 +01001312 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001313 if (g_fJustGotFocus)
1314 {
1315 g_fJustGotFocus = FALSE;
1316 return FALSE;
1317 }
1318
Bram Moolenaar0f873732019-12-05 20:28:46 +01001319 // unprocessed mouse click?
Bram Moolenaar071d4272004-06-13 20:20:40 +00001320 if (g_nMouseClick != -1)
1321 return TRUE;
1322
1323 nButton = -1;
1324 g_xMouse = pmer->dwMousePosition.X;
1325 g_yMouse = pmer->dwMousePosition.Y;
1326
1327 if (pmer->dwEventFlags == MOUSE_MOVED)
1328 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001329 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1330 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001331 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1332 return FALSE;
1333 }
1334
Bram Moolenaar0f873732019-12-05 20:28:46 +01001335 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001336 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1337 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001338 nButton = MOUSE_RELEASE;
1339
Bram Moolenaar0f873732019-12-05 20:28:46 +01001340 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001341 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001342 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001343# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001344 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001345 if (p_bevalterm)
1346 nButton = MOUSE_DRAG;
1347 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001348# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001349 return FALSE;
1350 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001351
Bram Moolenaar071d4272004-06-13 20:20:40 +00001352 s_fReleased = TRUE;
1353 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001354 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001355 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001356 // on a 2-button mouse, hold down left and right buttons
1357 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001358
1359 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1360 {
1361 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1362
Bram Moolenaar0f873732019-12-05 20:28:46 +01001363 // if either left or right button only is pressed, see if the
1364 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001365 if (dwLR == LEFT || dwLR == RIGHT)
1366 {
1367 for (;;)
1368 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001369 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001370 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1371 != WAIT_OBJECT_0)
1372 break;
1373 else
1374 {
1375 DWORD cRecords = 0;
1376 INPUT_RECORD ir;
1377 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1378
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001379 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001380
1381 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1382 || !(pmer2->dwButtonState & LEFT_RIGHT))
1383 break;
1384 else
1385 {
1386 if (pmer2->dwEventFlags != MOUSE_MOVED)
1387 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001388 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001389
1390 return decode_mouse_event(pmer2);
1391 }
1392 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1393 s_yOldMouse == pmer2->dwMousePosition.Y)
1394 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001395 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001396 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001397
Bram Moolenaar0f873732019-12-05 20:28:46 +01001398 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001399 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001400
1401 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1402 break;
1403 }
1404 else
1405 break;
1406 }
1407 }
1408 }
1409 }
1410 }
1411
1412 if (s_fNextIsMiddle)
1413 {
1414 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1415 ? MOUSE_DRAG : MOUSE_MIDDLE;
1416 s_fNextIsMiddle = FALSE;
1417 }
1418 else if (cButtons == 2 &&
1419 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1420 {
1421 nButton = MOUSE_MIDDLE;
1422
1423 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1424 {
1425 s_fNextIsMiddle = TRUE;
1426 nButton = MOUSE_RELEASE;
1427 }
1428 }
1429 else if ((pmer->dwButtonState & LEFT) == LEFT)
1430 nButton = MOUSE_LEFT;
1431 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1432 nButton = MOUSE_MIDDLE;
1433 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1434 nButton = MOUSE_RIGHT;
1435
1436 if (! s_fReleased && ! s_fNextIsMiddle
1437 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1438 return FALSE;
1439
1440 s_fReleased = s_fNextIsMiddle;
1441 }
1442
1443 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1444 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001445 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001446 if (nButton != -1 && nButton != MOUSE_RELEASE)
1447 {
1448 DWORD dwCurrentTime = GetTickCount();
1449
1450 if (s_xOldMouse != g_xMouse
1451 || s_yOldMouse != g_yMouse
1452 || s_nOldButton != nButton
1453 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001454# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001455 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001456# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001457 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1458 {
1459 s_cClicks = 1;
1460 }
1461 else if (++s_cClicks > 4)
1462 {
1463 s_cClicks = 1;
1464 }
1465
1466 s_dwLastClickTime = dwCurrentTime;
1467 }
1468 }
1469 else if (pmer->dwEventFlags == MOUSE_MOVED)
1470 {
1471 if (nButton != -1 && nButton != MOUSE_RELEASE)
1472 nButton = MOUSE_DRAG;
1473
1474 s_cClicks = 1;
1475 }
1476
1477 if (nButton == -1)
1478 return FALSE;
1479
1480 if (nButton != MOUSE_RELEASE)
1481 s_nOldButton = nButton;
1482
1483 g_nMouseClick = nButton;
1484
1485 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1486 g_nMouseClick |= MOUSE_SHIFT;
1487 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1488 g_nMouseClick |= MOUSE_CTRL;
1489 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1490 g_nMouseClick |= MOUSE_ALT;
1491
1492 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1493 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1494
Bram Moolenaar0f873732019-12-05 20:28:46 +01001495 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001496 if (s_xOldMouse == g_xMouse
1497 && s_yOldMouse == g_yMouse
1498 && s_nOldMouseClick == g_nMouseClick)
1499 {
1500 g_nMouseClick = -1;
1501 return FALSE;
1502 }
1503
1504 s_xOldMouse = g_xMouse;
1505 s_yOldMouse = g_yMouse;
1506 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001507# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001508 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001509# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001510 s_nOldMouseClick = g_nMouseClick;
1511
1512 return TRUE;
1513}
1514
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001515#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001516
1517
1518#ifdef MCH_CURSOR_SHAPE
1519/*
1520 * Set the shape of the cursor.
1521 * 'thickness' can be from 1 (thin) to 99 (block)
1522 */
1523 static void
1524mch_set_cursor_shape(int thickness)
1525{
1526 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1527 ConsoleCursorInfo.dwSize = thickness;
1528 ConsoleCursorInfo.bVisible = s_cursor_visible;
1529
1530 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1531 if (s_cursor_visible)
1532 SetConsoleCursorPosition(g_hConOut, g_coord);
1533}
1534
1535 void
1536mch_update_cursor(void)
1537{
1538 int idx;
1539 int thickness;
1540
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001541# ifdef VIMDLL
1542 if (gui.in_use)
1543 return;
1544# endif
1545
Bram Moolenaar071d4272004-06-13 20:20:40 +00001546 /*
1547 * How the cursor is drawn depends on the current mode.
1548 */
1549 idx = get_shape_idx(FALSE);
1550
1551 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001552 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00001553 else
1554 thickness = shape_table[idx].percentage;
1555 mch_set_cursor_shape(thickness);
1556}
1557#endif
1558
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001559#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001560/*
1561 * Handle FOCUS_EVENT.
1562 */
1563 static void
1564handle_focus_event(INPUT_RECORD ir)
1565{
1566 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1567 ui_focus_change((int)g_fJustGotFocus);
1568}
1569
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001570static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1571
Bram Moolenaar071d4272004-06-13 20:20:40 +00001572/*
1573 * Wait until console input from keyboard or mouse is available,
1574 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001575 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001576 * Return TRUE if something is available FALSE if not.
1577 */
1578 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001579WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001580{
1581 DWORD dwNow = 0, dwEndTime = 0;
1582 INPUT_RECORD ir;
1583 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001584 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001585# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001586 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001587# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001588
1589 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001590 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001591 dwEndTime = GetTickCount() + msec;
1592 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001593 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001594 dwEndTime = INFINITE;
1595
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001596 // We need to loop until the end of the time period, because
1597 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001598 for (;;)
1599 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001600 // Only process messages when waiting.
1601 if (msec != 0)
1602 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001603# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001604 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001605# endif
1606# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001607 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001608# endif
1609# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001610 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001611# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001612 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001613
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001614 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001615# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001616 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001617# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001618 )
1619 return TRUE;
1620
1621 if (msec > 0)
1622 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001623 // If the specified wait time has passed, return. Beware that
1624 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001625 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001626 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001627 break;
1628 }
1629 if (msec != 0)
1630 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001631 DWORD dwWaitTime = dwEndTime - dwNow;
1632
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001633 // Don't wait for more than 11 msec to avoid dropping characters,
1634 // check channel while waiting for input and handle a callback from
1635 // 'balloonexpr'.
1636 if (dwWaitTime > 11)
1637 dwWaitTime = 11;
1638
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001639# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001640 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001641 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001642# endif
1643# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001644 // When waiting very briefly don't trigger timers.
1645 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001646 {
1647 long due_time;
1648
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001649 // Trigger timers and then get the time in msec until the next
1650 // one is due. Wait up to that time.
1651 due_time = check_due_timer();
1652 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001653 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001654 // timer may have used feedkeys().
1655 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001656 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001657 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1658 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001659 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001660# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001661 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001662# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001663 // Wait for either an event on the console input or a
1664 // message in the client-server window.
1665 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1666 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001667# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001668 wait_for_single_object(g_hConIn, dwWaitTime)
1669 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001670# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001671 )
1672 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001673 }
1674
1675 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001676 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001677
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001678# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02001679 // May have to redraw if the cursor ends up in the wrong place.
1680 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01001681 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001682 {
1683 CONSOLE_SCREEN_BUFFER_INFO csbi;
1684
1685 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1686 {
1687 if (csbi.dwCursorPosition.Y != msg_row)
1688 {
matveyte08795e2021-05-07 15:00:17 +02001689 // The screen is now messed up, must redraw the command
1690 // line and later all the windows.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001691 redraw_all_later(CLEAR);
matveyte08795e2021-05-07 15:00:17 +02001692 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001693 redrawcmd();
1694 }
1695 }
1696 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001697# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001698
1699 if (cRecords > 0)
1700 {
1701 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1702 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001703# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01001704 // Windows IME sends two '\n's with only one 'ENTER'. First:
1705 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00001706 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001707 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1708 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001709 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001710 continue;
1711 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001712# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001713 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1714 NULL, FALSE))
1715 return TRUE;
1716 }
1717
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001718 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001719
1720 if (ir.EventType == FOCUS_EVENT)
1721 handle_focus_event(ir);
1722 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001723 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001724 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1725
Bram Moolenaar36698e32019-12-11 22:57:40 +01001726 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001727 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001728 if (dwSize.X != Columns || dwSize.Y != Rows)
1729 {
1730 CONSOLE_SCREEN_BUFFER_INFO csbi;
1731 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01001732 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001733 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01001734 if (dwSize.X != Columns || dwSize.Y != Rows)
1735 {
1736 ResizeConBuf(g_hConOut, dwSize);
1737 shell_resized();
1738 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001739 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001740 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001741 else if (ir.EventType == MOUSE_EVENT
1742 && decode_mouse_event(&ir.Event.MouseEvent))
1743 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001744 }
1745 else if (msec == 0)
1746 break;
1747 }
1748
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001749# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01001750 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001751 if (input_available())
1752 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001753# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001754
Bram Moolenaar071d4272004-06-13 20:20:40 +00001755 return FALSE;
1756}
1757
Bram Moolenaar071d4272004-06-13 20:20:40 +00001758/*
1759 * return non-zero if a character is available
1760 */
1761 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001762mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001763{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001764# ifdef VIMDLL
1765 if (gui.in_use)
1766 return TRUE;
1767# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001768 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001769}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001770
1771# if defined(FEAT_TERMINAL) || defined(PROTO)
1772/*
1773 * Check for any pending input or messages.
1774 */
1775 int
1776mch_check_messages(void)
1777{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001778# ifdef VIMDLL
1779 if (gui.in_use)
1780 return TRUE;
1781# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001782 return WaitForChar(0L, TRUE);
1783}
1784# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001785
1786/*
1787 * Create the console input. Used when reading stdin doesn't work.
1788 */
1789 static void
1790create_conin(void)
1791{
1792 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1793 FILE_SHARE_READ|FILE_SHARE_WRITE,
1794 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001795 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001796 did_create_conin = TRUE;
1797}
1798
1799/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001800 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001801 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001802 static WCHAR
1803tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001804{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001805 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001806
1807 for (;;)
1808 {
1809 INPUT_RECORD ir;
1810 DWORD cRecords = 0;
1811
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001812# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001813 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001814 if (input_available())
1815 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001816 if (g_nMouseClick != -1)
1817 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001818# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001819 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001820 {
1821 if (did_create_conin)
1822 read_error_exit();
1823 create_conin();
1824 continue;
1825 }
1826
1827 if (ir.EventType == KEY_EVENT)
1828 {
1829 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1830 pmodifiers, TRUE))
1831 return ch;
1832 }
1833 else if (ir.EventType == FOCUS_EVENT)
1834 handle_focus_event(ir);
1835 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1836 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001837 else if (ir.EventType == MOUSE_EVENT)
1838 {
1839 if (decode_mouse_event(&ir.Event.MouseEvent))
1840 return 0;
1841 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001842 }
1843}
Bram Moolenaar0f873732019-12-05 20:28:46 +01001844#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001845
1846
1847/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001848 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001849 * Get one or more characters from the keyboard or the mouse.
1850 * If time == 0, do not wait for characters.
1851 * If time == n, wait a short time for characters.
1852 * If time == -1, wait forever for characters.
1853 * Returns the number of characters read into buf.
1854 */
1855 int
1856mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001857 char_u *buf UNUSED,
1858 int maxlen UNUSED,
1859 long time UNUSED,
1860 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001861{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001862#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001863
1864 int len;
1865 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001866# ifdef VIMDLL
1867// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
1868# define TYPEAHEADSPACE 6
1869# else
1870# define TYPEAHEADSPACE 0
1871# endif
1872# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001873 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001874 static int typeaheadlen = 0;
1875
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001876# ifdef VIMDLL
1877 if (gui.in_use)
1878 return 0;
1879# endif
1880
Bram Moolenaar0f873732019-12-05 20:28:46 +01001881 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001882 if (typeaheadlen > 0)
1883 goto theend;
1884
Bram Moolenaar071d4272004-06-13 20:20:40 +00001885 if (time >= 0)
1886 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001887 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00001888 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001889 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001890 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00001891 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001892 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00001893
Bram Moolenaar3918c952005-03-15 22:34:55 +00001894 /*
1895 * If there is no character available within 2 seconds (default)
1896 * write the autoscript file to disk. Or cause the CursorHold event
1897 * to be triggered.
1898 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001899 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001900 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001901 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001902 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001903 buf[0] = K_SPECIAL;
1904 buf[1] = KS_EXTRA;
1905 buf[2] = (int)KE_CURSORHOLD;
1906 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001907 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001908 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001909 }
1910 }
1911
1912 /*
1913 * Try to read as many characters as there are, until the buffer is full.
1914 */
1915
Bram Moolenaar0f873732019-12-05 20:28:46 +01001916 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001917 g_fCBrkPressed = FALSE;
1918
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001919# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001920 if (fdDump)
1921 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001922# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001923
Bram Moolenaar0f873732019-12-05 20:28:46 +01001924 // Keep looping until there is something in the typeahead buffer and more
1925 // to get and still room in the buffer (up to two bytes for a char and
1926 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001927 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001928 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001929 {
1930 if (typebuf_changed(tb_change_cnt))
1931 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001932 // "buf" may be invalid now if a client put something in the
1933 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001934 typeaheadlen = 0;
1935 break;
1936 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001937 if (g_nMouseClick != -1)
1938 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001939# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001940 if (fdDump)
1941 fprintf(fdDump, "{%02x @ %d, %d}",
1942 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001943# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001944 typeahead[typeaheadlen++] = ESC + 128;
1945 typeahead[typeaheadlen++] = 'M';
1946 typeahead[typeaheadlen++] = g_nMouseClick;
1947 typeahead[typeaheadlen++] = g_xMouse + '!';
1948 typeahead[typeaheadlen++] = g_yMouse + '!';
1949 g_nMouseClick = -1;
1950 }
1951 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001952 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001953 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001954 int modifiers = 0;
1955
1956 c = tgetch(&modifiers, &ch2);
1957
1958 if (typebuf_changed(tb_change_cnt))
1959 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001960 // "buf" may be invalid now if a client put something in the
1961 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001962 typeaheadlen = 0;
1963 break;
1964 }
1965
1966 if (c == Ctrl_C && ctrl_c_interrupts)
1967 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001968# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001969 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001970# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001971 got_int = TRUE;
1972 }
1973
Bram Moolenaar071d4272004-06-13 20:20:40 +00001974 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001975 {
1976 int n = 1;
1977
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001978 if (ch2 == NUL)
1979 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001980 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001981 char_u *p;
1982 WCHAR ch[2];
1983
1984 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01001985 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001986 {
1987 ch[1] = tgetch(&modifiers, &ch2);
1988 n++;
1989 }
1990 p = utf16_to_enc(ch, &n);
1991 if (p != NULL)
1992 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001993 for (i = 0, j = 0; i < n; i++)
1994 {
1995 typeahead[typeaheadlen + j++] = p[i];
1996# ifdef VIMDLL
1997 if (p[i] == CSI)
1998 {
1999 typeahead[typeaheadlen + j++] = KS_EXTRA;
2000 typeahead[typeaheadlen + j++] = KE_CSI;
2001 }
2002# endif
2003 }
2004 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002005 vim_free(p);
2006 }
2007 }
2008 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002009 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002010 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002011# ifdef VIMDLL
2012 if (c == CSI)
2013 {
2014 typeahead[typeaheadlen + 1] = KS_EXTRA;
2015 typeahead[typeaheadlen + 2] = KE_CSI;
2016 n = 3;
2017 }
2018# endif
2019 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002020 if (ch2 != NUL)
2021 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002022 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002023 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002024 switch (ch2)
2025 {
2026 case (WCHAR)'\324': // SHIFT+Insert
2027 case (WCHAR)'\325': // CTRL+Insert
2028 case (WCHAR)'\327': // SHIFT+Delete
2029 case (WCHAR)'\330': // CTRL+Delete
2030 typeahead[typeaheadlen + n] = (char_u)ch2;
2031 n++;
2032 break;
2033
2034 default:
2035 typeahead[typeaheadlen + n] = 3;
2036 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2037 n += 2;
2038 break;
2039 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002040 }
2041 else
2042 {
2043 typeahead[typeaheadlen + n] = 3;
2044 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2045 n += 2;
2046 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002047 }
2048
Bram Moolenaar0f873732019-12-05 20:28:46 +01002049 // Use the ALT key to set the 8th bit of the character
2050 // when it's one byte, the 8th bit isn't set yet and not
2051 // using a double-byte encoding (would become a lead
2052 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002053 if ((modifiers & MOD_MASK_ALT)
2054 && n == 1
2055 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002056 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057 )
2058 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002059 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2060 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002061 modifiers &= ~MOD_MASK_ALT;
2062 }
2063
2064 if (modifiers != 0)
2065 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002066 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002067 mch_memmove(typeahead + typeaheadlen + 3,
2068 typeahead + typeaheadlen, n);
2069 typeahead[typeaheadlen++] = K_SPECIAL;
2070 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2071 typeahead[typeaheadlen++] = modifiers;
2072 }
2073
2074 typeaheadlen += n;
2075
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002076# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002077 if (fdDump)
2078 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002079# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002080 }
2081 }
2082 }
2083
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002084# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002085 if (fdDump)
2086 {
2087 fputs("]\n", fdDump);
2088 fflush(fdDump);
2089 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002090# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002091
Bram Moolenaar071d4272004-06-13 20:20:40 +00002092theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002093 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002094 len = 0;
2095 while (len < maxlen && typeaheadlen > 0)
2096 {
2097 buf[len++] = typeahead[0];
2098 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2099 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002100# ifdef FEAT_JOB_CHANNEL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002101 if (len > 0)
2102 {
2103 buf[len] = NUL;
2104 ch_log(NULL, "raw key input: \"%s\"", buf);
2105 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002106# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002107 return len;
2108
Bram Moolenaar0f873732019-12-05 20:28:46 +01002109#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002110 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002111#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002112}
2113
Bram Moolenaar82881492012-11-20 16:53:39 +01002114#ifndef PROTO
2115# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002116# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002117# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002118#endif
2119
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002120/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002121 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002122 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2123 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002124 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002125 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002126 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002127executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002128{
LemonBoy40fd7e62022-05-05 20:18:16 +01002129 int attrs = win32_getattrs((char_u *)name);
2130
2131 // The file doesn't exist or is a folder.
2132 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2133 return FALSE;
2134 // Check if the file is an AppExecLink, a special alias used by Windows
2135 // Store for its apps.
2136 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002137 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002138 char_u *res = resolve_appexeclink((char_u *)name);
2139 if (res == NULL)
2140 return FALSE;
2141 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002142 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002143 *path = res;
2144 else
2145 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002146 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002147 else if (path != NULL)
2148 *path = FullName_save((char_u *)name, FALSE);
2149 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002150}
2151
2152/*
2153 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2154 * If "use_path" is FALSE: Return TRUE if "name" exists.
2155 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2156 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2157 * the allocated memory.
2158 */
2159 static int
2160executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2161{
2162 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2163 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2164 // UTF-8.
2165 char_u buf[_MAX_PATH * 3];
2166 size_t len = STRLEN(name);
2167 size_t tmplen;
2168 char_u *p, *e, *e2;
2169 char_u *pathbuf = NULL;
2170 char_u *pathext = NULL;
2171 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002172 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002173 int noext = FALSE;
2174 int retval = FALSE;
2175
2176 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002177 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002178
2179 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002180 shname = gettail(p_sh);
2181 if (strstr((char *)shname, "sh") != NULL &&
2182 !(strstr((char *)shname, "powershell") != NULL
2183 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002184 noext = TRUE;
2185
2186 if (use_pathext)
2187 {
2188 pathext = mch_getenv("PATHEXT");
2189 if (pathext == NULL)
2190 pathext = (char_u *)".com;.exe;.bat;.cmd";
2191
2192 if (noext == FALSE)
2193 {
2194 /*
2195 * Loop over all extensions in $PATHEXT.
2196 * Check "name" ends with extension.
2197 */
2198 p = pathext;
2199 while (*p)
2200 {
2201 if (p[0] == ';'
2202 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2203 {
2204 // Skip empty or single ".".
2205 ++p;
2206 continue;
2207 }
2208 e = vim_strchr(p, ';');
2209 if (e == NULL)
2210 e = p + STRLEN(p);
2211 tmplen = e - p;
2212
2213 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2214 {
2215 noext = TRUE;
2216 break;
2217 }
2218
2219 p = e;
2220 }
2221 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002222 }
2223
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002224 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002225 if (pathext == NULL)
2226 pathext = (char_u *)".";
2227 else if (noext == TRUE)
2228 {
2229 if (pathextbuf == NULL)
2230 pathextbuf = alloc(STRLEN(pathext) + 3);
2231 if (pathextbuf == NULL)
2232 {
2233 retval = FALSE;
2234 goto theend;
2235 }
2236 STRCPY(pathextbuf, ".;");
2237 STRCAT(pathextbuf, pathext);
2238 pathext = pathextbuf;
2239 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002240
Bram Moolenaar95da1362020-05-30 18:37:55 +02002241 // Use $PATH when "use_path" is TRUE and "name" is basename.
2242 if (use_path && gettail((char_u *)name) == (char_u *)name)
2243 {
2244 p = mch_getenv("PATH");
2245 if (p != NULL)
2246 {
2247 pathbuf = alloc(STRLEN(p) + 3);
2248 if (pathbuf == NULL)
2249 {
2250 retval = FALSE;
2251 goto theend;
2252 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002253
2254 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2255 STRCPY(pathbuf, ".;");
2256 else
2257 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002258 STRCAT(pathbuf, p);
2259 }
2260 }
2261
2262 /*
2263 * Walk through all entries in $PATH to check if "name" exists there and
2264 * is an executable file.
2265 */
2266 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2267 while (*p)
2268 {
2269 if (*p == ';') // Skip empty entry
2270 {
2271 ++p;
2272 continue;
2273 }
2274 e = vim_strchr(p, ';');
2275 if (e == NULL)
2276 e = p + STRLEN(p);
2277
2278 if (e - p + len + 2 > sizeof(buf))
2279 {
2280 retval = FALSE;
2281 goto theend;
2282 }
2283 // A single "." that means current dir.
2284 if (e - p == 1 && *p == '.')
2285 STRCPY(buf, name);
2286 else
2287 {
2288 vim_strncpy(buf, p, e - p);
2289 add_pathsep(buf);
2290 STRCAT(buf, name);
2291 }
2292 tmplen = STRLEN(buf);
2293
2294 /*
2295 * Loop over all extensions in $PATHEXT.
2296 * Check "name" with extension added.
2297 */
2298 p = pathext;
2299 while (*p)
2300 {
2301 if (*p == ';')
2302 {
2303 // Skip empty entry
2304 ++p;
2305 continue;
2306 }
2307 e2 = vim_strchr(p, (int)';');
2308 if (e2 == NULL)
2309 e2 = p + STRLEN(p);
2310
2311 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2312 {
2313 // Not a single "." that means no extension is added.
2314 if (e2 - p + tmplen + 1 > sizeof(buf))
2315 {
2316 retval = FALSE;
2317 goto theend;
2318 }
2319 vim_strncpy(buf + tmplen, p, e2 - p);
2320 }
2321 if (executable_file((char *)buf, path))
2322 {
2323 retval = TRUE;
2324 goto theend;
2325 }
2326
2327 p = e2;
2328 }
2329
2330 p = e;
2331 }
2332
2333theend:
2334 free(pathextbuf);
2335 free(pathbuf);
2336 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002337}
2338
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002339#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2340 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002341/*
2342 * Bad parameter handler.
2343 *
2344 * Certain MS CRT functions will intentionally crash when passed invalid
2345 * parameters to highlight possible security holes. Setting this function as
2346 * the bad parameter handler will prevent the crash.
2347 *
2348 * In debug builds the parameters contain CRT information that might help track
2349 * down the source of a problem, but in non-debug builds the arguments are all
2350 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2351 * worth allowing these to make debugging of issues easier.
2352 */
2353 static void
2354bad_param_handler(const wchar_t *expression,
2355 const wchar_t *function,
2356 const wchar_t *file,
2357 unsigned int line,
2358 uintptr_t pReserved)
2359{
2360}
2361
2362# define SET_INVALID_PARAM_HANDLER \
2363 ((void)_set_invalid_parameter_handler(bad_param_handler))
2364#else
2365# define SET_INVALID_PARAM_HANDLER
2366#endif
2367
Bram Moolenaar4f974752019-02-17 17:44:42 +01002368#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002369
2370/*
2371 * GUI version of mch_init().
2372 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002373 static void
2374mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002375{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002376# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002377 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002378# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002379
Bram Moolenaar0f873732019-12-05 20:28:46 +01002380 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002381 SET_INVALID_PARAM_HANDLER;
2382
Bram Moolenaar0f873732019-12-05 20:28:46 +01002383 // Let critical errors result in a failure, not in a dialog box. Required
2384 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002385 SetErrorMode(SEM_FAILCRITICALERRORS);
2386
Bram Moolenaar0f873732019-12-05 20:28:46 +01002387 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002388
Bram Moolenaar0f873732019-12-05 20:28:46 +01002389 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002390 Rows = 25;
2391 Columns = 80;
2392
Bram Moolenaar0f873732019-12-05 20:28:46 +01002393 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002394 {
2395 char_u vimrun_location[_MAX_PATH + 4];
2396
Bram Moolenaar0f873732019-12-05 20:28:46 +01002397 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002398 STRCPY(vimrun_location, exe_name);
2399 STRCPY(gettail(vimrun_location), "vimrun.exe");
2400 if (mch_getperm(vimrun_location) >= 0)
2401 {
2402 if (*skiptowhite(vimrun_location) != NUL)
2403 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002404 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002405 mch_memmove(vimrun_location + 1, vimrun_location,
2406 STRLEN(vimrun_location) + 1);
2407 *vimrun_location = '"';
2408 STRCPY(gettail(vimrun_location), "vimrun\" ");
2409 }
2410 else
2411 STRCPY(gettail(vimrun_location), "vimrun ");
2412
2413 vimrun_path = (char *)vim_strsave(vimrun_location);
2414 s_dont_use_vimrun = FALSE;
2415 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002416 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002417 s_dont_use_vimrun = FALSE;
2418
Bram Moolenaar0f873732019-12-05 20:28:46 +01002419 // Don't give the warning for a missing vimrun.exe right now, but only
2420 // when vimrun was supposed to be used. Don't bother people that do
2421 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002422 if (s_dont_use_vimrun)
2423 need_vimrun_warning = TRUE;
2424 }
2425
2426 /*
2427 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2428 * Otherwise the default "findstr /n" is used.
2429 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002430 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01002431 set_option_value_give_err((char_u *)"grepprg",
2432 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002433
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002434# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002435 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002436# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002437
2438 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002439}
2440
2441
Bram Moolenaar0f873732019-12-05 20:28:46 +01002442#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002443
2444#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002445
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002446# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2447# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002448
2449/*
2450 * ClearConsoleBuffer()
2451 * Description:
2452 * Clears the entire contents of the console screen buffer, using the
2453 * specified attribute.
2454 * Returns:
2455 * TRUE on success
2456 */
2457 static BOOL
2458ClearConsoleBuffer(WORD wAttribute)
2459{
2460 CONSOLE_SCREEN_BUFFER_INFO csbi;
2461 COORD coord;
2462 DWORD NumCells, dummy;
2463
2464 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2465 return FALSE;
2466
2467 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2468 coord.X = 0;
2469 coord.Y = 0;
2470 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2471 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002472 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002473 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2474 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002475 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002476
2477 return TRUE;
2478}
2479
2480/*
2481 * FitConsoleWindow()
2482 * Description:
2483 * Checks if the console window will fit within given buffer dimensions.
2484 * Also, if requested, will shrink the window to fit.
2485 * Returns:
2486 * TRUE on success
2487 */
2488 static BOOL
2489FitConsoleWindow(
2490 COORD dwBufferSize,
2491 BOOL WantAdjust)
2492{
2493 CONSOLE_SCREEN_BUFFER_INFO csbi;
2494 COORD dwWindowSize;
2495 BOOL NeedAdjust = FALSE;
2496
2497 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2498 {
2499 /*
2500 * A buffer resize will fail if the current console window does
2501 * not lie completely within that buffer. To avoid this, we might
2502 * have to move and possibly shrink the window.
2503 */
2504 if (csbi.srWindow.Right >= dwBufferSize.X)
2505 {
2506 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2507 if (dwWindowSize.X > dwBufferSize.X)
2508 dwWindowSize.X = dwBufferSize.X;
2509 csbi.srWindow.Right = dwBufferSize.X - 1;
2510 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2511 NeedAdjust = TRUE;
2512 }
2513 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2514 {
2515 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2516 if (dwWindowSize.Y > dwBufferSize.Y)
2517 dwWindowSize.Y = dwBufferSize.Y;
2518 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2519 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2520 NeedAdjust = TRUE;
2521 }
2522 if (NeedAdjust && WantAdjust)
2523 {
2524 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2525 return FALSE;
2526 }
2527 return TRUE;
2528 }
2529
2530 return FALSE;
2531}
2532
2533typedef struct ConsoleBufferStruct
2534{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002535 BOOL IsValid;
2536 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002537 PCHAR_INFO Buffer;
2538 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002539 PSMALL_RECT Regions;
2540 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002541} ConsoleBuffer;
2542
2543/*
2544 * SaveConsoleBuffer()
2545 * Description:
2546 * Saves important information about the console buffer, including the
2547 * actual buffer contents. The saved information is suitable for later
2548 * restoration by RestoreConsoleBuffer().
2549 * Returns:
2550 * TRUE if all information was saved; FALSE otherwise
2551 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2552 */
2553 static BOOL
2554SaveConsoleBuffer(
2555 ConsoleBuffer *cb)
2556{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002557 DWORD NumCells;
2558 COORD BufferCoord;
2559 SMALL_RECT ReadRegion;
2560 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002561 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002562
Bram Moolenaar071d4272004-06-13 20:20:40 +00002563 if (cb == NULL)
2564 return FALSE;
2565
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002566 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002567 {
2568 cb->IsValid = FALSE;
2569 return FALSE;
2570 }
2571 cb->IsValid = TRUE;
2572
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002573 /*
2574 * Allocate a buffer large enough to hold the entire console screen
2575 * buffer. If this ConsoleBuffer structure has already been initialized
2576 * with a buffer of the correct size, then just use that one.
2577 */
2578 if (!cb->IsValid || cb->Buffer == NULL ||
2579 cb->BufferSize.X != cb->Info.dwSize.X ||
2580 cb->BufferSize.Y != cb->Info.dwSize.Y)
2581 {
2582 cb->BufferSize.X = cb->Info.dwSize.X;
2583 cb->BufferSize.Y = cb->Info.dwSize.Y;
2584 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2585 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002586 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002587 if (cb->Buffer == NULL)
2588 return FALSE;
2589 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002590
2591 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002592 * We will now copy the console screen buffer into our buffer.
2593 * ReadConsoleOutput() seems to be limited as far as how much you
2594 * can read at a time. Empirically, this number seems to be about
2595 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2596 * in chunks until it is all copied. The chunks will all have the
2597 * same horizontal characteristics, so initialize them now. The
2598 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002599 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002600 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002601 ReadRegion.Left = 0;
2602 ReadRegion.Right = cb->Info.dwSize.X - 1;
2603 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002604
2605 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2606 if (cb->Regions == NULL || numregions != cb->NumRegions)
2607 {
2608 cb->NumRegions = numregions;
2609 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002610 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002611 if (cb->Regions == NULL)
2612 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002613 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002614 return FALSE;
2615 }
2616 }
2617
2618 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002619 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002620 /*
2621 * Read into position (0, Y) in our buffer.
2622 */
2623 BufferCoord.Y = Y;
2624 /*
2625 * Read the region whose top left corner is (0, Y) and whose bottom
2626 * right corner is (width - 1, Y + Y_incr - 1). This should define
2627 * a region of size width by Y_incr. Don't worry if this region is
2628 * too large for the remaining buffer; it will be cropped.
2629 */
2630 ReadRegion.Top = Y;
2631 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002632 if (!ReadConsoleOutputW(g_hConOut, // output handle
2633 cb->Buffer, // our buffer
2634 cb->BufferSize, // dimensions of our buffer
2635 BufferCoord, // offset in our buffer
2636 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002637 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002638 VIM_CLEAR(cb->Buffer);
2639 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002640 return FALSE;
2641 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002642 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002643 }
2644
2645 return TRUE;
2646}
2647
2648/*
2649 * RestoreConsoleBuffer()
2650 * Description:
2651 * Restores important information about the console buffer, including the
2652 * actual buffer contents, if desired. The information to restore is in
2653 * the same format used by SaveConsoleBuffer().
2654 * Returns:
2655 * TRUE on success
2656 */
2657 static BOOL
2658RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002659 ConsoleBuffer *cb,
2660 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002661{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002662 COORD BufferCoord;
2663 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002664 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002665
2666 if (cb == NULL || !cb->IsValid)
2667 return FALSE;
2668
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002669 /*
2670 * Before restoring the buffer contents, clear the current buffer, and
2671 * restore the cursor position and window information. Doing this now
2672 * prevents old buffer contents from "flashing" onto the screen.
2673 */
2674 if (RestoreScreen)
2675 ClearConsoleBuffer(cb->Info.wAttributes);
2676
2677 FitConsoleWindow(cb->Info.dwSize, TRUE);
2678 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2679 return FALSE;
2680 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2681 return FALSE;
2682
2683 if (!RestoreScreen)
2684 {
2685 /*
2686 * No need to restore the screen buffer contents, so we're done.
2687 */
2688 return TRUE;
2689 }
2690
2691 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2692 return FALSE;
2693 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2694 return FALSE;
2695
2696 /*
2697 * Restore the screen buffer contents.
2698 */
2699 if (cb->Buffer != NULL)
2700 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002701 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002702 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002703 BufferCoord.X = cb->Regions[i].Left;
2704 BufferCoord.Y = cb->Regions[i].Top;
2705 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01002706 if (!WriteConsoleOutputW(g_hConOut, // output handle
2707 cb->Buffer, // our buffer
2708 cb->BufferSize, // dimensions of our buffer
2709 BufferCoord, // offset in our buffer
2710 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02002711 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002712 }
2713 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002714
2715 return TRUE;
2716}
2717
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002718# define FEAT_RESTORE_ORIG_SCREEN
2719# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002720static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002721# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002722static ConsoleBuffer g_cbNonTermcap = { 0 };
2723static ConsoleBuffer g_cbTermcap = { 0 };
2724
Bram Moolenaar071d4272004-06-13 20:20:40 +00002725char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01002726HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00002727static HICON g_hOrigIconSmall = NULL;
2728static HICON g_hOrigIcon = NULL;
2729static HICON g_hVimIcon = NULL;
2730static BOOL g_fCanChangeIcon = FALSE;
2731
Bram Moolenaar071d4272004-06-13 20:20:40 +00002732/*
2733 * GetConsoleIcon()
2734 * Description:
2735 * Attempts to retrieve the small icon and/or the big icon currently in
2736 * use by a given window.
2737 * Returns:
2738 * TRUE on success
2739 */
2740 static BOOL
2741GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002742 HWND hWnd,
2743 HICON *phIconSmall,
2744 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002745{
2746 if (hWnd == NULL)
2747 return FALSE;
2748
2749 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002750 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2751 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002752 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002753 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2754 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002755 return TRUE;
2756}
2757
2758/*
2759 * SetConsoleIcon()
2760 * Description:
2761 * Attempts to change the small icon and/or the big icon currently in
2762 * use by a given window.
2763 * Returns:
2764 * TRUE on success
2765 */
2766 static BOOL
2767SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002768 HWND hWnd,
2769 HICON hIconSmall,
2770 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002771{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002772 if (hWnd == NULL)
2773 return FALSE;
2774
2775 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002776 SendMessage(hWnd, WM_SETICON,
2777 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002778 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002779 SendMessage(hWnd, WM_SETICON,
2780 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002781 return TRUE;
2782}
2783
2784/*
2785 * SaveConsoleTitleAndIcon()
2786 * Description:
2787 * Saves the current console window title in g_szOrigTitle, for later
2788 * restoration. Also, attempts to obtain a handle to the console window,
2789 * and use it to save the small and big icons currently in use by the
2790 * console window. This is not always possible on some versions of Windows;
2791 * nor is it possible when running Vim remotely using Telnet (since the
2792 * console window the user sees is owned by a remote process).
2793 */
2794 static void
2795SaveConsoleTitleAndIcon(void)
2796{
Bram Moolenaar0f873732019-12-05 20:28:46 +01002797 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002798 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2799 return;
2800
2801 /*
2802 * Obtain a handle to the console window using GetConsoleWindow() from
2803 * KERNEL32.DLL; we need to handle in order to change the window icon.
2804 * This function only exists on NT-based Windows, starting with Windows
2805 * 2000. On older operating systems, we can't change the window icon
2806 * anyway.
2807 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002808 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002809 if (g_hWnd == NULL)
2810 return;
2811
Bram Moolenaar0f873732019-12-05 20:28:46 +01002812 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002813 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2814 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2815 return;
2816
Bram Moolenaar0f873732019-12-05 20:28:46 +01002817 // Extract the first icon contained in the Vim executable.
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002818 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002819 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002820 if (g_hVimIcon != NULL)
2821 g_fCanChangeIcon = TRUE;
2822}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002823
2824static int g_fWindInitCalled = FALSE;
2825static int g_fTermcapMode = FALSE;
2826static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002827
2828/*
2829 * non-GUI version of mch_init().
2830 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002831 static void
2832mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002833{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002834# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002835 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002836# endif
2837# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002838 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002839# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002840
Bram Moolenaar0f873732019-12-05 20:28:46 +01002841 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002842 SET_INVALID_PARAM_HANDLER;
2843
Bram Moolenaar0f873732019-12-05 20:28:46 +01002844 // Let critical errors result in a failure, not in a dialog box. Required
2845 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002846 SetErrorMode(SEM_FAILCRITICALERRORS);
2847
Bram Moolenaar0f873732019-12-05 20:28:46 +01002848 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002849 out_flush();
2850
Bram Moolenaar0f873732019-12-05 20:28:46 +01002851 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00002852 if (read_cmd_fd == 0)
2853 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2854 else
2855 create_conin();
2856 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2857
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002858# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01002859 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002860 SaveConsoleBuffer(&g_cbOrig);
2861 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002862# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01002863 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002864 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2865 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002866# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002867 if (cterm_normal_fg_color == 0)
2868 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2869 if (cterm_normal_bg_color == 0)
2870 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2871
Bram Moolenaarbdace832019-03-02 10:13:42 +01002872 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002873 g_color_index_fg = g_attrDefault & 0xf;
2874 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2875
Bram Moolenaar0f873732019-12-05 20:28:46 +01002876 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00002877 update_tcap(g_attrCurrent);
2878
2879 GetConsoleCursorInfo(g_hConOut, &g_cci);
2880 GetConsoleMode(g_hConIn, &g_cmodein);
2881 GetConsoleMode(g_hConOut, &g_cmodeout);
2882
Bram Moolenaar071d4272004-06-13 20:20:40 +00002883 SaveConsoleTitleAndIcon();
2884 /*
2885 * Set both the small and big icons of the console window to Vim's icon.
2886 * Note that Vim presently only has one size of icon (32x32), but it
2887 * automatically gets scaled down to 16x16 when setting the small icon.
2888 */
2889 if (g_fCanChangeIcon)
2890 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002891
2892 ui_get_shellsize();
2893
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002894# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002895 fdDump = fopen("dump", "wt");
2896
2897 if (fdDump)
2898 {
2899 time_t t;
2900
2901 time(&t);
2902 fputs(ctime(&t), fdDump);
2903 fflush(fdDump);
2904 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002905# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002906
2907 g_fWindInitCalled = TRUE;
2908
Bram Moolenaar071d4272004-06-13 20:20:40 +00002909 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002910
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002911# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002912 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002913# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002914
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02002915 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002916 vtp_init();
Bram Moolenaar06b7b582020-05-30 17:49:25 +02002917 wt_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002918}
2919
2920/*
2921 * non-GUI version of mch_exit().
2922 * Shut down and exit with status `r'
2923 * Careful: mch_exit() may be called before mch_init()!
2924 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002925 static void
2926mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002927{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002928 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002929
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002930 vtp_exit();
2931
Bram Moolenaar955f1982017-02-05 15:10:51 +01002932 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002933 if (g_fWindInitCalled)
2934 settmode(TMODE_COOK);
2935
Bram Moolenaar0f873732019-12-05 20:28:46 +01002936 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00002937
2938 if (g_fWindInitCalled)
2939 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02002940 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002941 /*
2942 * Restore both the small and big icons of the console window to
2943 * what they were at startup. Don't do this when the window is
2944 * closed, Vim would hang here.
2945 */
2946 if (g_fCanChangeIcon && !g_fForceExit)
2947 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002948
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002949# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002950 if (fdDump)
2951 {
2952 time_t t;
2953
2954 time(&t);
2955 fputs(ctime(&t), fdDump);
2956 fclose(fdDump);
2957 }
2958 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002959# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002960 }
2961
2962 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02002963 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002964 SetConsoleMode(g_hConOut, g_cmodeout);
2965
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002966# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00002967 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002968# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002969
2970 exit(r);
2971}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002972#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002973
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002974 void
2975mch_init(void)
2976{
2977#ifdef VIMDLL
2978 if (gui.starting)
2979 mch_init_g();
2980 else
2981 mch_init_c();
2982#elif defined(FEAT_GUI_MSWIN)
2983 mch_init_g();
2984#else
2985 mch_init_c();
2986#endif
2987}
2988
2989 void
2990mch_exit(int r)
2991{
Bram Moolenaar173d8412020-04-19 14:02:26 +02002992#ifdef FEAT_NETBEANS_INTG
2993 netbeans_send_disconnect();
2994#endif
2995
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002996#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02002997 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002998 mch_exit_g(r);
2999 else
3000 mch_exit_c(r);
3001#elif defined(FEAT_GUI_MSWIN)
3002 mch_exit_g(r);
3003#else
3004 mch_exit_c(r);
3005#endif
3006}
3007
Bram Moolenaar071d4272004-06-13 20:20:40 +00003008/*
3009 * Do we have an interactive window?
3010 */
3011 int
3012mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003013 int argc UNUSED,
3014 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003015{
3016 get_exe_name();
3017
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003018#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003019 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003020#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003021# ifdef VIMDLL
3022 if (gui.in_use)
3023 return OK;
3024# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025 if (isatty(1))
3026 return OK;
3027 return FAIL;
3028#endif
3029}
3030
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003031/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003032 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003033 * When "len" is > 0, also expand short to long filenames.
3034 */
3035 void
3036fname_case(
3037 char_u *name,
3038 int len)
3039{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003040 int flen;
3041 WCHAR *p;
3042 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003043
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003044 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003045 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003046 return;
3047
3048 slash_adjust(name);
3049
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003050 p = enc_to_utf16(name, NULL);
3051 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003052 return;
3053
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003054 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003055 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003056 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003057
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003058 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003059 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003060 if (len > 0 || flen >= (int)STRLEN(q))
3061 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3062 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003063 }
3064 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003065 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003066}
3067
3068
3069/*
3070 * Insert user name in s[len].
3071 */
3072 int
3073mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003074 char_u *s,
3075 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003076{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003077 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003078 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003079
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003080 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003081 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003082 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003083
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003084 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003085 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003086 vim_strncpy(s, p, len - 1);
3087 vim_free(p);
3088 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003089 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003090 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003091 s[0] = NUL;
3092 return FAIL;
3093}
3094
3095
3096/*
3097 * Insert host name in s[len].
3098 */
3099 void
3100mch_get_host_name(
3101 char_u *s,
3102 int len)
3103{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003104 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003105 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003106
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003107 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003108 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003109 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003110
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003111 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003112 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003113 vim_strncpy(s, p, len - 1);
3114 vim_free(p);
3115 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003116 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003117 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003118}
3119
3120
3121/*
3122 * return process ID
3123 */
3124 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003125mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003126{
3127 return (long)GetCurrentProcessId();
3128}
3129
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003130/*
3131 * return TRUE if process "pid" is still running
3132 */
3133 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003134mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003135{
3136 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3137 DWORD status = 0;
3138 int ret = FALSE;
3139
3140 if (hProcess == NULL)
3141 return FALSE; // might not have access
3142 if (GetExitCodeProcess(hProcess, &status) )
3143 ret = status == STILL_ACTIVE;
3144 CloseHandle(hProcess);
3145 return ret;
3146}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003147
3148/*
3149 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3150 * Return OK for success, FAIL for failure.
3151 */
3152 int
3153mch_dirname(
3154 char_u *buf,
3155 int len)
3156{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003157 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003158
Bram Moolenaar071d4272004-06-13 20:20:40 +00003159 /*
3160 * Originally this was:
3161 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3162 * But the Win32s known bug list says that getcwd() doesn't work
3163 * so use the Win32 system call instead. <Negri>
3164 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003165 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003166 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003167 WCHAR wcbuf[_MAX_PATH + 1];
3168 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003169
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003170 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003171 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003172 p = utf16_to_enc(wcbuf, NULL);
3173 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003174 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003175 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003176 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003177 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003178 }
3179 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003180 if (p == NULL)
3181 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003182
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003183 if (p != NULL)
3184 {
3185 vim_strncpy(buf, p, len - 1);
3186 vim_free(p);
3187 return OK;
3188 }
3189 }
3190 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003191}
3192
3193/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003194 * Get file permissions for "name".
3195 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003196 */
3197 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003198mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003199{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003200 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003201 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003202
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003203 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003204 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003205}
3206
3207
3208/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003209 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003210 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003211 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003212 */
3213 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003214mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003215{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003216 long n;
3217 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003218
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003219 p = enc_to_utf16(name, NULL);
3220 if (p == NULL)
3221 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003222
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003223 n = _wchmod(p, perm);
3224 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003225 if (n == -1)
3226 return FAIL;
3227
3228 win32_set_archive(name);
3229
3230 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003231}
3232
3233/*
3234 * Set hidden flag for "name".
3235 */
3236 void
3237mch_hide(char_u *name)
3238{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003239 int attrs = win32_getattrs(name);
3240 if (attrs == -1)
3241 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003242
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003243 attrs |= FILE_ATTRIBUTE_HIDDEN;
3244 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003245}
3246
3247/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003248 * Return TRUE if file "name" exists and is hidden.
3249 */
3250 int
3251mch_ishidden(char_u *name)
3252{
3253 int f = win32_getattrs(name);
3254
3255 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003256 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003257
3258 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3259}
3260
3261/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003262 * return TRUE if "name" is a directory
3263 * return FALSE if "name" is not a directory or upon error
3264 */
3265 int
3266mch_isdir(char_u *name)
3267{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003268 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003269
3270 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003271 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003272
3273 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3274}
3275
3276/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003277 * return TRUE if "name" is a directory, NOT a symlink to a directory
3278 * return FALSE if "name" is not a directory
3279 * return FALSE for error
3280 */
3281 int
3282mch_isrealdir(char_u *name)
3283{
3284 return mch_isdir(name) && !mch_is_symbolic_link(name);
3285}
3286
3287/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003288 * Create directory "name".
3289 * Return 0 on success, -1 on error.
3290 */
3291 int
3292mch_mkdir(char_u *name)
3293{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003294 WCHAR *p;
3295 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003296
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003297 p = enc_to_utf16(name, NULL);
3298 if (p == NULL)
3299 return -1;
3300 retval = _wmkdir(p);
3301 vim_free(p);
3302 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003303}
3304
3305/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003306 * Delete directory "name".
3307 * Return 0 on success, -1 on error.
3308 */
3309 int
3310mch_rmdir(char_u *name)
3311{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003312 WCHAR *p;
3313 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003314
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003315 p = enc_to_utf16(name, NULL);
3316 if (p == NULL)
3317 return -1;
3318 retval = _wrmdir(p);
3319 vim_free(p);
3320 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003321}
3322
3323/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003324 * Return TRUE if file "fname" has more than one link.
3325 */
3326 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003327mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003328{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003329 BY_HANDLE_FILE_INFORMATION info;
3330
3331 return win32_fileinfo(fname, &info) == FILEINFO_OK
3332 && info.nNumberOfLinks > 1;
3333}
3334
3335/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003336 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003337 */
3338 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003339mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003340{
3341 HANDLE hFind;
3342 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003343 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003344 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003345 WIN32_FIND_DATAW findDataW;
3346
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003347 wn = enc_to_utf16(name, NULL);
3348 if (wn == NULL)
3349 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003350
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003351 hFind = FindFirstFileW(wn, &findDataW);
3352 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003353 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003354 {
3355 fileFlags = findDataW.dwFileAttributes;
3356 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003357 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003358 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003359
3360 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003361 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3362 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003363 res = TRUE;
3364
3365 return res;
3366}
3367
3368/*
3369 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3370 * link.
3371 */
3372 int
3373mch_is_linked(char_u *fname)
3374{
3375 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3376 return TRUE;
3377 return FALSE;
3378}
3379
3380/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003381 * Get the by-handle-file-information for "fname".
3382 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003383 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003384 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3385 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3386 */
3387 int
3388win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3389{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003390 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003391 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003392 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003393
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003394 wn = enc_to_utf16(fname, NULL);
3395 if (wn == NULL)
3396 return FILEINFO_ENC_FAIL;
3397
3398 hFile = CreateFileW(wn, // file name
3399 GENERIC_READ, // access mode
3400 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3401 NULL, // security descriptor
3402 OPEN_EXISTING, // creation disposition
3403 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3404 NULL); // handle to template file
3405 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003406
3407 if (hFile != INVALID_HANDLE_VALUE)
3408 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003409 if (GetFileInformationByHandle(hFile, info) != 0)
3410 res = FILEINFO_OK;
3411 else
3412 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003413 CloseHandle(hFile);
3414 }
3415
Bram Moolenaar03f48552006-02-28 23:52:23 +00003416 return res;
3417}
3418
3419/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003420 * get file attributes for `name'
3421 * -1 : error
3422 * else FILE_ATTRIBUTE_* defined in winnt.h
3423 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003424 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003425win32_getattrs(char_u *name)
3426{
3427 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003428 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003429
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003430 p = enc_to_utf16(name, NULL);
3431 if (p == NULL)
3432 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003433
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003434 attr = GetFileAttributesW(p);
3435 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003436
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003437 return attr;
3438}
3439
3440/*
3441 * set file attributes for `name' to `attrs'
3442 *
3443 * return -1 for failure, 0 otherwise
3444 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003445 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003446win32_setattrs(char_u *name, int attrs)
3447{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003448 int res;
3449 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003450
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003451 p = enc_to_utf16(name, NULL);
3452 if (p == NULL)
3453 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003454
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003455 res = SetFileAttributesW(p, attrs);
3456 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003457
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003458 return res ? 0 : -1;
3459}
3460
3461/*
3462 * Set archive flag for "name".
3463 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003464 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003465win32_set_archive(char_u *name)
3466{
3467 int attrs = win32_getattrs(name);
3468 if (attrs == -1)
3469 return -1;
3470
3471 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3472 return win32_setattrs(name, attrs);
3473}
3474
3475/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003476 * Return TRUE if file or directory "name" is writable (not readonly).
3477 * Strange semantics of Win32: a readonly directory is writable, but you can't
3478 * delete a file. Let's say this means it is writable.
3479 */
3480 int
3481mch_writable(char_u *name)
3482{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003483 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003484
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003485 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3486 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003487}
3488
Bram Moolenaar071d4272004-06-13 20:20:40 +00003489/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003490 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003491 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003492 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3493 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003494 */
3495 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003496mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003497{
Bram Moolenaar95da1362020-05-30 18:37:55 +02003498 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003499}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003500
3501/*
3502 * Check what "name" is:
3503 * NODE_NORMAL: file or directory (or doesn't exist)
3504 * NODE_WRITABLE: writable device, socket, fifo, etc.
3505 * NODE_OTHER: non-writable things
3506 */
3507 int
3508mch_nodetype(char_u *name)
3509{
3510 HANDLE hFile;
3511 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003512 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003513
Bram Moolenaar0f873732019-12-05 20:28:46 +01003514 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3515 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3516 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00003517 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3518 return NODE_WRITABLE;
3519
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003520 wn = enc_to_utf16(name, NULL);
3521 if (wn == NULL)
3522 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003523
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003524 hFile = CreateFileW(wn, // file name
3525 GENERIC_WRITE, // access mode
3526 0, // share mode
3527 NULL, // security descriptor
3528 OPEN_EXISTING, // creation disposition
3529 0, // file attributes
3530 NULL); // handle to template file
3531 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003532 if (hFile == INVALID_HANDLE_VALUE)
3533 return NODE_NORMAL;
3534
3535 type = GetFileType(hFile);
3536 CloseHandle(hFile);
3537 if (type == FILE_TYPE_CHAR)
3538 return NODE_WRITABLE;
3539 if (type == FILE_TYPE_DISK)
3540 return NODE_NORMAL;
3541 return NODE_OTHER;
3542}
3543
3544#ifdef HAVE_ACL
3545struct my_acl
3546{
3547 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3548 PSID pSidOwner;
3549 PSID pSidGroup;
3550 PACL pDacl;
3551 PACL pSacl;
3552};
3553#endif
3554
3555/*
3556 * Return a pointer to the ACL of file "fname" in allocated memory.
3557 * Return NULL if the ACL is not available for whatever reason.
3558 */
3559 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003560mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003561{
3562#ifndef HAVE_ACL
3563 return (vim_acl_T)NULL;
3564#else
3565 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003566 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003567
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003568 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003569 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003570 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003571 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003572
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003573 wn = enc_to_utf16(fname, NULL);
3574 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003575 {
3576 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003577 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003578 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003579
3580 // Try to retrieve the entire security descriptor.
3581 err = GetNamedSecurityInfoW(
3582 wn, // Abstract filename
3583 SE_FILE_OBJECT, // File Object
3584 OWNER_SECURITY_INFORMATION |
3585 GROUP_SECURITY_INFORMATION |
3586 DACL_SECURITY_INFORMATION |
3587 SACL_SECURITY_INFORMATION,
3588 &p->pSidOwner, // Ownership information.
3589 &p->pSidGroup, // Group membership.
3590 &p->pDacl, // Discretionary information.
3591 &p->pSacl, // For auditing purposes.
3592 &p->pSecurityDescriptor);
3593 if (err == ERROR_ACCESS_DENIED ||
3594 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003595 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003596 // Retrieve only DACL.
3597 (void)GetNamedSecurityInfoW(
3598 wn,
3599 SE_FILE_OBJECT,
3600 DACL_SECURITY_INFORMATION,
3601 NULL,
3602 NULL,
3603 &p->pDacl,
3604 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003605 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003606 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003607 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003608 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003609 mch_free_acl((vim_acl_T)p);
3610 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003611 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003612 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003613 }
3614
3615 return (vim_acl_T)p;
3616#endif
3617}
3618
Bram Moolenaar27515922013-06-29 15:36:26 +02003619#ifdef HAVE_ACL
3620/*
3621 * Check if "acl" contains inherited ACE.
3622 */
3623 static BOOL
3624is_acl_inherited(PACL acl)
3625{
3626 DWORD i;
3627 ACL_SIZE_INFORMATION acl_info;
3628 PACCESS_ALLOWED_ACE ace;
3629
3630 acl_info.AceCount = 0;
3631 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3632 for (i = 0; i < acl_info.AceCount; i++)
3633 {
3634 GetAce(acl, i, (LPVOID *)&ace);
3635 if (ace->Header.AceFlags & INHERITED_ACE)
3636 return TRUE;
3637 }
3638 return FALSE;
3639}
3640#endif
3641
Bram Moolenaar071d4272004-06-13 20:20:40 +00003642/*
3643 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3644 * Errors are ignored.
3645 * This must only be called with "acl" equal to what mch_get_acl() returned.
3646 */
3647 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003648mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003649{
3650#ifdef HAVE_ACL
3651 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003652 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003653 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003654
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003655 if (p == NULL)
3656 return;
3657
3658 wn = enc_to_utf16(fname, NULL);
3659 if (wn == NULL)
3660 return;
3661
3662 // Set security flags
3663 if (p->pSidOwner)
3664 sec_info |= OWNER_SECURITY_INFORMATION;
3665 if (p->pSidGroup)
3666 sec_info |= GROUP_SECURITY_INFORMATION;
3667 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003668 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003669 sec_info |= DACL_SECURITY_INFORMATION;
3670 // Do not inherit its parent's DACL.
3671 // If the DACL is inherited, Cygwin permissions would be changed.
3672 if (!is_acl_inherited(p->pDacl))
3673 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003674 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003675 if (p->pSacl)
3676 sec_info |= SACL_SECURITY_INFORMATION;
3677
3678 (void)SetNamedSecurityInfoW(
3679 wn, // Abstract filename
3680 SE_FILE_OBJECT, // File Object
3681 sec_info,
3682 p->pSidOwner, // Ownership information.
3683 p->pSidGroup, // Group membership.
3684 p->pDacl, // Discretionary information.
3685 p->pSacl // For auditing purposes.
3686 );
3687 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003688#endif
3689}
3690
3691 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003692mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003693{
3694#ifdef HAVE_ACL
3695 struct my_acl *p = (struct my_acl *)acl;
3696
3697 if (p != NULL)
3698 {
3699 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3700 vim_free(p);
3701 }
3702#endif
3703}
3704
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003705#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003706
3707/*
3708 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3709 */
3710 static BOOL WINAPI
3711handler_routine(
3712 DWORD dwCtrlType)
3713{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003714 INPUT_RECORD ir;
3715 DWORD out;
3716
Bram Moolenaar071d4272004-06-13 20:20:40 +00003717 switch (dwCtrlType)
3718 {
3719 case CTRL_C_EVENT:
3720 if (ctrl_c_interrupts)
3721 g_fCtrlCPressed = TRUE;
3722 return TRUE;
3723
3724 case CTRL_BREAK_EVENT:
3725 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003726 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003727 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02003728 ir.EventType = KEY_EVENT;
3729 ir.Event.KeyEvent.bKeyDown = TRUE;
3730 ir.Event.KeyEvent.wRepeatCount = 1;
3731 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3732 ir.Event.KeyEvent.wVirtualScanCode = 0;
3733 ir.Event.KeyEvent.dwControlKeyState = 0;
3734 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3735 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003736 return TRUE;
3737
Bram Moolenaar0f873732019-12-05 20:28:46 +01003738 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00003739 case CTRL_CLOSE_EVENT:
3740 case CTRL_LOGOFF_EVENT:
3741 case CTRL_SHUTDOWN_EVENT:
3742 windgoto((int)Rows - 1, 0);
3743 g_fForceExit = TRUE;
3744
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003745 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003746 (dwCtrlType == CTRL_CLOSE_EVENT
3747 ? _("close")
3748 : dwCtrlType == CTRL_LOGOFF_EVENT
3749 ? _("logoff")
3750 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003751# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00003752 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003753# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003754
Bram Moolenaar0f873732019-12-05 20:28:46 +01003755 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00003756
Bram Moolenaar0f873732019-12-05 20:28:46 +01003757 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00003758
3759 default:
3760 return FALSE;
3761 }
3762}
3763
3764
3765/*
3766 * set the tty in (raw) ? "raw" : "cooked" mode
3767 */
3768 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02003769mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003770{
3771 DWORD cmodein;
3772 DWORD cmodeout;
3773 BOOL bEnableHandler;
3774
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003775# ifdef VIMDLL
3776 if (gui.in_use)
3777 return;
3778# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003779 GetConsoleMode(g_hConIn, &cmodein);
3780 GetConsoleMode(g_hConOut, &cmodeout);
3781 if (tmode == TMODE_RAW)
3782 {
3783 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3784 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003785 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003786 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003787 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003788 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
3789 }
3790 else
3791 {
3792 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
3793 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003794 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003795# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01003796 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
3797 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003798 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003799# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003800 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003801# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003802 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003803 bEnableHandler = TRUE;
3804 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01003805 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00003806 {
3807 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3808 ENABLE_ECHO_INPUT);
3809 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3810 bEnableHandler = FALSE;
3811 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003812 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003813 SetConsoleMode(g_hConOut, cmodeout);
3814 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3815
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003816# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003817 if (fdDump)
3818 {
3819 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3820 tmode == TMODE_RAW ? "raw" :
3821 tmode == TMODE_COOK ? "cooked" : "normal",
3822 cmodein, cmodeout);
3823 fflush(fdDump);
3824 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003825# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003826}
3827
3828
3829/*
3830 * Get the size of the current window in `Rows' and `Columns'
3831 * Return OK when size could be determined, FAIL otherwise.
3832 */
3833 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003834mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003835{
3836 CONSOLE_SCREEN_BUFFER_INFO csbi;
3837
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003838# ifdef VIMDLL
3839 if (gui.in_use)
3840 return OK;
3841# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003842 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3843 {
3844 /*
3845 * For some reason, we are trying to get the screen dimensions
3846 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3847 * variables are really intended to mean the size of Vim screen
3848 * while in termcap mode.
3849 */
3850 Rows = g_cbTermcap.Info.dwSize.Y;
3851 Columns = g_cbTermcap.Info.dwSize.X;
3852 }
3853 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3854 {
3855 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3856 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3857 }
3858 else
3859 {
3860 Rows = 25;
3861 Columns = 80;
3862 }
3863 return OK;
3864}
3865
3866/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003867 * Resize console buffer to 'COORD'
3868 */
3869 static void
3870ResizeConBuf(
3871 HANDLE hConsole,
3872 COORD coordScreen)
3873{
3874 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3875 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003876# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003877 if (fdDump)
3878 {
3879 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3880 GetLastError());
3881 fflush(fdDump);
3882 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003883# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003884 }
3885}
3886
3887/*
3888 * Resize console window size to 'srWindowRect'
3889 */
3890 static void
3891ResizeWindow(
3892 HANDLE hConsole,
3893 SMALL_RECT srWindowRect)
3894{
3895 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
3896 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003897# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003898 if (fdDump)
3899 {
3900 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3901 GetLastError());
3902 fflush(fdDump);
3903 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003904# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003905 }
3906}
3907
3908/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003909 * Set a console window to `xSize' * `ySize'
3910 */
3911 static void
3912ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003913 HANDLE hConsole,
3914 int xSize,
3915 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003916{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003917 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
3918 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003919 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003920 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02003921 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003922
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003923# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003924 if (fdDump)
3925 {
3926 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3927 fflush(fdDump);
3928 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003929# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003930
Bram Moolenaar0f873732019-12-05 20:28:46 +01003931 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00003932 coordScreen = GetLargestConsoleWindowSize(hConsole);
3933
Bram Moolenaar0f873732019-12-05 20:28:46 +01003934 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00003935 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3936 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3937 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3938
3939 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3940 {
3941 int sx, sy;
3942
3943 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3944 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3945 if (sy < ySize || sx < xSize)
3946 {
3947 /*
3948 * Increasing number of lines/columns, do buffer first.
3949 * Use the maximal size in x and y direction.
3950 */
3951 if (sy < ySize)
3952 coordScreen.Y = ySize;
3953 else
3954 coordScreen.Y = sy;
3955 if (sx < xSize)
3956 coordScreen.X = xSize;
3957 else
3958 coordScreen.X = sx;
3959 SetConsoleScreenBufferSize(hConsole, coordScreen);
3960 }
3961 }
3962
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003963 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003964 coordScreen.X = xSize;
3965 coordScreen.Y = ySize;
3966
Bram Moolenaar2551c032018-08-23 22:38:31 +02003967 // In the new console call API, only the first time in reverse order
3968 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003969 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003970 ResizeWindow(hConsole, srWindowRect);
3971 ResizeConBuf(hConsole, coordScreen);
3972 }
3973 else
3974 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003975 // Workaround for a Windows 10 bug
3976 cursor.X = srWindowRect.Left;
3977 cursor.Y = srWindowRect.Top;
3978 SetConsoleCursorPosition(hConsole, cursor);
3979
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003980 ResizeConBuf(hConsole, coordScreen);
3981 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02003982 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003983 }
3984}
3985
3986
3987/*
3988 * Set the console window to `Rows' * `Columns'
3989 */
3990 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003991mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003992{
3993 COORD coordScreen;
3994
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003995# ifdef VIMDLL
3996 if (gui.in_use)
3997 return;
3998# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01003999 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004000 if (suppress_winsize != 0)
4001 {
4002 suppress_winsize = 2;
4003 return;
4004 }
4005
4006 if (term_console)
4007 {
4008 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4009
Bram Moolenaar0f873732019-12-05 20:28:46 +01004010 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004011 if (Rows > coordScreen.Y)
4012 Rows = coordScreen.Y;
4013 if (Columns > coordScreen.X)
4014 Columns = coordScreen.X;
4015
4016 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4017 }
4018}
4019
4020/*
4021 * Rows and/or Columns has changed.
4022 */
4023 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004024mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004025{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004026# ifdef VIMDLL
4027 if (gui.in_use)
4028 return;
4029# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004030 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4031}
4032
4033
4034/*
4035 * Called when started up, to set the winsize that was delayed.
4036 */
4037 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004038mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004039{
4040 if (suppress_winsize == 2)
4041 {
4042 suppress_winsize = 0;
4043 mch_set_shellsize();
4044 shell_resized();
4045 }
4046 suppress_winsize = 0;
4047}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004048#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004049
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004050 static BOOL
4051vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004052 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004053 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004054 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004055 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004056 PROCESS_INFORMATION *pi,
4057 LPVOID *env,
4058 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004059{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004060 BOOL ret = FALSE;
4061 WCHAR *wcmd, *wcwd = NULL;
4062
4063 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4064 if (wcmd == NULL)
4065 return FALSE;
4066 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004067 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004068 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4069 if (wcwd == NULL)
4070 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004071 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004072
4073 ret = CreateProcessW(
4074 NULL, // Executable name
4075 wcmd, // Command to execute
4076 NULL, // Process security attributes
4077 NULL, // Thread security attributes
4078 inherit_handles, // Inherit handles
4079 flags, // Creation flags
4080 env, // Environment
4081 wcwd, // Current directory
4082 (LPSTARTUPINFOW)si, // Startup information
4083 pi); // Process information
4084theend:
4085 vim_free(wcmd);
4086 vim_free(wcwd);
4087 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004088}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004089
4090
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004091 static HINSTANCE
4092vim_shell_execute(
4093 char *cmd,
4094 INT n_show_cmd)
4095{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004096 HINSTANCE ret;
4097 WCHAR *wcmd;
4098
4099 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4100 if (wcmd == NULL)
4101 return (HINSTANCE) 0;
4102
4103 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4104 vim_free(wcmd);
4105 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004106}
4107
4108
Bram Moolenaar4f974752019-02-17 17:44:42 +01004109#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004110
4111/*
4112 * Specialised version of system() for Win32 GUI mode.
4113 * This version proceeds as follows:
4114 * 1. Create a console window for use by the subprocess
4115 * 2. Run the subprocess (it gets the allocated console by default)
4116 * 3. Wait for the subprocess to terminate and get its exit code
4117 * 4. Prompt the user to press a key to close the console window
4118 */
4119 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004120mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004121{
4122 STARTUPINFO si;
4123 PROCESS_INFORMATION pi;
4124 DWORD ret = 0;
4125 HWND hwnd = GetFocus();
4126
4127 si.cb = sizeof(si);
4128 si.lpReserved = NULL;
4129 si.lpDesktop = NULL;
4130 si.lpTitle = NULL;
4131 si.dwFlags = STARTF_USESHOWWINDOW;
4132 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004133 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004134 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004135 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004136 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004137 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004138 else
4139 si.wShowWindow = SW_SHOWNORMAL;
4140 si.cbReserved2 = 0;
4141 si.lpReserved2 = NULL;
4142
Bram Moolenaar0f873732019-12-05 20:28:46 +01004143 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004144 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004145 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4146 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004147
Bram Moolenaar0f873732019-12-05 20:28:46 +01004148 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004149 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004150# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004151 int delay = 1;
4152
Bram Moolenaar0f873732019-12-05 20:28:46 +01004153 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004154 for (;;)
4155 {
4156 MSG msg;
4157
K.Takatab7057bd2022-01-21 11:37:07 +00004158 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004159 {
4160 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004161 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004162 delay = 1;
4163 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004164 }
4165 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4166 break;
4167
Bram Moolenaar0f873732019-12-05 20:28:46 +01004168 // We start waiting for a very short time and then increase it, so
4169 // that we respond quickly when the process is quick, and don't
4170 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004171 if (delay < 50)
4172 delay += 10;
4173 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004174# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004175 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004176# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004177
Bram Moolenaar0f873732019-12-05 20:28:46 +01004178 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004179 GetExitCodeProcess(pi.hProcess, &ret);
4180 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004181
Bram Moolenaar0f873732019-12-05 20:28:46 +01004182 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004183 CloseHandle(pi.hThread);
4184 CloseHandle(pi.hProcess);
4185
Bram Moolenaar0f873732019-12-05 20:28:46 +01004186 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004187 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4188
4189 return ret;
4190}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004191
4192/*
4193 * Thread launched by the gui to send the current buffer data to the
4194 * process. This way avoid to hang up vim totally if the children
4195 * process take a long time to process the lines.
4196 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004197 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004198sub_process_writer(LPVOID param)
4199{
4200 HANDLE g_hChildStd_IN_Wr = param;
4201 linenr_T lnum = curbuf->b_op_start.lnum;
4202 DWORD len = 0;
4203 DWORD l;
4204 char_u *lp = ml_get(lnum);
4205 char_u *s;
4206 int written = 0;
4207
4208 for (;;)
4209 {
4210 l = (DWORD)STRLEN(lp + written);
4211 if (l == 0)
4212 len = 0;
4213 else if (lp[written] == NL)
4214 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004215 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004216 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4217 }
4218 else
4219 {
4220 s = vim_strchr(lp + written, NL);
4221 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4222 s == NULL ? l : (DWORD)(s - (lp + written)),
4223 &len, NULL);
4224 }
4225 if (len == (int)l)
4226 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004227 // Finished a line, add a NL, unless this line should not have
4228 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004229 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004230 || (!curbuf->b_p_bin
4231 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004232 || (lnum != curbuf->b_no_eol_lnum
4233 && (lnum != curbuf->b_ml.ml_line_count
4234 || curbuf->b_p_eol)))
4235 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004236 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4237 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004238 }
4239
4240 ++lnum;
4241 if (lnum > curbuf->b_op_end.lnum)
4242 break;
4243
4244 lp = ml_get(lnum);
4245 written = 0;
4246 }
4247 else if (len > 0)
4248 written += len;
4249 }
4250
Bram Moolenaar0f873732019-12-05 20:28:46 +01004251 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004252 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004253 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004254}
4255
4256
Bram Moolenaar0f873732019-12-05 20:28:46 +01004257# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004258
4259/*
4260 * This function read from the children's stdout and write the
4261 * data on screen or in the buffer accordingly.
4262 */
4263 static void
4264dump_pipe(int options,
4265 HANDLE g_hChildStd_OUT_Rd,
4266 garray_T *ga,
4267 char_u buffer[],
4268 DWORD *buffer_off)
4269{
4270 DWORD availableBytes = 0;
4271 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004272 int ret;
4273 DWORD len;
4274 DWORD toRead;
4275 int repeatCount;
4276
Bram Moolenaar0f873732019-12-05 20:28:46 +01004277 // we query the pipe to see if there is any data to read
4278 // to avoid to perform a blocking read
4279 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4280 NULL, // optional buffer
4281 0, // buffer size
4282 NULL, // number of read bytes
4283 &availableBytes, // available bytes total
4284 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004285
4286 repeatCount = 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004287 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004288 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004289 {
4290 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004291 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004292 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004293 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004294
Bram Moolenaar0f873732019-12-05 20:28:46 +01004295 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004296 if (len == 0)
4297 break;
4298
4299 availableBytes -= len;
4300
4301 if (options & SHELL_READ)
4302 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004303 // Do NUL -> NL translation, append NL separated
4304 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004305 for (i = 0; i < len; ++i)
4306 {
4307 if (buffer[i] == NL)
4308 append_ga_line(ga);
4309 else if (buffer[i] == NUL)
4310 ga_append(ga, NL);
4311 else
4312 ga_append(ga, buffer[i]);
4313 }
4314 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004315 else if (has_mbyte)
4316 {
4317 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004318 int c;
4319 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004320
4321 len += *buffer_off;
4322 buffer[len] = NUL;
4323
Bram Moolenaar0f873732019-12-05 20:28:46 +01004324 // Check if the last character in buffer[] is
4325 // incomplete, keep these bytes for the next
4326 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004327 for (p = buffer; p < buffer + len; p += l)
4328 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004329 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004330 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004331 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004332 else if (MB_BYTE2LEN(*p) != l)
4333 break;
4334 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004335 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004336 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004337 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004338 if (len >= 12)
4339 ++p;
4340 else
4341 {
4342 *buffer_off = len;
4343 return;
4344 }
4345 }
4346 c = *p;
4347 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004348 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004349 if (p < buffer + len)
4350 {
4351 *p = c;
4352 *buffer_off = (DWORD)((buffer + len) - p);
4353 mch_memmove(buffer, p, *buffer_off);
4354 return;
4355 }
4356 *buffer_off = 0;
4357 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004358 else
4359 {
4360 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004361 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004362 }
4363
4364 windgoto(msg_row, msg_col);
4365 cursor_on();
4366 out_flush();
4367 }
4368}
4369
4370/*
4371 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4372 * for communication and doesn't open any new window.
4373 */
4374 static int
4375mch_system_piped(char *cmd, int options)
4376{
4377 STARTUPINFO si;
4378 PROCESS_INFORMATION pi;
4379 DWORD ret = 0;
4380
4381 HANDLE g_hChildStd_IN_Rd = NULL;
4382 HANDLE g_hChildStd_IN_Wr = NULL;
4383 HANDLE g_hChildStd_OUT_Rd = NULL;
4384 HANDLE g_hChildStd_OUT_Wr = NULL;
4385
Bram Moolenaar0f873732019-12-05 20:28:46 +01004386 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004387 DWORD len;
4388
Bram Moolenaar0f873732019-12-05 20:28:46 +01004389 // buffer used to receive keys
4390 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4391 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004392
4393 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004394 int noread_cnt = 0;
4395 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004396 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004397 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004398 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004399
4400 SECURITY_ATTRIBUTES saAttr;
4401
Bram Moolenaar0f873732019-12-05 20:28:46 +01004402 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004403 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4404 saAttr.bInheritHandle = TRUE;
4405 saAttr.lpSecurityDescriptor = NULL;
4406
4407 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004408 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004409 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004410 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004411 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004412 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004413 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004414 {
4415 CloseHandle(g_hChildStd_IN_Rd);
4416 CloseHandle(g_hChildStd_IN_Wr);
4417 CloseHandle(g_hChildStd_OUT_Rd);
4418 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004419 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004420 }
4421
4422 si.cb = sizeof(si);
4423 si.lpReserved = NULL;
4424 si.lpDesktop = NULL;
4425 si.lpTitle = NULL;
4426 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4427
Bram Moolenaar0f873732019-12-05 20:28:46 +01004428 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004429 si.hStdError = g_hChildStd_OUT_Wr;
4430 si.hStdOutput = g_hChildStd_OUT_Wr;
4431 si.hStdInput = g_hChildStd_IN_Rd;
4432 si.wShowWindow = SW_HIDE;
4433 si.cbReserved2 = 0;
4434 si.lpReserved2 = NULL;
4435
4436 if (options & SHELL_READ)
4437 ga_init2(&ga, 1, BUFLEN);
4438
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004439 if (cmd != NULL)
4440 {
4441 p = (char *)vim_strsave((char_u *)cmd);
4442 if (p != NULL)
4443 unescape_shellxquote((char_u *)p, p_sxe);
4444 else
4445 p = cmd;
4446 }
4447
Bram Moolenaar0f873732019-12-05 20:28:46 +01004448 // Now, run the command.
4449 // About "Inherit handles" being TRUE: this command can be litigious,
4450 // handle inheritance was deactivated for pending temp file, but, if we
4451 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004452 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4453 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004454
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004455 if (p != cmd)
4456 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004457
Bram Moolenaar0f873732019-12-05 20:28:46 +01004458 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004459 CloseHandle(g_hChildStd_IN_Rd);
4460 CloseHandle(g_hChildStd_OUT_Wr);
4461
4462 if (options & SHELL_WRITE)
4463 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004464 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004465 _beginthreadex(NULL, // security attributes
4466 0, // default stack size
4467 sub_process_writer, // function to be executed
4468 g_hChildStd_IN_Wr, // parameter
4469 0, // creation flag, start immediately
4470 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004471 CloseHandle(thread);
4472 g_hChildStd_IN_Wr = NULL;
4473 }
4474
Bram Moolenaar0f873732019-12-05 20:28:46 +01004475 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004476 for (;;)
4477 {
4478 MSG msg;
4479
K.Takatab7057bd2022-01-21 11:37:07 +00004480 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004481 {
4482 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004483 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004484 }
4485
Bram Moolenaar0f873732019-12-05 20:28:46 +01004486 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004487 if ((options & (SHELL_READ|SHELL_WRITE))
4488# ifdef FEAT_GUI
4489 || gui.in_use
4490# endif
4491 )
4492 {
4493 len = 0;
4494 if (!(options & SHELL_EXPAND)
4495 && ((options &
4496 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4497 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4498# ifdef FEAT_GUI
4499 || gui.in_use
4500# endif
4501 )
4502 && (ta_len > 0 || noread_cnt > 4))
4503 {
4504 if (ta_len == 0)
4505 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004506 // Get extra characters when we don't have any. Reset the
4507 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004508 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004509 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4510 }
4511 if (ta_len > 0 || len > 0)
4512 {
4513 /*
4514 * For pipes: Check for CTRL-C: send interrupt signal to
4515 * child. Check for CTRL-D: EOF, close pipe to child.
4516 */
4517 if (len == 1 && cmd != NULL)
4518 {
4519 if (ta_buf[ta_len] == Ctrl_C)
4520 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004521 // Learn what exit code is expected, for
4522 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004523 TerminateProcess(pi.hProcess, 9);
4524 }
4525 if (ta_buf[ta_len] == Ctrl_D)
4526 {
4527 CloseHandle(g_hChildStd_IN_Wr);
4528 g_hChildStd_IN_Wr = NULL;
4529 }
4530 }
4531
Bram Moolenaarf4140482020-02-15 23:06:45 +01004532 term_replace_bs_del_keycode(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004533
4534 /*
4535 * For pipes: echo the typed characters. For a pty this
4536 * does not seem to work.
4537 */
4538 for (i = ta_len; i < ta_len + len; ++i)
4539 {
4540 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4541 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004542 else if (has_mbyte)
4543 {
4544 int l = (*mb_ptr2len)(ta_buf + i);
4545
4546 msg_outtrans_len(ta_buf + i, l);
4547 i += l - 1;
4548 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004549 else
4550 msg_outtrans_len(ta_buf + i, 1);
4551 }
4552 windgoto(msg_row, msg_col);
4553 out_flush();
4554
4555 ta_len += len;
4556
4557 /*
4558 * Write the characters to the child, unless EOF has been
4559 * typed for pipes. Write one character at a time, to
4560 * avoid losing too much typeahead. When writing buffer
4561 * lines, drop the typed characters (only check for
4562 * CTRL-C).
4563 */
4564 if (options & SHELL_WRITE)
4565 ta_len = 0;
4566 else if (g_hChildStd_IN_Wr != NULL)
4567 {
4568 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4569 1, &len, NULL);
4570 // if we are typing in, we want to keep things reactive
4571 delay = 1;
4572 if (len > 0)
4573 {
4574 ta_len -= len;
4575 mch_memmove(ta_buf, ta_buf + len, ta_len);
4576 }
4577 }
4578 }
4579 }
4580 }
4581
4582 if (ta_len)
4583 ui_inchar_undo(ta_buf, ta_len);
4584
4585 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4586 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004587 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004588 break;
4589 }
4590
4591 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004592 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004593
Bram Moolenaar0f873732019-12-05 20:28:46 +01004594 // We start waiting for a very short time and then increase it, so
4595 // that we respond quickly when the process is quick, and don't
4596 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004597 if (delay < 50)
4598 delay += 10;
4599 }
4600
Bram Moolenaar0f873732019-12-05 20:28:46 +01004601 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004602 CloseHandle(g_hChildStd_OUT_Rd);
4603 if (g_hChildStd_IN_Wr != NULL)
4604 CloseHandle(g_hChildStd_IN_Wr);
4605
4606 WaitForSingleObject(pi.hProcess, INFINITE);
4607
Bram Moolenaar0f873732019-12-05 20:28:46 +01004608 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004609 GetExitCodeProcess(pi.hProcess, &ret);
4610
4611 if (options & SHELL_READ)
4612 {
4613 if (ga.ga_len > 0)
4614 {
4615 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01004616 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004617 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4618 }
4619 else
4620 curbuf->b_no_eol_lnum = 0;
4621 ga_clear(&ga);
4622 }
4623
Bram Moolenaar0f873732019-12-05 20:28:46 +01004624 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004625 CloseHandle(pi.hThread);
4626 CloseHandle(pi.hProcess);
4627
4628 return ret;
4629}
4630
4631 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004632mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004633{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004634 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004635 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004636 return mch_system_piped(cmd, options);
4637 else
4638 return mch_system_classic(cmd, options);
4639}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004640#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004641
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004642#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004643 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02004644mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004645{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004646 int ret;
4647 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004648 char_u *buf;
4649 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004650
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004651 // If the command starts and ends with double quotes, enclose the command
4652 // in parentheses.
4653 len = STRLEN(cmd);
4654 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
4655 {
4656 len += 3;
4657 buf = alloc(len);
4658 if (buf == NULL)
4659 return -1;
4660 vim_snprintf((char *)buf, len, "(%s)", cmd);
4661 wcmd = enc_to_utf16(buf, NULL);
4662 free(buf);
4663 }
4664 else
4665 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4666
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004667 if (wcmd == NULL)
4668 return -1;
4669
4670 ret = _wsystem(wcmd);
4671 vim_free(wcmd);
4672 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004673}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004674
4675#endif
4676
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004677 static int
4678mch_system(char *cmd, int options)
4679{
4680#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004681 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004682 return mch_system_g(cmd, options);
4683 else
4684 return mch_system_c(cmd, options);
4685#elif defined(FEAT_GUI_MSWIN)
4686 return mch_system_g(cmd, options);
4687#else
4688 return mch_system_c(cmd, options);
4689#endif
4690}
4691
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004692#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4693/*
4694 * Use a terminal window to run a shell command in.
4695 */
4696 static int
4697mch_call_shell_terminal(
4698 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004699 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004700{
4701 jobopt_T opt;
4702 char_u *newcmd = NULL;
4703 typval_T argvar[2];
4704 long_u cmdlen;
4705 int retval = -1;
4706 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004707 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004708 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004709 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004710
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004711 if (cmd == NULL)
4712 cmdlen = STRLEN(p_sh) + 1;
4713 else
4714 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004715 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004716 if (newcmd == NULL)
4717 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004718 if (cmd == NULL)
4719 {
4720 STRCPY(newcmd, p_sh);
4721 ch_log(NULL, "starting terminal to run a shell");
4722 }
4723 else
4724 {
4725 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4726 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4727 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004728
4729 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004730
4731 argvar[0].v_type = VAR_STRING;
4732 argvar[0].vval.v_string = newcmd;
4733 argvar[1].v_type = VAR_UNKNOWN;
4734 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004735 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004736 {
4737 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004738 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004739 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004740
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004741 job = term_getjob(buf->b_term);
4742 ++job->jv_refcount;
4743
Bram Moolenaar0f873732019-12-05 20:28:46 +01004744 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004745 aucmd_prepbuf(&aco, buf);
4746
4747 clear_oparg(&oa);
4748 while (term_use_loop())
4749 {
4750 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4751 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004752 // If terminal_loop() returns OK we got a key that is handled
4753 // in Normal model. We don't do redrawing anyway.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004754 if (terminal_loop(TRUE) == OK)
4755 normal_cmd(&oa, TRUE);
4756 }
4757 else
4758 normal_cmd(&oa, TRUE);
4759 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004760 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004761 ch_log(NULL, "system command finished");
4762
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004763 job_unref(job);
4764
Bram Moolenaar0f873732019-12-05 20:28:46 +01004765 // restore curwin/curbuf and a few other things
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004766 aucmd_restbuf(&aco);
4767
4768 wait_return(TRUE);
4769 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4770
4771 vim_free(newcmd);
4772 return retval;
4773}
4774#endif
4775
Bram Moolenaar071d4272004-06-13 20:20:40 +00004776/*
4777 * Either execute a command by calling the shell or start a new shell
4778 */
4779 int
4780mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004781 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004782 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00004783{
4784 int x = 0;
4785 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004786 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004787
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01004788#ifdef FEAT_JOB_CHANNEL
4789 ch_log(NULL, "executing shell command: %s", cmd);
4790#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004791 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02004792 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004793 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004794 if (cmd == NULL)
4795 wcscat(szShellTitle, L" :sh");
4796 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004797 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004798 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004799
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004800 if (wn != NULL)
4801 {
4802 wcscat(szShellTitle, L" - !");
4803 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02004804 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004805 wcscat(szShellTitle, wn);
4806 SetConsoleTitleW(szShellTitle);
4807 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004808 }
4809 }
4810 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004811
4812 out_flush();
4813
4814#ifdef MCH_WRITE_DUMP
4815 if (fdDump)
4816 {
4817 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4818 fflush(fdDump);
4819 }
4820#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004821#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004822 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004823 if (
4824# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004825 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004826# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004827 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004828 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4829 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004830 char_u *cmdbase = cmd;
4831
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004832 if (cmdbase != NULL)
4833 // Skip a leading quote and (.
4834 while (*cmdbase == '"' || *cmdbase == '(')
4835 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004836
4837 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01004838 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
4839 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004840 {
4841 // Use a terminal window to run the command in.
4842 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004843 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004844 return x;
4845 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004846 }
4847#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004848
4849 /*
4850 * Catch all deadly signals while running the external command, because a
4851 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4852 */
4853 signal(SIGINT, SIG_IGN);
4854#if defined(__GNUC__) && !defined(__MINGW32__)
4855 signal(SIGKILL, SIG_IGN);
4856#else
4857 signal(SIGBREAK, SIG_IGN);
4858#endif
4859 signal(SIGILL, SIG_IGN);
4860 signal(SIGFPE, SIG_IGN);
4861 signal(SIGSEGV, SIG_IGN);
4862 signal(SIGTERM, SIG_IGN);
4863 signal(SIGABRT, SIG_IGN);
4864
4865 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004866 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00004867
4868 if (cmd == NULL)
4869 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004870 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004871 }
4872 else
4873 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004874 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004875 char_u *newcmd = NULL;
4876 char_u *cmdbase = cmd;
4877 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004878
Bram Moolenaar0f873732019-12-05 20:28:46 +01004879 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004880 if (*cmdbase == '"' )
4881 ++cmdbase;
4882 if (*cmdbase == '(')
4883 ++cmdbase;
4884
Bram Moolenaar1c465442017-03-12 20:10:05 +01004885 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004886 {
4887 STARTUPINFO si;
4888 PROCESS_INFORMATION pi;
4889 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004890 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004891 char_u *p;
4892
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004893 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004894 si.cb = sizeof(si);
4895 si.lpReserved = NULL;
4896 si.lpDesktop = NULL;
4897 si.lpTitle = NULL;
4898 si.dwFlags = 0;
4899 si.cbReserved2 = 0;
4900 si.lpReserved2 = NULL;
4901
4902 cmdbase = skipwhite(cmdbase + 5);
4903 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004904 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004905 {
4906 cmdbase = skipwhite(cmdbase + 4);
4907 si.dwFlags = STARTF_USESHOWWINDOW;
4908 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004909 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004910 }
4911 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004912 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004913 {
4914 cmdbase = skipwhite(cmdbase + 2);
4915 flags = CREATE_NO_WINDOW;
4916 si.dwFlags = STARTF_USESTDHANDLES;
4917 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004918 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004919 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004920 NULL, // Security att.
4921 OPEN_EXISTING, // Open flags
4922 FILE_ATTRIBUTE_NORMAL, // File att.
4923 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004924 si.hStdOutput = si.hStdInput;
4925 si.hStdError = si.hStdInput;
4926 }
4927
Bram Moolenaar0f873732019-12-05 20:28:46 +01004928 // Remove a trailing ", ) and )" if they have a match
4929 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004930 if (cmdbase > cmd)
4931 {
4932 p = cmdbase + STRLEN(cmdbase);
4933 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4934 *--p = NUL;
4935 if (p > cmdbase && p[-1] == ')'
4936 && (*cmd =='(' || cmd[1] == '('))
4937 *--p = NUL;
4938 }
4939
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004940 newcmd = cmdbase;
4941 unescape_shellxquote(cmdbase, p_sxe);
4942
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004943 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004944 * If creating new console, arguments are passed to the
4945 * 'cmd.exe' as-is. If it's not, arguments are not treated
4946 * correctly for current 'cmd.exe'. So unescape characters in
4947 * shellxescape except '|' for avoiding to be treated as
4948 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004949 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004950 if (flags != CREATE_NEW_CONSOLE)
4951 {
4952 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004953 char_u *cmd_shell = mch_getenv("COMSPEC");
4954
4955 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004956 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004957
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004958 subcmd = vim_strsave_escaped_ext(cmdbase,
4959 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004960 if (subcmd != NULL)
4961 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004962 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004963 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004964 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004965 if (newcmd != NULL)
4966 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004967 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004968 else
4969 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004970 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004971 }
4972 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004973
4974 /*
4975 * Now, start the command as a process, so that it doesn't
4976 * inherit our handles which causes unpleasant dangling swap
4977 * files if we exit before the spawned process
4978 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004979 if (vim_create_process((char *)newcmd, FALSE, flags,
4980 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004981 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004982 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4983 > (HINSTANCE)32)
4984 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004985 else
4986 {
4987 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01004988#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004989# ifdef VIMDLL
4990 if (gui.in_use)
4991# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00004992 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004993#endif
4994 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004995
4996 if (newcmd != cmdbase)
4997 vim_free(newcmd);
4998
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004999 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005000 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005001 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005002 CloseHandle(si.hStdInput);
5003 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005004 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005005 CloseHandle(pi.hThread);
5006 CloseHandle(pi.hProcess);
5007 }
5008 else
5009 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005010 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005011#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005012 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005013 (!s_dont_use_vimrun && p_stmp ?
5014 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5015 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005016#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005017 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005018
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005019 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005020 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005021 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005022#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005023 if (
5024# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005025 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005026# endif
5027 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005028 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005029 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5030 "External commands will not pause after completion.\n"
5031 "See :help win32-vimrun for more information.");
5032 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005033 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5034 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005035
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005036 if (wmsg != NULL && wtitle != NULL)
5037 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5038 vim_free(wmsg);
5039 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005040 need_vimrun_warning = FALSE;
5041 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005042 if (
5043# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005044 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005045# endif
5046 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005047 // Use vimrun to execute the command. It opens a console
5048 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005049 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005050 vimrun_path,
5051 (msg_silent != 0 || (options & SHELL_DOOUT))
5052 ? "-s " : "",
5053 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005054 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005055# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005056 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005057# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005058 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005059 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005060 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5061 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005062 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005063#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005064 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005065 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005066 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005067 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005068 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005069 }
5070 }
5071
5072 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005073 {
5074 // The shell may have messed with the mode, always set it.
5075 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005076 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005077 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005078
Bram Moolenaar0f873732019-12-05 20:28:46 +01005079 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005080 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005081#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005082 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005083 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005084#endif
5085 )
5086 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005087 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005088 msg_putchar('\n');
5089 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005090 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005091
5092 signal(SIGINT, SIG_DFL);
5093#if defined(__GNUC__) && !defined(__MINGW32__)
5094 signal(SIGKILL, SIG_DFL);
5095#else
5096 signal(SIGBREAK, SIG_DFL);
5097#endif
5098 signal(SIGILL, SIG_DFL);
5099 signal(SIGFPE, SIG_DFL);
5100 signal(SIGSEGV, SIG_DFL);
5101 signal(SIGTERM, SIG_DFL);
5102 signal(SIGABRT, SIG_DFL);
5103
5104 return x;
5105}
5106
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005107#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005108 static HANDLE
5109job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005110 char_u *fname,
5111 DWORD dwDesiredAccess,
5112 DWORD dwShareMode,
5113 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5114 DWORD dwCreationDisposition,
5115 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005116{
5117 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005118 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005119
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005120 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005121 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005122 return INVALID_HANDLE_VALUE;
5123
5124 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5125 lpSecurityAttributes, dwCreationDisposition,
5126 dwFlagsAndAttributes, NULL);
5127 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005128 return h;
5129}
5130
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005131/*
5132 * Turn the dictionary "env" into a NUL separated list that can be used as the
5133 * environment argument of vim_create_process().
5134 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005135 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005136win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005137{
5138 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005139 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005140 LPVOID base = GetEnvironmentStringsW();
5141
Bram Moolenaar0f873732019-12-05 20:28:46 +01005142 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005143 if (ga_grow(gap, 1) == FAIL)
5144 return;
5145
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005146 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005147 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005148 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005149 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005150 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005151 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005152 typval_T *item = &dict_lookup(hi)->di_tv;
5153 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005154 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005155 --todo;
5156 if (wkey != NULL && wval != NULL)
5157 {
5158 size_t n;
5159 size_t lkey = wcslen(wkey);
5160 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005161
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005162 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5163 continue;
5164 for (n = 0; n < lkey; n++)
5165 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5166 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5167 for (n = 0; n < lval; n++)
5168 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5169 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5170 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005171 vim_free(wkey);
5172 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005173 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005174 }
5175 }
5176
Bram Moolenaar355757a2020-02-10 22:06:32 +01005177 if (base)
5178 {
5179 WCHAR *p = (WCHAR*) base;
5180
5181 // for last \0
5182 if (ga_grow(gap, 1) == FAIL)
5183 return;
5184
5185 while (*p != 0 || *(p + 1) != 0)
5186 {
5187 if (ga_grow(gap, 1) == OK)
5188 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5189 p++;
5190 }
5191 FreeEnvironmentStrings(base);
5192 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5193 }
5194
Bram Moolenaar493359e2018-06-12 20:25:52 +02005195# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005196 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005197# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005198 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005199 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005200# endif
5201# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005202 char_u *version = get_vim_var_str(VV_VERSION);
5203 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005204# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005205 // size of "VIM_SERVERNAME=" and value,
5206 // plus "VIM_TERMINAL=" and value,
5207 // plus two terminating NULs
5208 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005209# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005210 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005211# endif
5212# ifdef FEAT_TERMINAL
5213 + 13 + version_len + 2
5214# endif
5215 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005216
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005217 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005218 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005219# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005220 for (n = 0; n < 15; n++)
5221 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5222 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005223 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005224 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5225 (WCHAR)servername[n];
5226 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005227# endif
5228# ifdef FEAT_TERMINAL
5229 if (is_terminal)
5230 {
5231 for (n = 0; n < 13; n++)
5232 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5233 (WCHAR)"VIM_TERMINAL="[n];
5234 for (n = 0; n < version_len; n++)
5235 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5236 (WCHAR)version[n];
5237 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5238 }
5239# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005240 }
5241 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005242# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005243}
5244
Bram Moolenaarb091f302019-01-19 14:37:00 +01005245/*
5246 * Create a pair of pipes.
5247 * Return TRUE for success, FALSE for failure.
5248 */
5249 static BOOL
5250create_pipe_pair(HANDLE handles[2])
5251{
5252 static LONG s;
5253 char name[64];
5254 SECURITY_ATTRIBUTES sa;
5255
5256 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5257 GetCurrentProcessId(),
5258 InterlockedIncrement(&s));
5259
5260 // Create named pipe. Max size of named pipe is 65535.
5261 handles[1] = CreateNamedPipe(
5262 name,
5263 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5264 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005265 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005266
5267 if (handles[1] == INVALID_HANDLE_VALUE)
5268 return FALSE;
5269
5270 sa.nLength = sizeof(sa);
5271 sa.bInheritHandle = TRUE;
5272 sa.lpSecurityDescriptor = NULL;
5273
5274 handles[0] = CreateFile(name,
5275 FILE_GENERIC_READ,
5276 FILE_SHARE_READ, &sa,
5277 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5278
5279 if (handles[0] == INVALID_HANDLE_VALUE)
5280 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005281 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005282 return FALSE;
5283 }
5284
5285 return TRUE;
5286}
5287
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005288 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005289mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005290{
5291 STARTUPINFO si;
5292 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005293 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005294 SECURITY_ATTRIBUTES saAttr;
5295 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005296 HANDLE ifd[2];
5297 HANDLE ofd[2];
5298 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005299 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005300
5301 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5302 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5303 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5304 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5305 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5306 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5307 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5308
5309 if (use_out_for_err && use_null_for_out)
5310 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005311
5312 ifd[0] = INVALID_HANDLE_VALUE;
5313 ifd[1] = INVALID_HANDLE_VALUE;
5314 ofd[0] = INVALID_HANDLE_VALUE;
5315 ofd[1] = INVALID_HANDLE_VALUE;
5316 efd[0] = INVALID_HANDLE_VALUE;
5317 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005318 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005319
Bram Moolenaar14207f42016-10-27 21:13:10 +02005320 jo = CreateJobObject(NULL, NULL);
5321 if (jo == NULL)
5322 {
5323 job->jv_status = JOB_FAILED;
5324 goto failed;
5325 }
5326
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005327 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005328 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005329
Bram Moolenaar76467df2016-02-12 19:30:26 +01005330 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005331 ZeroMemory(&si, sizeof(si));
5332 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005333 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005334 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005335
Bram Moolenaard8070362016-02-15 21:56:54 +01005336 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5337 saAttr.bInheritHandle = TRUE;
5338 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005339
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005340 if (use_file_for_in)
5341 {
5342 char_u *fname = options->jo_io_name[PART_IN];
5343
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005344 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5345 FILE_SHARE_READ | FILE_SHARE_WRITE,
5346 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5347 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005348 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005349 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005350 goto failed;
5351 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005352 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005353 else if (!use_null_for_in
5354 && (!create_pipe_pair(ifd)
5355 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005356 goto failed;
5357
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005358 if (use_file_for_out)
5359 {
5360 char_u *fname = options->jo_io_name[PART_OUT];
5361
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005362 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5363 FILE_SHARE_READ | FILE_SHARE_WRITE,
5364 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5365 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005366 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005367 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005368 goto failed;
5369 }
5370 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005371 else if (!use_null_for_out &&
5372 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005373 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005374 goto failed;
5375
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005376 if (use_file_for_err)
5377 {
5378 char_u *fname = options->jo_io_name[PART_ERR];
5379
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005380 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5381 FILE_SHARE_READ | FILE_SHARE_WRITE,
5382 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5383 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005384 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005385 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005386 goto failed;
5387 }
5388 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005389 else if (!use_out_for_err && !use_null_for_err &&
5390 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005391 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005392 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005393
Bram Moolenaard8070362016-02-15 21:56:54 +01005394 si.dwFlags |= STARTF_USESTDHANDLES;
5395 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005396 si.hStdOutput = ofd[1];
5397 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5398
5399 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5400 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005401 if (options->jo_set & JO_CHANNEL)
5402 {
5403 channel = options->jo_channel;
5404 if (channel != NULL)
5405 ++channel->ch_refcount;
5406 }
5407 else
5408 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005409 if (channel == NULL)
5410 goto failed;
5411 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005412
5413 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005414 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005415 CREATE_DEFAULT_ERROR_MODE |
5416 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005417 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005418 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005419 &si, &pi,
5420 ga.ga_data,
5421 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005422 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005423 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005424 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005425 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005426 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005427
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005428 ga_clear(&ga);
5429
Bram Moolenaar14207f42016-10-27 21:13:10 +02005430 if (!AssignProcessToJobObject(jo, pi.hProcess))
5431 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005432 // if failing, switch the way to terminate
5433 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005434 CloseHandle(jo);
5435 jo = NULL;
5436 }
5437 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005438 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005439 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005440 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005441 job->jv_status = JOB_STARTED;
5442
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005443 CloseHandle(ifd[0]);
5444 CloseHandle(ofd[1]);
5445 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005446 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005447
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005448 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005449 if (channel != NULL)
5450 {
5451 channel_set_pipes(channel,
5452 use_file_for_in || use_null_for_in
5453 ? INVALID_FD : (sock_T)ifd[1],
5454 use_file_for_out || use_null_for_out
5455 ? INVALID_FD : (sock_T)ofd[0],
5456 use_out_for_err || use_file_for_err || use_null_for_err
5457 ? INVALID_FD : (sock_T)efd[0]);
5458 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005459 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005460 return;
5461
5462failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005463 CloseHandle(ifd[0]);
5464 CloseHandle(ofd[0]);
5465 CloseHandle(efd[0]);
5466 CloseHandle(ifd[1]);
5467 CloseHandle(ofd[1]);
5468 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005469 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005470 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005471}
5472
5473 char *
5474mch_job_status(job_T *job)
5475{
5476 DWORD dwExitCode = 0;
5477
Bram Moolenaar76467df2016-02-12 19:30:26 +01005478 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5479 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005480 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005481 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005482 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005483 {
5484 ch_log(job->jv_channel, "Job ended");
5485 job->jv_status = JOB_ENDED;
5486 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005487 return "dead";
5488 }
5489 return "run";
5490}
5491
Bram Moolenaar97792de2016-10-15 18:36:49 +02005492 job_T *
5493mch_detect_ended_job(job_T *job_list)
5494{
5495 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5496 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5497 job_T *job = job_list;
5498
5499 while (job != NULL)
5500 {
5501 DWORD n;
5502 DWORD result;
5503
5504 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5505 && job != NULL; job = job->jv_next)
5506 {
5507 if (job->jv_status == JOB_STARTED)
5508 {
5509 jobHandles[n] = job->jv_proc_info.hProcess;
5510 jobArray[n] = job;
5511 ++n;
5512 }
5513 }
5514 if (n == 0)
5515 continue;
5516 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5517 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5518 {
5519 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5520
5521 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5522 return wait_job;
5523 }
5524 }
5525 return NULL;
5526}
5527
Bram Moolenaarfb630902016-10-29 14:55:00 +02005528 static BOOL
5529terminate_all(HANDLE process, int code)
5530{
5531 PROCESSENTRY32 pe;
5532 HANDLE h = INVALID_HANDLE_VALUE;
5533 DWORD pid = GetProcessId(process);
5534
5535 if (pid != 0)
5536 {
5537 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5538 if (h != INVALID_HANDLE_VALUE)
5539 {
5540 pe.dwSize = sizeof(PROCESSENTRY32);
5541 if (!Process32First(h, &pe))
5542 goto theend;
5543
5544 do
5545 {
5546 if (pe.th32ParentProcessID == pid)
5547 {
5548 HANDLE ph = OpenProcess(
5549 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5550 if (ph != NULL)
5551 {
5552 terminate_all(ph, code);
5553 CloseHandle(ph);
5554 }
5555 }
5556 } while (Process32Next(h, &pe));
5557
5558 CloseHandle(h);
5559 }
5560 }
5561
5562theend:
5563 return TerminateProcess(process, code);
5564}
5565
5566/*
5567 * Send a (deadly) signal to "job".
5568 * Return FAIL if it didn't work.
5569 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005570 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005571mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005572{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005573 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005574
Bram Moolenaar923d9262016-02-25 20:56:01 +01005575 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005576 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005577 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02005578 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005579 {
5580 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5581 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00005582 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005583 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01005584 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005585 }
5586
5587 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5588 return FAIL;
5589 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005590 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5591 job->jv_proc_info.dwProcessId)
5592 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005593 FreeConsole();
5594 return ret;
5595}
5596
5597/*
5598 * Clear the data related to "job".
5599 */
5600 void
5601mch_clear_job(job_T *job)
5602{
5603 if (job->jv_status != JOB_FAILED)
5604 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005605 if (job->jv_job_object != NULL)
5606 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005607 CloseHandle(job->jv_proc_info.hProcess);
5608 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005609}
5610#endif
5611
Bram Moolenaar071d4272004-06-13 20:20:40 +00005612
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005613#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005614
5615/*
5616 * Start termcap mode
5617 */
5618 static void
5619termcap_mode_start(void)
5620{
5621 DWORD cmodein;
5622
5623 if (g_fTermcapMode)
5624 return;
5625
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005626 if (!p_rs && USE_VTP)
5627 vtp_printf("\033[?1049h");
5628
Bram Moolenaar071d4272004-06-13 20:20:40 +00005629 SaveConsoleBuffer(&g_cbNonTermcap);
5630
5631 if (g_cbTermcap.IsValid)
5632 {
5633 /*
5634 * We've been in termcap mode before. Restore certain screen
5635 * characteristics, including the buffer size and the window
5636 * size. Since we will be redrawing the screen, we don't need
5637 * to restore the actual contents of the buffer.
5638 */
5639 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005640 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005641 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5642 Rows = g_cbTermcap.Info.dwSize.Y;
5643 Columns = g_cbTermcap.Info.dwSize.X;
5644 }
5645 else
5646 {
5647 /*
5648 * This is our first time entering termcap mode. Clear the console
5649 * screen buffer, and resize the buffer to match the current window
5650 * size. We will use this as the size of our editing environment.
5651 */
5652 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005653 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005654 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5655 }
5656
Bram Moolenaar071d4272004-06-13 20:20:40 +00005657 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005658
5659 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005660 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005661 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005662 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005663 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
5664 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005665 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005666 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005667 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005668 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5669 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005670 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005671 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005672
5673 redraw_later_clear();
5674 g_fTermcapMode = TRUE;
5675}
5676
5677
5678/*
5679 * End termcap mode
5680 */
5681 static void
5682termcap_mode_end(void)
5683{
5684 DWORD cmodein;
5685 ConsoleBuffer *cb;
5686 COORD coord;
5687 DWORD dwDummy;
5688
5689 if (!g_fTermcapMode)
5690 return;
5691
5692 SaveConsoleBuffer(&g_cbTermcap);
5693
5694 GetConsoleMode(g_hConIn, &cmodein);
5695 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005696 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5697 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005698
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005699# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005700 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005701# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005702 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005703# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005704 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01005705 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005706 SetConsoleCursorInfo(g_hConOut, &g_cci);
5707
5708 if (p_rs || exiting)
5709 {
5710 /*
5711 * Clear anything that happens to be on the current line.
5712 */
5713 coord.X = 0;
5714 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5715 FillConsoleOutputCharacter(g_hConOut, ' ',
5716 cb->Info.dwSize.X, coord, &dwDummy);
5717 /*
5718 * The following is just for aesthetics. If we are exiting without
5719 * restoring the screen, then we want to have a prompt string
5720 * appear at the bottom line. However, the command interpreter
5721 * seems to always advance the cursor one line before displaying
5722 * the prompt string, which causes the screen to scroll. To
5723 * counter this, move the cursor up one line before exiting.
5724 */
5725 if (exiting && !p_rs)
5726 coord.Y--;
5727 /*
5728 * Position the cursor at the leftmost column of the desired row.
5729 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005730 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005731 }
5732
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005733 if (!p_rs && USE_VTP)
Bram Moolenaar0afdcf82020-04-01 18:29:10 +02005734 vtp_printf("\033[?1049l");
5735
Bram Moolenaar071d4272004-06-13 20:20:40 +00005736 g_fTermcapMode = FALSE;
5737}
Bram Moolenaar0f873732019-12-05 20:28:46 +01005738#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005739
5740
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005741#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005742 void
5743mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005744 char_u *s UNUSED,
5745 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005746{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005747 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00005748}
5749
5750#else
5751
5752/*
5753 * clear `n' chars, starting from `coord'
5754 */
5755 static void
5756clear_chars(
5757 COORD coord,
5758 DWORD n)
5759{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005760 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02005761 {
5762 DWORD dwDummy;
5763
5764 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5765 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
5766 &dwDummy);
5767 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005768 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005769 {
5770 set_console_color_rgb();
5771 gotoxy(coord.X + 1, coord.Y + 1);
5772 vtp_printf("\033[%dX", n);
5773 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005774}
5775
5776
5777/*
5778 * Clear the screen
5779 */
5780 static void
5781clear_screen(void)
5782{
5783 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005784
5785 if (!USE_VTP)
5786 clear_chars(g_coord, Rows * Columns);
5787 else
5788 {
5789 set_console_color_rgb();
5790 gotoxy(1, 1);
5791 vtp_printf("\033[2J");
5792 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005793}
5794
5795
5796/*
5797 * Clear to end of display
5798 */
5799 static void
5800clear_to_end_of_display(void)
5801{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005802 COORD save = g_coord;
5803
5804 if (!USE_VTP)
5805 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005806 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005807 else
5808 {
5809 set_console_color_rgb();
5810 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5811 vtp_printf("\033[0J");
5812
5813 gotoxy(save.X + 1, save.Y + 1);
5814 g_coord = save;
5815 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005816}
5817
5818
5819/*
5820 * Clear to end of line
5821 */
5822 static void
5823clear_to_end_of_line(void)
5824{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005825 COORD save = g_coord;
5826
5827 if (!USE_VTP)
5828 clear_chars(g_coord, Columns - g_coord.X);
5829 else
5830 {
5831 set_console_color_rgb();
5832 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5833 vtp_printf("\033[0K");
5834
5835 gotoxy(save.X + 1, save.Y + 1);
5836 g_coord = save;
5837 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005838}
5839
5840
5841/*
5842 * Scroll the scroll region up by `cLines' lines
5843 */
5844 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005845scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005846{
5847 COORD oldcoord = g_coord;
5848
5849 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5850 delete_lines(cLines);
5851
5852 g_coord = oldcoord;
5853}
5854
5855
5856/*
5857 * Set the scroll region
5858 */
5859 static void
5860set_scroll_region(
5861 unsigned left,
5862 unsigned top,
5863 unsigned right,
5864 unsigned bottom)
5865{
5866 if (left >= right
5867 || top >= bottom
5868 || right > (unsigned) Columns - 1
5869 || bottom > (unsigned) Rows - 1)
5870 return;
5871
5872 g_srScrollRegion.Left = left;
5873 g_srScrollRegion.Top = top;
5874 g_srScrollRegion.Right = right;
5875 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005876}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005877
Bram Moolenaar6982f422019-02-16 16:48:01 +01005878 static void
5879set_scroll_region_tb(
5880 unsigned top,
5881 unsigned bottom)
5882{
5883 if (top >= bottom || bottom > (unsigned)Rows - 1)
5884 return;
5885
5886 g_srScrollRegion.Top = top;
5887 g_srScrollRegion.Bottom = bottom;
5888}
5889
5890 static void
5891set_scroll_region_lr(
5892 unsigned left,
5893 unsigned right)
5894{
5895 if (left >= right || right > (unsigned)Columns - 1)
5896 return;
5897
5898 g_srScrollRegion.Left = left;
5899 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005900}
5901
5902
5903/*
5904 * Insert `cLines' lines at the current cursor position
5905 */
5906 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005907insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005908{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005909 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005910 COORD dest;
5911 CHAR_INFO fill;
5912
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005913 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5914
Bram Moolenaar6982f422019-02-16 16:48:01 +01005915 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005916 dest.Y = g_coord.Y + cLines;
5917
Bram Moolenaar6982f422019-02-16 16:48:01 +01005918 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005919 source.Top = g_coord.Y;
5920 source.Right = g_srScrollRegion.Right;
5921 source.Bottom = g_srScrollRegion.Bottom - cLines;
5922
Bram Moolenaar6982f422019-02-16 16:48:01 +01005923 clip.Left = g_srScrollRegion.Left;
5924 clip.Top = g_coord.Y;
5925 clip.Right = g_srScrollRegion.Right;
5926 clip.Bottom = g_srScrollRegion.Bottom;
5927
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005928 fill.Char.AsciiChar = ' ';
5929 if (!USE_VTP)
5930 fill.Attributes = g_attrCurrent;
5931 else
5932 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005933
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005934 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005935
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005936 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5937
Bram Moolenaar6982f422019-02-16 16:48:01 +01005938 // Here we have to deal with a win32 console flake: If the scroll
5939 // region looks like abc and we scroll c to a and fill with d we get
5940 // cbd... if we scroll block c one line at a time to a, we get cdd...
5941 // vim expects cdd consistently... So we have to deal with that
5942 // here... (this also occurs scrolling the same way in the other
5943 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005944
5945 if (source.Bottom < dest.Y)
5946 {
5947 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005948 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005949
Bram Moolenaar6982f422019-02-16 16:48:01 +01005950 coord.X = source.Left;
5951 for (i = clip.Top; i < dest.Y; ++i)
5952 {
5953 coord.Y = i;
5954 clear_chars(coord, source.Right - source.Left + 1);
5955 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005956 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02005957
5958 if (USE_WT)
5959 {
5960 COORD coord;
5961 int i;
5962
5963 coord.X = source.Left;
5964 for (i = source.Top; i < dest.Y; ++i)
5965 {
5966 coord.Y = i;
5967 clear_chars(coord, source.Right - source.Left + 1);
5968 }
5969 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005970}
5971
5972
5973/*
5974 * Delete `cLines' lines at the current cursor position
5975 */
5976 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005977delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005978{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005979 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005980 COORD dest;
5981 CHAR_INFO fill;
5982 int nb;
5983
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005984 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5985
Bram Moolenaar6982f422019-02-16 16:48:01 +01005986 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005987 dest.Y = g_coord.Y;
5988
Bram Moolenaar6982f422019-02-16 16:48:01 +01005989 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005990 source.Top = g_coord.Y + cLines;
5991 source.Right = g_srScrollRegion.Right;
5992 source.Bottom = g_srScrollRegion.Bottom;
5993
Bram Moolenaar6982f422019-02-16 16:48:01 +01005994 clip.Left = g_srScrollRegion.Left;
5995 clip.Top = g_coord.Y;
5996 clip.Right = g_srScrollRegion.Right;
5997 clip.Bottom = g_srScrollRegion.Bottom;
5998
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005999 fill.Char.AsciiChar = ' ';
6000 if (!USE_VTP)
6001 fill.Attributes = g_attrCurrent;
6002 else
6003 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006004
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006005 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006006
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006007 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6008
Bram Moolenaar6982f422019-02-16 16:48:01 +01006009 // Here we have to deal with a win32 console flake; See insert_lines()
6010 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006011
6012 nb = dest.Y + (source.Bottom - source.Top) + 1;
6013
6014 if (nb < source.Top)
6015 {
6016 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006017 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006018
Bram Moolenaar6982f422019-02-16 16:48:01 +01006019 coord.X = source.Left;
6020 for (i = nb; i < clip.Bottom; ++i)
6021 {
6022 coord.Y = i;
6023 clear_chars(coord, source.Right - source.Left + 1);
6024 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006025 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006026
6027 if (USE_WT)
6028 {
6029 COORD coord;
6030 int i;
6031
6032 coord.X = source.Left;
6033 for (i = nb; i <= source.Bottom; ++i)
6034 {
6035 coord.Y = i;
6036 clear_chars(coord, source.Right - source.Left + 1);
6037 }
6038 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006039}
6040
6041
6042/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006043 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006044 */
6045 static void
6046gotoxy(
6047 unsigned x,
6048 unsigned y)
6049{
6050 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6051 return;
6052
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006053 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006054 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006055 // There are reports of double-width characters not displayed
6056 // correctly. This workaround should fix it, similar to how it's done
6057 // for VTP.
6058 g_coord.X = 0;
6059 SetConsoleCursorPosition(g_hConOut, g_coord);
6060
Bram Moolenaar2313b612019-09-27 14:14:32 +02006061 // external cursor coords are 1-based; internal are 0-based
6062 g_coord.X = x - 1;
6063 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006064 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006065 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006066 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006067 {
6068 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006069 // destruction. Insider build bug. Always enabled because it's cheap
6070 // and avoids mistakes with recognizing the build.
6071 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006072
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006073 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006074
6075 g_coord.X = x - 1;
6076 g_coord.Y = y - 1;
6077 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006078}
6079
6080
6081/*
6082 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006083 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006084 */
6085 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006086textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006087{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006088 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006089
6090 SetConsoleTextAttribute(g_hConOut, wAttr);
6091}
6092
6093
6094 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006095textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006096{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006097 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006098
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006099 if (!USE_VTP)
6100 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6101 else
6102 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006103}
6104
6105
6106 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006107textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006108{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006109 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006110
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006111 if (!USE_VTP)
6112 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6113 else
6114 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006115}
6116
6117
6118/*
6119 * restore the default text attribute (whatever we started with)
6120 */
6121 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006122normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006123{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006124 if (!USE_VTP)
6125 textattr(g_attrDefault);
6126 else
6127 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006128}
6129
6130
6131static WORD g_attrPreStandout = 0;
6132
6133/*
6134 * Make the text standout, by brightening it
6135 */
6136 static void
6137standout(void)
6138{
6139 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006140
Bram Moolenaar071d4272004-06-13 20:20:40 +00006141 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6142}
6143
6144
6145/*
6146 * Turn off standout mode
6147 */
6148 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006149standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006150{
6151 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006152 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006153
6154 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006155}
6156
6157
6158/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006159 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006160 */
6161 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006162mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006163{
6164 char_u *p;
6165 int n;
6166
6167 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6168 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006169 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006170# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006171 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006172# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006173 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006174 {
6175 p = T_ME + 2;
6176 n = getdigits(&p);
6177 if (*p == 'm' && n > 0)
6178 {
6179 cterm_normal_fg_color = (n & 0xf) + 1;
6180 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6181 }
6182 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006183# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006184 cterm_normal_fg_gui_color = INVALCOLOR;
6185 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006186# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006187}
6188
6189
6190/*
6191 * visual bell: flash the screen
6192 */
6193 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006194visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006195{
6196 COORD coordOrigin = {0, 0};
6197 WORD attrFlash = ~g_attrCurrent & 0xff;
6198
6199 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006200 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006201
6202 if (oldattrs == NULL)
6203 return;
6204 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6205 coordOrigin, &dwDummy);
6206 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6207 coordOrigin, &dwDummy);
6208
Bram Moolenaar0f873732019-12-05 20:28:46 +01006209 Sleep(15); // wait for 15 msec
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006210 if (!USE_VTP)
6211 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006212 coordOrigin, &dwDummy);
6213 vim_free(oldattrs);
6214}
6215
6216
6217/*
6218 * Make the cursor visible or invisible
6219 */
6220 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006221cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006222{
6223 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006224
6225 if (USE_VTP)
6226 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6227
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006228# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006229 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006230# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006231}
6232
6233
6234/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006235 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006236 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006237 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006238 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006239write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006240 char_u *pchBuf,
6241 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006242{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006243 COORD coord = g_coord;
6244 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006245 DWORD n, cchwritten;
6246 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006247 static WCHAR *unicodebuf = NULL;
6248 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006249 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006250 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006251 static WCHAR *utf8spbuf = NULL;
6252 static int utf8splength;
6253 static DWORD utf8spcells;
6254 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006255
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006256 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006257 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006258 utf8usingbuf = &unicodebuf;
6259 do
6260 {
6261 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6262 unicodebuf, unibuflen);
6263 if (length && length <= unibuflen)
6264 break;
6265 vim_free(unicodebuf);
6266 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6267 unibuflen = unibuflen ? 0 : length;
6268 } while(1);
6269 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006270 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006271 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6272 {
6273 if (utf8usingbuf != &utf8spbuf)
6274 {
6275 if (utf8spbuf == NULL)
6276 {
6277 cells = mb_string2cells((char_u *)" ", 1);
6278 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6279 utf8spbuf = LALLOC_MULT(WCHAR, length);
6280 if (utf8spbuf != NULL)
6281 {
6282 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6283 utf8usingbuf = &utf8spbuf;
6284 utf8splength = length;
6285 utf8spcells = cells;
6286 }
6287 }
6288 else
6289 {
6290 utf8usingbuf = &utf8spbuf;
6291 length = utf8splength;
6292 cells = utf8spcells;
6293 }
6294 }
6295 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006296
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006297 if (!USE_VTP)
6298 {
6299 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6300 coord, &written);
6301 // When writing fails or didn't write a single character, pretend one
6302 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006303 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006304 coord, &cchwritten) == 0
6305 || cchwritten == 0 || cchwritten == (DWORD)-1)
6306 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006307 }
6308 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006309 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006310 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006311 NULL) == 0 || cchwritten == 0)
6312 cchwritten = 1;
6313 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006314
K.Takata135e1522022-01-29 15:27:58 +00006315 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006316 {
6317 written = cbToWrite;
6318 g_coord.X += (SHORT)cells;
6319 }
6320 else
6321 {
6322 char_u *p = pchBuf;
6323 for (n = 0; n < cchwritten; n++)
6324 MB_CPTR_ADV(p);
6325 written = p - pchBuf;
6326 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006327 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006328
6329 while (g_coord.X > g_srScrollRegion.Right)
6330 {
6331 g_coord.X -= (SHORT) Columns;
6332 if (g_coord.Y < g_srScrollRegion.Bottom)
6333 g_coord.Y++;
6334 }
6335
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006336 // Cursor under VTP is always in the correct position, no need to reset.
6337 if (!USE_VTP)
6338 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006339
6340 return written;
6341}
6342
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006343 static char_u *
6344get_seq(
6345 int *args,
6346 int *count,
6347 char_u *head)
6348{
6349 int argc;
6350 char_u *p;
6351
6352 if (head == NULL || *head != '\033')
6353 return NULL;
6354
6355 argc = 0;
6356 p = head;
6357 ++p;
6358 do
6359 {
6360 ++p;
6361 args[argc] = getdigits(&p);
6362 argc += (argc < 15) ? 1 : 0;
6363 } while (*p == ';');
6364 *count = argc;
6365
6366 return p;
6367}
6368
6369 static char_u *
6370get_sgr(
6371 int *args,
6372 int *count,
6373 char_u *head)
6374{
6375 char_u *p = get_seq(args, count, head);
6376
6377 return (p && *p == 'm') ? ++p : NULL;
6378}
6379
6380/*
6381 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6382 */
6383 static char_u *
6384sgrn2(
6385 char_u *head,
6386 int n)
6387{
6388 int argc;
6389 int args[16];
6390 char_u *p = get_sgr(args, &argc, head);
6391
6392 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6393}
6394
6395/*
6396 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6397 */
6398 static char_u *
6399sgrnc(
6400 char_u *head,
6401 int n)
6402{
6403 int argc;
6404 int args[16];
6405 char_u *p = get_sgr(args, &argc, head);
6406
6407 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6408 ? p : NULL;
6409}
6410
6411 static char_u *
6412skipblank(char_u *q)
6413{
6414 char_u *p = q;
6415
6416 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6417 ++p;
6418 return p;
6419}
6420
6421/*
6422 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6423 * NULL.
6424 */
6425 static char_u *
6426sgrn2c(
6427 char_u *head,
6428 int n)
6429{
6430 char_u *p = sgrn2(head, n);
6431
6432 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6433}
6434
6435/*
6436 * If there is only a newline between the sequence immediately following it,
6437 * a pointer to the character following the newline is returned.
6438 * Otherwise NULL.
6439 */
6440 static char_u *
6441sgrn2cn(
6442 char_u *head,
6443 int n)
6444{
6445 char_u *p = sgrn2(head, n);
6446
6447 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6448}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006449
6450/*
6451 * mch_write(): write the output buffer to the screen, translating ESC
6452 * sequences into calls to console output routines.
6453 */
6454 void
6455mch_write(
6456 char_u *s,
6457 int len)
6458{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006459 char_u *end = s + len;
6460
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006461# ifdef VIMDLL
6462 if (gui.in_use)
6463 return;
6464# endif
6465
Bram Moolenaar071d4272004-06-13 20:20:40 +00006466 if (!term_console)
6467 {
6468 write(1, s, (unsigned)len);
6469 return;
6470 }
6471
Bram Moolenaar0f873732019-12-05 20:28:46 +01006472 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00006473 while (len--)
6474 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006475 int prefix = -1;
6476 char_u ch;
6477
6478 // While processing a sequence, on rare occasions it seems that another
6479 // sequence may be inserted asynchronously.
6480 if (len < 0)
6481 {
6482 redraw_all_later(CLEAR);
6483 return;
6484 }
6485
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006486 while (s + ++prefix < end)
6487 {
6488 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006489 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6490 && ch != '\a' && ch != '\033'))
6491 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006492 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006493
6494 if (p_wd)
6495 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006496 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006497 if (prefix != 0)
6498 prefix = 1;
6499 }
6500
6501 if (prefix != 0)
6502 {
6503 DWORD nWritten;
6504
6505 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006506# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006507 if (fdDump)
6508 {
6509 fputc('>', fdDump);
6510 fwrite(s, sizeof(char_u), nWritten, fdDump);
6511 fputs("<\n", fdDump);
6512 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006513# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006514 len -= (nWritten - 1);
6515 s += nWritten;
6516 }
6517 else if (s[0] == '\n')
6518 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006519 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00006520 if (g_coord.Y == g_srScrollRegion.Bottom)
6521 {
6522 scroll(1);
6523 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6524 }
6525 else
6526 {
6527 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6528 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006529# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006530 if (fdDump)
6531 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006532# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006533 s++;
6534 }
6535 else if (s[0] == '\r')
6536 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006537 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00006538 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006539# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006540 if (fdDump)
6541 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006542# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006543 s++;
6544 }
6545 else if (s[0] == '\b')
6546 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006547 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00006548 if (g_coord.X > g_srScrollRegion.Left)
6549 g_coord.X--;
6550 else if (g_coord.Y > g_srScrollRegion.Top)
6551 {
6552 g_coord.X = g_srScrollRegion.Right;
6553 g_coord.Y--;
6554 }
6555 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006556# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006557 if (fdDump)
6558 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006559# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006560 s++;
6561 }
6562 else if (s[0] == '\a')
6563 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006564 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00006565 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006566# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006567 if (fdDump)
6568 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006569# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006570 s++;
6571 }
6572 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6573 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006574# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006575 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006576# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006577 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006578 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006579 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006580
6581 switch (s[2])
6582 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006583 case '0': case '1': case '2': case '3': case '4':
6584 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006585 if (*(p = get_seq(args, &argc, s)) != 'm')
6586 goto notsgr;
6587
6588 p = s;
6589
6590 // Handling frequent optional sequences. Output to the screen
6591 // takes too long, so do not output as much as possible.
6592
6593 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
6594 // resetFG,FG,BG are omitted.
6595 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006596 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006597 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
6598 len = len + 1 - (int)(p - s);
6599 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006600 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006601 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006602
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006603 // If FG,BG,BG,FG of SGR are connected, the first FG can be
6604 // omitted.
6605 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
6606 p = sp;
6607
6608 // If FG,BG,FG,BG of SGR are connected, the first FG can be
6609 // omitted.
6610 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
6611 p = sp;
6612
6613 // If BG,BG of SGR are connected, the first BG can be omitted.
6614 if (sgrn2((sp = sgrn2(p, 48)), 48))
6615 p = sp;
6616
6617 // If restoreFG and FG are connected, the restoreFG can be
6618 // omitted.
6619 if (sgrn2((sp = sgrnc(p, 39)), 38))
6620 p = sp;
6621
6622 p = get_seq(args, &argc, p);
6623
6624notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006625 arg1 = args[0];
6626 arg2 = args[1];
6627 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006628 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006629 if (argc == 1 && args[0] == 0)
6630 normvideo();
6631 else if (argc == 1)
6632 {
6633 if (USE_VTP)
6634 textcolor((WORD) arg1);
6635 else
6636 textattr((WORD) arg1);
6637 }
6638 else if (USE_VTP)
6639 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006640 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006641 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006642 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006643 gotoxy(arg2, arg1);
6644 }
6645 else if (argc == 2 && *p == 'r')
6646 {
6647 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6648 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006649 else if (argc == 2 && *p == 'R')
6650 {
6651 set_scroll_region_tb(arg1, arg2);
6652 }
6653 else if (argc == 2 && *p == 'V')
6654 {
6655 set_scroll_region_lr(arg1, arg2);
6656 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006657 else if (argc == 1 && *p == 'A')
6658 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006659 gotoxy(g_coord.X + 1,
6660 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6661 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006662 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006663 {
6664 textbackground((WORD) arg1);
6665 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006666 else if (argc == 1 && *p == 'C')
6667 {
6668 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6669 g_coord.Y + 1);
6670 }
6671 else if (argc == 1 && *p == 'f')
6672 {
6673 textcolor((WORD) arg1);
6674 }
6675 else if (argc == 1 && *p == 'H')
6676 {
6677 gotoxy(1, arg1);
6678 }
6679 else if (argc == 1 && *p == 'L')
6680 {
6681 insert_lines(arg1);
6682 }
6683 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006684 {
6685 delete_lines(arg1);
6686 }
6687
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006688 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006689 s = p + 1;
6690 break;
6691
Bram Moolenaar071d4272004-06-13 20:20:40 +00006692 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006693 gotoxy(g_coord.X + 1,
6694 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6695 goto got3;
6696
6697 case 'B':
6698 visual_bell();
6699 goto got3;
6700
6701 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006702 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6703 g_coord.Y + 1);
6704 goto got3;
6705
6706 case 'E':
6707 termcap_mode_end();
6708 goto got3;
6709
6710 case 'F':
6711 standout();
6712 goto got3;
6713
6714 case 'f':
6715 standend();
6716 goto got3;
6717
6718 case 'H':
6719 gotoxy(1, 1);
6720 goto got3;
6721
6722 case 'j':
6723 clear_to_end_of_display();
6724 goto got3;
6725
6726 case 'J':
6727 clear_screen();
6728 goto got3;
6729
6730 case 'K':
6731 clear_to_end_of_line();
6732 goto got3;
6733
6734 case 'L':
6735 insert_lines(1);
6736 goto got3;
6737
6738 case 'M':
6739 delete_lines(1);
6740 goto got3;
6741
6742 case 'S':
6743 termcap_mode_start();
6744 goto got3;
6745
6746 case 'V':
6747 cursor_visible(TRUE);
6748 goto got3;
6749
6750 case 'v':
6751 cursor_visible(FALSE);
6752 goto got3;
6753
6754 got3:
6755 s += 3;
6756 len -= 2;
6757 }
6758
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006759# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006760 if (fdDump)
6761 {
6762 fputs("ESC | ", fdDump);
6763 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6764 fputc('\n', fdDump);
6765 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006766# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006767 }
6768 else
6769 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006770 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00006771 DWORD nWritten;
6772
6773 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006774# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006775 if (fdDump)
6776 {
6777 fputc('>', fdDump);
6778 fwrite(s, sizeof(char_u), nWritten, fdDump);
6779 fputs("<\n", fdDump);
6780 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006781# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006782
6783 len -= (nWritten - 1);
6784 s += nWritten;
6785 }
6786 }
6787
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006788# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006789 if (fdDump)
6790 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006791# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006792}
6793
Bram Moolenaar0f873732019-12-05 20:28:46 +01006794#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006795
6796
6797/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006798 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006799 */
6800 void
6801mch_delay(
6802 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02006803 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006804{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006805#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006806 Sleep((int)msec); // never wait for input
6807#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006808# ifdef VIMDLL
6809 if (gui.in_use)
6810 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006811 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006812 return;
6813 }
6814# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02006815 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006816# ifdef FEAT_MZSCHEME
6817 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6818 {
6819 int towait = p_mzq;
6820
Bram Moolenaar0f873732019-12-05 20:28:46 +01006821 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006822 while (msec > 0)
6823 {
6824 mzvim_check_threads();
6825 if (msec < towait)
6826 towait = msec;
6827 Sleep(towait);
6828 msec -= towait;
6829 }
6830 }
6831 else
6832# endif
6833 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006834 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006835 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006836#endif
6837}
6838
6839
6840/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006841 * This version of remove is not scared by a readonly (backup) file.
6842 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006843 * Return 0 for success, -1 for failure.
6844 */
6845 int
6846mch_remove(char_u *name)
6847{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006848 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006849 int n;
6850
Bram Moolenaar203258c2016-01-17 22:15:16 +01006851 /*
6852 * On Windows, deleting a directory's symbolic link is done by
6853 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6854 */
6855 if (mch_isdir(name) && mch_is_symbolic_link(name))
6856 return mch_rmdir(name);
6857
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006858 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6859
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006860 wn = enc_to_utf16(name, NULL);
6861 if (wn == NULL)
6862 return -1;
6863
6864 n = DeleteFileW(wn) ? 0 : -1;
6865 vim_free(wn);
6866 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006867}
6868
6869
6870/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006871 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006872 */
6873 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006874mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006875{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006876#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
6877# ifdef VIMDLL
6878 if (!gui.in_use)
6879# endif
6880 if (g_fCtrlCPressed || g_fCBrkPressed)
6881 {
6882 ctrl_break_was_pressed = g_fCBrkPressed;
6883 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6884 got_int = TRUE;
6885 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006886#endif
6887}
6888
Bram Moolenaar0f873732019-12-05 20:28:46 +01006889// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01006890#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006891
6892/*
6893 * How much main memory in KiB that can be used by VIM.
6894 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006895 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006896mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006897{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006898 MEMORYSTATUSEX ms;
6899
Bram Moolenaar0f873732019-12-05 20:28:46 +01006900 // Need to use GlobalMemoryStatusEx() when there is more memory than
6901 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006902 ms.dwLength = sizeof(MEMORYSTATUSEX);
6903 GlobalMemoryStatusEx(&ms);
6904 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006905 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006906 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006907 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006908 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006909 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006910 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006911 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006912 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006913 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01006914 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006915 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006916}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006917
Bram Moolenaar071d4272004-06-13 20:20:40 +00006918/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006919 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00006920 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6921 * file whose short file name is "FOO.BAR" (its long file name will
6922 * be correct: "foo.bar~"). Because a file can be accessed by
6923 * either its SFN or its LFN, "foo.bar" has effectively been
6924 * renamed to "foo.bar", which is not at all what was wanted. This
6925 * seems to happen only when renaming files with three-character
6926 * extensions by appending a suffix that does not include ".".
6927 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6928 *
6929 * There is another problem, which isn't really a bug but isn't right either:
6930 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6931 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6932 * service pack 6. Doesn't seem to happen on Windows 98.
6933 *
6934 * Like rename(), returns 0 upon success, non-zero upon failure.
6935 * Should probably set errno appropriately when errors occur.
6936 */
6937 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006938mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006939{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006940 WCHAR *p;
6941 int i;
6942 WCHAR szTempFile[_MAX_PATH + 1];
6943 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006944 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006945
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006946 // No need to play tricks unless the file name contains a "~" as the
6947 // seventh character.
6948 p = wold;
6949 for (i = 0; wold[i] != NUL; ++i)
6950 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6951 && wold[i + 1] != 0)
6952 p = wold + i + 1;
6953 if ((int)(wold + i - p) < 8 || p[6] != '~')
6954 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006955
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006956 // Get base path of new file name. Undocumented feature: If pszNewFile is
6957 // a directory, no error is returned and pszFilePart will be NULL.
6958 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006959 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006960 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006961
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006962 // Get (and create) a unique temporary file name in directory of new file
6963 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006964 return -2;
6965
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006966 // blow the temp file away
6967 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006968 return -3;
6969
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006970 // rename old file to the temp file
6971 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006972 return -4;
6973
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006974 // now create an empty file called pszOldFile; this prevents the operating
6975 // system using pszOldFile as an alias (SFN) if we're renaming within the
6976 // same directory. For example, we're editing a file called
6977 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6978 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
6979 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
6980 // cause all sorts of problems later in buf_write(). So, we create an
6981 // empty file called filena~1.txt and the system will have to find some
6982 // other SFN for filena~1.txt~, such as filena~2.txt
6983 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006984 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6985 return -5;
6986 if (!CloseHandle(hf))
6987 return -6;
6988
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006989 // rename the temp file to the new file
6990 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006991 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006992 // Renaming failed. Rename the file back to its old name, so that it
6993 // looks like nothing happened.
6994 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006995 return -7;
6996 }
6997
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006998 // Seems to be left around on Novell filesystems
6999 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007000
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007001 // finally, remove the empty old file
7002 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007003 return -8;
7004
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007005 return 0;
7006}
7007
7008
7009/*
7010 * Converts the filenames to UTF-16, then call mch_wrename().
7011 * Like rename(), returns 0 upon success, non-zero upon failure.
7012 */
7013 int
7014mch_rename(
7015 const char *pszOldFile,
7016 const char *pszNewFile)
7017{
7018 WCHAR *wold = NULL;
7019 WCHAR *wnew = NULL;
7020 int retval = -1;
7021
7022 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7023 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7024 if (wold != NULL && wnew != NULL)
7025 retval = mch_wrename(wold, wnew);
7026 vim_free(wold);
7027 vim_free(wnew);
7028 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007029}
7030
7031/*
7032 * Get the default shell for the current hardware platform
7033 */
7034 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007035default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007036{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007037 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007038}
7039
7040/*
7041 * mch_access() extends access() to do more detailed check on network drives.
7042 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7043 */
7044 int
7045mch_access(char *n, int p)
7046{
7047 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007048 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007049 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007050
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007051 wn = enc_to_utf16((char_u *)n, NULL);
7052 if (wn == NULL)
7053 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007054
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007055 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007056 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007057 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007058
7059 if (p & R_OK)
7060 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007061 // Read check is performed by seeing if we can do a find file on
7062 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007063 int i;
7064 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007065
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007066 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7067 TempNameW[i] = wn[i];
7068 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7069 TempNameW[i++] = '\\';
7070 TempNameW[i++] = '*';
7071 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007072
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007073 hFile = FindFirstFileW(TempNameW, &d);
7074 if (hFile == INVALID_HANDLE_VALUE)
7075 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007076 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007077 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007078 }
7079
7080 if (p & W_OK)
7081 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007082 // Trying to create a temporary file in the directory should catch
7083 // directories on read-only network shares. However, in
7084 // directories whose ACL allows writes but denies deletes will end
7085 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007086 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7087 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007088 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007089 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007090 }
7091 }
7092 else
7093 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007094 // Don't consider a file read-only if another process has opened it.
7095 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7096
Bram Moolenaar0f873732019-12-05 20:28:46 +01007097 // Trying to open the file for the required access does ACL, read-only
7098 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007099 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7100 | ((p & R_OK) ? GENERIC_READ : 0);
7101
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007102 hFile = CreateFileW(wn, access_mode, share_mode,
7103 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007104 if (hFile == INVALID_HANDLE_VALUE)
7105 goto getout;
7106 CloseHandle(hFile);
7107 }
7108
Bram Moolenaar0f873732019-12-05 20:28:46 +01007109 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007110getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007111 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007112 return retval;
7113}
7114
Bram Moolenaar071d4272004-06-13 20:20:40 +00007115/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007116 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007117 */
7118 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007119mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007120{
7121 WCHAR *wn;
7122 int f;
7123
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007124 wn = enc_to_utf16((char_u *)name, NULL);
7125 if (wn == NULL)
7126 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007127
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007128 f = _wopen(wn, flags, mode);
7129 vim_free(wn);
7130 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007131}
7132
7133/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007134 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007135 */
7136 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007137mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007138{
7139 WCHAR *wn, *wm;
7140 FILE *f = NULL;
7141
Bram Moolenaara12a1612019-01-24 16:39:02 +01007142#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007143 // Work around an annoying assertion in the Microsoft debug CRT
7144 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007145 char newMode = mode[strlen(mode) - 1];
7146 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007147
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007148 _get_fmode(&oldMode);
7149 if (newMode == 't')
7150 _set_fmode(_O_TEXT);
7151 else if (newMode == 'b')
7152 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007153#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007154 wn = enc_to_utf16((char_u *)name, NULL);
7155 wm = enc_to_utf16((char_u *)mode, NULL);
7156 if (wn != NULL && wm != NULL)
7157 f = _wfopen(wn, wm);
7158 vim_free(wn);
7159 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007160
Bram Moolenaara12a1612019-01-24 16:39:02 +01007161#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007162 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007163#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007164 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007165}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007166
Bram Moolenaar071d4272004-06-13 20:20:40 +00007167/*
7168 * SUB STREAM (aka info stream) handling:
7169 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007170 * NTFS can have sub streams for each file. The normal contents of a file is
7171 * stored in the main stream, and extra contents (author information, title and
7172 * so on) can be stored in a sub stream. After Windows 2000, the user can
7173 * access and store this information in sub streams via an explorer's property
7174 * menu item in the right click menu. This information in sub streams was lost
7175 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007176 *
7177 * Incomplete explanation:
7178 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7179 * More useful info and an example:
7180 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7181 */
7182
7183/*
7184 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7185 * and write to stream "substream" of file "to".
7186 * Errors are ignored.
7187 */
7188 static void
7189copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7190{
7191 HANDLE hTo;
7192 WCHAR *to_name;
7193
7194 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7195 wcscpy(to_name, to);
7196 wcscat(to_name, substream);
7197
7198 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7199 FILE_ATTRIBUTE_NORMAL, NULL);
7200 if (hTo != INVALID_HANDLE_VALUE)
7201 {
7202 long done;
7203 DWORD todo;
7204 DWORD readcnt, written;
7205 char buf[4096];
7206
Bram Moolenaar0f873732019-12-05 20:28:46 +01007207 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007208 for (done = 0; done < len; done += written)
7209 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007210 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007211 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7212 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007213 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7214 FALSE, FALSE, context)
7215 || readcnt != todo
7216 || !WriteFile(hTo, buf, todo, &written, NULL)
7217 || written != todo)
7218 break;
7219 }
7220 CloseHandle(hTo);
7221 }
7222
7223 free(to_name);
7224}
7225
7226/*
7227 * Copy info streams from file "from" to file "to".
7228 */
7229 static void
7230copy_infostreams(char_u *from, char_u *to)
7231{
7232 WCHAR *fromw;
7233 WCHAR *tow;
7234 HANDLE sh;
7235 WIN32_STREAM_ID sid;
7236 int headersize;
7237 WCHAR streamname[_MAX_PATH];
7238 DWORD readcount;
7239 void *context = NULL;
7240 DWORD lo, hi;
7241 int len;
7242
Bram Moolenaar0f873732019-12-05 20:28:46 +01007243 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007244 fromw = enc_to_utf16(from, NULL);
7245 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007246 if (fromw != NULL && tow != NULL)
7247 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007248 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007249 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7250 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7251 if (sh != INVALID_HANDLE_VALUE)
7252 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007253 // Use BackupRead() to find the info streams. Repeat until we
7254 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007255 for (;;)
7256 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007257 // Get the header to find the length of the stream name. If
7258 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007259 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007260 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007261 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7262 &readcount, FALSE, FALSE, &context)
7263 || readcount == 0)
7264 break;
7265
Bram Moolenaar0f873732019-12-05 20:28:46 +01007266 // We only deal with streams that have a name. The normal
7267 // file data appears to be without a name, even though docs
7268 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007269 if (sid.dwStreamNameSize > 0)
7270 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007271 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007272 if (!BackupRead(sh, (LPBYTE)streamname,
7273 sid.dwStreamNameSize,
7274 &readcount, FALSE, FALSE, &context))
7275 break;
7276
Bram Moolenaar0f873732019-12-05 20:28:46 +01007277 // Copy an info stream with a name ":anything:$DATA".
7278 // Skip "::$DATA", it has no stream name (examples suggest
7279 // it might be used for the normal file contents).
7280 // Note that BackupRead() counts bytes, but the name is in
7281 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007282 len = readcount / sizeof(WCHAR);
7283 streamname[len] = 0;
7284 if (len > 7 && wcsicmp(streamname + len - 6,
7285 L":$DATA") == 0)
7286 {
7287 streamname[len - 6] = 0;
7288 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007289 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007290 }
7291 }
7292
Bram Moolenaar0f873732019-12-05 20:28:46 +01007293 // Advance to the next stream. We might try seeking too far,
7294 // but BackupSeek() doesn't skip over stream borders, thus
7295 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007296 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007297 &lo, &hi, &context);
7298 }
7299
Bram Moolenaar0f873732019-12-05 20:28:46 +01007300 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007301 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7302
7303 CloseHandle(sh);
7304 }
7305 }
7306 vim_free(fromw);
7307 vim_free(tow);
7308}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007309
7310/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007311 * ntdll.dll definitions
7312 */
7313#define FileEaInformation 7
7314#ifndef STATUS_SUCCESS
7315# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7316#endif
7317
7318typedef struct _FILE_FULL_EA_INFORMATION_ {
7319 ULONG NextEntryOffset;
7320 UCHAR Flags;
7321 UCHAR EaNameLength;
7322 USHORT EaValueLength;
7323 CHAR EaName[1];
7324} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7325
7326typedef struct _FILE_EA_INFORMATION_ {
7327 ULONG EaSize;
7328} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7329
7330typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7331 PHANDLE FileHandle,
7332 ACCESS_MASK DesiredAccess,
7333 POBJECT_ATTRIBUTES ObjectAttributes,
7334 PIO_STATUS_BLOCK IoStatusBlock,
7335 ULONG ShareAccess,
7336 ULONG OpenOptions);
7337typedef NTSTATUS (NTAPI *PfnNtClose)(
7338 HANDLE Handle);
7339typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
7340 HANDLE FileHandle,
7341 PIO_STATUS_BLOCK IoStatusBlock,
7342 PVOID Buffer,
7343 ULONG Length);
7344typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7345 HANDLE FileHandle,
7346 PIO_STATUS_BLOCK IoStatusBlock,
7347 PVOID Buffer,
7348 ULONG Length,
7349 BOOLEAN ReturnSingleEntry,
7350 PVOID EaList,
7351 ULONG EaListLength,
7352 PULONG EaIndex,
7353 BOOLEAN RestartScan);
7354typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
7355 HANDLE FileHandle,
7356 PIO_STATUS_BLOCK IoStatusBlock,
7357 PVOID FileInformation,
7358 ULONG Length,
7359 FILE_INFORMATION_CLASS FileInformationClass);
7360typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7361 PUNICODE_STRING DestinationString,
7362 PCWSTR SourceString);
7363
7364PfnNtOpenFile pNtOpenFile = NULL;
7365PfnNtClose pNtClose = NULL;
7366PfnNtSetEaFile pNtSetEaFile = NULL;
7367PfnNtQueryEaFile pNtQueryEaFile = NULL;
7368PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7369PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
7370
7371/*
7372 * Load ntdll.dll functions.
7373 */
7374 static BOOL
7375load_ntdll(void)
7376{
7377 static int loaded = -1;
7378
7379 if (loaded == -1)
7380 {
7381 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7382 if (hNtdll != NULL)
7383 {
7384 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7385 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7386 pNtSetEaFile = (PfnNtSetEaFile)
7387 GetProcAddress(hNtdll, "NtSetEaFile");
7388 pNtQueryEaFile = (PfnNtQueryEaFile)
7389 GetProcAddress(hNtdll, "NtQueryEaFile");
7390 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7391 GetProcAddress(hNtdll, "NtQueryInformationFile");
7392 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7393 GetProcAddress(hNtdll, "RtlInitUnicodeString");
7394 }
7395 if (pNtOpenFile == NULL
7396 || pNtClose == NULL
7397 || pNtSetEaFile == NULL
7398 || pNtQueryEaFile == NULL
7399 || pNtQueryInformationFile == NULL
7400 || pRtlInitUnicodeString == NULL)
7401 loaded = FALSE;
7402 else
7403 loaded = TRUE;
7404 }
7405 return (BOOL) loaded;
7406}
7407
7408/*
7409 * Copy extended attributes (EA) from file "from" to file "to".
7410 */
7411 static void
7412copy_extattr(char_u *from, char_u *to)
7413{
7414 char_u *fromf = NULL;
7415 char_u *tof = NULL;
7416 WCHAR *fromw = NULL;
7417 WCHAR *tow = NULL;
7418 UNICODE_STRING u;
7419 HANDLE h;
7420 OBJECT_ATTRIBUTES oa;
7421 IO_STATUS_BLOCK iosb;
7422 FILE_EA_INFORMATION_ eainfo = {0};
7423 void *ea = NULL;
7424
7425 if (!load_ntdll())
7426 return;
7427
7428 // Convert the file names to the fully qualified object names.
7429 fromf = alloc(STRLEN(from) + 5);
7430 tof = alloc(STRLEN(to) + 5);
7431 if (fromf == NULL || tof == NULL)
7432 goto theend;
7433 STRCPY(fromf, "\\??\\");
7434 STRCAT(fromf, from);
7435 STRCPY(tof, "\\??\\");
7436 STRCAT(tof, to);
7437
7438 // Convert the names to wide characters.
7439 fromw = enc_to_utf16(fromf, NULL);
7440 tow = enc_to_utf16(tof, NULL);
7441 if (fromw == NULL || tow == NULL)
7442 goto theend;
7443
7444 // Get the EA.
7445 pRtlInitUnicodeString(&u, fromw);
7446 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7447 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7448 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7449 goto theend;
7450 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7451 FileEaInformation);
7452 if (eainfo.EaSize != 0)
7453 {
7454 ea = alloc(eainfo.EaSize);
7455 if (ea != NULL)
7456 {
7457 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7458 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7459 {
7460 vim_free(ea);
7461 ea = NULL;
7462 }
7463 }
7464 }
7465 pNtClose(h);
7466
7467 // Set the EA.
7468 if (ea != NULL)
7469 {
7470 pRtlInitUnicodeString(&u, tow);
7471 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7472 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7473 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7474 goto theend;
7475
7476 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
7477 pNtClose(h);
7478 }
7479
7480theend:
7481 vim_free(fromf);
7482 vim_free(tof);
7483 vim_free(fromw);
7484 vim_free(tow);
7485 vim_free(ea);
7486}
7487
7488/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007489 * Copy file attributes from file "from" to file "to".
7490 * For Windows NT and later we copy info streams.
7491 * Always returns zero, errors are ignored.
7492 */
7493 int
7494mch_copy_file_attribute(char_u *from, char_u *to)
7495{
Bram Moolenaar0f873732019-12-05 20:28:46 +01007496 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007497 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007498 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007499 return 0;
7500}
7501
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007502
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007503/*
K.Takatadc73b4b2021-06-08 18:32:36 +02007504 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007505 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007506static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007507static LPWSTR *ArglistW = NULL;
7508static int global_argc = 0;
7509static char **global_argv;
7510
Bram Moolenaar0f873732019-12-05 20:28:46 +01007511static int used_file_argc = 0; // last argument in global_argv[] used
7512 // for the argument list.
7513static int *used_file_indexes = NULL; // indexes in global_argv[] for
7514 // command line arguments added to
7515 // the argument list
7516static int used_file_count = 0; // nr of entries in used_file_indexes
7517static int used_file_literal = FALSE; // take file names literally
7518static int used_file_full_path = FALSE; // file name was full path
7519static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007520static int used_alist_count = 0;
7521
7522
7523/*
7524 * Get the command line arguments. Unicode version.
7525 * Returns argc. Zero when something fails.
7526 */
7527 int
7528get_cmd_argsW(char ***argvp)
7529{
7530 char **argv = NULL;
7531 int argc = 0;
7532 int i;
7533
Bram Moolenaar14993322014-09-09 12:25:33 +02007534 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007535 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7536 if (ArglistW != NULL)
7537 {
7538 argv = malloc((nArgsW + 1) * sizeof(char *));
7539 if (argv != NULL)
7540 {
7541 argc = nArgsW;
7542 argv[argc] = NULL;
7543 for (i = 0; i < argc; ++i)
7544 {
7545 int len;
7546
K.Takatadc73b4b2021-06-08 18:32:36 +02007547 // Convert each Unicode argument to UTF-8.
7548 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007549 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007550 (LPSTR *)&argv[i], &len, 0, 0);
7551 if (argv[i] == NULL)
7552 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007553 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007554 while (i > 0)
7555 free(argv[--i]);
7556 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007557 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007558 argc = 0;
7559 }
7560 }
7561 }
7562 }
7563
7564 global_argc = argc;
7565 global_argv = argv;
7566 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007567 {
7568 if (used_file_indexes != NULL)
7569 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007570 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007571 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007572
7573 if (argvp != NULL)
7574 *argvp = argv;
7575 return argc;
7576}
7577
7578 void
7579free_cmd_argsW(void)
7580{
7581 if (ArglistW != NULL)
7582 {
7583 GlobalFree(ArglistW);
7584 ArglistW = NULL;
7585 }
7586}
7587
7588/*
7589 * Remember "name" is an argument that was added to the argument list.
7590 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7591 * is called.
7592 */
7593 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007594used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007595{
7596 int i;
7597
7598 if (used_file_indexes == NULL)
7599 return;
7600 for (i = used_file_argc + 1; i < global_argc; ++i)
7601 if (STRCMP(global_argv[i], name) == 0)
7602 {
7603 used_file_argc = i;
7604 used_file_indexes[used_file_count++] = i;
7605 break;
7606 }
7607 used_file_literal = literal;
7608 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007609 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007610}
7611
7612/*
7613 * Remember the length of the argument list as it was. If it changes then we
7614 * leave it alone when 'encoding' is set.
7615 */
7616 void
7617set_alist_count(void)
7618{
7619 used_alist_count = GARGCOUNT;
7620}
7621
7622/*
7623 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02007624 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007625 * and convert them to 'encoding'.
7626 */
7627 void
7628fix_arg_enc(void)
7629{
7630 int i;
7631 int idx;
7632 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007633 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007634
Bram Moolenaar0f873732019-12-05 20:28:46 +01007635 // Safety checks:
7636 // - if argument count differs between the wide and non-wide argument
7637 // list, something must be wrong.
7638 // - the file name arguments must have been located.
7639 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007640 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007641 || ArglistW == NULL
7642 || used_file_indexes == NULL
7643 || used_file_count == 0
7644 || used_alist_count != GARGCOUNT)
7645 return;
7646
Bram Moolenaar0f873732019-12-05 20:28:46 +01007647 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007648 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007649 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007650 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00007651 for (i = 0; i < GARGCOUNT; ++i)
7652 fnum_list[i] = GARGLIST[i].ae_fnum;
7653
Bram Moolenaar0f873732019-12-05 20:28:46 +01007654 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007655 alist_clear(&global_alist);
7656 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007657 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007658
7659 for (i = 0; i < used_file_count; ++i)
7660 {
7661 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007662 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007663 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007664 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007665 int literal = used_file_literal;
7666
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007667#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01007668 // When using diff mode may need to concatenate file name to
7669 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007670 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7671 && !mch_isdir(alist_name(&GARGLIST[0])))
7672 {
7673 char_u *r;
7674
7675 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7676 if (r != NULL)
7677 {
7678 vim_free(str);
7679 str = r;
7680 }
7681 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007682#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01007683 // Re-use the old buffer by renaming it. When not using literal
7684 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00007685 if (used_file_literal)
7686 buf_set_name(fnum_list[i], str);
7687
Bram Moolenaar0f873732019-12-05 20:28:46 +01007688 // Check backtick literal. backtick literal is already expanded in
7689 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007690 if (literal == FALSE)
7691 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007692 size_t len = STRLEN(str);
7693
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007694 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7695 literal = TRUE;
7696 }
7697 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007698 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007699 }
7700
7701 if (!used_file_literal)
7702 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007703 // Now expand wildcards in the arguments.
7704 // Temporarily add '(' and ')' to 'isfname'. These are valid
7705 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00007706 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01007707 // Also, unset wildignore to not be influenced by this option.
7708 // The arguments specified in command-line should be kept even if
7709 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00007710 // Use :legacy so that it also works when in Vim9 script.
7711 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
7712 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007713 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00007714 do_cmdline_cmd(
7715 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
7716 do_cmdline_cmd(
7717 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007718 }
7719
Bram Moolenaar0f873732019-12-05 20:28:46 +01007720 // If wildcard expansion failed, we are editing the first file of the
7721 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007722 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7723 {
7724 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00007725 if (GARGCOUNT == 1 && used_file_full_path
7726 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
7727 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007728 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007729
7730 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007731}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007732
7733 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007734mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007735{
7736 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007737 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007738
Bram Moolenaar964b3742019-05-24 18:54:09 +02007739 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007740 if (envbuf == NULL)
7741 return -1;
7742
7743 sprintf((char *)envbuf, "%s=%s", var, value);
7744
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007745 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007746
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007747 vim_free(envbuf);
7748 if (p == NULL)
7749 return -1;
7750 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007751#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007752 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007753#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007754 // Unlike Un*x systems, we can free the string for _wputenv().
7755 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007756
7757 return 0;
7758}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007759
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007760/*
7761 * Support for 256 colors and 24-bit colors was added in Windows 10
7762 * version 1703 (Creators update).
7763 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007764#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7765
7766/*
7767 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02007768 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007769 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007770#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007771
7772/*
7773 * ConPTY differences between versions, need different logic.
7774 * version 1903 (May 2019 update).
7775 */
7776#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
7777
7778/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007779 * version 1909 (November 2019 update).
7780 */
7781#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
7782
7783/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007784 * Stay ahead of the next update, and when it's done, fix this.
7785 * version ? (2020 update, temporarily use the build number of insider preview)
7786 */
7787#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
7788
7789/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02007790 * Confirm until this version. Also the logic changes.
7791 * insider preview.
7792 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02007793#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007794
7795/*
7796 * Not stable now.
7797 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007798#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007799
7800 static void
7801vtp_flag_init(void)
7802{
7803 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007804#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007805 DWORD mode;
7806 HANDLE out;
7807
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007808# ifdef VIMDLL
7809 if (!gui.in_use)
7810# endif
7811 {
7812 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007813
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007814 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7815 GetConsoleMode(out, &mode);
7816 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7817 if (SetConsoleMode(out, mode) == 0)
7818 vtp_working = 0;
7819 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007820#endif
7821
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007822 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007823 conpty_working = 1;
7824 if (ver >= CONPTY_STABLE_BUILD)
7825 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007826
Bram Moolenaar57da6982019-09-13 22:30:11 +02007827 if (ver <= CONPTY_INSIDER_BUILD)
7828 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007829 if (ver <= CONPTY_1909_BUILD)
7830 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02007831 if (ver <= CONPTY_1903_BUILD)
7832 conpty_type = 2;
7833 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
7834 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007835
7836 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
7837 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007838}
7839
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007840#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007841
7842 static void
7843vtp_init(void)
7844{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007845 HMODULE hKerneldll;
7846 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007847# ifdef FEAT_TERMGUICOLORS
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01007848 COLORREF fg;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007849# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007850
Bram Moolenaar0f873732019-12-05 20:28:46 +01007851 // Use functions supported from Vista
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007852 hKerneldll = GetModuleHandle("kernel32.dll");
7853 if (hKerneldll != NULL)
7854 {
7855 pGetConsoleScreenBufferInfoEx =
7856 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7857 hKerneldll, "GetConsoleScreenBufferInfoEx");
7858 pSetConsoleScreenBufferInfoEx =
7859 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7860 hKerneldll, "SetConsoleScreenBufferInfoEx");
7861 if (pGetConsoleScreenBufferInfoEx != NULL
7862 && pSetConsoleScreenBufferInfoEx != NULL)
7863 has_csbiex = TRUE;
7864 }
7865
7866 csbi.cbSize = sizeof(csbi);
7867 if (has_csbiex)
7868 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007869 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7870 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
Bram Moolenaardf543822020-01-30 11:53:59 +01007871 store_console_bg_rgb = save_console_bg_rgb;
7872 store_console_fg_rgb = save_console_fg_rgb;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007873
7874# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007875 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007876 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007877 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007878# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007879
7880 set_console_color_rgb();
7881}
7882
7883 static void
7884vtp_exit(void)
7885{
Bram Moolenaardf543822020-01-30 11:53:59 +01007886 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007887}
7888
Bram Moolenaar06b7b582020-05-30 17:49:25 +02007889 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007890vtp_printf(
7891 char *format,
7892 ...)
7893{
7894 char_u buf[100];
7895 va_list list;
7896 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007897 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007898
7899 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007900 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007901 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007902 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007903 return (int)result;
7904}
7905
7906 static void
7907vtp_sgr_bulk(
7908 int arg)
7909{
7910 int args[1];
7911
7912 args[0] = arg;
7913 vtp_sgr_bulks(1, args);
7914}
7915
K.Takata6e1d31e2022-02-03 13:05:32 +00007916# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007917 if ((*p-- = "0123456789"[(n = x % 10)]) \
7918 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
7919 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
7920
K.Takata6e1d31e2022-02-03 13:05:32 +00007921# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007922 case x: \
7923 FAST256(newargs[x - 1]);
7924
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007925 static void
7926vtp_sgr_bulks(
7927 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007928 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007929{
K.Takata6e1d31e2022-02-03 13:05:32 +00007930# define MAXSGR 16
7931# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007932 char_u buf[SGRBUFSIZE];
7933 char_u *p;
7934 int in, out;
7935 int newargs[16];
7936 static int sgrfgr = -1, sgrfgg, sgrfgb;
7937 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007938
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007939 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007940 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007941 sgrfgr = sgrbgr = -1;
7942 vtp_printf("033[m");
7943 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007944 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007945
7946 in = out = 0;
7947 while (in < argc)
7948 {
7949 int s = args[in];
7950 int copylen = 1;
7951
7952 if (s == 38)
7953 {
7954 if (argc - in >= 5 && args[in + 1] == 2)
7955 {
7956 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
7957 && sgrfgb == args[in + 4])
7958 {
7959 in += 5;
7960 copylen = 0;
7961 }
7962 else
7963 {
7964 sgrfgr = args[in + 2];
7965 sgrfgg = args[in + 3];
7966 sgrfgb = args[in + 4];
7967 copylen = 5;
7968 }
7969 }
7970 else if (argc - in >= 3 && args[in + 1] == 5)
7971 {
7972 sgrfgr = -1;
7973 copylen = 3;
7974 }
7975 }
7976 else if (s == 48)
7977 {
7978 if (argc - in >= 5 && args[in + 1] == 2)
7979 {
7980 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
7981 && sgrbgb == args[in + 4])
7982 {
7983 in += 5;
7984 copylen = 0;
7985 }
7986 else
7987 {
7988 sgrbgr = args[in + 2];
7989 sgrbgg = args[in + 3];
7990 sgrbgb = args[in + 4];
7991 copylen = 5;
7992 }
7993 }
7994 else if (argc - in >= 3 && args[in + 1] == 5)
7995 {
7996 sgrbgr = -1;
7997 copylen = 3;
7998 }
7999 }
8000 else if (30 <= s && s <= 39)
8001 sgrfgr = -1;
8002 else if (90 <= s && s <= 97)
8003 sgrfgr = -1;
8004 else if (40 <= s && s <= 49)
8005 sgrbgr = -1;
8006 else if (100 <= s && s <= 107)
8007 sgrbgr = -1;
8008 else if (s == 0)
8009 sgrfgr = sgrbgr = -1;
8010
8011 while (copylen--)
8012 newargs[out++] = args[in++];
8013 }
8014
8015 p = &buf[sizeof(buf) - 1];
8016 *p-- = 'm';
8017
8018 switch (out)
8019 {
8020 int n, m;
8021 DWORD r;
8022
8023 FAST256CASE(16);
8024 *p-- = ';';
8025 FAST256CASE(15);
8026 *p-- = ';';
8027 FAST256CASE(14);
8028 *p-- = ';';
8029 FAST256CASE(13);
8030 *p-- = ';';
8031 FAST256CASE(12);
8032 *p-- = ';';
8033 FAST256CASE(11);
8034 *p-- = ';';
8035 FAST256CASE(10);
8036 *p-- = ';';
8037 FAST256CASE(9);
8038 *p-- = ';';
8039 FAST256CASE(8);
8040 *p-- = ';';
8041 FAST256CASE(7);
8042 *p-- = ';';
8043 FAST256CASE(6);
8044 *p-- = ';';
8045 FAST256CASE(5);
8046 *p-- = ';';
8047 FAST256CASE(4);
8048 *p-- = ';';
8049 FAST256CASE(3);
8050 *p-- = ';';
8051 FAST256CASE(2);
8052 *p-- = ';';
8053 FAST256CASE(1);
8054 *p-- = '[';
8055 *p = '\033';
8056 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8057 default:
8058 break;
8059 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008060}
8061
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008062 static void
8063wt_init(void)
8064{
8065 wt_working = (mch_getenv("WT_SESSION") != NULL);
8066}
8067
8068 int
8069use_wt(void)
8070{
8071 return USE_WT;
8072}
8073
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008074# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008075 static int
8076ctermtoxterm(
8077 int cterm)
8078{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008079 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008080
8081 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8082 return (((int)r << 16) | ((int)g << 8) | (int)b);
8083}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008084# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008085
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008086 static void
8087set_console_color_rgb(void)
8088{
8089# ifdef FEAT_TERMGUICOLORS
8090 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008091 guicolor_T fg, bg;
8092 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008093
8094 if (!USE_VTP)
8095 return;
8096
Bram Moolenaara050b942019-12-02 21:35:31 +01008097 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8098
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008099 if (USE_WT)
8100 {
8101 term_fg_rgb_color(fg);
8102 term_bg_rgb_color(bg);
8103 return;
8104 }
8105
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008106 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8107 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8108
8109 csbi.cbSize = sizeof(csbi);
8110 if (has_csbiex)
8111 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8112
8113 csbi.cbSize = sizeof(csbi);
8114 csbi.srWindow.Right += 1;
8115 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008116 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8117 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008118 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8119 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008120 if (has_csbiex)
8121 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8122# endif
8123}
8124
Bram Moolenaara050b942019-12-02 21:35:31 +01008125# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8126 void
8127get_default_console_color(
8128 int *cterm_fg,
8129 int *cterm_bg,
8130 guicolor_T *gui_fg,
8131 guicolor_T *gui_bg)
8132{
8133 int id;
8134 guicolor_T guifg = INVALCOLOR;
8135 guicolor_T guibg = INVALCOLOR;
8136 int ctermfg = 0;
8137 int ctermbg = 0;
8138
8139 id = syn_name2id((char_u *)"Normal");
8140 if (id > 0 && p_tgc)
8141 syn_id2colors(id, &guifg, &guibg);
8142 if (guifg == INVALCOLOR)
8143 {
8144 ctermfg = -1;
8145 if (id > 0)
8146 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8147 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
8148 : default_console_color_fg;
8149 cterm_normal_fg_gui_color = guifg;
8150 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8151 }
8152 if (guibg == INVALCOLOR)
8153 {
8154 ctermbg = -1;
8155 if (id > 0)
8156 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01008157 cterm_normal_bg_gui_color = guibg =
8158 ctermbg != -1 ? ctermtoxterm(ctermbg) : INVALCOLOR;
8159
8160 if (ctermbg < 0)
8161 ctermbg = 0;
Bram Moolenaara050b942019-12-02 21:35:31 +01008162 }
8163
8164 *cterm_fg = ctermfg;
8165 *cterm_bg = ctermbg;
8166 *gui_fg = guifg;
8167 *gui_bg = guibg;
8168}
8169# endif
8170
Bram Moolenaardf543822020-01-30 11:53:59 +01008171/*
8172 * Set the console colors to the original colors or the last set colors.
8173 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008174 static void
8175reset_console_color_rgb(void)
8176{
8177# ifdef FEAT_TERMGUICOLORS
8178 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8179
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008180 if (USE_WT)
8181 return;
8182
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008183 csbi.cbSize = sizeof(csbi);
8184 if (has_csbiex)
8185 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8186
8187 csbi.cbSize = sizeof(csbi);
8188 csbi.srWindow.Right += 1;
8189 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008190 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8191 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
8192 if (has_csbiex)
8193 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8194# endif
8195}
8196
8197/*
8198 * Set the console colors to the original colors.
8199 */
8200 static void
8201restore_console_color_rgb(void)
8202{
8203# ifdef FEAT_TERMGUICOLORS
8204 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8205
8206 csbi.cbSize = sizeof(csbi);
8207 if (has_csbiex)
8208 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8209
8210 csbi.cbSize = sizeof(csbi);
8211 csbi.srWindow.Right += 1;
8212 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008213 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8214 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008215 if (has_csbiex)
8216 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8217# endif
8218}
8219
8220 void
8221control_console_color_rgb(void)
8222{
8223 if (USE_VTP)
8224 set_console_color_rgb();
8225 else
8226 reset_console_color_rgb();
8227}
8228
8229 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008230use_vtp(void)
8231{
8232 return USE_VTP;
8233}
8234
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008235 int
8236is_term_win32(void)
8237{
8238 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8239}
8240
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008241 int
8242has_vtp_working(void)
8243{
8244 return vtp_working;
8245}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008246
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008247#endif
8248
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008249 int
8250has_conpty_working(void)
8251{
8252 return conpty_working;
8253}
8254
8255 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008256get_conpty_type(void)
8257{
8258 return conpty_type;
8259}
8260
8261 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008262is_conpty_stable(void)
8263{
8264 return conpty_stable;
8265}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008266
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008267 int
8268get_conpty_fix_type(void)
8269{
8270 return conpty_fix_type;
8271}
8272
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008273#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008274 void
8275resize_console_buf(void)
8276{
8277 CONSOLE_SCREEN_BUFFER_INFO csbi;
8278 COORD coord;
8279 SMALL_RECT newsize;
8280
8281 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8282 {
8283 coord.X = SRWIDTH(csbi.srWindow);
8284 coord.Y = SRHEIGHT(csbi.srWindow);
8285 SetConsoleScreenBufferSize(g_hConOut, coord);
8286
8287 newsize.Left = 0;
8288 newsize.Top = 0;
8289 newsize.Right = coord.X - 1;
8290 newsize.Bottom = coord.Y - 1;
8291 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8292
8293 SetConsoleScreenBufferSize(g_hConOut, coord);
8294 }
8295}
8296#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008297
8298 char *
8299GetWin32Error(void)
8300{
K.Takatad68b2fc2022-02-12 11:18:37 +00008301 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008302 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008303
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008304 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8305 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008306 if (oldmsg != NULL)
8307 LocalFree(oldmsg);
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008308 if (msg != NULL)
8309 {
8310 // remove trailing \r\n
8311 char *pcrlf = strstr(msg, "\r\n");
8312 if (pcrlf != NULL)
8313 *pcrlf = '\0';
K.Takatad68b2fc2022-02-12 11:18:37 +00008314 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008315 }
8316 return msg;
8317}