blob: 2a9d1cf57fd794d24981bd898eebe9250ceb1634 [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
12 * Used for both the console version and the Win32 GUI. A lot of code is for
Bram Moolenaar4f974752019-02-17 17:44:42 +010013 * the console version only, so there is a lot of "#ifndef FEAT_GUI_MSWIN".
Bram Moolenaar071d4272004-06-13 20:20:40 +000014 *
15 * Win32 (Windows NT and Windows 95) system-dependent routines.
16 * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17 * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18 *
19 * George V. Reilly <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
Bram Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010032
Bram Moolenaar0f873732019-12-05 20:28:46 +010033// cproto fails on missing include files
Bram Moolenaar82881492012-11-20 16:53:39 +010034#ifndef PROTO
35# include <process.h>
Bram Moolenaare7bebc42021-02-01 20:50:37 +010036# include <winternl.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010037#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000038
39#undef chdir
40#ifdef __GNUC__
41# ifndef __MINGW32__
42# include <dirent.h>
43# endif
44#else
45# include <direct.h>
46#endif
47
Bram Moolenaar82881492012-11-20 16:53:39 +010048#ifndef PROTO
Bram Moolenaar651fca82021-11-29 20:39:38 +000049# if !defined(FEAT_GUI_MSWIN)
Bram Moolenaar82881492012-11-20 16:53:39 +010050# include <shellapi.h>
51# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000052#endif
53
Bram Moolenaarfb630902016-10-29 14:55:00 +020054#ifdef FEAT_JOB_CHANNEL
55# include <tlhelp32.h>
56#endif
57
Bram Moolenaar071d4272004-06-13 20:20:40 +000058#ifdef __MINGW32__
59# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
60# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
61# endif
62# ifndef RIGHTMOST_BUTTON_PRESSED
63# define RIGHTMOST_BUTTON_PRESSED 0x0002
64# endif
65# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
66# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
67# endif
68# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
69# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
70# endif
71# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
72# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
73# endif
74
75/*
76 * EventFlags
77 */
78# ifndef MOUSE_MOVED
79# define MOUSE_MOVED 0x0001
80# endif
81# ifndef DOUBLE_CLICK
82# define DOUBLE_CLICK 0x0002
83# endif
84#endif
85
Bram Moolenaar0f873732019-12-05 20:28:46 +010086// Record all output and all keyboard & mouse input
87// #define MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +000088
89#ifdef MCH_WRITE_DUMP
90FILE* fdDump = NULL;
91#endif
92
93/*
94 * When generating prototypes for Win32 on Unix, these lines make the syntax
95 * errors disappear. They do not need to be correct.
96 */
97#ifdef PROTO
Bram Moolenaar912bc4a2019-12-01 18:58:11 +010098# define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000099typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000100typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000101typedef int ACCESS_MASK;
102typedef int BOOL;
Paul Ollis65745772022-06-05 16:55:54 +0100103typedef int BOOLEAN;
104typedef int CALLBACK;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000105typedef int COLORREF;
106typedef int CONSOLE_CURSOR_INFO;
107typedef int COORD;
108typedef int DWORD;
109typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100110typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000111typedef int HDC;
112typedef int HFONT;
113typedef int HICON;
114typedef int HINSTANCE;
115typedef int HWND;
116typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200117typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000118typedef int KEY_EVENT_RECORD;
119typedef int LOGFONT;
120typedef int LPBOOL;
121typedef int LPCTSTR;
122typedef int LPDWORD;
123typedef int LPSTR;
124typedef int LPTSTR;
125typedef int LPVOID;
126typedef int MOUSE_EVENT_RECORD;
127typedef int PACL;
128typedef int PDWORD;
129typedef int PHANDLE;
130typedef int PRINTDLG;
131typedef int PSECURITY_DESCRIPTOR;
132typedef int PSID;
133typedef int SECURITY_INFORMATION;
134typedef int SHORT;
135typedef int SMALL_RECT;
136typedef int TEXTMETRIC;
137typedef int TOKEN_INFORMATION_CLASS;
138typedef int TRUSTEE;
139typedef int WORD;
140typedef int WCHAR;
141typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100142typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200143typedef int SE_OBJECT_TYPE;
144typedef int PSNSECINFO;
145typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100146typedef int STARTUPINFO;
147typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200148typedef int LPSECURITY_ATTRIBUTES;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100149# define __stdcall // empty
Bram Moolenaar071d4272004-06-13 20:20:40 +0000150#endif
151
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200152#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100153// Win32 Console handles for input and output
Bram Moolenaar071d4272004-06-13 20:20:40 +0000154static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
155static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
156
Bram Moolenaar0f873732019-12-05 20:28:46 +0100157// Win32 Screen buffer,coordinate,console I/O information
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158static SMALL_RECT g_srScrollRegion;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100159static COORD g_coord; // 0-based, but external coords are 1-based
Bram Moolenaar071d4272004-06-13 20:20:40 +0000160
Bram Moolenaar0f873732019-12-05 20:28:46 +0100161// The attribute of the screen when the editor was started
162static WORD g_attrDefault = 7; // lightgray text on black background
Bram Moolenaar071d4272004-06-13 20:20:40 +0000163static WORD g_attrCurrent;
164
Bram Moolenaar0f873732019-12-05 20:28:46 +0100165static int g_fCBrkPressed = FALSE; // set by ctrl-break interrupt
166static int g_fCtrlCPressed = FALSE; // set when ctrl-C or ctrl-break detected
167static int g_fForceExit = FALSE; // set when forcefully exiting
Bram Moolenaar071d4272004-06-13 20:20:40 +0000168
Bram Moolenaar071d4272004-06-13 20:20:40 +0000169static void scroll(unsigned cLines);
170static void set_scroll_region(unsigned left, unsigned top,
171 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100172static void set_scroll_region_tb(unsigned top, unsigned bottom);
173static void set_scroll_region_lr(unsigned left, unsigned right);
174static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000175static void delete_lines(unsigned cLines);
176static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000177static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000178static int s_cursor_visible = TRUE;
179static int did_create_conin = FALSE;
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200180#endif
181#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000182static int s_dont_use_vimrun = TRUE;
183static int need_vimrun_warning = FALSE;
184static char *vimrun_path = "vimrun ";
185#endif
186
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200187static int win32_getattrs(char_u *name);
188static int win32_setattrs(char_u *name, int attrs);
189static int win32_set_archive(char_u *name);
190
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100191static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200192static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100193static int conpty_stable = 0;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +0200194static int conpty_fix_type = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100195static void vtp_flag_init();
196
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200197#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100198static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100199static void vtp_init();
200static void vtp_exit();
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100201static void vtp_sgr_bulk(int arg);
202static void vtp_sgr_bulks(int argc, int *argv);
203
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200204static int wt_working = 0;
205static void wt_init();
206
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100207static guicolor_T save_console_bg_rgb;
208static guicolor_T save_console_fg_rgb;
Bram Moolenaardf543822020-01-30 11:53:59 +0100209static guicolor_T store_console_bg_rgb;
210static guicolor_T store_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100211
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200212static int g_color_index_bg = 0;
213static int g_color_index_fg = 7;
214
215# ifdef FEAT_TERMGUICOLORS
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +0100216static int default_console_color_bg = 0x000000; // black
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200217static int default_console_color_fg = 0xc0c0c0; // white
218# endif
219
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100220# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200221# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200222# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100223# else
224# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200225# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100226# endif
227
228static void set_console_color_rgb(void);
229static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100230static void restore_console_color_rgb(void);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100231#endif
232
Bram Moolenaar0f873732019-12-05 20:28:46 +0100233// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100234#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
235# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
236#endif
237
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200238#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100239static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000240#endif
241
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200242static char_u *exe_path = NULL;
243
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100244static BOOL win8_or_later = FALSE;
245
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100246/*
247 * Get version number including build number
248 */
249typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100250#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100251 (((major) << 24) | ((minor) << 16) | (build))
252
253 static DWORD
254get_build_number(void)
255{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100256 OSVERSIONINFOW osver;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100257 HMODULE hNtdll;
258 PfnRtlGetVersion pRtlGetVersion;
259 DWORD ver = MAKE_VER(0, 0, 0);
260
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100261 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100262 hNtdll = GetModuleHandle("ntdll.dll");
263 if (hNtdll != NULL)
264 {
265 pRtlGetVersion =
266 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
267 pRtlGetVersion(&osver);
268 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
269 min(osver.dwMinorVersion, 255),
270 min(osver.dwBuildNumber, 32767));
271 }
272 return ver;
273}
274
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200275#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200276 static BOOL
277is_ambiwidth_event(
278 INPUT_RECORD *ir)
279{
280 return ir->EventType == KEY_EVENT
281 && ir->Event.KeyEvent.bKeyDown
282 && ir->Event.KeyEvent.wRepeatCount == 1
283 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
284 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000285 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200286 && ir->Event.KeyEvent.dwControlKeyState == 2;
287}
288
289 static void
290make_ambiwidth_event(
291 INPUT_RECORD *down,
292 INPUT_RECORD *up)
293{
294 down->Event.KeyEvent.wVirtualKeyCode = 0;
295 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000296 down->Event.KeyEvent.uChar.UnicodeChar
297 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200298 down->Event.KeyEvent.dwControlKeyState = 0;
299}
300
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100301/*
302 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100303 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100304 */
305 static BOOL
306read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100307 HANDLE hInput,
308 INPUT_RECORD *lpBuffer,
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100309 int nLength,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100310 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100311{
312 enum
313 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100314 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100315 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100316 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100317 static DWORD s_dwIndex = 0;
318 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100319 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100320 int head;
321 int tail;
322 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200323 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100324
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200325 if (nLength == -2)
326 return (s_dwMax > 0) ? TRUE : FALSE;
327
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100328 if (!win8_or_later)
329 {
330 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200331 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
332 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100333 }
334
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100335 if (s_dwMax == 0)
336 {
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200337 if (!USE_WT && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200338 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200339 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
340 if (dwEvents == 0 && nLength == -1)
341 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
342 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100343 s_dwIndex = 0;
344 s_dwMax = dwEvents;
345 if (dwEvents == 0)
346 {
347 *lpEvents = 0;
348 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100349 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100350
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200351 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
352 if (is_ambiwidth_event(&s_irCache[i]))
353 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
354
Bram Moolenaardd415a62014-02-05 14:02:27 +0100355 if (s_dwMax > 1)
356 {
357 head = 0;
358 tail = s_dwMax - 1;
359 while (head != tail)
360 {
361 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
362 && s_irCache[head + 1].EventType
363 == WINDOW_BUFFER_SIZE_EVENT)
364 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100365 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100366 for (i = head; i < tail; ++i)
367 s_irCache[i] = s_irCache[i + 1];
368 --tail;
369 continue;
370 }
371 head++;
372 }
373 s_dwMax = tail + 1;
374 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100375 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100376
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200377 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
378 {
379 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
380 {
381 s_irPseudo = s_irCache[s_dwIndex];
382 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
383 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
384 *lpBuffer = s_irPseudo;
385 *lpEvents = 1;
386 return TRUE;
387 }
388 }
389
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100390 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200391 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100392 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100393 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100394 return TRUE;
395}
396
397/*
398 * Version of PeekConsoleInput() that works with IME.
399 */
400 static BOOL
401peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100402 HANDLE hInput,
403 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200404 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100405 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100406{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100407 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100408}
409
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100410# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200411 static DWORD
412msg_wait_for_multiple_objects(
413 DWORD nCount,
414 LPHANDLE pHandles,
415 BOOL fWaitAll,
416 DWORD dwMilliseconds,
417 DWORD dwWakeMask)
418{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100419 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200420 return WAIT_OBJECT_0;
421 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
422 dwMilliseconds, dwWakeMask);
423}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100424# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200425
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100426# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200427 static DWORD
428wait_for_single_object(
429 HANDLE hHandle,
430 DWORD dwMilliseconds)
431{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100432 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200433 return WAIT_OBJECT_0;
434 return WaitForSingleObject(hHandle, dwMilliseconds);
435}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100436# endif
437#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200438
Bram Moolenaar071d4272004-06-13 20:20:40 +0000439 static void
440get_exe_name(void)
441{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100442 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
443 // as the maximum length that works (plus a NUL byte).
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100444#define MAX_ENV_PATH_LEN 8192
445 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200446 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000447
448 if (exe_name == NULL)
449 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100450 // store the name of the executable, may be used for $VIM
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100451 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000452 if (*temp != NUL)
453 exe_name = FullName_save((char_u *)temp, FALSE);
454 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000455
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200456 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000457 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200458 exe_path = vim_strnsave(exe_name, gettail_sep(exe_name) - exe_name);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200459 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000460 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100461 // Append our starting directory to $PATH, so that when doing
462 // "!xxd" it's found in our starting directory. Needed because
463 // SearchPath() also looks there.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200464 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100465 if (p == NULL
466 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200467 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100468 if (p == NULL || *p == NUL)
469 temp[0] = NUL;
470 else
471 {
472 STRCPY(temp, p);
473 STRCAT(temp, ";");
474 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200475 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100476 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200477 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000478 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000479 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000480}
481
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200482/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100483 * Unescape characters in "p" that appear in "escaped".
484 */
485 static void
486unescape_shellxquote(char_u *p, char_u *escaped)
487{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100488 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100489 int n;
490
491 while (*p != NUL)
492 {
493 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
494 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100495 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100496 p += n;
497 l -= n;
498 }
499}
500
501/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200502 * Load library "name".
503 */
504 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000505vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200506{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200507 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200508
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200509 // No need to load any library when registering OLE.
510 if (found_register_arg)
511 return dll;
512
Bram Moolenaar0f873732019-12-05 20:28:46 +0100513 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
514 // vimLoadLib() recursively, which causes a stack overflow.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200515 if (exe_path == NULL)
516 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200517 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200518 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200519 WCHAR old_dirw[MAXPATHL];
520
521 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
522 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100523 // Change directory to where the executable is, both to make
524 // sure we find a .dll there and to avoid looking for a .dll
525 // in the current directory.
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100526 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200527 dll = LoadLibrary(name);
528 SetCurrentDirectoryW(old_dirw);
529 return dll;
530 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200531 }
532 return dll;
533}
534
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200535#if defined(VIMDLL) || defined(PROTO)
536/*
537 * Check if the current executable file is for the GUI subsystem.
538 */
539 int
540mch_is_gui_executable(void)
541{
542 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
543 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
544 PIMAGE_NT_HEADERS pPE;
545
546 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
547 return FALSE;
548 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
549 if (pPE->Signature != IMAGE_NT_SIGNATURE)
550 return FALSE;
551 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
552 return TRUE;
553 return FALSE;
554}
555#endif
556
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000557#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
558 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100559/*
560 * Get related information about 'funcname' which is imported by 'hInst'.
561 * If 'info' is 0, return the function address.
562 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000563 * If 'info' is 2, hook the function with 'ptr', and return the original
564 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100565 */
566 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000567get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
568 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100569{
570 PBYTE pImage = (PBYTE)hInst;
571 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
572 PIMAGE_NT_HEADERS pPE;
573 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100574 PIMAGE_THUNK_DATA pIAT; // Import Address Table
575 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100576 PIMAGE_IMPORT_BY_NAME pImpName;
577
578 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
579 return NULL;
580 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
581 if (pPE->Signature != IMAGE_NT_SIGNATURE)
582 return NULL;
583 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
584 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
585 .VirtualAddress);
586 for (; pImpDesc->FirstThunk; ++pImpDesc)
587 {
588 if (!pImpDesc->OriginalFirstThunk)
589 continue;
590 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
591 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
592 for (; pIAT->u1.Function; ++pIAT, ++pINT)
593 {
594 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
595 continue;
596 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
597 + (UINT_PTR)(pINT->u1.AddressOfData));
598 if (strcmp((char *)pImpName->Name, funcname) == 0)
599 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000600 void *original;
601 DWORD old, new = PAGE_READWRITE;
602
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100603 switch (info)
604 {
605 case 0:
606 return (void *)pIAT->u1.Function;
607 case 1:
608 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000609 case 2:
610 original = (void *)pIAT->u1.Function;
611 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
612 new, &old);
613 pIAT->u1.Function = (UINT_PTR)ptr;
614 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
615 old, &new);
616 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100617 default:
618 return NULL;
619 }
620 }
621 }
622 }
623 return NULL;
624}
625
626/*
627 * Get the module handle which 'funcname' in 'hInst' is imported from.
628 */
629 HINSTANCE
630find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
631{
632 char *modulename;
633
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000634 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100635 if (modulename != NULL)
636 return GetModuleHandleA(modulename);
637 return NULL;
638}
639
640/*
641 * Get the address of 'funcname' which is imported by 'hInst' DLL.
642 */
643 void *
644get_dll_import_func(HINSTANCE hInst, const char *funcname)
645{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000646 return get_imported_func_info(hInst, funcname, 0, NULL);
647}
648
649/*
650 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
651 * and return the original function address.
652 */
653 void *
654hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
655{
656 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100657}
658#endif
659
Bram Moolenaar071d4272004-06-13 20:20:40 +0000660#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
661# ifndef GETTEXT_DLL
662# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200663# define GETTEXT_DLL_ALT1 "libintl-8.dll"
664# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000665# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100666// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000667static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200668static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000669static char *null_libintl_textdomain(const char *);
670static char *null_libintl_bindtextdomain(const char *, const char *);
671static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100672static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000673
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200674static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000675char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200676char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
677 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000678char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
679char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000680 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000681char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
682 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100683int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000684
685 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100686dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000687{
688 int i;
689 static struct
690 {
691 char *name;
692 FARPROC *ptr;
693 } libintl_entry[] =
694 {
695 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200696 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000697 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
698 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
699 {NULL, NULL}
700 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100701 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000702
Bram Moolenaar7554c542018-10-06 15:03:15 +0200703 // No need to initialize twice.
704 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000705 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200706 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100707 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100708# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100709 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200710 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100711# endif
712# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200713 if (!hLibintlDLL)
714 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100715# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100716 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000717 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200718 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000719 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200720 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000721 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200722 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000723 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200724 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000725 }
726 for (i = 0; libintl_entry[i].name != NULL
727 && libintl_entry[i].ptr != NULL; ++i)
728 {
K.Takata54119102022-02-03 13:33:03 +0000729 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000730 libintl_entry[i].name)) == NULL)
731 {
732 dyn_libintl_end();
733 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000734 {
735 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000736 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000737 verbose_leave();
738 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000739 return 0;
740 }
741 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000742
Bram Moolenaar0f873732019-12-05 20:28:46 +0100743 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100744 dyn_libintl_bind_textdomain_codeset = (char *(*)(const char *, const char *))
745 GetProcAddress(hLibintlDLL, "bind_textdomain_codeset");
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000746 if (dyn_libintl_bind_textdomain_codeset == NULL)
747 dyn_libintl_bind_textdomain_codeset =
748 null_libintl_bind_textdomain_codeset;
749
Bram Moolenaar0f873732019-12-05 20:28:46 +0100750 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100751 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
752 if (hmsvcrt != NULL)
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100753 dyn_libintl_wputenv = (int (*)(const wchar_t *))
754 GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100755 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
756 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100757
Bram Moolenaar071d4272004-06-13 20:20:40 +0000758 return 1;
759}
760
761 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100762dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000763{
764 if (hLibintlDLL)
765 FreeLibrary(hLibintlDLL);
766 hLibintlDLL = NULL;
767 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200768 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000769 dyn_libintl_textdomain = null_libintl_textdomain;
770 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000771 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100772 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000773}
774
775 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000776null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000777{
778 return (char*)msgid;
779}
780
781 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200782null_libintl_ngettext(
783 const char *msgid,
784 const char *msgid_plural,
785 unsigned long n)
786{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200787 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200788}
789
Bram Moolenaaree695f72016-08-03 22:08:45 +0200790 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100791null_libintl_bindtextdomain(
792 const char *domainname UNUSED,
793 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000794{
795 return NULL;
796}
797
798 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100799null_libintl_bind_textdomain_codeset(
800 const char *domainname UNUSED,
801 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000802{
803 return NULL;
804}
805
806 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100807null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000808{
809 return NULL;
810}
811
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200812 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100813null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100814{
815 return 0;
816}
817
Bram Moolenaar0f873732019-12-05 20:28:46 +0100818#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000819
Bram Moolenaar0f873732019-12-05 20:28:46 +0100820// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000821
822#ifndef VER_PLATFORM_WIN32_WINDOWS
823# define VER_PLATFORM_WIN32_WINDOWS 1
824#endif
825
Bram Moolenaar071d4272004-06-13 20:20:40 +0000826#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100827# ifndef PROTO
828# include <aclapi.h>
829# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200830# ifndef PROTECTED_DACL_SECURITY_INFORMATION
831# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
832# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000833#endif
834
Bram Moolenaar27515922013-06-29 15:36:26 +0200835#ifdef HAVE_ACL
836/*
837 * Enables or disables the specified privilege.
838 */
839 static BOOL
840win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
841{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100842 BOOL bResult;
843 LUID luid;
844 HANDLE hToken;
845 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200846
847 if (!OpenProcessToken(GetCurrentProcess(),
848 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
849 return FALSE;
850
851 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
852 {
853 CloseHandle(hToken);
854 return FALSE;
855 }
856
Bram Moolenaar45500912014-07-09 20:51:07 +0200857 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200858 tokenPrivileges.Privileges[0].Luid = luid;
859 tokenPrivileges.Privileges[0].Attributes = bEnable ?
860 SE_PRIVILEGE_ENABLED : 0;
861
862 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
863 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
864
865 CloseHandle(hToken);
866
867 return bResult && GetLastError() == ERROR_SUCCESS;
868}
869#endif
870
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100871#ifdef _MSC_VER
872// Suppress the deprecation warning for using GetVersionEx().
873// It is needed for implementing "windowsversion()".
874# pragma warning(push)
875# pragma warning(disable: 4996)
876#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000877/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200878 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000879 */
880 void
881PlatformId(void)
882{
883 static int done = FALSE;
884
885 if (!done)
886 {
887 OSVERSIONINFO ovi;
888
889 ovi.dwOSVersionInfoSize = sizeof(ovi);
890 GetVersionEx(&ovi);
891
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200892#ifdef FEAT_EVAL
Bram Moolenaar0c1e3742019-12-27 13:49:24 +0100893 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
894 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200895#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100896 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
897 || ovi.dwMajorVersion > 6)
898 win8_or_later = TRUE;
899
Bram Moolenaar071d4272004-06-13 20:20:40 +0000900#ifdef HAVE_ACL
Bram Moolenaar0f873732019-12-05 20:28:46 +0100901 // Enable privilege for getting or setting SACLs.
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200902 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000903#endif
904 done = TRUE;
905 }
906}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100907#ifdef _MSC_VER
908# pragma warning(pop)
909#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000910
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200911#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000912
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100913# define SHIFT (SHIFT_PRESSED)
914# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
915# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
916# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000917
918
Bram Moolenaar0f873732019-12-05 20:28:46 +0100919// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
920// We map function keys to their ANSI terminal equivalents, as produced
921// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
922// ANSI key with a value >= '\300' is nonstandard, but provided anyway
923// so that the user can have access to all SHIFT-, CTRL-, and ALT-
924// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000925
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000926static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000927{
928 WORD wVirtKey;
929 BOOL fAnsiKey;
930 int chAlone;
931 int chShift;
932 int chCtrl;
933 int chAlt;
934} VirtKeyMap[] =
935{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200936// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000937 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
938
939 { VK_F1, TRUE, ';', 'T', '^', 'h', },
940 { VK_F2, TRUE, '<', 'U', '_', 'i', },
941 { VK_F3, TRUE, '=', 'V', '`', 'j', },
942 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
943 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
944 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
945 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
946 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
947 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
948 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200949 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
950 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000951
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200952 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
953 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
954 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
955 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
956 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
957 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
958 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
959 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
960 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
961 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100962 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000963
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200964 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000965
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100966# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200967 // Most people don't have F13-F20, but what the hell...
968 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
969 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
970 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
971 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
972 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
973 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
974 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
975 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100976# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200977 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
978 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
979 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
980 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000981
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200982 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
983 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
984 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
985 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
986 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
987 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
988 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
989 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
990 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
991 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100992 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000993};
994
995
Bram Moolenaar0f873732019-12-05 20:28:46 +0100996/*
997 * The return code indicates key code size.
998 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000999 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001000win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001001 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001002{
1003 UINT uMods = pker->dwControlKeyState;
1004 static int s_iIsDead = 0;
1005 static WORD awAnsiCode[2];
1006 static BYTE abKeystate[256];
1007
1008
1009 if (s_iIsDead == 2)
1010 {
K.Takata972db232022-02-04 10:45:38 +00001011 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001012 s_iIsDead = 0;
1013 return 1;
1014 }
1015
K.Takata972db232022-02-04 10:45:38 +00001016 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001017 return 1;
1018
Bram Moolenaara80faa82020-04-12 19:37:17 +02001019 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001020
Bram Moolenaar0f873732019-12-05 20:28:46 +01001021 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001022 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001023
1024 if (uMods & SHIFT_PRESSED)
1025 abKeystate[VK_SHIFT] = 0x80;
1026 if (uMods & CAPSLOCK_ON)
1027 abKeystate[VK_CAPITAL] = 1;
1028
1029 if ((uMods & ALT_GR) == ALT_GR)
1030 {
1031 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1032 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1033 }
1034
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001035 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1036 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001037
1038 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001039 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001040
1041 return s_iIsDead;
1042}
1043
Bram Moolenaar071d4272004-06-13 20:20:40 +00001044static BOOL g_fJustGotFocus = FALSE;
1045
1046/*
1047 * Decode a KEY_EVENT into one or two keystrokes
1048 */
1049 static BOOL
1050decode_key_event(
1051 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001052 WCHAR *pch,
1053 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001054 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001055 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001056{
1057 int i;
1058 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1059
1060 *pch = *pch2 = NUL;
1061 g_fJustGotFocus = FALSE;
1062
Bram Moolenaar0f873732019-12-05 20:28:46 +01001063 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001064 if (!pker->bKeyDown)
1065 return FALSE;
1066
Bram Moolenaar0f873732019-12-05 20:28:46 +01001067 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001068 switch (pker->wVirtualKeyCode)
1069 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001070 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001071 case VK_SHIFT:
1072 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001073 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001074 return FALSE;
1075
1076 default:
1077 break;
1078 }
1079
Bram Moolenaar0f873732019-12-05 20:28:46 +01001080 // special cases
K.Takata972db232022-02-04 10:45:38 +00001081 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0
1082 && pker->uChar.UnicodeChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001083 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001084 // Ctrl-6 is Ctrl-^
Bram Moolenaar071d4272004-06-13 20:20:40 +00001085 if (pker->wVirtualKeyCode == '6')
1086 {
1087 *pch = Ctrl_HAT;
1088 return TRUE;
1089 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001090 // Ctrl-2 is Ctrl-@
Bram Moolenaar071d4272004-06-13 20:20:40 +00001091 else if (pker->wVirtualKeyCode == '2')
1092 {
1093 *pch = NUL;
1094 return TRUE;
1095 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001096 // Ctrl-- is Ctrl-_
Bram Moolenaar071d4272004-06-13 20:20:40 +00001097 else if (pker->wVirtualKeyCode == 0xBD)
1098 {
1099 *pch = Ctrl__;
1100 return TRUE;
1101 }
1102 }
1103
Bram Moolenaar0f873732019-12-05 20:28:46 +01001104 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001105 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1106 {
1107 *pch = K_NUL;
1108 *pch2 = '\017';
1109 return TRUE;
1110 }
1111
K.Takataeeec2542021-06-02 13:28:16 +02001112 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001113 {
1114 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1115 {
1116 if (nModifs == 0)
1117 *pch = VirtKeyMap[i].chAlone;
1118 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1119 *pch = VirtKeyMap[i].chShift;
1120 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1121 *pch = VirtKeyMap[i].chCtrl;
1122 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1123 *pch = VirtKeyMap[i].chAlt;
1124
1125 if (*pch != 0)
1126 {
1127 if (VirtKeyMap[i].fAnsiKey)
1128 {
1129 *pch2 = *pch;
1130 *pch = K_NUL;
1131 }
1132
1133 return TRUE;
1134 }
1135 }
1136 }
1137
1138 i = win32_kbd_patch_key(pker);
1139
1140 if (i < 0)
1141 *pch = NUL;
1142 else
1143 {
K.Takata972db232022-02-04 10:45:38 +00001144 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001145
1146 if (pmodifiers != NULL)
1147 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001148 // Pass on the ALT key as a modifier, but only when not combined
1149 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001150 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1151 *pmodifiers |= MOD_MASK_ALT;
1152
Bram Moolenaar0f873732019-12-05 20:28:46 +01001153 // Pass on SHIFT only for special keys, because we don't know when
1154 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001155 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1156 *pmodifiers |= MOD_MASK_SHIFT;
1157
Bram Moolenaar0f873732019-12-05 20:28:46 +01001158 // Pass on CTRL only for non-special keys, because we don't know
1159 // when it's already included with the character. And not when
1160 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001161 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1162 && *pch >= 0x20 && *pch < 0x80)
1163 *pmodifiers |= MOD_MASK_CTRL;
1164 }
1165 }
1166
1167 return (*pch != NUL);
1168}
1169
Bram Moolenaar0f873732019-12-05 20:28:46 +01001170#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001171
1172
Bram Moolenaar071d4272004-06-13 20:20:40 +00001173/*
1174 * For the GUI the mouse handling is in gui_w32.c.
1175 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001176#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001177 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001178mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001179{
1180}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001181#else
Bram Moolenaar0f873732019-12-05 20:28:46 +01001182static int g_fMouseAvail = FALSE; // mouse present
1183static int g_fMouseActive = FALSE; // mouse enabled
1184static int g_nMouseClick = -1; // mouse status
1185static int g_xMouse; // mouse x coordinate
1186static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001187static DWORD g_cmodein = 0; // Original console input mode
1188static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001189
1190/*
1191 * Enable or disable mouse input
1192 */
1193 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001194mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001195{
1196 DWORD cmodein;
1197
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001198# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001199 if (gui.in_use)
1200 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001201# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001202 if (!g_fMouseAvail)
1203 return;
1204
1205 g_fMouseActive = on;
1206 GetConsoleMode(g_hConIn, &cmodein);
1207
1208 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001209 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001210 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001211 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1212 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001213 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001214 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001215 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001216 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1217 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001218
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001219 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001220}
1221
Bram Moolenaar157d8132018-03-06 17:09:20 +01001222
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001223# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001224/*
1225 * Called when 'balloonevalterm' changed.
1226 */
1227 void
1228mch_bevalterm_changed(void)
1229{
1230 mch_setmouse(g_fMouseActive);
1231}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001232# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001233
Bram Moolenaar071d4272004-06-13 20:20:40 +00001234/*
1235 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1236 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1237 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1238 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1239 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1240 * and we return the mouse position in g_xMouse and g_yMouse.
1241 *
1242 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1243 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1244 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1245 *
1246 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1247 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1248 *
1249 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1250 * moves, even if it stays within the same character cell. We ignore
1251 * all MOUSE_MOVED messages if the position hasn't really changed, and
1252 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1253 * we're only interested in MOUSE_DRAG).
1254 *
1255 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1256 * 2-button mouses by pressing the left & right buttons simultaneously.
1257 * In practice, it's almost impossible to click both at the same time,
1258 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1259 * in such cases, if the user is clicking quickly.
1260 */
1261 static BOOL
1262decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001263 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001264{
1265 static int s_nOldButton = -1;
1266 static int s_nOldMouseClick = -1;
1267 static int s_xOldMouse = -1;
1268 static int s_yOldMouse = -1;
1269 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001270# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001271 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001272# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001273 static int s_cClicks = 1;
1274 static BOOL s_fReleased = TRUE;
1275 static DWORD s_dwLastClickTime = 0;
1276 static BOOL s_fNextIsMiddle = FALSE;
1277
Bram Moolenaar0f873732019-12-05 20:28:46 +01001278 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001279
1280 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1281 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1282 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1283 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1284
1285 int nButton;
1286
1287 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1288 cButtons = 2;
1289
1290 if (!g_fMouseAvail || !g_fMouseActive)
1291 {
1292 g_nMouseClick = -1;
1293 return FALSE;
1294 }
1295
Bram Moolenaar0f873732019-12-05 20:28:46 +01001296 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001297 if (g_fJustGotFocus)
1298 {
1299 g_fJustGotFocus = FALSE;
1300 return FALSE;
1301 }
1302
Bram Moolenaar0f873732019-12-05 20:28:46 +01001303 // unprocessed mouse click?
Bram Moolenaar071d4272004-06-13 20:20:40 +00001304 if (g_nMouseClick != -1)
1305 return TRUE;
1306
1307 nButton = -1;
1308 g_xMouse = pmer->dwMousePosition.X;
1309 g_yMouse = pmer->dwMousePosition.Y;
1310
1311 if (pmer->dwEventFlags == MOUSE_MOVED)
1312 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001313 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1314 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001315 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1316 return FALSE;
1317 }
1318
Bram Moolenaar0f873732019-12-05 20:28:46 +01001319 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001320 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1321 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001322 nButton = MOUSE_RELEASE;
1323
Bram Moolenaar0f873732019-12-05 20:28:46 +01001324 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001325 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001326 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001327# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001328 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001329 if (p_bevalterm)
1330 nButton = MOUSE_DRAG;
1331 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001332# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001333 return FALSE;
1334 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001335
Bram Moolenaar071d4272004-06-13 20:20:40 +00001336 s_fReleased = TRUE;
1337 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001338 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001339 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001340 // on a 2-button mouse, hold down left and right buttons
1341 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001342
1343 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1344 {
1345 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1346
Bram Moolenaar0f873732019-12-05 20:28:46 +01001347 // if either left or right button only is pressed, see if the
1348 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001349 if (dwLR == LEFT || dwLR == RIGHT)
1350 {
1351 for (;;)
1352 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001353 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001354 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1355 != WAIT_OBJECT_0)
1356 break;
1357 else
1358 {
1359 DWORD cRecords = 0;
1360 INPUT_RECORD ir;
1361 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1362
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001363 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001364
1365 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1366 || !(pmer2->dwButtonState & LEFT_RIGHT))
1367 break;
1368 else
1369 {
1370 if (pmer2->dwEventFlags != MOUSE_MOVED)
1371 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001372 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001373
1374 return decode_mouse_event(pmer2);
1375 }
1376 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1377 s_yOldMouse == pmer2->dwMousePosition.Y)
1378 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001379 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001380 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001381
Bram Moolenaar0f873732019-12-05 20:28:46 +01001382 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001383 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001384
1385 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1386 break;
1387 }
1388 else
1389 break;
1390 }
1391 }
1392 }
1393 }
1394 }
1395
1396 if (s_fNextIsMiddle)
1397 {
1398 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1399 ? MOUSE_DRAG : MOUSE_MIDDLE;
1400 s_fNextIsMiddle = FALSE;
1401 }
1402 else if (cButtons == 2 &&
1403 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1404 {
1405 nButton = MOUSE_MIDDLE;
1406
1407 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1408 {
1409 s_fNextIsMiddle = TRUE;
1410 nButton = MOUSE_RELEASE;
1411 }
1412 }
1413 else if ((pmer->dwButtonState & LEFT) == LEFT)
1414 nButton = MOUSE_LEFT;
1415 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1416 nButton = MOUSE_MIDDLE;
1417 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1418 nButton = MOUSE_RIGHT;
1419
1420 if (! s_fReleased && ! s_fNextIsMiddle
1421 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1422 return FALSE;
1423
1424 s_fReleased = s_fNextIsMiddle;
1425 }
1426
1427 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1428 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001429 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001430 if (nButton != -1 && nButton != MOUSE_RELEASE)
1431 {
1432 DWORD dwCurrentTime = GetTickCount();
1433
1434 if (s_xOldMouse != g_xMouse
1435 || s_yOldMouse != g_yMouse
1436 || s_nOldButton != nButton
1437 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001438# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001439 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001440# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001441 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1442 {
1443 s_cClicks = 1;
1444 }
1445 else if (++s_cClicks > 4)
1446 {
1447 s_cClicks = 1;
1448 }
1449
1450 s_dwLastClickTime = dwCurrentTime;
1451 }
1452 }
1453 else if (pmer->dwEventFlags == MOUSE_MOVED)
1454 {
1455 if (nButton != -1 && nButton != MOUSE_RELEASE)
1456 nButton = MOUSE_DRAG;
1457
1458 s_cClicks = 1;
1459 }
1460
1461 if (nButton == -1)
1462 return FALSE;
1463
1464 if (nButton != MOUSE_RELEASE)
1465 s_nOldButton = nButton;
1466
1467 g_nMouseClick = nButton;
1468
1469 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1470 g_nMouseClick |= MOUSE_SHIFT;
1471 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1472 g_nMouseClick |= MOUSE_CTRL;
1473 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1474 g_nMouseClick |= MOUSE_ALT;
1475
1476 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1477 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1478
Bram Moolenaar0f873732019-12-05 20:28:46 +01001479 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001480 if (s_xOldMouse == g_xMouse
1481 && s_yOldMouse == g_yMouse
1482 && s_nOldMouseClick == g_nMouseClick)
1483 {
1484 g_nMouseClick = -1;
1485 return FALSE;
1486 }
1487
1488 s_xOldMouse = g_xMouse;
1489 s_yOldMouse = g_yMouse;
1490 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001491# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001492 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001493# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001494 s_nOldMouseClick = g_nMouseClick;
1495
1496 return TRUE;
1497}
1498
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001499#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001500
1501
1502#ifdef MCH_CURSOR_SHAPE
1503/*
1504 * Set the shape of the cursor.
1505 * 'thickness' can be from 1 (thin) to 99 (block)
1506 */
1507 static void
1508mch_set_cursor_shape(int thickness)
1509{
K.Takatadf5320c2022-09-01 13:20:16 +01001510 if (USE_VTP || USE_WT)
1511 {
1512 if (*T_CSI == NUL)
1513 {
1514 // If 't_SI' is not set, use the default cursor styles.
1515 if (thickness < 50)
1516 vtp_printf("\033[3 q"); // underline
1517 else
1518 vtp_printf("\033[0 q"); // default
1519 }
1520 }
1521 else
1522 {
1523 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1524 ConsoleCursorInfo.dwSize = thickness;
1525 ConsoleCursorInfo.bVisible = s_cursor_visible;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001526
K.Takatadf5320c2022-09-01 13:20:16 +01001527 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1528 if (s_cursor_visible)
1529 SetConsoleCursorPosition(g_hConOut, g_coord);
1530 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001531}
1532
1533 void
1534mch_update_cursor(void)
1535{
1536 int idx;
1537 int thickness;
1538
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001539# ifdef VIMDLL
1540 if (gui.in_use)
1541 return;
1542# endif
1543
Bram Moolenaar071d4272004-06-13 20:20:40 +00001544 /*
1545 * How the cursor is drawn depends on the current mode.
1546 */
1547 idx = get_shape_idx(FALSE);
1548
1549 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001550 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00001551 else
1552 thickness = shape_table[idx].percentage;
1553 mch_set_cursor_shape(thickness);
1554}
1555#endif
1556
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001557#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001558/*
1559 * Handle FOCUS_EVENT.
1560 */
1561 static void
1562handle_focus_event(INPUT_RECORD ir)
1563{
1564 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1565 ui_focus_change((int)g_fJustGotFocus);
1566}
1567
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001568static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1569
Bram Moolenaar071d4272004-06-13 20:20:40 +00001570/*
1571 * Wait until console input from keyboard or mouse is available,
1572 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001573 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001574 * Return TRUE if something is available FALSE if not.
1575 */
1576 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001577WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001578{
1579 DWORD dwNow = 0, dwEndTime = 0;
1580 INPUT_RECORD ir;
1581 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001582 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001583# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001584 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001585# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001586
1587 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001588 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001589 dwEndTime = GetTickCount() + msec;
1590 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001591 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001592 dwEndTime = INFINITE;
1593
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001594 // We need to loop until the end of the time period, because
1595 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001596 for (;;)
1597 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001598 // Only process messages when waiting.
1599 if (msec != 0)
1600 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001601# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001602 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001603# endif
1604# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001605 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001606# endif
1607# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001608 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001609# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001610 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001611
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001612 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001613# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001614 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001615# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001616 )
1617 return TRUE;
1618
1619 if (msec > 0)
1620 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001621 // If the specified wait time has passed, return. Beware that
1622 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001623 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001624 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001625 break;
1626 }
1627 if (msec != 0)
1628 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001629 DWORD dwWaitTime = dwEndTime - dwNow;
1630
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001631 // Don't wait for more than 11 msec to avoid dropping characters,
1632 // check channel while waiting for input and handle a callback from
1633 // 'balloonexpr'.
1634 if (dwWaitTime > 11)
1635 dwWaitTime = 11;
1636
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001637# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001638 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001639 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001640# endif
1641# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001642 // When waiting very briefly don't trigger timers.
1643 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001644 {
1645 long due_time;
1646
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001647 // Trigger timers and then get the time in msec until the next
1648 // one is due. Wait up to that time.
1649 due_time = check_due_timer();
1650 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001651 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001652 // timer may have used feedkeys().
1653 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001654 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001655 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1656 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001657 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001658# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001659 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001660# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001661 // Wait for either an event on the console input or a
1662 // message in the client-server window.
1663 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1664 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001665# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001666 wait_for_single_object(g_hConIn, dwWaitTime)
1667 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001668# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001669 )
1670 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001671 }
1672
1673 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001674 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001675
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001676# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02001677 // May have to redraw if the cursor ends up in the wrong place.
1678 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01001679 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001680 {
1681 CONSOLE_SCREEN_BUFFER_INFO csbi;
1682
1683 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1684 {
1685 if (csbi.dwCursorPosition.Y != msg_row)
1686 {
matveyte08795e2021-05-07 15:00:17 +02001687 // The screen is now messed up, must redraw the command
1688 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01001689 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02001690 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001691 redrawcmd();
1692 }
1693 }
1694 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001695# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001696
1697 if (cRecords > 0)
1698 {
1699 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1700 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001701# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01001702 // Windows IME sends two '\n's with only one 'ENTER'. First:
1703 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00001704 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001705 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1706 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001707 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001708 continue;
1709 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001710# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001711 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1712 NULL, FALSE))
1713 return TRUE;
1714 }
1715
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001716 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717
1718 if (ir.EventType == FOCUS_EVENT)
1719 handle_focus_event(ir);
1720 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001721 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001722 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1723
Bram Moolenaar36698e32019-12-11 22:57:40 +01001724 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001725 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001726 if (dwSize.X != Columns || dwSize.Y != Rows)
1727 {
1728 CONSOLE_SCREEN_BUFFER_INFO csbi;
1729 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01001730 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001731 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01001732 if (dwSize.X != Columns || dwSize.Y != Rows)
1733 {
1734 ResizeConBuf(g_hConOut, dwSize);
1735 shell_resized();
1736 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001737 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001738 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001739 else if (ir.EventType == MOUSE_EVENT
1740 && decode_mouse_event(&ir.Event.MouseEvent))
1741 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001742 }
1743 else if (msec == 0)
1744 break;
1745 }
1746
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001747# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01001748 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001749 if (input_available())
1750 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001751# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001752
Bram Moolenaar071d4272004-06-13 20:20:40 +00001753 return FALSE;
1754}
1755
Bram Moolenaar071d4272004-06-13 20:20:40 +00001756/*
1757 * return non-zero if a character is available
1758 */
1759 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001760mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001761{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001762# ifdef VIMDLL
1763 if (gui.in_use)
1764 return TRUE;
1765# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001766 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001767}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001768
1769# if defined(FEAT_TERMINAL) || defined(PROTO)
1770/*
1771 * Check for any pending input or messages.
1772 */
1773 int
1774mch_check_messages(void)
1775{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001776# ifdef VIMDLL
1777 if (gui.in_use)
1778 return TRUE;
1779# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001780 return WaitForChar(0L, TRUE);
1781}
1782# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001783
1784/*
1785 * Create the console input. Used when reading stdin doesn't work.
1786 */
1787 static void
1788create_conin(void)
1789{
1790 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1791 FILE_SHARE_READ|FILE_SHARE_WRITE,
1792 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001793 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001794 did_create_conin = TRUE;
1795}
1796
1797/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001798 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001799 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001800 static WCHAR
1801tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001802{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001803 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001804
1805 for (;;)
1806 {
1807 INPUT_RECORD ir;
1808 DWORD cRecords = 0;
1809
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001810# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001811 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001812 if (input_available())
1813 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001814 if (g_nMouseClick != -1)
1815 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001816# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001817 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001818 {
1819 if (did_create_conin)
1820 read_error_exit();
1821 create_conin();
1822 continue;
1823 }
1824
1825 if (ir.EventType == KEY_EVENT)
1826 {
1827 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1828 pmodifiers, TRUE))
1829 return ch;
1830 }
1831 else if (ir.EventType == FOCUS_EVENT)
1832 handle_focus_event(ir);
1833 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1834 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001835 else if (ir.EventType == MOUSE_EVENT)
1836 {
1837 if (decode_mouse_event(&ir.Event.MouseEvent))
1838 return 0;
1839 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001840 }
1841}
Bram Moolenaar0f873732019-12-05 20:28:46 +01001842#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001843
1844
1845/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001846 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001847 * Get one or more characters from the keyboard or the mouse.
1848 * If time == 0, do not wait for characters.
1849 * If time == n, wait a short time for characters.
1850 * If time == -1, wait forever for characters.
1851 * Returns the number of characters read into buf.
1852 */
1853 int
1854mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001855 char_u *buf UNUSED,
1856 int maxlen UNUSED,
1857 long time UNUSED,
1858 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001859{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001860#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001861
1862 int len;
1863 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001864# ifdef VIMDLL
1865// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
1866# define TYPEAHEADSPACE 6
1867# else
1868# define TYPEAHEADSPACE 0
1869# endif
1870# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001871 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001872 static int typeaheadlen = 0;
1873
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001874# ifdef VIMDLL
1875 if (gui.in_use)
1876 return 0;
1877# endif
1878
Bram Moolenaar0f873732019-12-05 20:28:46 +01001879 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001880 if (typeaheadlen > 0)
1881 goto theend;
1882
Bram Moolenaar071d4272004-06-13 20:20:40 +00001883 if (time >= 0)
1884 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001885 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00001886 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001887 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001888 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00001889 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001890 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00001891
Bram Moolenaar3918c952005-03-15 22:34:55 +00001892 /*
1893 * If there is no character available within 2 seconds (default)
1894 * write the autoscript file to disk. Or cause the CursorHold event
1895 * to be triggered.
1896 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001897 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001898 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001899 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001900 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001901 buf[0] = K_SPECIAL;
1902 buf[1] = KS_EXTRA;
1903 buf[2] = (int)KE_CURSORHOLD;
1904 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001905 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001906 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001907 }
1908 }
1909
1910 /*
1911 * Try to read as many characters as there are, until the buffer is full.
1912 */
1913
Bram Moolenaar0f873732019-12-05 20:28:46 +01001914 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001915 g_fCBrkPressed = FALSE;
1916
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001917# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001918 if (fdDump)
1919 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001920# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001921
Bram Moolenaar0f873732019-12-05 20:28:46 +01001922 // Keep looping until there is something in the typeahead buffer and more
1923 // to get and still room in the buffer (up to two bytes for a char and
1924 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001925 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001926 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001927 {
1928 if (typebuf_changed(tb_change_cnt))
1929 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001930 // "buf" may be invalid now if a client put something in the
1931 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001932 typeaheadlen = 0;
1933 break;
1934 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001935 if (g_nMouseClick != -1)
1936 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001937# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001938 if (fdDump)
1939 fprintf(fdDump, "{%02x @ %d, %d}",
1940 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001941# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001942 typeahead[typeaheadlen++] = ESC + 128;
1943 typeahead[typeaheadlen++] = 'M';
1944 typeahead[typeaheadlen++] = g_nMouseClick;
1945 typeahead[typeaheadlen++] = g_xMouse + '!';
1946 typeahead[typeaheadlen++] = g_yMouse + '!';
1947 g_nMouseClick = -1;
1948 }
1949 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001950 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001951 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001952 int modifiers = 0;
1953
1954 c = tgetch(&modifiers, &ch2);
1955
1956 if (typebuf_changed(tb_change_cnt))
1957 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001958 // "buf" may be invalid now if a client put something in the
1959 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001960 typeaheadlen = 0;
1961 break;
1962 }
1963
1964 if (c == Ctrl_C && ctrl_c_interrupts)
1965 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001966# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001967 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001968# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001969 got_int = TRUE;
1970 }
1971
Bram Moolenaar071d4272004-06-13 20:20:40 +00001972 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001973 {
1974 int n = 1;
1975
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001976 if (ch2 == NUL)
1977 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001978 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001979 char_u *p;
1980 WCHAR ch[2];
1981
1982 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01001983 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001984 {
1985 ch[1] = tgetch(&modifiers, &ch2);
1986 n++;
1987 }
1988 p = utf16_to_enc(ch, &n);
1989 if (p != NULL)
1990 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001991 for (i = 0, j = 0; i < n; i++)
1992 {
1993 typeahead[typeaheadlen + j++] = p[i];
1994# ifdef VIMDLL
1995 if (p[i] == CSI)
1996 {
1997 typeahead[typeaheadlen + j++] = KS_EXTRA;
1998 typeahead[typeaheadlen + j++] = KE_CSI;
1999 }
2000# endif
2001 }
2002 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002003 vim_free(p);
2004 }
2005 }
2006 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002007 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002008 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002009# ifdef VIMDLL
2010 if (c == CSI)
2011 {
2012 typeahead[typeaheadlen + 1] = KS_EXTRA;
2013 typeahead[typeaheadlen + 2] = KE_CSI;
2014 n = 3;
2015 }
2016# endif
2017 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002018 if (ch2 != NUL)
2019 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002020 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002021 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002022 switch (ch2)
2023 {
2024 case (WCHAR)'\324': // SHIFT+Insert
2025 case (WCHAR)'\325': // CTRL+Insert
2026 case (WCHAR)'\327': // SHIFT+Delete
2027 case (WCHAR)'\330': // CTRL+Delete
2028 typeahead[typeaheadlen + n] = (char_u)ch2;
2029 n++;
2030 break;
2031
2032 default:
2033 typeahead[typeaheadlen + n] = 3;
2034 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2035 n += 2;
2036 break;
2037 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002038 }
2039 else
2040 {
2041 typeahead[typeaheadlen + n] = 3;
2042 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2043 n += 2;
2044 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002045 }
2046
Bram Moolenaar0f873732019-12-05 20:28:46 +01002047 // Use the ALT key to set the 8th bit of the character
2048 // when it's one byte, the 8th bit isn't set yet and not
2049 // using a double-byte encoding (would become a lead
2050 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002051 if ((modifiers & MOD_MASK_ALT)
2052 && n == 1
2053 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002054 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002055 )
2056 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002057 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2058 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002059 modifiers &= ~MOD_MASK_ALT;
2060 }
2061
2062 if (modifiers != 0)
2063 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002064 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002065 mch_memmove(typeahead + typeaheadlen + 3,
2066 typeahead + typeaheadlen, n);
2067 typeahead[typeaheadlen++] = K_SPECIAL;
2068 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2069 typeahead[typeaheadlen++] = modifiers;
2070 }
2071
2072 typeaheadlen += n;
2073
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002074# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002075 if (fdDump)
2076 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002077# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002078 }
2079 }
2080 }
2081
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002082# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002083 if (fdDump)
2084 {
2085 fputs("]\n", fdDump);
2086 fflush(fdDump);
2087 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002088# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002089
Bram Moolenaar071d4272004-06-13 20:20:40 +00002090theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002091 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002092 len = 0;
2093 while (len < maxlen && typeaheadlen > 0)
2094 {
2095 buf[len++] = typeahead[0];
2096 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2097 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002098# ifdef FEAT_JOB_CHANNEL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002099 if (len > 0)
2100 {
2101 buf[len] = NUL;
2102 ch_log(NULL, "raw key input: \"%s\"", buf);
2103 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002104# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002105 return len;
2106
Bram Moolenaar0f873732019-12-05 20:28:46 +01002107#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002108 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002109#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002110}
2111
Bram Moolenaar82881492012-11-20 16:53:39 +01002112#ifndef PROTO
2113# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002114# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002115# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002116#endif
2117
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002118/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002119 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002120 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2121 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002122 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002123 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002124 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002125executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002126{
LemonBoy40fd7e62022-05-05 20:18:16 +01002127 int attrs = win32_getattrs((char_u *)name);
2128
2129 // The file doesn't exist or is a folder.
2130 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2131 return FALSE;
2132 // Check if the file is an AppExecLink, a special alias used by Windows
2133 // Store for its apps.
2134 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002135 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002136 char_u *res = resolve_appexeclink((char_u *)name);
2137 if (res == NULL)
2138 return FALSE;
2139 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002140 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002141 *path = res;
2142 else
2143 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002144 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002145 else if (path != NULL)
2146 *path = FullName_save((char_u *)name, FALSE);
2147 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002148}
2149
2150/*
2151 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2152 * If "use_path" is FALSE: Return TRUE if "name" exists.
2153 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2154 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2155 * the allocated memory.
2156 */
2157 static int
2158executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2159{
2160 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2161 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2162 // UTF-8.
2163 char_u buf[_MAX_PATH * 3];
2164 size_t len = STRLEN(name);
2165 size_t tmplen;
2166 char_u *p, *e, *e2;
2167 char_u *pathbuf = NULL;
2168 char_u *pathext = NULL;
2169 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002170 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002171 int noext = FALSE;
2172 int retval = FALSE;
2173
2174 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002175 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002176
2177 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002178 shname = gettail(p_sh);
2179 if (strstr((char *)shname, "sh") != NULL &&
2180 !(strstr((char *)shname, "powershell") != NULL
2181 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002182 noext = TRUE;
2183
2184 if (use_pathext)
2185 {
2186 pathext = mch_getenv("PATHEXT");
2187 if (pathext == NULL)
2188 pathext = (char_u *)".com;.exe;.bat;.cmd";
2189
2190 if (noext == FALSE)
2191 {
2192 /*
2193 * Loop over all extensions in $PATHEXT.
2194 * Check "name" ends with extension.
2195 */
2196 p = pathext;
2197 while (*p)
2198 {
2199 if (p[0] == ';'
2200 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2201 {
2202 // Skip empty or single ".".
2203 ++p;
2204 continue;
2205 }
2206 e = vim_strchr(p, ';');
2207 if (e == NULL)
2208 e = p + STRLEN(p);
2209 tmplen = e - p;
2210
2211 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2212 {
2213 noext = TRUE;
2214 break;
2215 }
2216
2217 p = e;
2218 }
2219 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002220 }
2221
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002222 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002223 if (pathext == NULL)
2224 pathext = (char_u *)".";
2225 else if (noext == TRUE)
2226 {
2227 if (pathextbuf == NULL)
2228 pathextbuf = alloc(STRLEN(pathext) + 3);
2229 if (pathextbuf == NULL)
2230 {
2231 retval = FALSE;
2232 goto theend;
2233 }
2234 STRCPY(pathextbuf, ".;");
2235 STRCAT(pathextbuf, pathext);
2236 pathext = pathextbuf;
2237 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002238
Bram Moolenaar95da1362020-05-30 18:37:55 +02002239 // Use $PATH when "use_path" is TRUE and "name" is basename.
2240 if (use_path && gettail((char_u *)name) == (char_u *)name)
2241 {
2242 p = mch_getenv("PATH");
2243 if (p != NULL)
2244 {
2245 pathbuf = alloc(STRLEN(p) + 3);
2246 if (pathbuf == NULL)
2247 {
2248 retval = FALSE;
2249 goto theend;
2250 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002251
2252 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2253 STRCPY(pathbuf, ".;");
2254 else
2255 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002256 STRCAT(pathbuf, p);
2257 }
2258 }
2259
2260 /*
2261 * Walk through all entries in $PATH to check if "name" exists there and
2262 * is an executable file.
2263 */
2264 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2265 while (*p)
2266 {
2267 if (*p == ';') // Skip empty entry
2268 {
2269 ++p;
2270 continue;
2271 }
2272 e = vim_strchr(p, ';');
2273 if (e == NULL)
2274 e = p + STRLEN(p);
2275
2276 if (e - p + len + 2 > sizeof(buf))
2277 {
2278 retval = FALSE;
2279 goto theend;
2280 }
2281 // A single "." that means current dir.
2282 if (e - p == 1 && *p == '.')
2283 STRCPY(buf, name);
2284 else
2285 {
2286 vim_strncpy(buf, p, e - p);
2287 add_pathsep(buf);
2288 STRCAT(buf, name);
2289 }
2290 tmplen = STRLEN(buf);
2291
2292 /*
2293 * Loop over all extensions in $PATHEXT.
2294 * Check "name" with extension added.
2295 */
2296 p = pathext;
2297 while (*p)
2298 {
2299 if (*p == ';')
2300 {
2301 // Skip empty entry
2302 ++p;
2303 continue;
2304 }
2305 e2 = vim_strchr(p, (int)';');
2306 if (e2 == NULL)
2307 e2 = p + STRLEN(p);
2308
2309 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2310 {
2311 // Not a single "." that means no extension is added.
2312 if (e2 - p + tmplen + 1 > sizeof(buf))
2313 {
2314 retval = FALSE;
2315 goto theend;
2316 }
2317 vim_strncpy(buf + tmplen, p, e2 - p);
2318 }
2319 if (executable_file((char *)buf, path))
2320 {
2321 retval = TRUE;
2322 goto theend;
2323 }
2324
2325 p = e2;
2326 }
2327
2328 p = e;
2329 }
2330
2331theend:
2332 free(pathextbuf);
2333 free(pathbuf);
2334 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002335}
2336
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002337#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2338 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002339/*
2340 * Bad parameter handler.
2341 *
2342 * Certain MS CRT functions will intentionally crash when passed invalid
2343 * parameters to highlight possible security holes. Setting this function as
2344 * the bad parameter handler will prevent the crash.
2345 *
2346 * In debug builds the parameters contain CRT information that might help track
2347 * down the source of a problem, but in non-debug builds the arguments are all
2348 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2349 * worth allowing these to make debugging of issues easier.
2350 */
2351 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002352bad_param_handler(const wchar_t *expression UNUSED,
2353 const wchar_t *function UNUSED,
2354 const wchar_t *file UNUSED,
2355 unsigned int line UNUSED,
2356 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002357{
2358}
2359
2360# define SET_INVALID_PARAM_HANDLER \
2361 ((void)_set_invalid_parameter_handler(bad_param_handler))
2362#else
2363# define SET_INVALID_PARAM_HANDLER
2364#endif
2365
Bram Moolenaar4f974752019-02-17 17:44:42 +01002366#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002367
2368/*
2369 * GUI version of mch_init().
2370 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002371 static void
2372mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002373{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002374# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002375 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002376# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002377
Bram Moolenaar0f873732019-12-05 20:28:46 +01002378 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002379 SET_INVALID_PARAM_HANDLER;
2380
Bram Moolenaar0f873732019-12-05 20:28:46 +01002381 // Let critical errors result in a failure, not in a dialog box. Required
2382 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002383 SetErrorMode(SEM_FAILCRITICALERRORS);
2384
Bram Moolenaar0f873732019-12-05 20:28:46 +01002385 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002386
Bram Moolenaar0f873732019-12-05 20:28:46 +01002387 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002388 Rows = 25;
2389 Columns = 80;
2390
Bram Moolenaar0f873732019-12-05 20:28:46 +01002391 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002392 {
2393 char_u vimrun_location[_MAX_PATH + 4];
2394
Bram Moolenaar0f873732019-12-05 20:28:46 +01002395 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002396 STRCPY(vimrun_location, exe_name);
2397 STRCPY(gettail(vimrun_location), "vimrun.exe");
2398 if (mch_getperm(vimrun_location) >= 0)
2399 {
2400 if (*skiptowhite(vimrun_location) != NUL)
2401 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002402 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002403 mch_memmove(vimrun_location + 1, vimrun_location,
2404 STRLEN(vimrun_location) + 1);
2405 *vimrun_location = '"';
2406 STRCPY(gettail(vimrun_location), "vimrun\" ");
2407 }
2408 else
2409 STRCPY(gettail(vimrun_location), "vimrun ");
2410
2411 vimrun_path = (char *)vim_strsave(vimrun_location);
2412 s_dont_use_vimrun = FALSE;
2413 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002414 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002415 s_dont_use_vimrun = FALSE;
2416
Bram Moolenaar0f873732019-12-05 20:28:46 +01002417 // Don't give the warning for a missing vimrun.exe right now, but only
2418 // when vimrun was supposed to be used. Don't bother people that do
2419 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002420 if (s_dont_use_vimrun)
2421 need_vimrun_warning = TRUE;
2422 }
2423
2424 /*
2425 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2426 * Otherwise the default "findstr /n" is used.
2427 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002428 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01002429 set_option_value_give_err((char_u *)"grepprg",
2430 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002431
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002432# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002433 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002434# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002435
2436 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002437}
2438
2439
Bram Moolenaar0f873732019-12-05 20:28:46 +01002440#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002441
2442#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002443
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002444# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2445# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002446
2447/*
2448 * ClearConsoleBuffer()
2449 * Description:
2450 * Clears the entire contents of the console screen buffer, using the
2451 * specified attribute.
2452 * Returns:
2453 * TRUE on success
2454 */
2455 static BOOL
2456ClearConsoleBuffer(WORD wAttribute)
2457{
2458 CONSOLE_SCREEN_BUFFER_INFO csbi;
2459 COORD coord;
2460 DWORD NumCells, dummy;
2461
2462 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2463 return FALSE;
2464
2465 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2466 coord.X = 0;
2467 coord.Y = 0;
2468 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2469 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002470 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002471 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2472 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002473 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002474
2475 return TRUE;
2476}
2477
2478/*
2479 * FitConsoleWindow()
2480 * Description:
2481 * Checks if the console window will fit within given buffer dimensions.
2482 * Also, if requested, will shrink the window to fit.
2483 * Returns:
2484 * TRUE on success
2485 */
2486 static BOOL
2487FitConsoleWindow(
2488 COORD dwBufferSize,
2489 BOOL WantAdjust)
2490{
2491 CONSOLE_SCREEN_BUFFER_INFO csbi;
2492 COORD dwWindowSize;
2493 BOOL NeedAdjust = FALSE;
2494
2495 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2496 {
2497 /*
2498 * A buffer resize will fail if the current console window does
2499 * not lie completely within that buffer. To avoid this, we might
2500 * have to move and possibly shrink the window.
2501 */
2502 if (csbi.srWindow.Right >= dwBufferSize.X)
2503 {
2504 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2505 if (dwWindowSize.X > dwBufferSize.X)
2506 dwWindowSize.X = dwBufferSize.X;
2507 csbi.srWindow.Right = dwBufferSize.X - 1;
2508 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2509 NeedAdjust = TRUE;
2510 }
2511 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2512 {
2513 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2514 if (dwWindowSize.Y > dwBufferSize.Y)
2515 dwWindowSize.Y = dwBufferSize.Y;
2516 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2517 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2518 NeedAdjust = TRUE;
2519 }
2520 if (NeedAdjust && WantAdjust)
2521 {
2522 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2523 return FALSE;
2524 }
2525 return TRUE;
2526 }
2527
2528 return FALSE;
2529}
2530
2531typedef struct ConsoleBufferStruct
2532{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002533 BOOL IsValid;
2534 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002535 PCHAR_INFO Buffer;
2536 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002537 PSMALL_RECT Regions;
2538 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002539} ConsoleBuffer;
2540
2541/*
2542 * SaveConsoleBuffer()
2543 * Description:
2544 * Saves important information about the console buffer, including the
2545 * actual buffer contents. The saved information is suitable for later
2546 * restoration by RestoreConsoleBuffer().
2547 * Returns:
2548 * TRUE if all information was saved; FALSE otherwise
2549 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2550 */
2551 static BOOL
2552SaveConsoleBuffer(
2553 ConsoleBuffer *cb)
2554{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002555 DWORD NumCells;
2556 COORD BufferCoord;
2557 SMALL_RECT ReadRegion;
2558 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002559 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002560
Bram Moolenaar071d4272004-06-13 20:20:40 +00002561 if (cb == NULL)
2562 return FALSE;
2563
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002564 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002565 {
2566 cb->IsValid = FALSE;
2567 return FALSE;
2568 }
2569 cb->IsValid = TRUE;
2570
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002571 /*
2572 * Allocate a buffer large enough to hold the entire console screen
2573 * buffer. If this ConsoleBuffer structure has already been initialized
2574 * with a buffer of the correct size, then just use that one.
2575 */
2576 if (!cb->IsValid || cb->Buffer == NULL ||
2577 cb->BufferSize.X != cb->Info.dwSize.X ||
2578 cb->BufferSize.Y != cb->Info.dwSize.Y)
2579 {
2580 cb->BufferSize.X = cb->Info.dwSize.X;
2581 cb->BufferSize.Y = cb->Info.dwSize.Y;
2582 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2583 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002584 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002585 if (cb->Buffer == NULL)
2586 return FALSE;
2587 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002588
2589 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002590 * We will now copy the console screen buffer into our buffer.
2591 * ReadConsoleOutput() seems to be limited as far as how much you
2592 * can read at a time. Empirically, this number seems to be about
2593 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2594 * in chunks until it is all copied. The chunks will all have the
2595 * same horizontal characteristics, so initialize them now. The
2596 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002597 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002598 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002599 ReadRegion.Left = 0;
2600 ReadRegion.Right = cb->Info.dwSize.X - 1;
2601 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002602
2603 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2604 if (cb->Regions == NULL || numregions != cb->NumRegions)
2605 {
2606 cb->NumRegions = numregions;
2607 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002608 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002609 if (cb->Regions == NULL)
2610 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002611 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002612 return FALSE;
2613 }
2614 }
2615
2616 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002617 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002618 /*
2619 * Read into position (0, Y) in our buffer.
2620 */
2621 BufferCoord.Y = Y;
2622 /*
2623 * Read the region whose top left corner is (0, Y) and whose bottom
2624 * right corner is (width - 1, Y + Y_incr - 1). This should define
2625 * a region of size width by Y_incr. Don't worry if this region is
2626 * too large for the remaining buffer; it will be cropped.
2627 */
2628 ReadRegion.Top = Y;
2629 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002630 if (!ReadConsoleOutputW(g_hConOut, // output handle
2631 cb->Buffer, // our buffer
2632 cb->BufferSize, // dimensions of our buffer
2633 BufferCoord, // offset in our buffer
2634 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002635 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002636 VIM_CLEAR(cb->Buffer);
2637 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002638 return FALSE;
2639 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002640 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002641 }
2642
2643 return TRUE;
2644}
2645
2646/*
2647 * RestoreConsoleBuffer()
2648 * Description:
2649 * Restores important information about the console buffer, including the
2650 * actual buffer contents, if desired. The information to restore is in
2651 * the same format used by SaveConsoleBuffer().
2652 * Returns:
2653 * TRUE on success
2654 */
2655 static BOOL
2656RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002657 ConsoleBuffer *cb,
2658 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002659{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002660 COORD BufferCoord;
2661 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002662 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002663
2664 if (cb == NULL || !cb->IsValid)
2665 return FALSE;
2666
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002667 /*
2668 * Before restoring the buffer contents, clear the current buffer, and
2669 * restore the cursor position and window information. Doing this now
2670 * prevents old buffer contents from "flashing" onto the screen.
2671 */
2672 if (RestoreScreen)
2673 ClearConsoleBuffer(cb->Info.wAttributes);
2674
2675 FitConsoleWindow(cb->Info.dwSize, TRUE);
2676 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2677 return FALSE;
2678 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2679 return FALSE;
2680
2681 if (!RestoreScreen)
2682 {
2683 /*
2684 * No need to restore the screen buffer contents, so we're done.
2685 */
2686 return TRUE;
2687 }
2688
2689 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2690 return FALSE;
2691 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2692 return FALSE;
2693
2694 /*
2695 * Restore the screen buffer contents.
2696 */
2697 if (cb->Buffer != NULL)
2698 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002699 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002700 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002701 BufferCoord.X = cb->Regions[i].Left;
2702 BufferCoord.Y = cb->Regions[i].Top;
2703 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01002704 if (!WriteConsoleOutputW(g_hConOut, // output handle
2705 cb->Buffer, // our buffer
2706 cb->BufferSize, // dimensions of our buffer
2707 BufferCoord, // offset in our buffer
2708 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02002709 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002710 }
2711 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002712
2713 return TRUE;
2714}
2715
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002716# define FEAT_RESTORE_ORIG_SCREEN
2717# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002718static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002719# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002720static ConsoleBuffer g_cbNonTermcap = { 0 };
2721static ConsoleBuffer g_cbTermcap = { 0 };
2722
Bram Moolenaar071d4272004-06-13 20:20:40 +00002723char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01002724HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00002725static HICON g_hOrigIconSmall = NULL;
2726static HICON g_hOrigIcon = NULL;
2727static HICON g_hVimIcon = NULL;
2728static BOOL g_fCanChangeIcon = FALSE;
2729
Bram Moolenaar071d4272004-06-13 20:20:40 +00002730/*
2731 * GetConsoleIcon()
2732 * Description:
2733 * Attempts to retrieve the small icon and/or the big icon currently in
2734 * use by a given window.
2735 * Returns:
2736 * TRUE on success
2737 */
2738 static BOOL
2739GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002740 HWND hWnd,
2741 HICON *phIconSmall,
2742 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002743{
2744 if (hWnd == NULL)
2745 return FALSE;
2746
2747 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002748 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2749 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002750 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002751 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2752 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002753 return TRUE;
2754}
2755
2756/*
2757 * SetConsoleIcon()
2758 * Description:
2759 * Attempts to change the small icon and/or the big icon currently in
2760 * use by a given window.
2761 * Returns:
2762 * TRUE on success
2763 */
2764 static BOOL
2765SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002766 HWND hWnd,
2767 HICON hIconSmall,
2768 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002769{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002770 if (hWnd == NULL)
2771 return FALSE;
2772
2773 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002774 SendMessage(hWnd, WM_SETICON,
2775 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002776 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002777 SendMessage(hWnd, WM_SETICON,
2778 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002779 return TRUE;
2780}
2781
2782/*
2783 * SaveConsoleTitleAndIcon()
2784 * Description:
2785 * Saves the current console window title in g_szOrigTitle, for later
2786 * restoration. Also, attempts to obtain a handle to the console window,
2787 * and use it to save the small and big icons currently in use by the
2788 * console window. This is not always possible on some versions of Windows;
2789 * nor is it possible when running Vim remotely using Telnet (since the
2790 * console window the user sees is owned by a remote process).
2791 */
2792 static void
2793SaveConsoleTitleAndIcon(void)
2794{
Bram Moolenaar0f873732019-12-05 20:28:46 +01002795 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002796 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2797 return;
2798
2799 /*
2800 * Obtain a handle to the console window using GetConsoleWindow() from
2801 * KERNEL32.DLL; we need to handle in order to change the window icon.
2802 * This function only exists on NT-based Windows, starting with Windows
2803 * 2000. On older operating systems, we can't change the window icon
2804 * anyway.
2805 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002806 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002807 if (g_hWnd == NULL)
2808 return;
2809
Bram Moolenaar0f873732019-12-05 20:28:46 +01002810 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002811 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2812 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2813 return;
2814
Bram Moolenaar0f873732019-12-05 20:28:46 +01002815 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01002816 if (
2817# ifdef FEAT_LIBCALL
2818 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
2819# endif
2820 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002821 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002822 if (g_hVimIcon != NULL)
2823 g_fCanChangeIcon = TRUE;
2824}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002825
2826static int g_fWindInitCalled = FALSE;
2827static int g_fTermcapMode = FALSE;
2828static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002829
2830/*
2831 * non-GUI version of mch_init().
2832 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002833 static void
2834mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002835{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002836# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002837 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002838# endif
2839# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002840 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002841# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002842
Bram Moolenaar0f873732019-12-05 20:28:46 +01002843 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002844 SET_INVALID_PARAM_HANDLER;
2845
Bram Moolenaar0f873732019-12-05 20:28:46 +01002846 // Let critical errors result in a failure, not in a dialog box. Required
2847 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002848 SetErrorMode(SEM_FAILCRITICALERRORS);
2849
Bram Moolenaar0f873732019-12-05 20:28:46 +01002850 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002851 out_flush();
2852
Bram Moolenaar0f873732019-12-05 20:28:46 +01002853 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00002854 if (read_cmd_fd == 0)
2855 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2856 else
2857 create_conin();
2858 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2859
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002860# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01002861 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002862 SaveConsoleBuffer(&g_cbOrig);
2863 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002864# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01002865 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002866 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2867 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002868# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002869 if (cterm_normal_fg_color == 0)
2870 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2871 if (cterm_normal_bg_color == 0)
2872 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2873
Bram Moolenaarbdace832019-03-02 10:13:42 +01002874 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002875 g_color_index_fg = g_attrDefault & 0xf;
2876 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2877
Bram Moolenaar0f873732019-12-05 20:28:46 +01002878 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00002879 update_tcap(g_attrCurrent);
2880
2881 GetConsoleCursorInfo(g_hConOut, &g_cci);
2882 GetConsoleMode(g_hConIn, &g_cmodein);
2883 GetConsoleMode(g_hConOut, &g_cmodeout);
2884
Bram Moolenaar071d4272004-06-13 20:20:40 +00002885 SaveConsoleTitleAndIcon();
2886 /*
2887 * Set both the small and big icons of the console window to Vim's icon.
2888 * Note that Vim presently only has one size of icon (32x32), but it
2889 * automatically gets scaled down to 16x16 when setting the small icon.
2890 */
2891 if (g_fCanChangeIcon)
2892 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002893
2894 ui_get_shellsize();
2895
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002896# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002897 fdDump = fopen("dump", "wt");
2898
2899 if (fdDump)
2900 {
2901 time_t t;
2902
2903 time(&t);
2904 fputs(ctime(&t), fdDump);
2905 fflush(fdDump);
2906 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002907# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002908
2909 g_fWindInitCalled = TRUE;
2910
Bram Moolenaar071d4272004-06-13 20:20:40 +00002911 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002912
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002913# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002914 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002915# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002916
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02002917 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002918 vtp_init();
Bram Moolenaar06b7b582020-05-30 17:49:25 +02002919 wt_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002920}
2921
2922/*
2923 * non-GUI version of mch_exit().
2924 * Shut down and exit with status `r'
2925 * Careful: mch_exit() may be called before mch_init()!
2926 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002927 static void
2928mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002929{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002930 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002931
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002932 vtp_exit();
2933
Bram Moolenaar955f1982017-02-05 15:10:51 +01002934 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002935 if (g_fWindInitCalled)
2936 settmode(TMODE_COOK);
2937
Bram Moolenaar0f873732019-12-05 20:28:46 +01002938 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00002939
2940 if (g_fWindInitCalled)
2941 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02002942 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002943 /*
2944 * Restore both the small and big icons of the console window to
2945 * what they were at startup. Don't do this when the window is
2946 * closed, Vim would hang here.
2947 */
2948 if (g_fCanChangeIcon && !g_fForceExit)
2949 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002950
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002951# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002952 if (fdDump)
2953 {
2954 time_t t;
2955
2956 time(&t);
2957 fputs(ctime(&t), fdDump);
2958 fclose(fdDump);
2959 }
2960 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002961# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002962 }
2963
2964 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02002965 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002966 SetConsoleMode(g_hConOut, g_cmodeout);
2967
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002968# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00002969 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002970# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002971
2972 exit(r);
2973}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002974#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002975
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002976 void
2977mch_init(void)
2978{
2979#ifdef VIMDLL
2980 if (gui.starting)
2981 mch_init_g();
2982 else
2983 mch_init_c();
2984#elif defined(FEAT_GUI_MSWIN)
2985 mch_init_g();
2986#else
2987 mch_init_c();
2988#endif
2989}
2990
2991 void
2992mch_exit(int r)
2993{
Bram Moolenaar173d8412020-04-19 14:02:26 +02002994#ifdef FEAT_NETBEANS_INTG
2995 netbeans_send_disconnect();
2996#endif
2997
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002998#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02002999 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003000 mch_exit_g(r);
3001 else
3002 mch_exit_c(r);
3003#elif defined(FEAT_GUI_MSWIN)
3004 mch_exit_g(r);
3005#else
3006 mch_exit_c(r);
3007#endif
3008}
3009
Bram Moolenaar071d4272004-06-13 20:20:40 +00003010/*
3011 * Do we have an interactive window?
3012 */
3013 int
3014mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003015 int argc UNUSED,
3016 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003017{
3018 get_exe_name();
3019
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003020#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003021 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003022#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003023# ifdef VIMDLL
3024 if (gui.in_use)
3025 return OK;
3026# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003027 if (isatty(1))
3028 return OK;
3029 return FAIL;
3030#endif
3031}
3032
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003033/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003034 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003035 * When "len" is > 0, also expand short to long filenames.
3036 */
3037 void
3038fname_case(
3039 char_u *name,
3040 int len)
3041{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003042 int flen;
3043 WCHAR *p;
3044 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003045
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003046 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003047 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048 return;
3049
3050 slash_adjust(name);
3051
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003052 p = enc_to_utf16(name, NULL);
3053 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003054 return;
3055
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003056 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003057 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003058 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003059
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003060 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003061 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003062 if (len > 0 || flen >= (int)STRLEN(q))
3063 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3064 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003065 }
3066 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003067 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003068}
3069
3070
3071/*
3072 * Insert user name in s[len].
3073 */
3074 int
3075mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003076 char_u *s,
3077 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003078{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003079 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003080 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003081
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003082 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003083 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003084 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003085
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003086 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003087 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003088 vim_strncpy(s, p, len - 1);
3089 vim_free(p);
3090 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003091 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003092 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003093 s[0] = NUL;
3094 return FAIL;
3095}
3096
3097
3098/*
3099 * Insert host name in s[len].
3100 */
3101 void
3102mch_get_host_name(
3103 char_u *s,
3104 int len)
3105{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003106 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003107 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003108
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003109 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003110 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003111 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003112
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003113 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003114 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003115 vim_strncpy(s, p, len - 1);
3116 vim_free(p);
3117 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003118 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003119 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003120}
3121
3122
3123/*
3124 * return process ID
3125 */
3126 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003127mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003128{
3129 return (long)GetCurrentProcessId();
3130}
3131
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003132/*
3133 * return TRUE if process "pid" is still running
3134 */
3135 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003136mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003137{
3138 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3139 DWORD status = 0;
3140 int ret = FALSE;
3141
3142 if (hProcess == NULL)
3143 return FALSE; // might not have access
3144 if (GetExitCodeProcess(hProcess, &status) )
3145 ret = status == STILL_ACTIVE;
3146 CloseHandle(hProcess);
3147 return ret;
3148}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003149
3150/*
3151 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3152 * Return OK for success, FAIL for failure.
3153 */
3154 int
3155mch_dirname(
3156 char_u *buf,
3157 int len)
3158{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003159 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003160
Bram Moolenaar071d4272004-06-13 20:20:40 +00003161 /*
3162 * Originally this was:
3163 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3164 * But the Win32s known bug list says that getcwd() doesn't work
3165 * so use the Win32 system call instead. <Negri>
3166 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003167 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003168 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003169 WCHAR wcbuf[_MAX_PATH + 1];
3170 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003171
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003172 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003173 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003174 p = utf16_to_enc(wcbuf, NULL);
3175 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003176 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003177 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003178 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003179 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003180 }
3181 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003182 if (p == NULL)
3183 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003184
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003185 if (p != NULL)
3186 {
3187 vim_strncpy(buf, p, len - 1);
3188 vim_free(p);
3189 return OK;
3190 }
3191 }
3192 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003193}
3194
3195/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003196 * Get file permissions for "name".
3197 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003198 */
3199 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003200mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003201{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003202 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003203 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003204
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003205 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003206 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003207}
3208
3209
3210/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003211 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003212 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003213 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003214 */
3215 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003216mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003217{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003218 long n;
3219 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003220
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003221 p = enc_to_utf16(name, NULL);
3222 if (p == NULL)
3223 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003224
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003225 n = _wchmod(p, perm);
3226 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003227 if (n == -1)
3228 return FAIL;
3229
3230 win32_set_archive(name);
3231
3232 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003233}
3234
3235/*
3236 * Set hidden flag for "name".
3237 */
3238 void
3239mch_hide(char_u *name)
3240{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003241 int attrs = win32_getattrs(name);
3242 if (attrs == -1)
3243 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003244
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003245 attrs |= FILE_ATTRIBUTE_HIDDEN;
3246 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003247}
3248
3249/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003250 * Return TRUE if file "name" exists and is hidden.
3251 */
3252 int
3253mch_ishidden(char_u *name)
3254{
3255 int f = win32_getattrs(name);
3256
3257 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003258 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003259
3260 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3261}
3262
3263/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003264 * return TRUE if "name" is a directory
3265 * return FALSE if "name" is not a directory or upon error
3266 */
3267 int
3268mch_isdir(char_u *name)
3269{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003270 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003271
3272 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003273 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003274
3275 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3276}
3277
3278/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003279 * return TRUE if "name" is a directory, NOT a symlink to a directory
3280 * return FALSE if "name" is not a directory
3281 * return FALSE for error
3282 */
3283 int
3284mch_isrealdir(char_u *name)
3285{
3286 return mch_isdir(name) && !mch_is_symbolic_link(name);
3287}
3288
3289/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003290 * Create directory "name".
3291 * Return 0 on success, -1 on error.
3292 */
3293 int
3294mch_mkdir(char_u *name)
3295{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003296 WCHAR *p;
3297 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003298
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003299 p = enc_to_utf16(name, NULL);
3300 if (p == NULL)
3301 return -1;
3302 retval = _wmkdir(p);
3303 vim_free(p);
3304 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003305}
3306
3307/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003308 * Delete directory "name".
3309 * Return 0 on success, -1 on error.
3310 */
3311 int
3312mch_rmdir(char_u *name)
3313{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003314 WCHAR *p;
3315 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003316
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003317 p = enc_to_utf16(name, NULL);
3318 if (p == NULL)
3319 return -1;
3320 retval = _wrmdir(p);
3321 vim_free(p);
3322 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003323}
3324
3325/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003326 * Return TRUE if file "fname" has more than one link.
3327 */
3328 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003329mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003330{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003331 BY_HANDLE_FILE_INFORMATION info;
3332
3333 return win32_fileinfo(fname, &info) == FILEINFO_OK
3334 && info.nNumberOfLinks > 1;
3335}
3336
3337/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003338 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003339 */
3340 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003341mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003342{
3343 HANDLE hFind;
3344 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003345 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003346 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003347 WIN32_FIND_DATAW findDataW;
3348
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003349 wn = enc_to_utf16(name, NULL);
3350 if (wn == NULL)
3351 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003352
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003353 hFind = FindFirstFileW(wn, &findDataW);
3354 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003355 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003356 {
3357 fileFlags = findDataW.dwFileAttributes;
3358 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003359 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003360 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003361
3362 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003363 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3364 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003365 res = TRUE;
3366
3367 return res;
3368}
3369
3370/*
3371 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3372 * link.
3373 */
3374 int
3375mch_is_linked(char_u *fname)
3376{
3377 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3378 return TRUE;
3379 return FALSE;
3380}
3381
3382/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003383 * Get the by-handle-file-information for "fname".
3384 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003385 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003386 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3387 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3388 */
3389 int
3390win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3391{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003392 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003393 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003394 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003395
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003396 wn = enc_to_utf16(fname, NULL);
3397 if (wn == NULL)
3398 return FILEINFO_ENC_FAIL;
3399
3400 hFile = CreateFileW(wn, // file name
3401 GENERIC_READ, // access mode
3402 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3403 NULL, // security descriptor
3404 OPEN_EXISTING, // creation disposition
3405 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3406 NULL); // handle to template file
3407 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003408
3409 if (hFile != INVALID_HANDLE_VALUE)
3410 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003411 if (GetFileInformationByHandle(hFile, info) != 0)
3412 res = FILEINFO_OK;
3413 else
3414 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003415 CloseHandle(hFile);
3416 }
3417
Bram Moolenaar03f48552006-02-28 23:52:23 +00003418 return res;
3419}
3420
3421/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003422 * get file attributes for `name'
3423 * -1 : error
3424 * else FILE_ATTRIBUTE_* defined in winnt.h
3425 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003426 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003427win32_getattrs(char_u *name)
3428{
3429 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003430 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003431
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003432 p = enc_to_utf16(name, NULL);
3433 if (p == NULL)
3434 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003435
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003436 attr = GetFileAttributesW(p);
3437 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003438
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003439 return attr;
3440}
3441
3442/*
3443 * set file attributes for `name' to `attrs'
3444 *
3445 * return -1 for failure, 0 otherwise
3446 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003447 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003448win32_setattrs(char_u *name, int attrs)
3449{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003450 int res;
3451 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003452
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003453 p = enc_to_utf16(name, NULL);
3454 if (p == NULL)
3455 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003456
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003457 res = SetFileAttributesW(p, attrs);
3458 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003459
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003460 return res ? 0 : -1;
3461}
3462
3463/*
3464 * Set archive flag for "name".
3465 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003466 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003467win32_set_archive(char_u *name)
3468{
3469 int attrs = win32_getattrs(name);
3470 if (attrs == -1)
3471 return -1;
3472
3473 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3474 return win32_setattrs(name, attrs);
3475}
3476
3477/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003478 * Return TRUE if file or directory "name" is writable (not readonly).
3479 * Strange semantics of Win32: a readonly directory is writable, but you can't
3480 * delete a file. Let's say this means it is writable.
3481 */
3482 int
3483mch_writable(char_u *name)
3484{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003485 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003486
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003487 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3488 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003489}
3490
Bram Moolenaar071d4272004-06-13 20:20:40 +00003491/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003492 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003493 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003494 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3495 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003496 */
3497 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01003498mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003499{
Bram Moolenaar95da1362020-05-30 18:37:55 +02003500 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003501}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003502
3503/*
3504 * Check what "name" is:
3505 * NODE_NORMAL: file or directory (or doesn't exist)
3506 * NODE_WRITABLE: writable device, socket, fifo, etc.
3507 * NODE_OTHER: non-writable things
3508 */
3509 int
3510mch_nodetype(char_u *name)
3511{
3512 HANDLE hFile;
3513 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003514 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003515
Bram Moolenaar0f873732019-12-05 20:28:46 +01003516 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3517 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3518 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00003519 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3520 return NODE_WRITABLE;
3521
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003522 wn = enc_to_utf16(name, NULL);
3523 if (wn == NULL)
3524 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003525
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003526 hFile = CreateFileW(wn, // file name
3527 GENERIC_WRITE, // access mode
3528 0, // share mode
3529 NULL, // security descriptor
3530 OPEN_EXISTING, // creation disposition
3531 0, // file attributes
3532 NULL); // handle to template file
3533 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003534 if (hFile == INVALID_HANDLE_VALUE)
3535 return NODE_NORMAL;
3536
3537 type = GetFileType(hFile);
3538 CloseHandle(hFile);
3539 if (type == FILE_TYPE_CHAR)
3540 return NODE_WRITABLE;
3541 if (type == FILE_TYPE_DISK)
3542 return NODE_NORMAL;
3543 return NODE_OTHER;
3544}
3545
3546#ifdef HAVE_ACL
3547struct my_acl
3548{
3549 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3550 PSID pSidOwner;
3551 PSID pSidGroup;
3552 PACL pDacl;
3553 PACL pSacl;
3554};
3555#endif
3556
3557/*
3558 * Return a pointer to the ACL of file "fname" in allocated memory.
3559 * Return NULL if the ACL is not available for whatever reason.
3560 */
3561 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003562mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003563{
3564#ifndef HAVE_ACL
3565 return (vim_acl_T)NULL;
3566#else
3567 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003568 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003569
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003570 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003571 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003572 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003573 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003574
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003575 wn = enc_to_utf16(fname, NULL);
3576 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003577 {
3578 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003579 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003580 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003581
3582 // Try to retrieve the entire security descriptor.
3583 err = GetNamedSecurityInfoW(
3584 wn, // Abstract filename
3585 SE_FILE_OBJECT, // File Object
3586 OWNER_SECURITY_INFORMATION |
3587 GROUP_SECURITY_INFORMATION |
3588 DACL_SECURITY_INFORMATION |
3589 SACL_SECURITY_INFORMATION,
3590 &p->pSidOwner, // Ownership information.
3591 &p->pSidGroup, // Group membership.
3592 &p->pDacl, // Discretionary information.
3593 &p->pSacl, // For auditing purposes.
3594 &p->pSecurityDescriptor);
3595 if (err == ERROR_ACCESS_DENIED ||
3596 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003597 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003598 // Retrieve only DACL.
3599 (void)GetNamedSecurityInfoW(
3600 wn,
3601 SE_FILE_OBJECT,
3602 DACL_SECURITY_INFORMATION,
3603 NULL,
3604 NULL,
3605 &p->pDacl,
3606 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003607 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003608 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003609 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003610 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003611 mch_free_acl((vim_acl_T)p);
3612 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003613 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003614 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003615 }
3616
3617 return (vim_acl_T)p;
3618#endif
3619}
3620
Bram Moolenaar27515922013-06-29 15:36:26 +02003621#ifdef HAVE_ACL
3622/*
3623 * Check if "acl" contains inherited ACE.
3624 */
3625 static BOOL
3626is_acl_inherited(PACL acl)
3627{
3628 DWORD i;
3629 ACL_SIZE_INFORMATION acl_info;
3630 PACCESS_ALLOWED_ACE ace;
3631
3632 acl_info.AceCount = 0;
3633 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3634 for (i = 0; i < acl_info.AceCount; i++)
3635 {
3636 GetAce(acl, i, (LPVOID *)&ace);
3637 if (ace->Header.AceFlags & INHERITED_ACE)
3638 return TRUE;
3639 }
3640 return FALSE;
3641}
3642#endif
3643
Bram Moolenaar071d4272004-06-13 20:20:40 +00003644/*
3645 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3646 * Errors are ignored.
3647 * This must only be called with "acl" equal to what mch_get_acl() returned.
3648 */
3649 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003650mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003651{
3652#ifdef HAVE_ACL
3653 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003654 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003655 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003656
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003657 if (p == NULL)
3658 return;
3659
3660 wn = enc_to_utf16(fname, NULL);
3661 if (wn == NULL)
3662 return;
3663
3664 // Set security flags
3665 if (p->pSidOwner)
3666 sec_info |= OWNER_SECURITY_INFORMATION;
3667 if (p->pSidGroup)
3668 sec_info |= GROUP_SECURITY_INFORMATION;
3669 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003670 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003671 sec_info |= DACL_SECURITY_INFORMATION;
3672 // Do not inherit its parent's DACL.
3673 // If the DACL is inherited, Cygwin permissions would be changed.
3674 if (!is_acl_inherited(p->pDacl))
3675 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003676 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003677 if (p->pSacl)
3678 sec_info |= SACL_SECURITY_INFORMATION;
3679
3680 (void)SetNamedSecurityInfoW(
3681 wn, // Abstract filename
3682 SE_FILE_OBJECT, // File Object
3683 sec_info,
3684 p->pSidOwner, // Ownership information.
3685 p->pSidGroup, // Group membership.
3686 p->pDacl, // Discretionary information.
3687 p->pSacl // For auditing purposes.
3688 );
3689 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003690#endif
3691}
3692
3693 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003694mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003695{
3696#ifdef HAVE_ACL
3697 struct my_acl *p = (struct my_acl *)acl;
3698
3699 if (p != NULL)
3700 {
3701 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3702 vim_free(p);
3703 }
3704#endif
3705}
3706
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003707#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003708
3709/*
3710 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3711 */
3712 static BOOL WINAPI
3713handler_routine(
3714 DWORD dwCtrlType)
3715{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003716 INPUT_RECORD ir;
3717 DWORD out;
3718
Bram Moolenaar071d4272004-06-13 20:20:40 +00003719 switch (dwCtrlType)
3720 {
3721 case CTRL_C_EVENT:
3722 if (ctrl_c_interrupts)
3723 g_fCtrlCPressed = TRUE;
3724 return TRUE;
3725
3726 case CTRL_BREAK_EVENT:
3727 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003728 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003729 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02003730 ir.EventType = KEY_EVENT;
3731 ir.Event.KeyEvent.bKeyDown = TRUE;
3732 ir.Event.KeyEvent.wRepeatCount = 1;
3733 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3734 ir.Event.KeyEvent.wVirtualScanCode = 0;
3735 ir.Event.KeyEvent.dwControlKeyState = 0;
3736 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3737 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003738 return TRUE;
3739
Bram Moolenaar0f873732019-12-05 20:28:46 +01003740 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00003741 case CTRL_CLOSE_EVENT:
3742 case CTRL_LOGOFF_EVENT:
3743 case CTRL_SHUTDOWN_EVENT:
3744 windgoto((int)Rows - 1, 0);
3745 g_fForceExit = TRUE;
3746
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003747 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003748 (dwCtrlType == CTRL_CLOSE_EVENT
3749 ? _("close")
3750 : dwCtrlType == CTRL_LOGOFF_EVENT
3751 ? _("logoff")
3752 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003753# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00003754 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003755# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003756
Bram Moolenaar0f873732019-12-05 20:28:46 +01003757 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00003758
Bram Moolenaar0f873732019-12-05 20:28:46 +01003759 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00003760
3761 default:
3762 return FALSE;
3763 }
3764}
3765
3766
3767/*
3768 * set the tty in (raw) ? "raw" : "cooked" mode
3769 */
3770 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02003771mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003772{
3773 DWORD cmodein;
3774 DWORD cmodeout;
3775 BOOL bEnableHandler;
3776
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003777# ifdef VIMDLL
3778 if (gui.in_use)
3779 return;
3780# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003781 GetConsoleMode(g_hConIn, &cmodein);
3782 GetConsoleMode(g_hConOut, &cmodeout);
3783 if (tmode == TMODE_RAW)
3784 {
3785 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3786 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003787 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003788 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003789 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003790 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
3791 }
3792 else
3793 {
3794 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
3795 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003796 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003797# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01003798 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
3799 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003800 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003801# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003802 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003803# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003804 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003805 bEnableHandler = TRUE;
3806 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01003807 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00003808 {
3809 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3810 ENABLE_ECHO_INPUT);
3811 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3812 bEnableHandler = FALSE;
3813 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003814 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003815 SetConsoleMode(g_hConOut, cmodeout);
3816 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3817
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003818# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003819 if (fdDump)
3820 {
3821 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3822 tmode == TMODE_RAW ? "raw" :
3823 tmode == TMODE_COOK ? "cooked" : "normal",
3824 cmodein, cmodeout);
3825 fflush(fdDump);
3826 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003827# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003828}
3829
3830
3831/*
3832 * Get the size of the current window in `Rows' and `Columns'
3833 * Return OK when size could be determined, FAIL otherwise.
3834 */
3835 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003836mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003837{
3838 CONSOLE_SCREEN_BUFFER_INFO csbi;
3839
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003840# ifdef VIMDLL
3841 if (gui.in_use)
3842 return OK;
3843# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003844 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3845 {
3846 /*
3847 * For some reason, we are trying to get the screen dimensions
3848 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3849 * variables are really intended to mean the size of Vim screen
3850 * while in termcap mode.
3851 */
3852 Rows = g_cbTermcap.Info.dwSize.Y;
3853 Columns = g_cbTermcap.Info.dwSize.X;
3854 }
3855 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3856 {
3857 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3858 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3859 }
3860 else
3861 {
3862 Rows = 25;
3863 Columns = 80;
3864 }
3865 return OK;
3866}
3867
3868/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003869 * Resize console buffer to 'COORD'
3870 */
3871 static void
3872ResizeConBuf(
3873 HANDLE hConsole,
3874 COORD coordScreen)
3875{
3876 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3877 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003878# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003879 if (fdDump)
3880 {
3881 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3882 GetLastError());
3883 fflush(fdDump);
3884 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003885# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003886 }
3887}
3888
3889/*
3890 * Resize console window size to 'srWindowRect'
3891 */
3892 static void
3893ResizeWindow(
3894 HANDLE hConsole,
3895 SMALL_RECT srWindowRect)
3896{
3897 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
3898 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003899# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003900 if (fdDump)
3901 {
3902 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3903 GetLastError());
3904 fflush(fdDump);
3905 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003906# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003907 }
3908}
3909
3910/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003911 * Set a console window to `xSize' * `ySize'
3912 */
3913 static void
3914ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003915 HANDLE hConsole,
3916 int xSize,
3917 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003918{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003919 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
3920 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003921 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003922 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02003923 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003924
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003925# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003926 if (fdDump)
3927 {
3928 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3929 fflush(fdDump);
3930 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003931# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003932
Bram Moolenaar0f873732019-12-05 20:28:46 +01003933 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00003934 coordScreen = GetLargestConsoleWindowSize(hConsole);
3935
Bram Moolenaar0f873732019-12-05 20:28:46 +01003936 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00003937 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3938 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3939 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3940
3941 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3942 {
3943 int sx, sy;
3944
3945 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3946 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3947 if (sy < ySize || sx < xSize)
3948 {
3949 /*
3950 * Increasing number of lines/columns, do buffer first.
3951 * Use the maximal size in x and y direction.
3952 */
3953 if (sy < ySize)
3954 coordScreen.Y = ySize;
3955 else
3956 coordScreen.Y = sy;
3957 if (sx < xSize)
3958 coordScreen.X = xSize;
3959 else
3960 coordScreen.X = sx;
3961 SetConsoleScreenBufferSize(hConsole, coordScreen);
3962 }
3963 }
3964
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003965 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003966 coordScreen.X = xSize;
3967 coordScreen.Y = ySize;
3968
Bram Moolenaar2551c032018-08-23 22:38:31 +02003969 // In the new console call API, only the first time in reverse order
3970 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003971 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003972 ResizeWindow(hConsole, srWindowRect);
3973 ResizeConBuf(hConsole, coordScreen);
3974 }
3975 else
3976 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003977 // Workaround for a Windows 10 bug
3978 cursor.X = srWindowRect.Left;
3979 cursor.Y = srWindowRect.Top;
3980 SetConsoleCursorPosition(hConsole, cursor);
3981
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003982 ResizeConBuf(hConsole, coordScreen);
3983 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02003984 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003985 }
3986}
3987
3988
3989/*
3990 * Set the console window to `Rows' * `Columns'
3991 */
3992 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003993mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003994{
3995 COORD coordScreen;
3996
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003997# ifdef VIMDLL
3998 if (gui.in_use)
3999 return;
4000# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004001 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004002 if (suppress_winsize != 0)
4003 {
4004 suppress_winsize = 2;
4005 return;
4006 }
4007
4008 if (term_console)
4009 {
4010 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4011
Bram Moolenaar0f873732019-12-05 20:28:46 +01004012 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004013 if (Rows > coordScreen.Y)
4014 Rows = coordScreen.Y;
4015 if (Columns > coordScreen.X)
4016 Columns = coordScreen.X;
4017
4018 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4019 }
4020}
4021
4022/*
4023 * Rows and/or Columns has changed.
4024 */
4025 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004026mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004027{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004028# ifdef VIMDLL
4029 if (gui.in_use)
4030 return;
4031# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004032 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4033}
4034
4035
4036/*
4037 * Called when started up, to set the winsize that was delayed.
4038 */
4039 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004040mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004041{
4042 if (suppress_winsize == 2)
4043 {
4044 suppress_winsize = 0;
4045 mch_set_shellsize();
4046 shell_resized();
4047 }
4048 suppress_winsize = 0;
4049}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004050#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004051
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004052 static BOOL
4053vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004054 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004055 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004056 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004057 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004058 PROCESS_INFORMATION *pi,
4059 LPVOID *env,
4060 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004061{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004062 BOOL ret = FALSE;
4063 WCHAR *wcmd, *wcwd = NULL;
4064
4065 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4066 if (wcmd == NULL)
4067 return FALSE;
4068 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004069 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004070 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4071 if (wcwd == NULL)
4072 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004073 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004074
4075 ret = CreateProcessW(
4076 NULL, // Executable name
4077 wcmd, // Command to execute
4078 NULL, // Process security attributes
4079 NULL, // Thread security attributes
4080 inherit_handles, // Inherit handles
4081 flags, // Creation flags
4082 env, // Environment
4083 wcwd, // Current directory
4084 (LPSTARTUPINFOW)si, // Startup information
4085 pi); // Process information
4086theend:
4087 vim_free(wcmd);
4088 vim_free(wcwd);
4089 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004090}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004091
4092
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004093 static HINSTANCE
4094vim_shell_execute(
4095 char *cmd,
4096 INT n_show_cmd)
4097{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004098 HINSTANCE ret;
4099 WCHAR *wcmd;
4100
4101 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4102 if (wcmd == NULL)
4103 return (HINSTANCE) 0;
4104
4105 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4106 vim_free(wcmd);
4107 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004108}
4109
4110
Bram Moolenaar4f974752019-02-17 17:44:42 +01004111#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004112
4113/*
4114 * Specialised version of system() for Win32 GUI mode.
4115 * This version proceeds as follows:
4116 * 1. Create a console window for use by the subprocess
4117 * 2. Run the subprocess (it gets the allocated console by default)
4118 * 3. Wait for the subprocess to terminate and get its exit code
4119 * 4. Prompt the user to press a key to close the console window
4120 */
4121 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004122mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004123{
4124 STARTUPINFO si;
4125 PROCESS_INFORMATION pi;
4126 DWORD ret = 0;
4127 HWND hwnd = GetFocus();
4128
4129 si.cb = sizeof(si);
4130 si.lpReserved = NULL;
4131 si.lpDesktop = NULL;
4132 si.lpTitle = NULL;
4133 si.dwFlags = STARTF_USESHOWWINDOW;
4134 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004135 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004136 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004137 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004138 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004139 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004140 else
4141 si.wShowWindow = SW_SHOWNORMAL;
4142 si.cbReserved2 = 0;
4143 si.lpReserved2 = NULL;
4144
Bram Moolenaar0f873732019-12-05 20:28:46 +01004145 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004146 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004147 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4148 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004149
Bram Moolenaar0f873732019-12-05 20:28:46 +01004150 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004151 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004152# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004153 int delay = 1;
4154
Bram Moolenaar0f873732019-12-05 20:28:46 +01004155 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004156 for (;;)
4157 {
4158 MSG msg;
4159
K.Takatab7057bd2022-01-21 11:37:07 +00004160 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004161 {
4162 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004163 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004164 delay = 1;
4165 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004166 }
4167 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4168 break;
4169
Bram Moolenaar0f873732019-12-05 20:28:46 +01004170 // We start waiting for a very short time and then increase it, so
4171 // that we respond quickly when the process is quick, and don't
4172 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004173 if (delay < 50)
4174 delay += 10;
4175 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004176# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004177 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004178# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004179
Bram Moolenaar0f873732019-12-05 20:28:46 +01004180 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004181 GetExitCodeProcess(pi.hProcess, &ret);
4182 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004183
Bram Moolenaar0f873732019-12-05 20:28:46 +01004184 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004185 CloseHandle(pi.hThread);
4186 CloseHandle(pi.hProcess);
4187
Bram Moolenaar0f873732019-12-05 20:28:46 +01004188 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004189 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4190
4191 return ret;
4192}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004193
4194/*
4195 * Thread launched by the gui to send the current buffer data to the
4196 * process. This way avoid to hang up vim totally if the children
4197 * process take a long time to process the lines.
4198 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004199 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004200sub_process_writer(LPVOID param)
4201{
4202 HANDLE g_hChildStd_IN_Wr = param;
4203 linenr_T lnum = curbuf->b_op_start.lnum;
4204 DWORD len = 0;
4205 DWORD l;
4206 char_u *lp = ml_get(lnum);
4207 char_u *s;
4208 int written = 0;
4209
4210 for (;;)
4211 {
4212 l = (DWORD)STRLEN(lp + written);
4213 if (l == 0)
4214 len = 0;
4215 else if (lp[written] == NL)
4216 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004217 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004218 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4219 }
4220 else
4221 {
4222 s = vim_strchr(lp + written, NL);
4223 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4224 s == NULL ? l : (DWORD)(s - (lp + written)),
4225 &len, NULL);
4226 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004227 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004228 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004229 // Finished a line, add a NL, unless this line should not have
4230 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004231 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004232 || (!curbuf->b_p_bin
4233 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004234 || (lnum != curbuf->b_no_eol_lnum
4235 && (lnum != curbuf->b_ml.ml_line_count
4236 || curbuf->b_p_eol)))
4237 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004238 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4239 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004240 }
4241
4242 ++lnum;
4243 if (lnum > curbuf->b_op_end.lnum)
4244 break;
4245
4246 lp = ml_get(lnum);
4247 written = 0;
4248 }
4249 else if (len > 0)
4250 written += len;
4251 }
4252
Bram Moolenaar0f873732019-12-05 20:28:46 +01004253 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004254 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004255 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004256}
4257
4258
Bram Moolenaar0f873732019-12-05 20:28:46 +01004259# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004260
4261/*
4262 * This function read from the children's stdout and write the
4263 * data on screen or in the buffer accordingly.
4264 */
4265 static void
4266dump_pipe(int options,
4267 HANDLE g_hChildStd_OUT_Rd,
4268 garray_T *ga,
4269 char_u buffer[],
4270 DWORD *buffer_off)
4271{
4272 DWORD availableBytes = 0;
4273 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004274 int ret;
4275 DWORD len;
4276 DWORD toRead;
4277 int repeatCount;
4278
Bram Moolenaar0f873732019-12-05 20:28:46 +01004279 // we query the pipe to see if there is any data to read
4280 // to avoid to perform a blocking read
4281 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4282 NULL, // optional buffer
4283 0, // buffer size
4284 NULL, // number of read bytes
4285 &availableBytes, // available bytes total
4286 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004287
4288 repeatCount = 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004289 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004290 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004291 {
4292 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004293 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004294 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004295 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004296
Bram Moolenaar0f873732019-12-05 20:28:46 +01004297 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004298 if (len == 0)
4299 break;
4300
4301 availableBytes -= len;
4302
4303 if (options & SHELL_READ)
4304 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004305 // Do NUL -> NL translation, append NL separated
4306 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004307 for (i = 0; i < len; ++i)
4308 {
4309 if (buffer[i] == NL)
4310 append_ga_line(ga);
4311 else if (buffer[i] == NUL)
4312 ga_append(ga, NL);
4313 else
4314 ga_append(ga, buffer[i]);
4315 }
4316 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004317 else if (has_mbyte)
4318 {
4319 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004320 int c;
4321 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004322
4323 len += *buffer_off;
4324 buffer[len] = NUL;
4325
Bram Moolenaar0f873732019-12-05 20:28:46 +01004326 // Check if the last character in buffer[] is
4327 // incomplete, keep these bytes for the next
4328 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004329 for (p = buffer; p < buffer + len; p += l)
4330 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004331 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004332 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004333 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004334 else if (MB_BYTE2LEN(*p) != l)
4335 break;
4336 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004337 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004338 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004339 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004340 if (len >= 12)
4341 ++p;
4342 else
4343 {
4344 *buffer_off = len;
4345 return;
4346 }
4347 }
4348 c = *p;
4349 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004350 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004351 if (p < buffer + len)
4352 {
4353 *p = c;
4354 *buffer_off = (DWORD)((buffer + len) - p);
4355 mch_memmove(buffer, p, *buffer_off);
4356 return;
4357 }
4358 *buffer_off = 0;
4359 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004360 else
4361 {
4362 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004363 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004364 }
4365
4366 windgoto(msg_row, msg_col);
4367 cursor_on();
4368 out_flush();
4369 }
4370}
4371
4372/*
4373 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4374 * for communication and doesn't open any new window.
4375 */
4376 static int
4377mch_system_piped(char *cmd, int options)
4378{
4379 STARTUPINFO si;
4380 PROCESS_INFORMATION pi;
4381 DWORD ret = 0;
4382
4383 HANDLE g_hChildStd_IN_Rd = NULL;
4384 HANDLE g_hChildStd_IN_Wr = NULL;
4385 HANDLE g_hChildStd_OUT_Rd = NULL;
4386 HANDLE g_hChildStd_OUT_Wr = NULL;
4387
Bram Moolenaar0f873732019-12-05 20:28:46 +01004388 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004389 DWORD len;
4390
Bram Moolenaar0f873732019-12-05 20:28:46 +01004391 // buffer used to receive keys
4392 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4393 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004394
4395 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004396 int noread_cnt = 0;
4397 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004398 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004399 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004400 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004401
4402 SECURITY_ATTRIBUTES saAttr;
4403
Bram Moolenaar0f873732019-12-05 20:28:46 +01004404 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004405 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4406 saAttr.bInheritHandle = TRUE;
4407 saAttr.lpSecurityDescriptor = NULL;
4408
4409 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004410 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004411 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004412 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004413 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004414 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004415 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004416 {
4417 CloseHandle(g_hChildStd_IN_Rd);
4418 CloseHandle(g_hChildStd_IN_Wr);
4419 CloseHandle(g_hChildStd_OUT_Rd);
4420 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004421 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004422 }
4423
4424 si.cb = sizeof(si);
4425 si.lpReserved = NULL;
4426 si.lpDesktop = NULL;
4427 si.lpTitle = NULL;
4428 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4429
Bram Moolenaar0f873732019-12-05 20:28:46 +01004430 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004431 si.hStdError = g_hChildStd_OUT_Wr;
4432 si.hStdOutput = g_hChildStd_OUT_Wr;
4433 si.hStdInput = g_hChildStd_IN_Rd;
4434 si.wShowWindow = SW_HIDE;
4435 si.cbReserved2 = 0;
4436 si.lpReserved2 = NULL;
4437
4438 if (options & SHELL_READ)
4439 ga_init2(&ga, 1, BUFLEN);
4440
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004441 if (cmd != NULL)
4442 {
4443 p = (char *)vim_strsave((char_u *)cmd);
4444 if (p != NULL)
4445 unescape_shellxquote((char_u *)p, p_sxe);
4446 else
4447 p = cmd;
4448 }
4449
Bram Moolenaar0f873732019-12-05 20:28:46 +01004450 // Now, run the command.
4451 // About "Inherit handles" being TRUE: this command can be litigious,
4452 // handle inheritance was deactivated for pending temp file, but, if we
4453 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004454 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4455 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004456
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004457 if (p != cmd)
4458 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004459
Bram Moolenaar0f873732019-12-05 20:28:46 +01004460 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004461 CloseHandle(g_hChildStd_IN_Rd);
4462 CloseHandle(g_hChildStd_OUT_Wr);
4463
4464 if (options & SHELL_WRITE)
4465 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004466 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004467 _beginthreadex(NULL, // security attributes
4468 0, // default stack size
4469 sub_process_writer, // function to be executed
4470 g_hChildStd_IN_Wr, // parameter
4471 0, // creation flag, start immediately
4472 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004473 CloseHandle(thread);
4474 g_hChildStd_IN_Wr = NULL;
4475 }
4476
Bram Moolenaar0f873732019-12-05 20:28:46 +01004477 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004478 for (;;)
4479 {
4480 MSG msg;
4481
K.Takatab7057bd2022-01-21 11:37:07 +00004482 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004483 {
4484 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004485 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004486 }
4487
Bram Moolenaar0f873732019-12-05 20:28:46 +01004488 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004489 if ((options & (SHELL_READ|SHELL_WRITE))
4490# ifdef FEAT_GUI
4491 || gui.in_use
4492# endif
4493 )
4494 {
4495 len = 0;
4496 if (!(options & SHELL_EXPAND)
4497 && ((options &
4498 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4499 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4500# ifdef FEAT_GUI
4501 || gui.in_use
4502# endif
4503 )
4504 && (ta_len > 0 || noread_cnt > 4))
4505 {
4506 if (ta_len == 0)
4507 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004508 // Get extra characters when we don't have any. Reset the
4509 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004510 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004511 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4512 }
4513 if (ta_len > 0 || len > 0)
4514 {
4515 /*
4516 * For pipes: Check for CTRL-C: send interrupt signal to
4517 * child. Check for CTRL-D: EOF, close pipe to child.
4518 */
4519 if (len == 1 && cmd != NULL)
4520 {
4521 if (ta_buf[ta_len] == Ctrl_C)
4522 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004523 // Learn what exit code is expected, for
4524 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004525 TerminateProcess(pi.hProcess, 9);
4526 }
4527 if (ta_buf[ta_len] == Ctrl_D)
4528 {
4529 CloseHandle(g_hChildStd_IN_Wr);
4530 g_hChildStd_IN_Wr = NULL;
4531 }
4532 }
4533
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01004534 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004535
4536 /*
4537 * For pipes: echo the typed characters. For a pty this
4538 * does not seem to work.
4539 */
4540 for (i = ta_len; i < ta_len + len; ++i)
4541 {
4542 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4543 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004544 else if (has_mbyte)
4545 {
4546 int l = (*mb_ptr2len)(ta_buf + i);
4547
4548 msg_outtrans_len(ta_buf + i, l);
4549 i += l - 1;
4550 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004551 else
4552 msg_outtrans_len(ta_buf + i, 1);
4553 }
4554 windgoto(msg_row, msg_col);
4555 out_flush();
4556
4557 ta_len += len;
4558
4559 /*
4560 * Write the characters to the child, unless EOF has been
4561 * typed for pipes. Write one character at a time, to
4562 * avoid losing too much typeahead. When writing buffer
4563 * lines, drop the typed characters (only check for
4564 * CTRL-C).
4565 */
4566 if (options & SHELL_WRITE)
4567 ta_len = 0;
4568 else if (g_hChildStd_IN_Wr != NULL)
4569 {
4570 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4571 1, &len, NULL);
4572 // if we are typing in, we want to keep things reactive
4573 delay = 1;
4574 if (len > 0)
4575 {
4576 ta_len -= len;
4577 mch_memmove(ta_buf, ta_buf + len, ta_len);
4578 }
4579 }
4580 }
4581 }
4582 }
4583
4584 if (ta_len)
4585 ui_inchar_undo(ta_buf, ta_len);
4586
4587 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4588 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004589 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004590 break;
4591 }
4592
4593 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004594 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004595
Bram Moolenaar0f873732019-12-05 20:28:46 +01004596 // We start waiting for a very short time and then increase it, so
4597 // that we respond quickly when the process is quick, and don't
4598 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004599 if (delay < 50)
4600 delay += 10;
4601 }
4602
Bram Moolenaar0f873732019-12-05 20:28:46 +01004603 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004604 CloseHandle(g_hChildStd_OUT_Rd);
4605 if (g_hChildStd_IN_Wr != NULL)
4606 CloseHandle(g_hChildStd_IN_Wr);
4607
4608 WaitForSingleObject(pi.hProcess, INFINITE);
4609
Bram Moolenaar0f873732019-12-05 20:28:46 +01004610 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004611 GetExitCodeProcess(pi.hProcess, &ret);
4612
4613 if (options & SHELL_READ)
4614 {
4615 if (ga.ga_len > 0)
4616 {
4617 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01004618 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004619 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4620 }
4621 else
4622 curbuf->b_no_eol_lnum = 0;
4623 ga_clear(&ga);
4624 }
4625
Bram Moolenaar0f873732019-12-05 20:28:46 +01004626 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004627 CloseHandle(pi.hThread);
4628 CloseHandle(pi.hProcess);
4629
4630 return ret;
4631}
4632
4633 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004634mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004635{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004636 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004637 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004638 return mch_system_piped(cmd, options);
4639 else
4640 return mch_system_classic(cmd, options);
4641}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004642#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004643
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004644#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004645 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02004646mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004647{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004648 int ret;
4649 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004650 char_u *buf;
4651 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004652
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004653 // If the command starts and ends with double quotes, enclose the command
4654 // in parentheses.
4655 len = STRLEN(cmd);
4656 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
4657 {
4658 len += 3;
4659 buf = alloc(len);
4660 if (buf == NULL)
4661 return -1;
4662 vim_snprintf((char *)buf, len, "(%s)", cmd);
4663 wcmd = enc_to_utf16(buf, NULL);
4664 free(buf);
4665 }
4666 else
4667 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4668
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004669 if (wcmd == NULL)
4670 return -1;
4671
4672 ret = _wsystem(wcmd);
4673 vim_free(wcmd);
4674 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004675}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004676
4677#endif
4678
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004679 static int
4680mch_system(char *cmd, int options)
4681{
4682#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004683 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004684 return mch_system_g(cmd, options);
4685 else
4686 return mch_system_c(cmd, options);
4687#elif defined(FEAT_GUI_MSWIN)
4688 return mch_system_g(cmd, options);
4689#else
4690 return mch_system_c(cmd, options);
4691#endif
4692}
4693
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004694#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4695/*
4696 * Use a terminal window to run a shell command in.
4697 */
4698 static int
4699mch_call_shell_terminal(
4700 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004701 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004702{
4703 jobopt_T opt;
4704 char_u *newcmd = NULL;
4705 typval_T argvar[2];
4706 long_u cmdlen;
4707 int retval = -1;
4708 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004709 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004710 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004711 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004712
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004713 if (cmd == NULL)
4714 cmdlen = STRLEN(p_sh) + 1;
4715 else
4716 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004717 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004718 if (newcmd == NULL)
4719 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004720 if (cmd == NULL)
4721 {
4722 STRCPY(newcmd, p_sh);
4723 ch_log(NULL, "starting terminal to run a shell");
4724 }
4725 else
4726 {
4727 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4728 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4729 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004730
4731 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004732
4733 argvar[0].v_type = VAR_STRING;
4734 argvar[0].vval.v_string = newcmd;
4735 argvar[1].v_type = VAR_UNKNOWN;
4736 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004737 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004738 {
4739 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004740 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004741 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004742
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004743 job = term_getjob(buf->b_term);
4744 ++job->jv_refcount;
4745
Bram Moolenaar0f873732019-12-05 20:28:46 +01004746 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004747 aucmd_prepbuf(&aco, buf);
4748
4749 clear_oparg(&oa);
4750 while (term_use_loop())
4751 {
4752 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4753 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004754 // If terminal_loop() returns OK we got a key that is handled
4755 // in Normal model. We don't do redrawing anyway.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004756 if (terminal_loop(TRUE) == OK)
4757 normal_cmd(&oa, TRUE);
4758 }
4759 else
4760 normal_cmd(&oa, TRUE);
4761 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004762 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004763 ch_log(NULL, "system command finished");
4764
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004765 job_unref(job);
4766
Bram Moolenaar0f873732019-12-05 20:28:46 +01004767 // restore curwin/curbuf and a few other things
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004768 aucmd_restbuf(&aco);
4769
4770 wait_return(TRUE);
4771 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4772
4773 vim_free(newcmd);
4774 return retval;
4775}
4776#endif
4777
Bram Moolenaar071d4272004-06-13 20:20:40 +00004778/*
4779 * Either execute a command by calling the shell or start a new shell
4780 */
4781 int
4782mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004783 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004784 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00004785{
4786 int x = 0;
4787 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004788 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004789
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01004790#ifdef FEAT_JOB_CHANNEL
4791 ch_log(NULL, "executing shell command: %s", cmd);
4792#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004793 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02004794 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004795 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004796 if (cmd == NULL)
4797 wcscat(szShellTitle, L" :sh");
4798 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004799 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004800 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004801
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004802 if (wn != NULL)
4803 {
4804 wcscat(szShellTitle, L" - !");
4805 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02004806 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004807 wcscat(szShellTitle, wn);
4808 SetConsoleTitleW(szShellTitle);
4809 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004810 }
4811 }
4812 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004813
4814 out_flush();
4815
4816#ifdef MCH_WRITE_DUMP
4817 if (fdDump)
4818 {
4819 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4820 fflush(fdDump);
4821 }
4822#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004823#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004824 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004825 if (
4826# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004827 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004828# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004829 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004830 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4831 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004832 char_u *cmdbase = cmd;
4833
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004834 if (cmdbase != NULL)
4835 // Skip a leading quote and (.
4836 while (*cmdbase == '"' || *cmdbase == '(')
4837 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004838
4839 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01004840 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
4841 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004842 {
4843 // Use a terminal window to run the command in.
4844 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004845 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004846 return x;
4847 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004848 }
4849#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004850
4851 /*
4852 * Catch all deadly signals while running the external command, because a
4853 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4854 */
4855 signal(SIGINT, SIG_IGN);
4856#if defined(__GNUC__) && !defined(__MINGW32__)
4857 signal(SIGKILL, SIG_IGN);
4858#else
4859 signal(SIGBREAK, SIG_IGN);
4860#endif
4861 signal(SIGILL, SIG_IGN);
4862 signal(SIGFPE, SIG_IGN);
4863 signal(SIGSEGV, SIG_IGN);
4864 signal(SIGTERM, SIG_IGN);
4865 signal(SIGABRT, SIG_IGN);
4866
4867 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004868 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00004869
4870 if (cmd == NULL)
4871 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004872 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004873 }
4874 else
4875 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004876 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004877 char_u *newcmd = NULL;
4878 char_u *cmdbase = cmd;
4879 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004880
Bram Moolenaar0f873732019-12-05 20:28:46 +01004881 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004882 if (*cmdbase == '"' )
4883 ++cmdbase;
4884 if (*cmdbase == '(')
4885 ++cmdbase;
4886
Bram Moolenaar1c465442017-03-12 20:10:05 +01004887 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004888 {
4889 STARTUPINFO si;
4890 PROCESS_INFORMATION pi;
4891 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004892 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004893 char_u *p;
4894
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004895 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004896 si.cb = sizeof(si);
4897 si.lpReserved = NULL;
4898 si.lpDesktop = NULL;
4899 si.lpTitle = NULL;
4900 si.dwFlags = 0;
4901 si.cbReserved2 = 0;
4902 si.lpReserved2 = NULL;
4903
4904 cmdbase = skipwhite(cmdbase + 5);
4905 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004906 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004907 {
4908 cmdbase = skipwhite(cmdbase + 4);
4909 si.dwFlags = STARTF_USESHOWWINDOW;
4910 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004911 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004912 }
4913 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004914 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004915 {
4916 cmdbase = skipwhite(cmdbase + 2);
4917 flags = CREATE_NO_WINDOW;
4918 si.dwFlags = STARTF_USESTDHANDLES;
4919 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004920 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004921 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004922 NULL, // Security att.
4923 OPEN_EXISTING, // Open flags
4924 FILE_ATTRIBUTE_NORMAL, // File att.
4925 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004926 si.hStdOutput = si.hStdInput;
4927 si.hStdError = si.hStdInput;
4928 }
4929
Bram Moolenaar0f873732019-12-05 20:28:46 +01004930 // Remove a trailing ", ) and )" if they have a match
4931 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004932 if (cmdbase > cmd)
4933 {
4934 p = cmdbase + STRLEN(cmdbase);
4935 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4936 *--p = NUL;
4937 if (p > cmdbase && p[-1] == ')'
4938 && (*cmd =='(' || cmd[1] == '('))
4939 *--p = NUL;
4940 }
4941
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004942 newcmd = cmdbase;
4943 unescape_shellxquote(cmdbase, p_sxe);
4944
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004945 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004946 * If creating new console, arguments are passed to the
4947 * 'cmd.exe' as-is. If it's not, arguments are not treated
4948 * correctly for current 'cmd.exe'. So unescape characters in
4949 * shellxescape except '|' for avoiding to be treated as
4950 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004951 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004952 if (flags != CREATE_NEW_CONSOLE)
4953 {
4954 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004955 char_u *cmd_shell = mch_getenv("COMSPEC");
4956
4957 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004958 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004959
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004960 subcmd = vim_strsave_escaped_ext(cmdbase,
4961 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004962 if (subcmd != NULL)
4963 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004964 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004965 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004966 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004967 if (newcmd != NULL)
4968 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004969 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004970 else
4971 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004972 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004973 }
4974 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004975
4976 /*
4977 * Now, start the command as a process, so that it doesn't
4978 * inherit our handles which causes unpleasant dangling swap
4979 * files if we exit before the spawned process
4980 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004981 if (vim_create_process((char *)newcmd, FALSE, flags,
4982 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004983 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004984 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4985 > (HINSTANCE)32)
4986 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004987 else
4988 {
4989 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01004990#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004991# ifdef VIMDLL
4992 if (gui.in_use)
4993# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00004994 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004995#endif
4996 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004997
4998 if (newcmd != cmdbase)
4999 vim_free(newcmd);
5000
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005001 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005002 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005003 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005004 CloseHandle(si.hStdInput);
5005 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005006 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005007 CloseHandle(pi.hThread);
5008 CloseHandle(pi.hProcess);
5009 }
5010 else
5011 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005012 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005013#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005014 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005015 (!s_dont_use_vimrun && p_stmp ?
5016 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5017 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005018#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005019 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005020
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005021 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005022 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005023 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005024#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005025 if (
5026# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005027 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005028# endif
5029 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005030 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005031 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5032 "External commands will not pause after completion.\n"
5033 "See :help win32-vimrun for more information.");
5034 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005035 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5036 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005037
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005038 if (wmsg != NULL && wtitle != NULL)
5039 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5040 vim_free(wmsg);
5041 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005042 need_vimrun_warning = FALSE;
5043 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005044 if (
5045# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005046 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005047# endif
5048 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005049 // Use vimrun to execute the command. It opens a console
5050 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005051 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005052 vimrun_path,
5053 (msg_silent != 0 || (options & SHELL_DOOUT))
5054 ? "-s " : "",
5055 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005056 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005057# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005058 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005059# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005060 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005061 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005062 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5063 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005064 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005065#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005066 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005067 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005068 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005069 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005070 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005071 }
5072 }
5073
5074 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005075 {
5076 // The shell may have messed with the mode, always set it.
5077 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005078 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005079 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005080
Bram Moolenaar0f873732019-12-05 20:28:46 +01005081 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005082 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005083#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005084 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005085 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005086#endif
5087 )
5088 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005089 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005090 msg_putchar('\n');
5091 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005092 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005093
5094 signal(SIGINT, SIG_DFL);
5095#if defined(__GNUC__) && !defined(__MINGW32__)
5096 signal(SIGKILL, SIG_DFL);
5097#else
5098 signal(SIGBREAK, SIG_DFL);
5099#endif
5100 signal(SIGILL, SIG_DFL);
5101 signal(SIGFPE, SIG_DFL);
5102 signal(SIGSEGV, SIG_DFL);
5103 signal(SIGTERM, SIG_DFL);
5104 signal(SIGABRT, SIG_DFL);
5105
5106 return x;
5107}
5108
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005109#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005110 static HANDLE
5111job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005112 char_u *fname,
5113 DWORD dwDesiredAccess,
5114 DWORD dwShareMode,
5115 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5116 DWORD dwCreationDisposition,
5117 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005118{
5119 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005120 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005121
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005122 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005123 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005124 return INVALID_HANDLE_VALUE;
5125
5126 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5127 lpSecurityAttributes, dwCreationDisposition,
5128 dwFlagsAndAttributes, NULL);
5129 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005130 return h;
5131}
5132
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005133/*
5134 * Turn the dictionary "env" into a NUL separated list that can be used as the
5135 * environment argument of vim_create_process().
5136 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005137 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005138win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005139{
5140 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005141 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005142 LPVOID base = GetEnvironmentStringsW();
5143
Bram Moolenaar0f873732019-12-05 20:28:46 +01005144 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005145 if (ga_grow(gap, 1) == FAIL)
5146 return;
5147
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005148 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005149 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005150 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005151 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005152 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005153 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005154 typval_T *item = &dict_lookup(hi)->di_tv;
5155 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005156 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005157 --todo;
5158 if (wkey != NULL && wval != NULL)
5159 {
5160 size_t n;
5161 size_t lkey = wcslen(wkey);
5162 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005163
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005164 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5165 continue;
5166 for (n = 0; n < lkey; n++)
5167 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5168 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5169 for (n = 0; n < lval; n++)
5170 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5171 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5172 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005173 vim_free(wkey);
5174 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005175 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005176 }
5177 }
5178
Bram Moolenaar355757a2020-02-10 22:06:32 +01005179 if (base)
5180 {
5181 WCHAR *p = (WCHAR*) base;
5182
5183 // for last \0
5184 if (ga_grow(gap, 1) == FAIL)
5185 return;
5186
5187 while (*p != 0 || *(p + 1) != 0)
5188 {
5189 if (ga_grow(gap, 1) == OK)
5190 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5191 p++;
5192 }
5193 FreeEnvironmentStrings(base);
5194 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5195 }
5196
Bram Moolenaar493359e2018-06-12 20:25:52 +02005197# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005198 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005199# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005200 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005201 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005202# endif
5203# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005204 char_u *version = get_vim_var_str(VV_VERSION);
5205 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005206# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005207 // size of "VIM_SERVERNAME=" and value,
5208 // plus "VIM_TERMINAL=" and value,
5209 // plus two terminating NULs
5210 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005211# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005212 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005213# endif
5214# ifdef FEAT_TERMINAL
5215 + 13 + version_len + 2
5216# endif
5217 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005218
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005219 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005220 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005221# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005222 for (n = 0; n < 15; n++)
5223 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5224 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005225 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005226 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5227 (WCHAR)servername[n];
5228 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005229# endif
5230# ifdef FEAT_TERMINAL
5231 if (is_terminal)
5232 {
5233 for (n = 0; n < 13; n++)
5234 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5235 (WCHAR)"VIM_TERMINAL="[n];
5236 for (n = 0; n < version_len; n++)
5237 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5238 (WCHAR)version[n];
5239 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5240 }
5241# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005242 }
5243 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005244# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005245}
5246
Bram Moolenaarb091f302019-01-19 14:37:00 +01005247/*
5248 * Create a pair of pipes.
5249 * Return TRUE for success, FALSE for failure.
5250 */
5251 static BOOL
5252create_pipe_pair(HANDLE handles[2])
5253{
5254 static LONG s;
5255 char name[64];
5256 SECURITY_ATTRIBUTES sa;
5257
5258 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5259 GetCurrentProcessId(),
5260 InterlockedIncrement(&s));
5261
5262 // Create named pipe. Max size of named pipe is 65535.
5263 handles[1] = CreateNamedPipe(
5264 name,
5265 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5266 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005267 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005268
5269 if (handles[1] == INVALID_HANDLE_VALUE)
5270 return FALSE;
5271
5272 sa.nLength = sizeof(sa);
5273 sa.bInheritHandle = TRUE;
5274 sa.lpSecurityDescriptor = NULL;
5275
5276 handles[0] = CreateFile(name,
5277 FILE_GENERIC_READ,
5278 FILE_SHARE_READ, &sa,
5279 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5280
5281 if (handles[0] == INVALID_HANDLE_VALUE)
5282 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005283 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005284 return FALSE;
5285 }
5286
5287 return TRUE;
5288}
5289
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005290 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005291mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005292{
5293 STARTUPINFO si;
5294 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005295 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005296 SECURITY_ATTRIBUTES saAttr;
5297 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005298 HANDLE ifd[2];
5299 HANDLE ofd[2];
5300 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005301 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005302
5303 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5304 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5305 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5306 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5307 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5308 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5309 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5310
5311 if (use_out_for_err && use_null_for_out)
5312 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005313
5314 ifd[0] = INVALID_HANDLE_VALUE;
5315 ifd[1] = INVALID_HANDLE_VALUE;
5316 ofd[0] = INVALID_HANDLE_VALUE;
5317 ofd[1] = INVALID_HANDLE_VALUE;
5318 efd[0] = INVALID_HANDLE_VALUE;
5319 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005320 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005321
Bram Moolenaar14207f42016-10-27 21:13:10 +02005322 jo = CreateJobObject(NULL, NULL);
5323 if (jo == NULL)
5324 {
5325 job->jv_status = JOB_FAILED;
5326 goto failed;
5327 }
5328
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005329 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005330 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005331
Bram Moolenaar76467df2016-02-12 19:30:26 +01005332 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005333 ZeroMemory(&si, sizeof(si));
5334 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005335 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005336 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005337
Bram Moolenaard8070362016-02-15 21:56:54 +01005338 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5339 saAttr.bInheritHandle = TRUE;
5340 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005341
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005342 if (use_file_for_in)
5343 {
5344 char_u *fname = options->jo_io_name[PART_IN];
5345
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005346 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5347 FILE_SHARE_READ | FILE_SHARE_WRITE,
5348 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5349 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005350 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005351 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005352 goto failed;
5353 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005354 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005355 else if (!use_null_for_in
5356 && (!create_pipe_pair(ifd)
5357 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005358 goto failed;
5359
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005360 if (use_file_for_out)
5361 {
5362 char_u *fname = options->jo_io_name[PART_OUT];
5363
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005364 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5365 FILE_SHARE_READ | FILE_SHARE_WRITE,
5366 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5367 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005368 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005369 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005370 goto failed;
5371 }
5372 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005373 else if (!use_null_for_out &&
5374 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005375 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005376 goto failed;
5377
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005378 if (use_file_for_err)
5379 {
5380 char_u *fname = options->jo_io_name[PART_ERR];
5381
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005382 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5383 FILE_SHARE_READ | FILE_SHARE_WRITE,
5384 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5385 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005386 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005387 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005388 goto failed;
5389 }
5390 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005391 else if (!use_out_for_err && !use_null_for_err &&
5392 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005393 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005394 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005395
Bram Moolenaard8070362016-02-15 21:56:54 +01005396 si.dwFlags |= STARTF_USESTDHANDLES;
5397 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005398 si.hStdOutput = ofd[1];
5399 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5400
5401 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5402 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005403 if (options->jo_set & JO_CHANNEL)
5404 {
5405 channel = options->jo_channel;
5406 if (channel != NULL)
5407 ++channel->ch_refcount;
5408 }
5409 else
5410 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005411 if (channel == NULL)
5412 goto failed;
5413 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005414
5415 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005416 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005417 CREATE_DEFAULT_ERROR_MODE |
5418 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005419 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005420 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005421 &si, &pi,
5422 ga.ga_data,
5423 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005424 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005425 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005426 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005427 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005428 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005429
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005430 ga_clear(&ga);
5431
Bram Moolenaar14207f42016-10-27 21:13:10 +02005432 if (!AssignProcessToJobObject(jo, pi.hProcess))
5433 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005434 // if failing, switch the way to terminate
5435 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005436 CloseHandle(jo);
5437 jo = NULL;
5438 }
5439 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005440 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005441 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005442 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005443 job->jv_status = JOB_STARTED;
5444
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005445 CloseHandle(ifd[0]);
5446 CloseHandle(ofd[1]);
5447 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005448 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005449
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005450 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005451 if (channel != NULL)
5452 {
5453 channel_set_pipes(channel,
5454 use_file_for_in || use_null_for_in
5455 ? INVALID_FD : (sock_T)ifd[1],
5456 use_file_for_out || use_null_for_out
5457 ? INVALID_FD : (sock_T)ofd[0],
5458 use_out_for_err || use_file_for_err || use_null_for_err
5459 ? INVALID_FD : (sock_T)efd[0]);
5460 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005461 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005462 return;
5463
5464failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005465 CloseHandle(ifd[0]);
5466 CloseHandle(ofd[0]);
5467 CloseHandle(efd[0]);
5468 CloseHandle(ifd[1]);
5469 CloseHandle(ofd[1]);
5470 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005471 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005472 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005473}
5474
5475 char *
5476mch_job_status(job_T *job)
5477{
5478 DWORD dwExitCode = 0;
5479
Bram Moolenaar76467df2016-02-12 19:30:26 +01005480 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5481 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005482 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005483 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005484 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005485 {
5486 ch_log(job->jv_channel, "Job ended");
5487 job->jv_status = JOB_ENDED;
5488 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005489 return "dead";
5490 }
5491 return "run";
5492}
5493
Bram Moolenaar97792de2016-10-15 18:36:49 +02005494 job_T *
5495mch_detect_ended_job(job_T *job_list)
5496{
5497 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5498 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5499 job_T *job = job_list;
5500
5501 while (job != NULL)
5502 {
5503 DWORD n;
5504 DWORD result;
5505
5506 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5507 && job != NULL; job = job->jv_next)
5508 {
5509 if (job->jv_status == JOB_STARTED)
5510 {
5511 jobHandles[n] = job->jv_proc_info.hProcess;
5512 jobArray[n] = job;
5513 ++n;
5514 }
5515 }
5516 if (n == 0)
5517 continue;
5518 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5519 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5520 {
5521 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5522
5523 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5524 return wait_job;
5525 }
5526 }
5527 return NULL;
5528}
5529
Bram Moolenaarfb630902016-10-29 14:55:00 +02005530 static BOOL
5531terminate_all(HANDLE process, int code)
5532{
5533 PROCESSENTRY32 pe;
5534 HANDLE h = INVALID_HANDLE_VALUE;
5535 DWORD pid = GetProcessId(process);
5536
5537 if (pid != 0)
5538 {
5539 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5540 if (h != INVALID_HANDLE_VALUE)
5541 {
5542 pe.dwSize = sizeof(PROCESSENTRY32);
5543 if (!Process32First(h, &pe))
5544 goto theend;
5545
5546 do
5547 {
5548 if (pe.th32ParentProcessID == pid)
5549 {
5550 HANDLE ph = OpenProcess(
5551 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5552 if (ph != NULL)
5553 {
5554 terminate_all(ph, code);
5555 CloseHandle(ph);
5556 }
5557 }
5558 } while (Process32Next(h, &pe));
5559
5560 CloseHandle(h);
5561 }
5562 }
5563
5564theend:
5565 return TerminateProcess(process, code);
5566}
5567
5568/*
5569 * Send a (deadly) signal to "job".
5570 * Return FAIL if it didn't work.
5571 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005572 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005573mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005574{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005575 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005576
Bram Moolenaar923d9262016-02-25 20:56:01 +01005577 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005578 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005579 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02005580 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005581 {
5582 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5583 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00005584 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005585 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01005586 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005587 }
5588
5589 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5590 return FAIL;
5591 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005592 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5593 job->jv_proc_info.dwProcessId)
5594 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005595 FreeConsole();
5596 return ret;
5597}
5598
5599/*
5600 * Clear the data related to "job".
5601 */
5602 void
5603mch_clear_job(job_T *job)
5604{
5605 if (job->jv_status != JOB_FAILED)
5606 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005607 if (job->jv_job_object != NULL)
5608 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005609 CloseHandle(job->jv_proc_info.hProcess);
5610 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005611}
5612#endif
5613
Bram Moolenaar071d4272004-06-13 20:20:40 +00005614
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005615#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005616
5617/*
5618 * Start termcap mode
5619 */
5620 static void
5621termcap_mode_start(void)
5622{
5623 DWORD cmodein;
5624
5625 if (g_fTermcapMode)
5626 return;
5627
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005628 if (!p_rs && USE_VTP)
5629 vtp_printf("\033[?1049h");
5630
Bram Moolenaar071d4272004-06-13 20:20:40 +00005631 SaveConsoleBuffer(&g_cbNonTermcap);
5632
5633 if (g_cbTermcap.IsValid)
5634 {
5635 /*
5636 * We've been in termcap mode before. Restore certain screen
5637 * characteristics, including the buffer size and the window
5638 * size. Since we will be redrawing the screen, we don't need
5639 * to restore the actual contents of the buffer.
5640 */
5641 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005642 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005643 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5644 Rows = g_cbTermcap.Info.dwSize.Y;
5645 Columns = g_cbTermcap.Info.dwSize.X;
5646 }
5647 else
5648 {
5649 /*
5650 * This is our first time entering termcap mode. Clear the console
5651 * screen buffer, and resize the buffer to match the current window
5652 * size. We will use this as the size of our editing environment.
5653 */
5654 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005655 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005656 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5657 }
5658
Bram Moolenaar071d4272004-06-13 20:20:40 +00005659 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005660
5661 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005662 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005663 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005664 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005665 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
5666 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005667 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005668 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005669 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005670 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5671 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005672 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005673 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005674
5675 redraw_later_clear();
5676 g_fTermcapMode = TRUE;
5677}
5678
5679
5680/*
5681 * End termcap mode
5682 */
5683 static void
5684termcap_mode_end(void)
5685{
5686 DWORD cmodein;
5687 ConsoleBuffer *cb;
5688 COORD coord;
5689 DWORD dwDummy;
5690
5691 if (!g_fTermcapMode)
5692 return;
5693
5694 SaveConsoleBuffer(&g_cbTermcap);
5695
5696 GetConsoleMode(g_hConIn, &cmodein);
5697 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005698 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5699 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005700
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005701# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005702 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005703# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005704 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005705# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005706 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01005707 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005708 SetConsoleCursorInfo(g_hConOut, &g_cci);
5709
5710 if (p_rs || exiting)
5711 {
5712 /*
5713 * Clear anything that happens to be on the current line.
5714 */
5715 coord.X = 0;
5716 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5717 FillConsoleOutputCharacter(g_hConOut, ' ',
5718 cb->Info.dwSize.X, coord, &dwDummy);
5719 /*
5720 * The following is just for aesthetics. If we are exiting without
5721 * restoring the screen, then we want to have a prompt string
5722 * appear at the bottom line. However, the command interpreter
5723 * seems to always advance the cursor one line before displaying
5724 * the prompt string, which causes the screen to scroll. To
5725 * counter this, move the cursor up one line before exiting.
5726 */
5727 if (exiting && !p_rs)
5728 coord.Y--;
5729 /*
5730 * Position the cursor at the leftmost column of the desired row.
5731 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005732 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005733 }
5734
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005735 if (!p_rs && USE_VTP)
Bram Moolenaar0afdcf82020-04-01 18:29:10 +02005736 vtp_printf("\033[?1049l");
5737
Bram Moolenaar071d4272004-06-13 20:20:40 +00005738 g_fTermcapMode = FALSE;
5739}
Bram Moolenaar0f873732019-12-05 20:28:46 +01005740#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005741
5742
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005743#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005744 void
5745mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005746 char_u *s UNUSED,
5747 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005748{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005749 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00005750}
5751
5752#else
5753
5754/*
5755 * clear `n' chars, starting from `coord'
5756 */
5757 static void
5758clear_chars(
5759 COORD coord,
5760 DWORD n)
5761{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005762 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02005763 {
5764 DWORD dwDummy;
5765
5766 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5767 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
5768 &dwDummy);
5769 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005770 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005771 {
5772 set_console_color_rgb();
5773 gotoxy(coord.X + 1, coord.Y + 1);
5774 vtp_printf("\033[%dX", n);
5775 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005776}
5777
5778
5779/*
5780 * Clear the screen
5781 */
5782 static void
5783clear_screen(void)
5784{
5785 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005786
5787 if (!USE_VTP)
5788 clear_chars(g_coord, Rows * Columns);
5789 else
5790 {
5791 set_console_color_rgb();
5792 gotoxy(1, 1);
5793 vtp_printf("\033[2J");
5794 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005795}
5796
5797
5798/*
5799 * Clear to end of display
5800 */
5801 static void
5802clear_to_end_of_display(void)
5803{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005804 COORD save = g_coord;
5805
5806 if (!USE_VTP)
5807 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005808 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005809 else
5810 {
5811 set_console_color_rgb();
5812 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5813 vtp_printf("\033[0J");
5814
5815 gotoxy(save.X + 1, save.Y + 1);
5816 g_coord = save;
5817 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005818}
5819
5820
5821/*
5822 * Clear to end of line
5823 */
5824 static void
5825clear_to_end_of_line(void)
5826{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005827 COORD save = g_coord;
5828
5829 if (!USE_VTP)
5830 clear_chars(g_coord, Columns - g_coord.X);
5831 else
5832 {
5833 set_console_color_rgb();
5834 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5835 vtp_printf("\033[0K");
5836
5837 gotoxy(save.X + 1, save.Y + 1);
5838 g_coord = save;
5839 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005840}
5841
5842
5843/*
5844 * Scroll the scroll region up by `cLines' lines
5845 */
5846 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005847scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005848{
5849 COORD oldcoord = g_coord;
5850
5851 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5852 delete_lines(cLines);
5853
5854 g_coord = oldcoord;
5855}
5856
5857
5858/*
5859 * Set the scroll region
5860 */
5861 static void
5862set_scroll_region(
5863 unsigned left,
5864 unsigned top,
5865 unsigned right,
5866 unsigned bottom)
5867{
5868 if (left >= right
5869 || top >= bottom
5870 || right > (unsigned) Columns - 1
5871 || bottom > (unsigned) Rows - 1)
5872 return;
5873
5874 g_srScrollRegion.Left = left;
5875 g_srScrollRegion.Top = top;
5876 g_srScrollRegion.Right = right;
5877 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005878}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005879
Bram Moolenaar6982f422019-02-16 16:48:01 +01005880 static void
5881set_scroll_region_tb(
5882 unsigned top,
5883 unsigned bottom)
5884{
5885 if (top >= bottom || bottom > (unsigned)Rows - 1)
5886 return;
5887
5888 g_srScrollRegion.Top = top;
5889 g_srScrollRegion.Bottom = bottom;
5890}
5891
5892 static void
5893set_scroll_region_lr(
5894 unsigned left,
5895 unsigned right)
5896{
5897 if (left >= right || right > (unsigned)Columns - 1)
5898 return;
5899
5900 g_srScrollRegion.Left = left;
5901 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005902}
5903
5904
5905/*
5906 * Insert `cLines' lines at the current cursor position
5907 */
5908 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005909insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005910{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005911 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005912 COORD dest;
5913 CHAR_INFO fill;
5914
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005915 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5916
Bram Moolenaar6982f422019-02-16 16:48:01 +01005917 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005918 dest.Y = g_coord.Y + cLines;
5919
Bram Moolenaar6982f422019-02-16 16:48:01 +01005920 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005921 source.Top = g_coord.Y;
5922 source.Right = g_srScrollRegion.Right;
5923 source.Bottom = g_srScrollRegion.Bottom - cLines;
5924
Bram Moolenaar6982f422019-02-16 16:48:01 +01005925 clip.Left = g_srScrollRegion.Left;
5926 clip.Top = g_coord.Y;
5927 clip.Right = g_srScrollRegion.Right;
5928 clip.Bottom = g_srScrollRegion.Bottom;
5929
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005930 fill.Char.AsciiChar = ' ';
5931 if (!USE_VTP)
5932 fill.Attributes = g_attrCurrent;
5933 else
5934 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005935
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005936 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005937
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005938 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5939
Bram Moolenaar6982f422019-02-16 16:48:01 +01005940 // Here we have to deal with a win32 console flake: If the scroll
5941 // region looks like abc and we scroll c to a and fill with d we get
5942 // cbd... if we scroll block c one line at a time to a, we get cdd...
5943 // vim expects cdd consistently... So we have to deal with that
5944 // here... (this also occurs scrolling the same way in the other
5945 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005946
5947 if (source.Bottom < dest.Y)
5948 {
5949 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005950 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005951
Bram Moolenaar6982f422019-02-16 16:48:01 +01005952 coord.X = source.Left;
5953 for (i = clip.Top; i < dest.Y; ++i)
5954 {
5955 coord.Y = i;
5956 clear_chars(coord, source.Right - source.Left + 1);
5957 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005958 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02005959
5960 if (USE_WT)
5961 {
5962 COORD coord;
5963 int i;
5964
5965 coord.X = source.Left;
5966 for (i = source.Top; i < dest.Y; ++i)
5967 {
5968 coord.Y = i;
5969 clear_chars(coord, source.Right - source.Left + 1);
5970 }
5971 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005972}
5973
5974
5975/*
5976 * Delete `cLines' lines at the current cursor position
5977 */
5978 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005979delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005980{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005981 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005982 COORD dest;
5983 CHAR_INFO fill;
5984 int nb;
5985
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005986 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5987
Bram Moolenaar6982f422019-02-16 16:48:01 +01005988 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005989 dest.Y = g_coord.Y;
5990
Bram Moolenaar6982f422019-02-16 16:48:01 +01005991 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005992 source.Top = g_coord.Y + cLines;
5993 source.Right = g_srScrollRegion.Right;
5994 source.Bottom = g_srScrollRegion.Bottom;
5995
Bram Moolenaar6982f422019-02-16 16:48:01 +01005996 clip.Left = g_srScrollRegion.Left;
5997 clip.Top = g_coord.Y;
5998 clip.Right = g_srScrollRegion.Right;
5999 clip.Bottom = g_srScrollRegion.Bottom;
6000
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006001 fill.Char.AsciiChar = ' ';
6002 if (!USE_VTP)
6003 fill.Attributes = g_attrCurrent;
6004 else
6005 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006006
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006007 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006008
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006009 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6010
Bram Moolenaar6982f422019-02-16 16:48:01 +01006011 // Here we have to deal with a win32 console flake; See insert_lines()
6012 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006013
6014 nb = dest.Y + (source.Bottom - source.Top) + 1;
6015
6016 if (nb < source.Top)
6017 {
6018 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006019 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006020
Bram Moolenaar6982f422019-02-16 16:48:01 +01006021 coord.X = source.Left;
6022 for (i = nb; i < clip.Bottom; ++i)
6023 {
6024 coord.Y = i;
6025 clear_chars(coord, source.Right - source.Left + 1);
6026 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006027 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006028
6029 if (USE_WT)
6030 {
6031 COORD coord;
6032 int i;
6033
6034 coord.X = source.Left;
6035 for (i = nb; i <= source.Bottom; ++i)
6036 {
6037 coord.Y = i;
6038 clear_chars(coord, source.Right - source.Left + 1);
6039 }
6040 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006041}
6042
6043
6044/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006045 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006046 */
6047 static void
6048gotoxy(
6049 unsigned x,
6050 unsigned y)
6051{
6052 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6053 return;
6054
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006055 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006056 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006057 // There are reports of double-width characters not displayed
6058 // correctly. This workaround should fix it, similar to how it's done
6059 // for VTP.
6060 g_coord.X = 0;
6061 SetConsoleCursorPosition(g_hConOut, g_coord);
6062
Bram Moolenaar2313b612019-09-27 14:14:32 +02006063 // external cursor coords are 1-based; internal are 0-based
6064 g_coord.X = x - 1;
6065 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006066 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006067 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006068 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006069 {
6070 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006071 // destruction. Insider build bug. Always enabled because it's cheap
6072 // and avoids mistakes with recognizing the build.
6073 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006074
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006075 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006076
6077 g_coord.X = x - 1;
6078 g_coord.Y = y - 1;
6079 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006080}
6081
6082
6083/*
6084 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006085 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006086 */
6087 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006088textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006089{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006090 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006091
6092 SetConsoleTextAttribute(g_hConOut, wAttr);
6093}
6094
6095
6096 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006097textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006098{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006099 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006100
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006101 if (!USE_VTP)
6102 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6103 else
6104 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006105}
6106
6107
6108 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006109textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006110{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006111 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006112
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006113 if (!USE_VTP)
6114 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6115 else
6116 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006117}
6118
6119
6120/*
6121 * restore the default text attribute (whatever we started with)
6122 */
6123 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006124normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006125{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006126 if (!USE_VTP)
6127 textattr(g_attrDefault);
6128 else
6129 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006130}
6131
6132
6133static WORD g_attrPreStandout = 0;
6134
6135/*
6136 * Make the text standout, by brightening it
6137 */
6138 static void
6139standout(void)
6140{
6141 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006142
Bram Moolenaar071d4272004-06-13 20:20:40 +00006143 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6144}
6145
6146
6147/*
6148 * Turn off standout mode
6149 */
6150 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006151standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006152{
6153 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006154 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006155
6156 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006157}
6158
6159
6160/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006161 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006162 */
6163 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006164mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006165{
6166 char_u *p;
6167 int n;
6168
6169 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6170 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006171 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006172# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006173 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006174# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006175 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006176 {
6177 p = T_ME + 2;
6178 n = getdigits(&p);
6179 if (*p == 'm' && n > 0)
6180 {
6181 cterm_normal_fg_color = (n & 0xf) + 1;
6182 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6183 }
6184 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006185# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006186 cterm_normal_fg_gui_color = INVALCOLOR;
6187 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006188# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006189}
6190
6191
6192/*
6193 * visual bell: flash the screen
6194 */
6195 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006196visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006197{
6198 COORD coordOrigin = {0, 0};
6199 WORD attrFlash = ~g_attrCurrent & 0xff;
6200
6201 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006202 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006203
6204 if (oldattrs == NULL)
6205 return;
6206 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6207 coordOrigin, &dwDummy);
6208 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6209 coordOrigin, &dwDummy);
6210
Bram Moolenaar0f873732019-12-05 20:28:46 +01006211 Sleep(15); // wait for 15 msec
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006212 if (!USE_VTP)
6213 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006214 coordOrigin, &dwDummy);
6215 vim_free(oldattrs);
6216}
6217
6218
6219/*
6220 * Make the cursor visible or invisible
6221 */
6222 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006223cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006224{
6225 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006226
6227 if (USE_VTP)
6228 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6229
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006230# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006231 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006232# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006233}
6234
6235
6236/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006237 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006238 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006239 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006240 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006241write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006242 char_u *pchBuf,
6243 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006244{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006245 COORD coord = g_coord;
6246 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006247 DWORD n, cchwritten;
6248 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006249 static WCHAR *unicodebuf = NULL;
6250 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006251 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006252 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006253 static WCHAR *utf8spbuf = NULL;
6254 static int utf8splength;
6255 static DWORD utf8spcells;
6256 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006257
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006258 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006259 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006260 utf8usingbuf = &unicodebuf;
6261 do
6262 {
6263 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6264 unicodebuf, unibuflen);
6265 if (length && length <= unibuflen)
6266 break;
6267 vim_free(unicodebuf);
6268 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6269 unibuflen = unibuflen ? 0 : length;
6270 } while(1);
6271 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006272 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006273 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6274 {
6275 if (utf8usingbuf != &utf8spbuf)
6276 {
6277 if (utf8spbuf == NULL)
6278 {
6279 cells = mb_string2cells((char_u *)" ", 1);
6280 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6281 utf8spbuf = LALLOC_MULT(WCHAR, length);
6282 if (utf8spbuf != NULL)
6283 {
6284 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6285 utf8usingbuf = &utf8spbuf;
6286 utf8splength = length;
6287 utf8spcells = cells;
6288 }
6289 }
6290 else
6291 {
6292 utf8usingbuf = &utf8spbuf;
6293 length = utf8splength;
6294 cells = utf8spcells;
6295 }
6296 }
6297 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006298
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006299 if (!USE_VTP)
6300 {
6301 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6302 coord, &written);
6303 // When writing fails or didn't write a single character, pretend one
6304 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006305 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006306 coord, &cchwritten) == 0
6307 || cchwritten == 0 || cchwritten == (DWORD)-1)
6308 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006309 }
6310 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006311 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006312 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006313 NULL) == 0 || cchwritten == 0)
6314 cchwritten = 1;
6315 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006316
K.Takata135e1522022-01-29 15:27:58 +00006317 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006318 {
6319 written = cbToWrite;
6320 g_coord.X += (SHORT)cells;
6321 }
6322 else
6323 {
6324 char_u *p = pchBuf;
6325 for (n = 0; n < cchwritten; n++)
6326 MB_CPTR_ADV(p);
6327 written = p - pchBuf;
6328 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006329 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006330
6331 while (g_coord.X > g_srScrollRegion.Right)
6332 {
6333 g_coord.X -= (SHORT) Columns;
6334 if (g_coord.Y < g_srScrollRegion.Bottom)
6335 g_coord.Y++;
6336 }
6337
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006338 // Cursor under VTP is always in the correct position, no need to reset.
6339 if (!USE_VTP)
6340 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006341
6342 return written;
6343}
6344
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006345 static char_u *
6346get_seq(
6347 int *args,
6348 int *count,
6349 char_u *head)
6350{
6351 int argc;
6352 char_u *p;
6353
6354 if (head == NULL || *head != '\033')
6355 return NULL;
6356
6357 argc = 0;
6358 p = head;
6359 ++p;
6360 do
6361 {
6362 ++p;
6363 args[argc] = getdigits(&p);
6364 argc += (argc < 15) ? 1 : 0;
6365 } while (*p == ';');
6366 *count = argc;
6367
6368 return p;
6369}
6370
6371 static char_u *
6372get_sgr(
6373 int *args,
6374 int *count,
6375 char_u *head)
6376{
6377 char_u *p = get_seq(args, count, head);
6378
6379 return (p && *p == 'm') ? ++p : NULL;
6380}
6381
6382/*
6383 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6384 */
6385 static char_u *
6386sgrn2(
6387 char_u *head,
6388 int n)
6389{
6390 int argc;
6391 int args[16];
6392 char_u *p = get_sgr(args, &argc, head);
6393
6394 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6395}
6396
6397/*
6398 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6399 */
6400 static char_u *
6401sgrnc(
6402 char_u *head,
6403 int n)
6404{
6405 int argc;
6406 int args[16];
6407 char_u *p = get_sgr(args, &argc, head);
6408
6409 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6410 ? p : NULL;
6411}
6412
6413 static char_u *
6414skipblank(char_u *q)
6415{
6416 char_u *p = q;
6417
6418 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6419 ++p;
6420 return p;
6421}
6422
6423/*
6424 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6425 * NULL.
6426 */
6427 static char_u *
6428sgrn2c(
6429 char_u *head,
6430 int n)
6431{
6432 char_u *p = sgrn2(head, n);
6433
6434 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6435}
6436
6437/*
6438 * If there is only a newline between the sequence immediately following it,
6439 * a pointer to the character following the newline is returned.
6440 * Otherwise NULL.
6441 */
6442 static char_u *
6443sgrn2cn(
6444 char_u *head,
6445 int n)
6446{
6447 char_u *p = sgrn2(head, n);
6448
6449 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6450}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006451
6452/*
6453 * mch_write(): write the output buffer to the screen, translating ESC
6454 * sequences into calls to console output routines.
6455 */
6456 void
6457mch_write(
6458 char_u *s,
6459 int len)
6460{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006461 char_u *end = s + len;
6462
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006463# ifdef VIMDLL
6464 if (gui.in_use)
6465 return;
6466# endif
6467
Bram Moolenaar071d4272004-06-13 20:20:40 +00006468 if (!term_console)
6469 {
6470 write(1, s, (unsigned)len);
6471 return;
6472 }
6473
Bram Moolenaar0f873732019-12-05 20:28:46 +01006474 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00006475 while (len--)
6476 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006477 int prefix = -1;
6478 char_u ch;
6479
6480 // While processing a sequence, on rare occasions it seems that another
6481 // sequence may be inserted asynchronously.
6482 if (len < 0)
6483 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006484 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006485 return;
6486 }
6487
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006488 while (s + ++prefix < end)
6489 {
6490 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006491 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6492 && ch != '\a' && ch != '\033'))
6493 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006494 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006495
6496 if (p_wd)
6497 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006498 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006499 if (prefix != 0)
6500 prefix = 1;
6501 }
6502
6503 if (prefix != 0)
6504 {
6505 DWORD nWritten;
6506
6507 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006508# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006509 if (fdDump)
6510 {
6511 fputc('>', fdDump);
6512 fwrite(s, sizeof(char_u), nWritten, fdDump);
6513 fputs("<\n", fdDump);
6514 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006515# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006516 len -= (nWritten - 1);
6517 s += nWritten;
6518 }
6519 else if (s[0] == '\n')
6520 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006521 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00006522 if (g_coord.Y == g_srScrollRegion.Bottom)
6523 {
6524 scroll(1);
6525 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6526 }
6527 else
6528 {
6529 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6530 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006531# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006532 if (fdDump)
6533 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006534# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006535 s++;
6536 }
6537 else if (s[0] == '\r')
6538 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006539 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00006540 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006541# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006542 if (fdDump)
6543 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006544# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006545 s++;
6546 }
6547 else if (s[0] == '\b')
6548 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006549 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00006550 if (g_coord.X > g_srScrollRegion.Left)
6551 g_coord.X--;
6552 else if (g_coord.Y > g_srScrollRegion.Top)
6553 {
6554 g_coord.X = g_srScrollRegion.Right;
6555 g_coord.Y--;
6556 }
6557 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006558# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006559 if (fdDump)
6560 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006561# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006562 s++;
6563 }
6564 else if (s[0] == '\a')
6565 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006566 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00006567 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006568# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006569 if (fdDump)
6570 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006571# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006572 s++;
6573 }
6574 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6575 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006576# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006577 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006578# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006579 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006580 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006581 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006582
6583 switch (s[2])
6584 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006585 case '0': case '1': case '2': case '3': case '4':
6586 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006587 if (*(p = get_seq(args, &argc, s)) != 'm')
6588 goto notsgr;
6589
6590 p = s;
6591
6592 // Handling frequent optional sequences. Output to the screen
6593 // takes too long, so do not output as much as possible.
6594
6595 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
6596 // resetFG,FG,BG are omitted.
6597 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006598 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006599 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
6600 len = len + 1 - (int)(p - s);
6601 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006602 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006603 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006604
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006605 // If FG,BG,BG,FG of SGR are connected, the first FG can be
6606 // omitted.
6607 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
6608 p = sp;
6609
6610 // If FG,BG,FG,BG of SGR are connected, the first FG can be
6611 // omitted.
6612 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
6613 p = sp;
6614
6615 // If BG,BG of SGR are connected, the first BG can be omitted.
6616 if (sgrn2((sp = sgrn2(p, 48)), 48))
6617 p = sp;
6618
6619 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01006620 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006621 if (sgrn2((sp = sgrnc(p, 39)), 38))
6622 p = sp;
6623
6624 p = get_seq(args, &argc, p);
6625
6626notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006627 arg1 = args[0];
6628 arg2 = args[1];
6629 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006630 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006631 if (argc == 1 && args[0] == 0)
6632 normvideo();
6633 else if (argc == 1)
6634 {
6635 if (USE_VTP)
6636 textcolor((WORD) arg1);
6637 else
6638 textattr((WORD) arg1);
6639 }
6640 else if (USE_VTP)
6641 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006642 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006643 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006644 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006645 gotoxy(arg2, arg1);
6646 }
6647 else if (argc == 2 && *p == 'r')
6648 {
6649 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6650 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006651 else if (argc == 2 && *p == 'R')
6652 {
6653 set_scroll_region_tb(arg1, arg2);
6654 }
6655 else if (argc == 2 && *p == 'V')
6656 {
6657 set_scroll_region_lr(arg1, arg2);
6658 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006659 else if (argc == 1 && *p == 'A')
6660 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006661 gotoxy(g_coord.X + 1,
6662 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6663 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006664 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006665 {
6666 textbackground((WORD) arg1);
6667 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006668 else if (argc == 1 && *p == 'C')
6669 {
6670 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6671 g_coord.Y + 1);
6672 }
6673 else if (argc == 1 && *p == 'f')
6674 {
6675 textcolor((WORD) arg1);
6676 }
6677 else if (argc == 1 && *p == 'H')
6678 {
6679 gotoxy(1, arg1);
6680 }
6681 else if (argc == 1 && *p == 'L')
6682 {
6683 insert_lines(arg1);
6684 }
6685 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006686 {
6687 delete_lines(arg1);
6688 }
6689
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006690 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006691 s = p + 1;
6692 break;
6693
Bram Moolenaar071d4272004-06-13 20:20:40 +00006694 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006695 gotoxy(g_coord.X + 1,
6696 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6697 goto got3;
6698
6699 case 'B':
6700 visual_bell();
6701 goto got3;
6702
6703 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006704 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6705 g_coord.Y + 1);
6706 goto got3;
6707
6708 case 'E':
6709 termcap_mode_end();
6710 goto got3;
6711
6712 case 'F':
6713 standout();
6714 goto got3;
6715
6716 case 'f':
6717 standend();
6718 goto got3;
6719
6720 case 'H':
6721 gotoxy(1, 1);
6722 goto got3;
6723
6724 case 'j':
6725 clear_to_end_of_display();
6726 goto got3;
6727
6728 case 'J':
6729 clear_screen();
6730 goto got3;
6731
6732 case 'K':
6733 clear_to_end_of_line();
6734 goto got3;
6735
6736 case 'L':
6737 insert_lines(1);
6738 goto got3;
6739
6740 case 'M':
6741 delete_lines(1);
6742 goto got3;
6743
6744 case 'S':
6745 termcap_mode_start();
6746 goto got3;
6747
6748 case 'V':
6749 cursor_visible(TRUE);
6750 goto got3;
6751
6752 case 'v':
6753 cursor_visible(FALSE);
6754 goto got3;
6755
6756 got3:
6757 s += 3;
6758 len -= 2;
6759 }
6760
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006761# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006762 if (fdDump)
6763 {
6764 fputs("ESC | ", fdDump);
6765 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6766 fputc('\n', fdDump);
6767 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006768# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006769 }
K.Takatadf5320c2022-09-01 13:20:16 +01006770 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
6771 {
6772 int l = 2;
6773
6774 if (isdigit(s[l]))
6775 l++;
6776 if (s[l] == ' ' && s[l + 1] == 'q')
6777 {
6778 // DECSCUSR (cursor style) sequences
6779 if (USE_VTP || USE_WT)
6780 vtp_printf("%.*s", l + 2, s); // Pass through
6781 s += l + 2;
6782 len -= l + 1;
6783 }
6784 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006785 else
6786 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006787 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00006788 DWORD nWritten;
6789
6790 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006791# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006792 if (fdDump)
6793 {
6794 fputc('>', fdDump);
6795 fwrite(s, sizeof(char_u), nWritten, fdDump);
6796 fputs("<\n", fdDump);
6797 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006798# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006799
6800 len -= (nWritten - 1);
6801 s += nWritten;
6802 }
6803 }
6804
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006805# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006806 if (fdDump)
6807 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006808# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006809}
6810
Bram Moolenaar0f873732019-12-05 20:28:46 +01006811#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006812
6813
6814/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006815 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006816 */
6817 void
6818mch_delay(
6819 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02006820 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006821{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006822#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006823 Sleep((int)msec); // never wait for input
6824#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006825# ifdef VIMDLL
6826 if (gui.in_use)
6827 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006828 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006829 return;
6830 }
6831# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02006832 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006833# ifdef FEAT_MZSCHEME
6834 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6835 {
6836 int towait = p_mzq;
6837
Bram Moolenaar0f873732019-12-05 20:28:46 +01006838 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006839 while (msec > 0)
6840 {
6841 mzvim_check_threads();
6842 if (msec < towait)
6843 towait = msec;
6844 Sleep(towait);
6845 msec -= towait;
6846 }
6847 }
6848 else
6849# endif
6850 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006851 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006852 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006853#endif
6854}
6855
6856
6857/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006858 * This version of remove is not scared by a readonly (backup) file.
6859 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006860 * Return 0 for success, -1 for failure.
6861 */
6862 int
6863mch_remove(char_u *name)
6864{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006865 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006866 int n;
6867
Bram Moolenaar203258c2016-01-17 22:15:16 +01006868 /*
6869 * On Windows, deleting a directory's symbolic link is done by
6870 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6871 */
6872 if (mch_isdir(name) && mch_is_symbolic_link(name))
6873 return mch_rmdir(name);
6874
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006875 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6876
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006877 wn = enc_to_utf16(name, NULL);
6878 if (wn == NULL)
6879 return -1;
6880
6881 n = DeleteFileW(wn) ? 0 : -1;
6882 vim_free(wn);
6883 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006884}
6885
6886
6887/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006888 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006889 */
6890 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006891mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006892{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006893#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
6894# ifdef VIMDLL
6895 if (!gui.in_use)
6896# endif
6897 if (g_fCtrlCPressed || g_fCBrkPressed)
6898 {
6899 ctrl_break_was_pressed = g_fCBrkPressed;
6900 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6901 got_int = TRUE;
6902 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006903#endif
6904}
6905
Bram Moolenaar0f873732019-12-05 20:28:46 +01006906// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01006907#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006908
6909/*
6910 * How much main memory in KiB that can be used by VIM.
6911 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006912 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006913mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006914{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006915 MEMORYSTATUSEX ms;
6916
Bram Moolenaar0f873732019-12-05 20:28:46 +01006917 // Need to use GlobalMemoryStatusEx() when there is more memory than
6918 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006919 ms.dwLength = sizeof(MEMORYSTATUSEX);
6920 GlobalMemoryStatusEx(&ms);
6921 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006922 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006923 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006924 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006925 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006926 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006927 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006928 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006929 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006930 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01006931 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006932 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006933}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006934
Bram Moolenaar071d4272004-06-13 20:20:40 +00006935/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006936 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00006937 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6938 * file whose short file name is "FOO.BAR" (its long file name will
6939 * be correct: "foo.bar~"). Because a file can be accessed by
6940 * either its SFN or its LFN, "foo.bar" has effectively been
6941 * renamed to "foo.bar", which is not at all what was wanted. This
6942 * seems to happen only when renaming files with three-character
6943 * extensions by appending a suffix that does not include ".".
6944 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6945 *
6946 * There is another problem, which isn't really a bug but isn't right either:
6947 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6948 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6949 * service pack 6. Doesn't seem to happen on Windows 98.
6950 *
6951 * Like rename(), returns 0 upon success, non-zero upon failure.
6952 * Should probably set errno appropriately when errors occur.
6953 */
6954 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006955mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006956{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006957 WCHAR *p;
6958 int i;
6959 WCHAR szTempFile[_MAX_PATH + 1];
6960 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006961 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006962
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006963 // No need to play tricks unless the file name contains a "~" as the
6964 // seventh character.
6965 p = wold;
6966 for (i = 0; wold[i] != NUL; ++i)
6967 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6968 && wold[i + 1] != 0)
6969 p = wold + i + 1;
6970 if ((int)(wold + i - p) < 8 || p[6] != '~')
6971 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006972
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006973 // Get base path of new file name. Undocumented feature: If pszNewFile is
6974 // a directory, no error is returned and pszFilePart will be NULL.
6975 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006976 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006977 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006978
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006979 // Get (and create) a unique temporary file name in directory of new file
6980 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006981 return -2;
6982
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006983 // blow the temp file away
6984 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006985 return -3;
6986
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006987 // rename old file to the temp file
6988 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006989 return -4;
6990
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006991 // now create an empty file called pszOldFile; this prevents the operating
6992 // system using pszOldFile as an alias (SFN) if we're renaming within the
6993 // same directory. For example, we're editing a file called
6994 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6995 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
6996 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
6997 // cause all sorts of problems later in buf_write(). So, we create an
6998 // empty file called filena~1.txt and the system will have to find some
6999 // other SFN for filena~1.txt~, such as filena~2.txt
7000 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007001 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7002 return -5;
7003 if (!CloseHandle(hf))
7004 return -6;
7005
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007006 // rename the temp file to the new file
7007 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007008 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007009 // Renaming failed. Rename the file back to its old name, so that it
7010 // looks like nothing happened.
7011 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007012 return -7;
7013 }
7014
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007015 // Seems to be left around on Novell filesystems
7016 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007017
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007018 // finally, remove the empty old file
7019 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007020 return -8;
7021
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007022 return 0;
7023}
7024
7025
7026/*
7027 * Converts the filenames to UTF-16, then call mch_wrename().
7028 * Like rename(), returns 0 upon success, non-zero upon failure.
7029 */
7030 int
7031mch_rename(
7032 const char *pszOldFile,
7033 const char *pszNewFile)
7034{
7035 WCHAR *wold = NULL;
7036 WCHAR *wnew = NULL;
7037 int retval = -1;
7038
7039 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7040 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7041 if (wold != NULL && wnew != NULL)
7042 retval = mch_wrename(wold, wnew);
7043 vim_free(wold);
7044 vim_free(wnew);
7045 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007046}
7047
7048/*
7049 * Get the default shell for the current hardware platform
7050 */
7051 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007052default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007053{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007054 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007055}
7056
7057/*
7058 * mch_access() extends access() to do more detailed check on network drives.
7059 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7060 */
7061 int
7062mch_access(char *n, int p)
7063{
7064 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007065 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007066 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007067
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007068 wn = enc_to_utf16((char_u *)n, NULL);
7069 if (wn == NULL)
7070 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007071
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007072 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007073 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007074 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007075
7076 if (p & R_OK)
7077 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007078 // Read check is performed by seeing if we can do a find file on
7079 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007080 int i;
7081 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007082
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007083 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7084 TempNameW[i] = wn[i];
7085 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7086 TempNameW[i++] = '\\';
7087 TempNameW[i++] = '*';
7088 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007089
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007090 hFile = FindFirstFileW(TempNameW, &d);
7091 if (hFile == INVALID_HANDLE_VALUE)
7092 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007093 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007094 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007095 }
7096
7097 if (p & W_OK)
7098 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007099 // Trying to create a temporary file in the directory should catch
7100 // directories on read-only network shares. However, in
7101 // directories whose ACL allows writes but denies deletes will end
7102 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007103 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7104 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007105 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007106 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007107 }
7108 }
7109 else
7110 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007111 // Don't consider a file read-only if another process has opened it.
7112 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7113
Bram Moolenaar0f873732019-12-05 20:28:46 +01007114 // Trying to open the file for the required access does ACL, read-only
7115 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007116 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7117 | ((p & R_OK) ? GENERIC_READ : 0);
7118
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007119 hFile = CreateFileW(wn, access_mode, share_mode,
7120 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007121 if (hFile == INVALID_HANDLE_VALUE)
7122 goto getout;
7123 CloseHandle(hFile);
7124 }
7125
Bram Moolenaar0f873732019-12-05 20:28:46 +01007126 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007127getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007128 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007129 return retval;
7130}
7131
Bram Moolenaar071d4272004-06-13 20:20:40 +00007132/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007133 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007134 */
7135 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007136mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007137{
7138 WCHAR *wn;
7139 int f;
7140
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007141 wn = enc_to_utf16((char_u *)name, NULL);
7142 if (wn == NULL)
7143 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007144
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007145 f = _wopen(wn, flags, mode);
7146 vim_free(wn);
7147 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007148}
7149
7150/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007151 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007152 */
7153 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007154mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007155{
7156 WCHAR *wn, *wm;
7157 FILE *f = NULL;
7158
Bram Moolenaara12a1612019-01-24 16:39:02 +01007159#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007160 // Work around an annoying assertion in the Microsoft debug CRT
7161 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007162 char newMode = mode[strlen(mode) - 1];
7163 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007164
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007165 _get_fmode(&oldMode);
7166 if (newMode == 't')
7167 _set_fmode(_O_TEXT);
7168 else if (newMode == 'b')
7169 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007170#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007171 wn = enc_to_utf16((char_u *)name, NULL);
7172 wm = enc_to_utf16((char_u *)mode, NULL);
7173 if (wn != NULL && wm != NULL)
7174 f = _wfopen(wn, wm);
7175 vim_free(wn);
7176 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007177
Bram Moolenaara12a1612019-01-24 16:39:02 +01007178#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007179 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007180#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007181 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007182}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007183
Bram Moolenaar071d4272004-06-13 20:20:40 +00007184/*
7185 * SUB STREAM (aka info stream) handling:
7186 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007187 * NTFS can have sub streams for each file. The normal contents of a file is
7188 * stored in the main stream, and extra contents (author information, title and
7189 * so on) can be stored in a sub stream. After Windows 2000, the user can
7190 * access and store this information in sub streams via an explorer's property
7191 * menu item in the right click menu. This information in sub streams was lost
7192 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007193 *
7194 * Incomplete explanation:
7195 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7196 * More useful info and an example:
7197 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7198 */
7199
7200/*
7201 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7202 * and write to stream "substream" of file "to".
7203 * Errors are ignored.
7204 */
7205 static void
7206copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7207{
7208 HANDLE hTo;
7209 WCHAR *to_name;
7210
7211 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7212 wcscpy(to_name, to);
7213 wcscat(to_name, substream);
7214
7215 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7216 FILE_ATTRIBUTE_NORMAL, NULL);
7217 if (hTo != INVALID_HANDLE_VALUE)
7218 {
7219 long done;
7220 DWORD todo;
7221 DWORD readcnt, written;
7222 char buf[4096];
7223
Bram Moolenaar0f873732019-12-05 20:28:46 +01007224 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007225 for (done = 0; done < len; done += written)
7226 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007227 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007228 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7229 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007230 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7231 FALSE, FALSE, context)
7232 || readcnt != todo
7233 || !WriteFile(hTo, buf, todo, &written, NULL)
7234 || written != todo)
7235 break;
7236 }
7237 CloseHandle(hTo);
7238 }
7239
7240 free(to_name);
7241}
7242
7243/*
7244 * Copy info streams from file "from" to file "to".
7245 */
7246 static void
7247copy_infostreams(char_u *from, char_u *to)
7248{
7249 WCHAR *fromw;
7250 WCHAR *tow;
7251 HANDLE sh;
7252 WIN32_STREAM_ID sid;
7253 int headersize;
7254 WCHAR streamname[_MAX_PATH];
7255 DWORD readcount;
7256 void *context = NULL;
7257 DWORD lo, hi;
7258 int len;
7259
Bram Moolenaar0f873732019-12-05 20:28:46 +01007260 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007261 fromw = enc_to_utf16(from, NULL);
7262 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007263 if (fromw != NULL && tow != NULL)
7264 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007265 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007266 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7267 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7268 if (sh != INVALID_HANDLE_VALUE)
7269 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007270 // Use BackupRead() to find the info streams. Repeat until we
7271 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007272 for (;;)
7273 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007274 // Get the header to find the length of the stream name. If
7275 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007276 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007277 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007278 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7279 &readcount, FALSE, FALSE, &context)
7280 || readcount == 0)
7281 break;
7282
Bram Moolenaar0f873732019-12-05 20:28:46 +01007283 // We only deal with streams that have a name. The normal
7284 // file data appears to be without a name, even though docs
7285 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007286 if (sid.dwStreamNameSize > 0)
7287 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007288 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007289 if (!BackupRead(sh, (LPBYTE)streamname,
7290 sid.dwStreamNameSize,
7291 &readcount, FALSE, FALSE, &context))
7292 break;
7293
Bram Moolenaar0f873732019-12-05 20:28:46 +01007294 // Copy an info stream with a name ":anything:$DATA".
7295 // Skip "::$DATA", it has no stream name (examples suggest
7296 // it might be used for the normal file contents).
7297 // Note that BackupRead() counts bytes, but the name is in
7298 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007299 len = readcount / sizeof(WCHAR);
7300 streamname[len] = 0;
7301 if (len > 7 && wcsicmp(streamname + len - 6,
7302 L":$DATA") == 0)
7303 {
7304 streamname[len - 6] = 0;
7305 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007306 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007307 }
7308 }
7309
Bram Moolenaar0f873732019-12-05 20:28:46 +01007310 // Advance to the next stream. We might try seeking too far,
7311 // but BackupSeek() doesn't skip over stream borders, thus
7312 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007313 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007314 &lo, &hi, &context);
7315 }
7316
Bram Moolenaar0f873732019-12-05 20:28:46 +01007317 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007318 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7319
7320 CloseHandle(sh);
7321 }
7322 }
7323 vim_free(fromw);
7324 vim_free(tow);
7325}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007326
7327/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007328 * ntdll.dll definitions
7329 */
7330#define FileEaInformation 7
7331#ifndef STATUS_SUCCESS
7332# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7333#endif
7334
7335typedef struct _FILE_FULL_EA_INFORMATION_ {
7336 ULONG NextEntryOffset;
7337 UCHAR Flags;
7338 UCHAR EaNameLength;
7339 USHORT EaValueLength;
7340 CHAR EaName[1];
7341} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7342
7343typedef struct _FILE_EA_INFORMATION_ {
7344 ULONG EaSize;
7345} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7346
Paul Ollis65745772022-06-05 16:55:54 +01007347#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007348typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7349 PHANDLE FileHandle,
7350 ACCESS_MASK DesiredAccess,
7351 POBJECT_ATTRIBUTES ObjectAttributes,
7352 PIO_STATUS_BLOCK IoStatusBlock,
7353 ULONG ShareAccess,
7354 ULONG OpenOptions);
7355typedef NTSTATUS (NTAPI *PfnNtClose)(
7356 HANDLE Handle);
7357typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007358 HANDLE FileHandle,
7359 PIO_STATUS_BLOCK IoStatusBlock,
7360 PVOID Buffer,
7361 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007362typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7363 HANDLE FileHandle,
7364 PIO_STATUS_BLOCK IoStatusBlock,
7365 PVOID Buffer,
7366 ULONG Length,
7367 BOOLEAN ReturnSingleEntry,
7368 PVOID EaList,
7369 ULONG EaListLength,
7370 PULONG EaIndex,
7371 BOOLEAN RestartScan);
7372typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007373 HANDLE FileHandle,
7374 PIO_STATUS_BLOCK IoStatusBlock,
7375 PVOID FileInformation,
7376 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007377 FILE_INFORMATION_CLASS FileInformationClass);
7378typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7379 PUNICODE_STRING DestinationString,
7380 PCWSTR SourceString);
7381
7382PfnNtOpenFile pNtOpenFile = NULL;
7383PfnNtClose pNtClose = NULL;
7384PfnNtSetEaFile pNtSetEaFile = NULL;
7385PfnNtQueryEaFile pNtQueryEaFile = NULL;
7386PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7387PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01007388#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007389
7390/*
7391 * Load ntdll.dll functions.
7392 */
7393 static BOOL
7394load_ntdll(void)
7395{
7396 static int loaded = -1;
7397
7398 if (loaded == -1)
7399 {
7400 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7401 if (hNtdll != NULL)
7402 {
7403 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7404 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7405 pNtSetEaFile = (PfnNtSetEaFile)
7406 GetProcAddress(hNtdll, "NtSetEaFile");
7407 pNtQueryEaFile = (PfnNtQueryEaFile)
7408 GetProcAddress(hNtdll, "NtQueryEaFile");
7409 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7410 GetProcAddress(hNtdll, "NtQueryInformationFile");
7411 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7412 GetProcAddress(hNtdll, "RtlInitUnicodeString");
7413 }
7414 if (pNtOpenFile == NULL
7415 || pNtClose == NULL
7416 || pNtSetEaFile == NULL
7417 || pNtQueryEaFile == NULL
7418 || pNtQueryInformationFile == NULL
7419 || pRtlInitUnicodeString == NULL)
7420 loaded = FALSE;
7421 else
7422 loaded = TRUE;
7423 }
7424 return (BOOL) loaded;
7425}
7426
7427/*
7428 * Copy extended attributes (EA) from file "from" to file "to".
7429 */
7430 static void
7431copy_extattr(char_u *from, char_u *to)
7432{
7433 char_u *fromf = NULL;
7434 char_u *tof = NULL;
7435 WCHAR *fromw = NULL;
7436 WCHAR *tow = NULL;
7437 UNICODE_STRING u;
7438 HANDLE h;
7439 OBJECT_ATTRIBUTES oa;
7440 IO_STATUS_BLOCK iosb;
7441 FILE_EA_INFORMATION_ eainfo = {0};
7442 void *ea = NULL;
7443
7444 if (!load_ntdll())
7445 return;
7446
7447 // Convert the file names to the fully qualified object names.
7448 fromf = alloc(STRLEN(from) + 5);
7449 tof = alloc(STRLEN(to) + 5);
7450 if (fromf == NULL || tof == NULL)
7451 goto theend;
7452 STRCPY(fromf, "\\??\\");
7453 STRCAT(fromf, from);
7454 STRCPY(tof, "\\??\\");
7455 STRCAT(tof, to);
7456
7457 // Convert the names to wide characters.
7458 fromw = enc_to_utf16(fromf, NULL);
7459 tow = enc_to_utf16(tof, NULL);
7460 if (fromw == NULL || tow == NULL)
7461 goto theend;
7462
7463 // Get the EA.
7464 pRtlInitUnicodeString(&u, fromw);
7465 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7466 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7467 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7468 goto theend;
7469 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7470 FileEaInformation);
7471 if (eainfo.EaSize != 0)
7472 {
7473 ea = alloc(eainfo.EaSize);
7474 if (ea != NULL)
7475 {
7476 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7477 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7478 {
7479 vim_free(ea);
7480 ea = NULL;
7481 }
7482 }
7483 }
7484 pNtClose(h);
7485
7486 // Set the EA.
7487 if (ea != NULL)
7488 {
7489 pRtlInitUnicodeString(&u, tow);
7490 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7491 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7492 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7493 goto theend;
7494
7495 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
7496 pNtClose(h);
7497 }
7498
7499theend:
7500 vim_free(fromf);
7501 vim_free(tof);
7502 vim_free(fromw);
7503 vim_free(tow);
7504 vim_free(ea);
7505}
7506
7507/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007508 * Copy file attributes from file "from" to file "to".
7509 * For Windows NT and later we copy info streams.
7510 * Always returns zero, errors are ignored.
7511 */
7512 int
7513mch_copy_file_attribute(char_u *from, char_u *to)
7514{
Bram Moolenaar0f873732019-12-05 20:28:46 +01007515 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007516 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007517 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007518 return 0;
7519}
7520
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007521
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007522/*
K.Takatadc73b4b2021-06-08 18:32:36 +02007523 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007524 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007525static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007526static LPWSTR *ArglistW = NULL;
7527static int global_argc = 0;
7528static char **global_argv;
7529
Bram Moolenaar0f873732019-12-05 20:28:46 +01007530static int used_file_argc = 0; // last argument in global_argv[] used
7531 // for the argument list.
7532static int *used_file_indexes = NULL; // indexes in global_argv[] for
7533 // command line arguments added to
7534 // the argument list
7535static int used_file_count = 0; // nr of entries in used_file_indexes
7536static int used_file_literal = FALSE; // take file names literally
7537static int used_file_full_path = FALSE; // file name was full path
7538static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007539static int used_alist_count = 0;
7540
7541
7542/*
7543 * Get the command line arguments. Unicode version.
7544 * Returns argc. Zero when something fails.
7545 */
7546 int
7547get_cmd_argsW(char ***argvp)
7548{
7549 char **argv = NULL;
7550 int argc = 0;
7551 int i;
7552
Bram Moolenaar14993322014-09-09 12:25:33 +02007553 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007554 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7555 if (ArglistW != NULL)
7556 {
7557 argv = malloc((nArgsW + 1) * sizeof(char *));
7558 if (argv != NULL)
7559 {
7560 argc = nArgsW;
7561 argv[argc] = NULL;
7562 for (i = 0; i < argc; ++i)
7563 {
7564 int len;
7565
K.Takatadc73b4b2021-06-08 18:32:36 +02007566 // Convert each Unicode argument to UTF-8.
7567 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007568 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007569 (LPSTR *)&argv[i], &len, 0, 0);
7570 if (argv[i] == NULL)
7571 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007572 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007573 while (i > 0)
7574 free(argv[--i]);
7575 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007576 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007577 argc = 0;
7578 }
7579 }
7580 }
7581 }
7582
7583 global_argc = argc;
7584 global_argv = argv;
7585 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007586 {
7587 if (used_file_indexes != NULL)
7588 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007589 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007590 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007591
7592 if (argvp != NULL)
7593 *argvp = argv;
7594 return argc;
7595}
7596
7597 void
7598free_cmd_argsW(void)
7599{
7600 if (ArglistW != NULL)
7601 {
7602 GlobalFree(ArglistW);
7603 ArglistW = NULL;
7604 }
7605}
7606
7607/*
7608 * Remember "name" is an argument that was added to the argument list.
7609 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7610 * is called.
7611 */
7612 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007613used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007614{
7615 int i;
7616
7617 if (used_file_indexes == NULL)
7618 return;
7619 for (i = used_file_argc + 1; i < global_argc; ++i)
7620 if (STRCMP(global_argv[i], name) == 0)
7621 {
7622 used_file_argc = i;
7623 used_file_indexes[used_file_count++] = i;
7624 break;
7625 }
7626 used_file_literal = literal;
7627 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007628 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007629}
7630
7631/*
7632 * Remember the length of the argument list as it was. If it changes then we
7633 * leave it alone when 'encoding' is set.
7634 */
7635 void
7636set_alist_count(void)
7637{
7638 used_alist_count = GARGCOUNT;
7639}
7640
7641/*
7642 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02007643 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007644 * and convert them to 'encoding'.
7645 */
7646 void
7647fix_arg_enc(void)
7648{
7649 int i;
7650 int idx;
7651 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007652 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007653
Bram Moolenaar0f873732019-12-05 20:28:46 +01007654 // Safety checks:
7655 // - if argument count differs between the wide and non-wide argument
7656 // list, something must be wrong.
7657 // - the file name arguments must have been located.
7658 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007659 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007660 || ArglistW == NULL
7661 || used_file_indexes == NULL
7662 || used_file_count == 0
7663 || used_alist_count != GARGCOUNT)
7664 return;
7665
Bram Moolenaar0f873732019-12-05 20:28:46 +01007666 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007667 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007668 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007669 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00007670 for (i = 0; i < GARGCOUNT; ++i)
7671 fnum_list[i] = GARGLIST[i].ae_fnum;
7672
Bram Moolenaar0f873732019-12-05 20:28:46 +01007673 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007674 alist_clear(&global_alist);
7675 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007676 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007677
7678 for (i = 0; i < used_file_count; ++i)
7679 {
7680 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007681 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007682 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007683 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007684 int literal = used_file_literal;
7685
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007686#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01007687 // When using diff mode may need to concatenate file name to
7688 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007689 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7690 && !mch_isdir(alist_name(&GARGLIST[0])))
7691 {
7692 char_u *r;
7693
7694 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7695 if (r != NULL)
7696 {
7697 vim_free(str);
7698 str = r;
7699 }
7700 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007701#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01007702 // Re-use the old buffer by renaming it. When not using literal
7703 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00007704 if (used_file_literal)
7705 buf_set_name(fnum_list[i], str);
7706
Bram Moolenaar0f873732019-12-05 20:28:46 +01007707 // Check backtick literal. backtick literal is already expanded in
7708 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007709 if (literal == FALSE)
7710 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007711 size_t len = STRLEN(str);
7712
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007713 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7714 literal = TRUE;
7715 }
7716 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007717 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007718 }
7719
7720 if (!used_file_literal)
7721 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007722 // Now expand wildcards in the arguments.
7723 // Temporarily add '(' and ')' to 'isfname'. These are valid
7724 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00007725 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01007726 // Also, unset wildignore to not be influenced by this option.
7727 // The arguments specified in command-line should be kept even if
7728 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00007729 // Use :legacy so that it also works when in Vim9 script.
7730 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
7731 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007732 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00007733 do_cmdline_cmd(
7734 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
7735 do_cmdline_cmd(
7736 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007737 }
7738
Bram Moolenaar0f873732019-12-05 20:28:46 +01007739 // If wildcard expansion failed, we are editing the first file of the
7740 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007741 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7742 {
7743 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00007744 if (GARGCOUNT == 1 && used_file_full_path
7745 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
7746 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007747 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007748
7749 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007750}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007751
7752 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007753mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007754{
7755 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007756 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007757
Bram Moolenaar964b3742019-05-24 18:54:09 +02007758 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007759 if (envbuf == NULL)
7760 return -1;
7761
7762 sprintf((char *)envbuf, "%s=%s", var, value);
7763
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007764 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007765
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007766 vim_free(envbuf);
7767 if (p == NULL)
7768 return -1;
7769 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007770#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007771 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007772#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007773 // Unlike Un*x systems, we can free the string for _wputenv().
7774 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007775
7776 return 0;
7777}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007778
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007779/*
7780 * Support for 256 colors and 24-bit colors was added in Windows 10
7781 * version 1703 (Creators update).
7782 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007783#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7784
7785/*
7786 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02007787 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007788 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007789#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007790
7791/*
7792 * ConPTY differences between versions, need different logic.
7793 * version 1903 (May 2019 update).
7794 */
7795#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
7796
7797/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007798 * version 1909 (November 2019 update).
7799 */
7800#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
7801
7802/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007803 * Stay ahead of the next update, and when it's done, fix this.
7804 * version ? (2020 update, temporarily use the build number of insider preview)
7805 */
7806#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
7807
7808/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02007809 * Confirm until this version. Also the logic changes.
7810 * insider preview.
7811 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02007812#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007813
7814/*
7815 * Not stable now.
7816 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007817#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007818
7819 static void
7820vtp_flag_init(void)
7821{
7822 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007823#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007824 DWORD mode;
7825 HANDLE out;
7826
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007827# ifdef VIMDLL
7828 if (!gui.in_use)
7829# endif
7830 {
7831 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007832
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007833 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7834 GetConsoleMode(out, &mode);
7835 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7836 if (SetConsoleMode(out, mode) == 0)
7837 vtp_working = 0;
7838 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007839#endif
7840
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007841 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007842 conpty_working = 1;
7843 if (ver >= CONPTY_STABLE_BUILD)
7844 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007845
Bram Moolenaar57da6982019-09-13 22:30:11 +02007846 if (ver <= CONPTY_INSIDER_BUILD)
7847 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007848 if (ver <= CONPTY_1909_BUILD)
7849 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02007850 if (ver <= CONPTY_1903_BUILD)
7851 conpty_type = 2;
7852 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
7853 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007854
7855 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
7856 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007857}
7858
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007859#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007860
7861 static void
7862vtp_init(void)
7863{
K.Takata27b53be2022-09-18 12:25:49 +01007864 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007865# ifdef FEAT_TERMGUICOLORS
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01007866 COLORREF fg;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007867# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007868
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007869 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01007870 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007871 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7872 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
Bram Moolenaardf543822020-01-30 11:53:59 +01007873 store_console_bg_rgb = save_console_bg_rgb;
7874 store_console_fg_rgb = save_console_fg_rgb;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007875
7876# ifdef FEAT_TERMGUICOLORS
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01007877 if (!USE_WT)
7878 {
7879 COLORREF bg;
7880 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7881 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7882 default_console_color_bg = bg;
7883 }
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007884 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007885 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007886 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007887# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007888
7889 set_console_color_rgb();
7890}
7891
7892 static void
7893vtp_exit(void)
7894{
Bram Moolenaardf543822020-01-30 11:53:59 +01007895 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007896}
7897
Bram Moolenaar06b7b582020-05-30 17:49:25 +02007898 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007899vtp_printf(
7900 char *format,
7901 ...)
7902{
7903 char_u buf[100];
7904 va_list list;
7905 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007906 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007907
7908 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007909 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007910 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007911 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007912 return (int)result;
7913}
7914
7915 static void
7916vtp_sgr_bulk(
7917 int arg)
7918{
7919 int args[1];
7920
7921 args[0] = arg;
7922 vtp_sgr_bulks(1, args);
7923}
7924
K.Takata6e1d31e2022-02-03 13:05:32 +00007925# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007926 if ((*p-- = "0123456789"[(n = x % 10)]) \
7927 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
7928 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
7929
K.Takata6e1d31e2022-02-03 13:05:32 +00007930# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007931 case x: \
7932 FAST256(newargs[x - 1]);
7933
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007934 static void
7935vtp_sgr_bulks(
7936 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007937 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007938{
K.Takata6e1d31e2022-02-03 13:05:32 +00007939# define MAXSGR 16
7940# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007941 char_u buf[SGRBUFSIZE];
7942 char_u *p;
7943 int in, out;
7944 int newargs[16];
7945 static int sgrfgr = -1, sgrfgg, sgrfgb;
7946 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007947
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007948 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007949 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007950 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01007951 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007952 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007953 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007954
7955 in = out = 0;
7956 while (in < argc)
7957 {
7958 int s = args[in];
7959 int copylen = 1;
7960
7961 if (s == 38)
7962 {
7963 if (argc - in >= 5 && args[in + 1] == 2)
7964 {
7965 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
7966 && sgrfgb == args[in + 4])
7967 {
7968 in += 5;
7969 copylen = 0;
7970 }
7971 else
7972 {
7973 sgrfgr = args[in + 2];
7974 sgrfgg = args[in + 3];
7975 sgrfgb = args[in + 4];
7976 copylen = 5;
7977 }
7978 }
7979 else if (argc - in >= 3 && args[in + 1] == 5)
7980 {
7981 sgrfgr = -1;
7982 copylen = 3;
7983 }
7984 }
7985 else if (s == 48)
7986 {
7987 if (argc - in >= 5 && args[in + 1] == 2)
7988 {
7989 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
7990 && sgrbgb == args[in + 4])
7991 {
7992 in += 5;
7993 copylen = 0;
7994 }
7995 else
7996 {
7997 sgrbgr = args[in + 2];
7998 sgrbgg = args[in + 3];
7999 sgrbgb = args[in + 4];
8000 copylen = 5;
8001 }
8002 }
8003 else if (argc - in >= 3 && args[in + 1] == 5)
8004 {
8005 sgrbgr = -1;
8006 copylen = 3;
8007 }
8008 }
8009 else if (30 <= s && s <= 39)
8010 sgrfgr = -1;
8011 else if (90 <= s && s <= 97)
8012 sgrfgr = -1;
8013 else if (40 <= s && s <= 49)
8014 sgrbgr = -1;
8015 else if (100 <= s && s <= 107)
8016 sgrbgr = -1;
8017 else if (s == 0)
8018 sgrfgr = sgrbgr = -1;
8019
8020 while (copylen--)
8021 newargs[out++] = args[in++];
8022 }
8023
8024 p = &buf[sizeof(buf) - 1];
8025 *p-- = 'm';
8026
8027 switch (out)
8028 {
8029 int n, m;
8030 DWORD r;
8031
8032 FAST256CASE(16);
8033 *p-- = ';';
8034 FAST256CASE(15);
8035 *p-- = ';';
8036 FAST256CASE(14);
8037 *p-- = ';';
8038 FAST256CASE(13);
8039 *p-- = ';';
8040 FAST256CASE(12);
8041 *p-- = ';';
8042 FAST256CASE(11);
8043 *p-- = ';';
8044 FAST256CASE(10);
8045 *p-- = ';';
8046 FAST256CASE(9);
8047 *p-- = ';';
8048 FAST256CASE(8);
8049 *p-- = ';';
8050 FAST256CASE(7);
8051 *p-- = ';';
8052 FAST256CASE(6);
8053 *p-- = ';';
8054 FAST256CASE(5);
8055 *p-- = ';';
8056 FAST256CASE(4);
8057 *p-- = ';';
8058 FAST256CASE(3);
8059 *p-- = ';';
8060 FAST256CASE(2);
8061 *p-- = ';';
8062 FAST256CASE(1);
8063 *p-- = '[';
8064 *p = '\033';
8065 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8066 default:
8067 break;
8068 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008069}
8070
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008071 static void
8072wt_init(void)
8073{
8074 wt_working = (mch_getenv("WT_SESSION") != NULL);
8075}
8076
8077 int
8078use_wt(void)
8079{
8080 return USE_WT;
8081}
8082
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008083# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008084 static int
8085ctermtoxterm(
8086 int cterm)
8087{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008088 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008089
8090 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8091 return (((int)r << 16) | ((int)g << 8) | (int)b);
8092}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008093# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008094
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008095 static void
8096set_console_color_rgb(void)
8097{
8098# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008099 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008100 guicolor_T fg, bg;
8101 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008102
8103 if (!USE_VTP)
8104 return;
8105
Bram Moolenaara050b942019-12-02 21:35:31 +01008106 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8107
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008108 if (USE_WT)
8109 {
8110 term_fg_rgb_color(fg);
8111 term_bg_rgb_color(bg);
8112 return;
8113 }
8114
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008115 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8116 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8117
8118 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008119 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008120
8121 csbi.cbSize = sizeof(csbi);
8122 csbi.srWindow.Right += 1;
8123 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008124 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8125 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008126 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8127 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
K.Takata27b53be2022-09-18 12:25:49 +01008128 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008129# endif
8130}
8131
Bram Moolenaara050b942019-12-02 21:35:31 +01008132# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8133 void
8134get_default_console_color(
8135 int *cterm_fg,
8136 int *cterm_bg,
8137 guicolor_T *gui_fg,
8138 guicolor_T *gui_bg)
8139{
8140 int id;
8141 guicolor_T guifg = INVALCOLOR;
8142 guicolor_T guibg = INVALCOLOR;
8143 int ctermfg = 0;
8144 int ctermbg = 0;
8145
8146 id = syn_name2id((char_u *)"Normal");
8147 if (id > 0 && p_tgc)
8148 syn_id2colors(id, &guifg, &guibg);
8149 if (guifg == INVALCOLOR)
8150 {
8151 ctermfg = -1;
8152 if (id > 0)
8153 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8154 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
8155 : default_console_color_fg;
8156 cterm_normal_fg_gui_color = guifg;
8157 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8158 }
8159 if (guibg == INVALCOLOR)
8160 {
8161 ctermbg = -1;
8162 if (id > 0)
8163 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
K.Takatae53a0d42022-09-05 21:45:11 +01008164 if (USE_WT)
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008165 {
8166 cterm_normal_bg_gui_color = guibg =
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01008167 ctermbg != -1 ? ctermtoxterm(ctermbg) : INVALCOLOR;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008168 if (ctermbg < 0)
8169 ctermbg = 0;
8170 }
K.Takatae53a0d42022-09-05 21:45:11 +01008171 else
8172 {
8173 guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8174 : default_console_color_bg;
8175 cterm_normal_bg_gui_color = guibg;
8176 ctermbg = ctermbg < 0 ? 0 : ctermbg;
8177 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008178 }
8179
8180 *cterm_fg = ctermfg;
8181 *cterm_bg = ctermbg;
8182 *gui_fg = guifg;
8183 *gui_bg = guibg;
8184}
8185# endif
8186
Bram Moolenaardf543822020-01-30 11:53:59 +01008187/*
8188 * Set the console colors to the original colors or the last set colors.
8189 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008190 static void
8191reset_console_color_rgb(void)
8192{
8193# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008194 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008195
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008196 if (USE_WT)
8197 return;
8198
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008199 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008200 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008201
8202 csbi.cbSize = sizeof(csbi);
8203 csbi.srWindow.Right += 1;
8204 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008205 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8206 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008207 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008208# endif
8209}
8210
8211/*
8212 * Set the console colors to the original colors.
8213 */
8214 static void
8215restore_console_color_rgb(void)
8216{
8217# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008218 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008219
8220 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008221 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008222
8223 csbi.cbSize = sizeof(csbi);
8224 csbi.srWindow.Right += 1;
8225 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008226 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8227 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008228 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008229# endif
8230}
8231
8232 void
8233control_console_color_rgb(void)
8234{
8235 if (USE_VTP)
8236 set_console_color_rgb();
8237 else
8238 reset_console_color_rgb();
8239}
8240
8241 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008242use_vtp(void)
8243{
8244 return USE_VTP;
8245}
8246
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008247 int
8248is_term_win32(void)
8249{
8250 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8251}
8252
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008253 int
8254has_vtp_working(void)
8255{
8256 return vtp_working;
8257}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008258
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008259#endif
8260
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008261 int
8262has_conpty_working(void)
8263{
8264 return conpty_working;
8265}
8266
8267 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008268get_conpty_type(void)
8269{
8270 return conpty_type;
8271}
8272
8273 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008274is_conpty_stable(void)
8275{
8276 return conpty_stable;
8277}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008278
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008279 int
8280get_conpty_fix_type(void)
8281{
8282 return conpty_fix_type;
8283}
8284
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008285#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008286 void
8287resize_console_buf(void)
8288{
8289 CONSOLE_SCREEN_BUFFER_INFO csbi;
8290 COORD coord;
8291 SMALL_RECT newsize;
8292
8293 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8294 {
8295 coord.X = SRWIDTH(csbi.srWindow);
8296 coord.Y = SRHEIGHT(csbi.srWindow);
8297 SetConsoleScreenBufferSize(g_hConOut, coord);
8298
8299 newsize.Left = 0;
8300 newsize.Top = 0;
8301 newsize.Right = coord.X - 1;
8302 newsize.Bottom = coord.Y - 1;
8303 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8304
8305 SetConsoleScreenBufferSize(g_hConOut, coord);
8306 }
8307}
8308#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008309
8310 char *
8311GetWin32Error(void)
8312{
K.Takatad68b2fc2022-02-12 11:18:37 +00008313 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008314 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008315
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008316 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8317 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008318 if (oldmsg != NULL)
8319 LocalFree(oldmsg);
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008320 if (msg != NULL)
8321 {
8322 // remove trailing \r\n
8323 char *pcrlf = strstr(msg, "\r\n");
8324 if (pcrlf != NULL)
8325 *pcrlf = '\0';
K.Takatad68b2fc2022-02-12 11:18:37 +00008326 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008327 }
8328 return msg;
8329}
Paul Ollis65745772022-06-05 16:55:54 +01008330
8331#if defined(FEAT_RELTIME) || defined(PROTO)
8332static HANDLE timer_handle;
8333static int timer_active = FALSE;
8334
8335/*
8336 * Calls to start_timeout alternate the return value pointer between the two
8337 * entries in timeout_flags. If the previously active timeout is very close to
8338 * expiring when start_timeout() is called then a race condition means that the
8339 * set_flag() function may still be invoked after the previous timer is
8340 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8341 * timeouts.
8342 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008343static sig_atomic_t timeout_flags[2];
8344static int timeout_flag_idx = 0;
8345static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01008346
8347
8348 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01008349set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01008350{
8351 int *timeout_flag = (int *)param;
8352
8353 *timeout_flag = TRUE;
8354}
8355
8356/*
8357 * Stop any active timeout.
8358 */
8359 void
8360stop_timeout(void)
8361{
8362 if (timer_active)
8363 {
8364 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
8365 timer_active = FALSE;
8366 if (!ret && GetLastError() != ERROR_IO_PENDING)
8367 {
8368 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
8369 }
8370 }
8371 *timeout_flag = FALSE;
8372}
8373
8374/*
8375 * Start the timeout timer.
8376 *
8377 * The period is defined in milliseconds.
8378 *
8379 * The return value is a pointer to a flag that is initialised to 0. If the
8380 * timeout expires, the flag is set to 1. This will only return pointers to
8381 * static memory; i.e. any pointer returned by this function may always be
8382 * safely dereferenced.
8383 *
8384 * This function is not expected to fail, but if it does it still returns a
8385 * valid flag pointer; the flag will remain stuck at zero.
8386 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008387 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01008388start_timeout(long msec)
8389{
Paul Ollis65745772022-06-05 16:55:54 +01008390 BOOL ret;
8391
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008392 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01008393
8394 stop_timeout();
8395 ret = CreateTimerQueueTimer(
8396 &timer_handle, NULL, set_flag, timeout_flag,
8397 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
8398 if (!ret)
8399 {
8400 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
8401 }
8402 else
8403 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008404 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01008405 timer_active = TRUE;
8406 *timeout_flag = FALSE;
8407 }
8408 return timeout_flag;
8409}
8410#endif