blob: 4c97b31002a51b7c2a1182ca8365304667800ccf [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
12 * Used for both the console version and the Win32 GUI. A lot of code is for
Bram Moolenaar4f974752019-02-17 17:44:42 +010013 * the console version only, so there is a lot of "#ifndef FEAT_GUI_MSWIN".
Bram Moolenaar071d4272004-06-13 20:20:40 +000014 *
15 * Win32 (Windows NT and Windows 95) system-dependent routines.
16 * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17 * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18 *
19 * George V. Reilly <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
Bram Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010032
Bram Moolenaar0f873732019-12-05 20:28:46 +010033// cproto fails on missing include files
Bram Moolenaar82881492012-11-20 16:53:39 +010034#ifndef PROTO
35# include <process.h>
Bram Moolenaare7bebc42021-02-01 20:50:37 +010036# include <winternl.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010037#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000038
39#undef chdir
40#ifdef __GNUC__
41# ifndef __MINGW32__
42# include <dirent.h>
43# endif
44#else
45# include <direct.h>
46#endif
47
Bram Moolenaar82881492012-11-20 16:53:39 +010048#ifndef PROTO
Bram Moolenaar651fca82021-11-29 20:39:38 +000049# if !defined(FEAT_GUI_MSWIN)
Bram Moolenaar82881492012-11-20 16:53:39 +010050# include <shellapi.h>
51# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000052#endif
53
Bram Moolenaarfb630902016-10-29 14:55:00 +020054#ifdef FEAT_JOB_CHANNEL
55# include <tlhelp32.h>
56#endif
57
Bram Moolenaar071d4272004-06-13 20:20:40 +000058#ifdef __MINGW32__
59# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
60# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
61# endif
62# ifndef RIGHTMOST_BUTTON_PRESSED
63# define RIGHTMOST_BUTTON_PRESSED 0x0002
64# endif
65# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
66# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
67# endif
68# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
69# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
70# endif
71# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
72# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
73# endif
74
75/*
76 * EventFlags
77 */
78# ifndef MOUSE_MOVED
79# define MOUSE_MOVED 0x0001
80# endif
81# ifndef DOUBLE_CLICK
82# define DOUBLE_CLICK 0x0002
83# endif
84#endif
85
Bram Moolenaar0f873732019-12-05 20:28:46 +010086// Record all output and all keyboard & mouse input
87// #define MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +000088
89#ifdef MCH_WRITE_DUMP
90FILE* fdDump = NULL;
91#endif
92
93/*
94 * When generating prototypes for Win32 on Unix, these lines make the syntax
95 * errors disappear. They do not need to be correct.
96 */
97#ifdef PROTO
Bram Moolenaar912bc4a2019-12-01 18:58:11 +010098# define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000099typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000100typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000101typedef int ACCESS_MASK;
102typedef int BOOL;
Paul Ollis65745772022-06-05 16:55:54 +0100103typedef int BOOLEAN;
104typedef int CALLBACK;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000105typedef int COLORREF;
106typedef int CONSOLE_CURSOR_INFO;
107typedef int COORD;
108typedef int DWORD;
109typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100110typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000111typedef int HDC;
112typedef int HFONT;
113typedef int HICON;
114typedef int HINSTANCE;
115typedef int HWND;
116typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200117typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000118typedef int KEY_EVENT_RECORD;
119typedef int LOGFONT;
120typedef int LPBOOL;
121typedef int LPCTSTR;
122typedef int LPDWORD;
123typedef int LPSTR;
124typedef int LPTSTR;
125typedef int LPVOID;
126typedef int MOUSE_EVENT_RECORD;
127typedef int PACL;
128typedef int PDWORD;
129typedef int PHANDLE;
130typedef int PRINTDLG;
131typedef int PSECURITY_DESCRIPTOR;
132typedef int PSID;
133typedef int SECURITY_INFORMATION;
134typedef int SHORT;
135typedef int SMALL_RECT;
136typedef int TEXTMETRIC;
137typedef int TOKEN_INFORMATION_CLASS;
138typedef int TRUSTEE;
139typedef int WORD;
140typedef int WCHAR;
141typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100142typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200143typedef int SE_OBJECT_TYPE;
144typedef int PSNSECINFO;
145typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100146typedef int STARTUPINFO;
147typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200148typedef int LPSECURITY_ATTRIBUTES;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100149# define __stdcall // empty
Bram Moolenaar071d4272004-06-13 20:20:40 +0000150#endif
151
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200152#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100153// Win32 Console handles for input and output
Bram Moolenaar071d4272004-06-13 20:20:40 +0000154static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
155static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
156
Bram Moolenaar0f873732019-12-05 20:28:46 +0100157// Win32 Screen buffer,coordinate,console I/O information
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158static SMALL_RECT g_srScrollRegion;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100159static COORD g_coord; // 0-based, but external coords are 1-based
Bram Moolenaar071d4272004-06-13 20:20:40 +0000160
Bram Moolenaar0f873732019-12-05 20:28:46 +0100161// The attribute of the screen when the editor was started
162static WORD g_attrDefault = 7; // lightgray text on black background
Bram Moolenaar071d4272004-06-13 20:20:40 +0000163static WORD g_attrCurrent;
164
Bram Moolenaar0f873732019-12-05 20:28:46 +0100165static int g_fCBrkPressed = FALSE; // set by ctrl-break interrupt
166static int g_fCtrlCPressed = FALSE; // set when ctrl-C or ctrl-break detected
167static int g_fForceExit = FALSE; // set when forcefully exiting
Bram Moolenaar071d4272004-06-13 20:20:40 +0000168
Bram Moolenaar071d4272004-06-13 20:20:40 +0000169static void scroll(unsigned cLines);
170static void set_scroll_region(unsigned left, unsigned top,
171 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100172static void set_scroll_region_tb(unsigned top, unsigned bottom);
173static void set_scroll_region_lr(unsigned left, unsigned right);
174static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000175static void delete_lines(unsigned cLines);
176static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000177static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000178static int s_cursor_visible = TRUE;
179static int did_create_conin = FALSE;
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200180#endif
181#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000182static int s_dont_use_vimrun = TRUE;
183static int need_vimrun_warning = FALSE;
184static char *vimrun_path = "vimrun ";
185#endif
186
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200187static int win32_getattrs(char_u *name);
188static int win32_setattrs(char_u *name, int attrs);
189static int win32_set_archive(char_u *name);
190
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100191static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200192static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100193static int conpty_stable = 0;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +0200194static int conpty_fix_type = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100195static void vtp_flag_init();
196
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200197#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100198static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100199static void vtp_init();
200static void vtp_exit();
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100201static void vtp_sgr_bulk(int arg);
202static void vtp_sgr_bulks(int argc, int *argv);
203
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200204static int wt_working = 0;
Christopher Plewright1140b512022-11-12 18:46:05 +0000205static void wt_init(void);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200206
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200207static int g_color_index_bg = 0;
208static int g_color_index_fg = 7;
209
210# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +0000211static guicolor_T save_console_bg_rgb;
212static guicolor_T save_console_fg_rgb;
213static guicolor_T store_console_bg_rgb;
214static guicolor_T store_console_fg_rgb;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +0100215static int default_console_color_bg = 0x000000; // black
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200216static int default_console_color_fg = 0xc0c0c0; // white
Christopher Plewright38804d62022-11-09 23:55:52 +0000217# define USE_VTP (vtp_working && is_term_win32())
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200218# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100219# else
220# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200221# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100222# endif
223
224static void set_console_color_rgb(void);
225static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100226static void restore_console_color_rgb(void);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100227#endif
228
Bram Moolenaar0f873732019-12-05 20:28:46 +0100229// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100230#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
231# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
232#endif
233
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200234#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100235static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000236#endif
237
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200238static char_u *exe_path = NULL;
239
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100240static BOOL win8_or_later = FALSE;
Christopher Plewright1140b512022-11-12 18:46:05 +0000241static BOOL win11_or_later = FALSE;
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100242
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100243/*
244 * Get version number including build number
245 */
246typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100247#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100248 (((major) << 24) | ((minor) << 16) | (build))
249
250 static DWORD
251get_build_number(void)
252{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100253 OSVERSIONINFOW osver;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100254 HMODULE hNtdll;
255 PfnRtlGetVersion pRtlGetVersion;
256 DWORD ver = MAKE_VER(0, 0, 0);
257
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100258 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100259 hNtdll = GetModuleHandle("ntdll.dll");
260 if (hNtdll != NULL)
261 {
262 pRtlGetVersion =
263 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
264 pRtlGetVersion(&osver);
265 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
266 min(osver.dwMinorVersion, 255),
267 min(osver.dwBuildNumber, 32767));
268 }
269 return ver;
270}
271
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200272#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200273 static BOOL
274is_ambiwidth_event(
275 INPUT_RECORD *ir)
276{
277 return ir->EventType == KEY_EVENT
278 && ir->Event.KeyEvent.bKeyDown
279 && ir->Event.KeyEvent.wRepeatCount == 1
280 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
281 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000282 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200283 && ir->Event.KeyEvent.dwControlKeyState == 2;
284}
285
286 static void
287make_ambiwidth_event(
288 INPUT_RECORD *down,
289 INPUT_RECORD *up)
290{
291 down->Event.KeyEvent.wVirtualKeyCode = 0;
292 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000293 down->Event.KeyEvent.uChar.UnicodeChar
294 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200295 down->Event.KeyEvent.dwControlKeyState = 0;
296}
297
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100298/*
299 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100300 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100301 */
302 static BOOL
303read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100304 HANDLE hInput,
305 INPUT_RECORD *lpBuffer,
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100306 int nLength,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100307 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100308{
309 enum
310 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100311 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100312 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100313 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100314 static DWORD s_dwIndex = 0;
315 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100316 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100317 int head;
318 int tail;
319 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200320 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100321
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200322 if (nLength == -2)
323 return (s_dwMax > 0) ? TRUE : FALSE;
324
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100325 if (!win8_or_later)
326 {
327 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200328 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
329 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100330 }
331
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100332 if (s_dwMax == 0)
333 {
Christopher Plewright38804d62022-11-09 23:55:52 +0000334 if (!vtp_working && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200335 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200336 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
337 if (dwEvents == 0 && nLength == -1)
338 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
339 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100340 s_dwIndex = 0;
341 s_dwMax = dwEvents;
342 if (dwEvents == 0)
343 {
344 *lpEvents = 0;
345 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100346 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100347
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200348 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
349 if (is_ambiwidth_event(&s_irCache[i]))
350 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
351
Bram Moolenaardd415a62014-02-05 14:02:27 +0100352 if (s_dwMax > 1)
353 {
354 head = 0;
355 tail = s_dwMax - 1;
356 while (head != tail)
357 {
358 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
359 && s_irCache[head + 1].EventType
360 == WINDOW_BUFFER_SIZE_EVENT)
361 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100362 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100363 for (i = head; i < tail; ++i)
364 s_irCache[i] = s_irCache[i + 1];
365 --tail;
366 continue;
367 }
368 head++;
369 }
370 s_dwMax = tail + 1;
371 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100372 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100373
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200374 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
375 {
376 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
377 {
378 s_irPseudo = s_irCache[s_dwIndex];
379 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
380 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
381 *lpBuffer = s_irPseudo;
382 *lpEvents = 1;
383 return TRUE;
384 }
385 }
386
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100387 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200388 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100389 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100390 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100391 return TRUE;
392}
393
394/*
395 * Version of PeekConsoleInput() that works with IME.
396 */
397 static BOOL
398peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100399 HANDLE hInput,
400 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200401 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100402 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100403{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100404 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100405}
406
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100407# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200408 static DWORD
409msg_wait_for_multiple_objects(
410 DWORD nCount,
411 LPHANDLE pHandles,
412 BOOL fWaitAll,
413 DWORD dwMilliseconds,
414 DWORD dwWakeMask)
415{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100416 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200417 return WAIT_OBJECT_0;
418 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
419 dwMilliseconds, dwWakeMask);
420}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100421# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200422
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100423# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200424 static DWORD
425wait_for_single_object(
426 HANDLE hHandle,
427 DWORD dwMilliseconds)
428{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100429 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200430 return WAIT_OBJECT_0;
431 return WaitForSingleObject(hHandle, dwMilliseconds);
432}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100433# endif
434#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200435
Bram Moolenaar071d4272004-06-13 20:20:40 +0000436 static void
437get_exe_name(void)
438{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100439 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
440 // as the maximum length that works (plus a NUL byte).
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100441#define MAX_ENV_PATH_LEN 8192
442 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200443 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000444
445 if (exe_name == NULL)
446 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100447 // store the name of the executable, may be used for $VIM
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100448 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000449 if (*temp != NUL)
450 exe_name = FullName_save((char_u *)temp, FALSE);
451 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000452
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200453 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000454 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200455 exe_path = vim_strnsave(exe_name, gettail_sep(exe_name) - exe_name);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200456 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000457 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100458 // Append our starting directory to $PATH, so that when doing
459 // "!xxd" it's found in our starting directory. Needed because
460 // SearchPath() also looks there.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200461 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100462 if (p == NULL
463 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200464 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100465 if (p == NULL || *p == NUL)
466 temp[0] = NUL;
467 else
468 {
469 STRCPY(temp, p);
470 STRCAT(temp, ";");
471 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200472 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100473 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200474 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000475 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000476 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000477}
478
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200479/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100480 * Unescape characters in "p" that appear in "escaped".
481 */
482 static void
483unescape_shellxquote(char_u *p, char_u *escaped)
484{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100485 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100486 int n;
487
488 while (*p != NUL)
489 {
490 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
491 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100492 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100493 p += n;
494 l -= n;
495 }
496}
497
498/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200499 * Load library "name".
500 */
501 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000502vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200503{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200504 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200505
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200506 // No need to load any library when registering OLE.
507 if (found_register_arg)
508 return dll;
509
Bram Moolenaar0f873732019-12-05 20:28:46 +0100510 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
511 // vimLoadLib() recursively, which causes a stack overflow.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200512 if (exe_path == NULL)
513 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200514 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200515 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200516 WCHAR old_dirw[MAXPATHL];
517
518 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
519 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100520 // Change directory to where the executable is, both to make
521 // sure we find a .dll there and to avoid looking for a .dll
522 // in the current directory.
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100523 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200524 dll = LoadLibrary(name);
525 SetCurrentDirectoryW(old_dirw);
526 return dll;
527 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200528 }
529 return dll;
530}
531
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200532#if defined(VIMDLL) || defined(PROTO)
533/*
534 * Check if the current executable file is for the GUI subsystem.
535 */
536 int
537mch_is_gui_executable(void)
538{
539 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
540 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
541 PIMAGE_NT_HEADERS pPE;
542
543 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
544 return FALSE;
545 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
546 if (pPE->Signature != IMAGE_NT_SIGNATURE)
547 return FALSE;
548 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
549 return TRUE;
550 return FALSE;
551}
552#endif
553
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000554#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
555 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100556/*
557 * Get related information about 'funcname' which is imported by 'hInst'.
558 * If 'info' is 0, return the function address.
559 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000560 * If 'info' is 2, hook the function with 'ptr', and return the original
561 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100562 */
563 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000564get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
565 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100566{
567 PBYTE pImage = (PBYTE)hInst;
568 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
569 PIMAGE_NT_HEADERS pPE;
570 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100571 PIMAGE_THUNK_DATA pIAT; // Import Address Table
572 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100573 PIMAGE_IMPORT_BY_NAME pImpName;
574
575 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
576 return NULL;
577 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
578 if (pPE->Signature != IMAGE_NT_SIGNATURE)
579 return NULL;
580 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
581 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
582 .VirtualAddress);
583 for (; pImpDesc->FirstThunk; ++pImpDesc)
584 {
585 if (!pImpDesc->OriginalFirstThunk)
586 continue;
587 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
588 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
589 for (; pIAT->u1.Function; ++pIAT, ++pINT)
590 {
591 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
592 continue;
593 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
594 + (UINT_PTR)(pINT->u1.AddressOfData));
595 if (strcmp((char *)pImpName->Name, funcname) == 0)
596 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000597 void *original;
598 DWORD old, new = PAGE_READWRITE;
599
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100600 switch (info)
601 {
602 case 0:
603 return (void *)pIAT->u1.Function;
604 case 1:
605 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000606 case 2:
607 original = (void *)pIAT->u1.Function;
608 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
609 new, &old);
610 pIAT->u1.Function = (UINT_PTR)ptr;
611 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
612 old, &new);
613 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100614 default:
615 return NULL;
616 }
617 }
618 }
619 }
620 return NULL;
621}
622
623/*
624 * Get the module handle which 'funcname' in 'hInst' is imported from.
625 */
626 HINSTANCE
627find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
628{
629 char *modulename;
630
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000631 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100632 if (modulename != NULL)
633 return GetModuleHandleA(modulename);
634 return NULL;
635}
636
637/*
638 * Get the address of 'funcname' which is imported by 'hInst' DLL.
639 */
640 void *
641get_dll_import_func(HINSTANCE hInst, const char *funcname)
642{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000643 return get_imported_func_info(hInst, funcname, 0, NULL);
644}
645
646/*
647 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
648 * and return the original function address.
649 */
650 void *
651hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
652{
653 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100654}
655#endif
656
Bram Moolenaar071d4272004-06-13 20:20:40 +0000657#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
658# ifndef GETTEXT_DLL
659# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200660# define GETTEXT_DLL_ALT1 "libintl-8.dll"
661# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000662# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100663// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000664static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200665static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000666static char *null_libintl_textdomain(const char *);
667static char *null_libintl_bindtextdomain(const char *, const char *);
668static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100669static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000670
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200671static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000672char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200673char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
674 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000675char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
676char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000677 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000678char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
679 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100680int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000681
682 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100683dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000684{
685 int i;
686 static struct
687 {
688 char *name;
689 FARPROC *ptr;
690 } libintl_entry[] =
691 {
692 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200693 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000694 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
695 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
696 {NULL, NULL}
697 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100698 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000699
Bram Moolenaar7554c542018-10-06 15:03:15 +0200700 // No need to initialize twice.
701 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000702 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200703 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100704 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100705# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100706 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200707 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100708# endif
709# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200710 if (!hLibintlDLL)
711 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100712# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100713 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000714 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200715 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000716 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200717 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000718 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200719 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000720 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200721 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000722 }
723 for (i = 0; libintl_entry[i].name != NULL
724 && libintl_entry[i].ptr != NULL; ++i)
725 {
K.Takata54119102022-02-03 13:33:03 +0000726 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000727 libintl_entry[i].name)) == NULL)
728 {
729 dyn_libintl_end();
730 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000731 {
732 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000733 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000734 verbose_leave();
735 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000736 return 0;
737 }
738 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000739
Bram Moolenaar0f873732019-12-05 20:28:46 +0100740 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100741 dyn_libintl_bind_textdomain_codeset = (char *(*)(const char *, const char *))
742 GetProcAddress(hLibintlDLL, "bind_textdomain_codeset");
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000743 if (dyn_libintl_bind_textdomain_codeset == NULL)
744 dyn_libintl_bind_textdomain_codeset =
745 null_libintl_bind_textdomain_codeset;
746
Bram Moolenaar0f873732019-12-05 20:28:46 +0100747 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100748 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
749 if (hmsvcrt != NULL)
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100750 dyn_libintl_wputenv = (int (*)(const wchar_t *))
751 GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100752 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
753 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100754
Bram Moolenaar071d4272004-06-13 20:20:40 +0000755 return 1;
756}
757
758 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100759dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000760{
761 if (hLibintlDLL)
762 FreeLibrary(hLibintlDLL);
763 hLibintlDLL = NULL;
764 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200765 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000766 dyn_libintl_textdomain = null_libintl_textdomain;
767 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000768 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100769 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000770}
771
772 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000773null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000774{
775 return (char*)msgid;
776}
777
778 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200779null_libintl_ngettext(
780 const char *msgid,
781 const char *msgid_plural,
782 unsigned long n)
783{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200784 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200785}
786
Bram Moolenaaree695f72016-08-03 22:08:45 +0200787 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100788null_libintl_bindtextdomain(
789 const char *domainname UNUSED,
790 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000791{
792 return NULL;
793}
794
795 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100796null_libintl_bind_textdomain_codeset(
797 const char *domainname UNUSED,
798 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000799{
800 return NULL;
801}
802
803 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100804null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000805{
806 return NULL;
807}
808
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200809 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100810null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100811{
812 return 0;
813}
814
Bram Moolenaar0f873732019-12-05 20:28:46 +0100815#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000816
Bram Moolenaar0f873732019-12-05 20:28:46 +0100817// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000818
819#ifndef VER_PLATFORM_WIN32_WINDOWS
820# define VER_PLATFORM_WIN32_WINDOWS 1
821#endif
822
Bram Moolenaar071d4272004-06-13 20:20:40 +0000823#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100824# ifndef PROTO
825# include <aclapi.h>
826# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200827# ifndef PROTECTED_DACL_SECURITY_INFORMATION
828# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
829# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000830#endif
831
Bram Moolenaar27515922013-06-29 15:36:26 +0200832#ifdef HAVE_ACL
833/*
834 * Enables or disables the specified privilege.
835 */
836 static BOOL
837win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
838{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100839 BOOL bResult;
840 LUID luid;
841 HANDLE hToken;
842 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200843
844 if (!OpenProcessToken(GetCurrentProcess(),
845 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
846 return FALSE;
847
848 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
849 {
850 CloseHandle(hToken);
851 return FALSE;
852 }
853
Bram Moolenaar45500912014-07-09 20:51:07 +0200854 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200855 tokenPrivileges.Privileges[0].Luid = luid;
856 tokenPrivileges.Privileges[0].Attributes = bEnable ?
857 SE_PRIVILEGE_ENABLED : 0;
858
859 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
860 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
861
862 CloseHandle(hToken);
863
864 return bResult && GetLastError() == ERROR_SUCCESS;
865}
866#endif
867
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100868#ifdef _MSC_VER
869// Suppress the deprecation warning for using GetVersionEx().
870// It is needed for implementing "windowsversion()".
871# pragma warning(push)
872# pragma warning(disable: 4996)
873#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000874/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200875 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000876 */
877 void
878PlatformId(void)
879{
880 static int done = FALSE;
881
882 if (!done)
883 {
884 OSVERSIONINFO ovi;
885
886 ovi.dwOSVersionInfoSize = sizeof(ovi);
887 GetVersionEx(&ovi);
888
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200889#ifdef FEAT_EVAL
Bram Moolenaar0c1e3742019-12-27 13:49:24 +0100890 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
891 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200892#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100893 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
894 || ovi.dwMajorVersion > 6)
895 win8_or_later = TRUE;
896
Christopher Plewright1140b512022-11-12 18:46:05 +0000897 if ((ovi.dwMajorVersion == 10 && ovi.dwBuildNumber >= 22000)
898 || ovi.dwMajorVersion > 10)
899 win11_or_later = TRUE;
900
Bram Moolenaar071d4272004-06-13 20:20:40 +0000901#ifdef HAVE_ACL
Bram Moolenaar0f873732019-12-05 20:28:46 +0100902 // Enable privilege for getting or setting SACLs.
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200903 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000904#endif
905 done = TRUE;
906 }
907}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100908#ifdef _MSC_VER
909# pragma warning(pop)
910#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000911
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200912#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000913
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100914# define SHIFT (SHIFT_PRESSED)
915# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
916# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
917# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000918
919
Bram Moolenaar0f873732019-12-05 20:28:46 +0100920// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
921// We map function keys to their ANSI terminal equivalents, as produced
922// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
923// ANSI key with a value >= '\300' is nonstandard, but provided anyway
924// so that the user can have access to all SHIFT-, CTRL-, and ALT-
925// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000926
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000927static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000928{
929 WORD wVirtKey;
930 BOOL fAnsiKey;
931 int chAlone;
932 int chShift;
933 int chCtrl;
934 int chAlt;
935} VirtKeyMap[] =
936{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200937// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000938 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
939
940 { VK_F1, TRUE, ';', 'T', '^', 'h', },
941 { VK_F2, TRUE, '<', 'U', '_', 'i', },
942 { VK_F3, TRUE, '=', 'V', '`', 'j', },
943 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
944 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
945 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
946 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
947 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
948 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
949 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200950 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
951 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000952
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200953 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
954 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
955 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
956 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
957 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
958 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
959 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
960 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
961 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
962 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100963 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000964
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200965 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000966
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100967# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200968 // Most people don't have F13-F20, but what the hell...
969 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
970 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
971 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
972 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
973 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
974 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
975 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
976 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100977# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200978 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
979 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
980 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
981 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000982
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200983 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
984 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
985 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
986 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
987 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
988 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
989 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
990 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
991 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
992 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100993 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000994};
995
996
Bram Moolenaar0f873732019-12-05 20:28:46 +0100997/*
998 * The return code indicates key code size.
999 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001000 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001001win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001002 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001003{
1004 UINT uMods = pker->dwControlKeyState;
1005 static int s_iIsDead = 0;
1006 static WORD awAnsiCode[2];
1007 static BYTE abKeystate[256];
1008
1009
1010 if (s_iIsDead == 2)
1011 {
K.Takata972db232022-02-04 10:45:38 +00001012 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001013 s_iIsDead = 0;
1014 return 1;
1015 }
1016
K.Takata972db232022-02-04 10:45:38 +00001017 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001018 return 1;
1019
Bram Moolenaara80faa82020-04-12 19:37:17 +02001020 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001021
Bram Moolenaar0f873732019-12-05 20:28:46 +01001022 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001023 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001024
1025 if (uMods & SHIFT_PRESSED)
1026 abKeystate[VK_SHIFT] = 0x80;
1027 if (uMods & CAPSLOCK_ON)
1028 abKeystate[VK_CAPITAL] = 1;
1029
1030 if ((uMods & ALT_GR) == ALT_GR)
1031 {
1032 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1033 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1034 }
1035
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001036 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1037 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001038
1039 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001040 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001041
1042 return s_iIsDead;
1043}
1044
Bram Moolenaar071d4272004-06-13 20:20:40 +00001045static BOOL g_fJustGotFocus = FALSE;
1046
1047/*
1048 * Decode a KEY_EVENT into one or two keystrokes
1049 */
1050 static BOOL
1051decode_key_event(
1052 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001053 WCHAR *pch,
1054 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001055 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001056 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001057{
1058 int i;
1059 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1060
1061 *pch = *pch2 = NUL;
1062 g_fJustGotFocus = FALSE;
1063
Bram Moolenaar0f873732019-12-05 20:28:46 +01001064 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001065 if (!pker->bKeyDown)
1066 return FALSE;
1067
Bram Moolenaar0f873732019-12-05 20:28:46 +01001068 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001069 switch (pker->wVirtualKeyCode)
1070 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001071 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001072 case VK_SHIFT:
1073 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001074 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001075 return FALSE;
1076
1077 default:
1078 break;
1079 }
1080
Bram Moolenaar0f873732019-12-05 20:28:46 +01001081 // special cases
K.Takata972db232022-02-04 10:45:38 +00001082 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0
1083 && pker->uChar.UnicodeChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001084 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001085 // Ctrl-6 is Ctrl-^
Bram Moolenaar071d4272004-06-13 20:20:40 +00001086 if (pker->wVirtualKeyCode == '6')
1087 {
1088 *pch = Ctrl_HAT;
1089 return TRUE;
1090 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001091 // Ctrl-2 is Ctrl-@
Bram Moolenaar071d4272004-06-13 20:20:40 +00001092 else if (pker->wVirtualKeyCode == '2')
1093 {
1094 *pch = NUL;
1095 return TRUE;
1096 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001097 // Ctrl-- is Ctrl-_
Bram Moolenaar071d4272004-06-13 20:20:40 +00001098 else if (pker->wVirtualKeyCode == 0xBD)
1099 {
1100 *pch = Ctrl__;
1101 return TRUE;
1102 }
1103 }
1104
Bram Moolenaar0f873732019-12-05 20:28:46 +01001105 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001106 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1107 {
1108 *pch = K_NUL;
1109 *pch2 = '\017';
1110 return TRUE;
1111 }
1112
K.Takataeeec2542021-06-02 13:28:16 +02001113 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001114 {
1115 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1116 {
1117 if (nModifs == 0)
1118 *pch = VirtKeyMap[i].chAlone;
1119 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1120 *pch = VirtKeyMap[i].chShift;
1121 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1122 *pch = VirtKeyMap[i].chCtrl;
1123 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1124 *pch = VirtKeyMap[i].chAlt;
1125
1126 if (*pch != 0)
1127 {
1128 if (VirtKeyMap[i].fAnsiKey)
1129 {
1130 *pch2 = *pch;
1131 *pch = K_NUL;
1132 }
1133
1134 return TRUE;
1135 }
1136 }
1137 }
1138
1139 i = win32_kbd_patch_key(pker);
1140
1141 if (i < 0)
1142 *pch = NUL;
1143 else
1144 {
K.Takata972db232022-02-04 10:45:38 +00001145 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001146
1147 if (pmodifiers != NULL)
1148 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001149 // Pass on the ALT key as a modifier, but only when not combined
1150 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001151 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1152 *pmodifiers |= MOD_MASK_ALT;
1153
Bram Moolenaar0f873732019-12-05 20:28:46 +01001154 // Pass on SHIFT only for special keys, because we don't know when
1155 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001156 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1157 *pmodifiers |= MOD_MASK_SHIFT;
1158
Bram Moolenaar0f873732019-12-05 20:28:46 +01001159 // Pass on CTRL only for non-special keys, because we don't know
1160 // when it's already included with the character. And not when
1161 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001162 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1163 && *pch >= 0x20 && *pch < 0x80)
1164 *pmodifiers |= MOD_MASK_CTRL;
1165 }
1166 }
1167
1168 return (*pch != NUL);
1169}
1170
Bram Moolenaar0f873732019-12-05 20:28:46 +01001171#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001172
1173
Bram Moolenaar071d4272004-06-13 20:20:40 +00001174/*
1175 * For the GUI the mouse handling is in gui_w32.c.
1176 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001177#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001178 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001179mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001180{
1181}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001182#else
Bram Moolenaar0f873732019-12-05 20:28:46 +01001183static int g_fMouseAvail = FALSE; // mouse present
1184static int g_fMouseActive = FALSE; // mouse enabled
1185static int g_nMouseClick = -1; // mouse status
1186static int g_xMouse; // mouse x coordinate
1187static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001188static DWORD g_cmodein = 0; // Original console input mode
1189static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001190
1191/*
1192 * Enable or disable mouse input
1193 */
1194 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001195mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001196{
1197 DWORD cmodein;
1198
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001199# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001200 if (gui.in_use)
1201 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001202# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001203 if (!g_fMouseAvail)
1204 return;
1205
1206 g_fMouseActive = on;
1207 GetConsoleMode(g_hConIn, &cmodein);
1208
1209 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001210 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001211 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001212 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1213 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001214 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001215 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001216 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001217 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1218 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001219
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001220 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001221}
1222
Bram Moolenaar157d8132018-03-06 17:09:20 +01001223
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001224# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001225/*
1226 * Called when 'balloonevalterm' changed.
1227 */
1228 void
1229mch_bevalterm_changed(void)
1230{
1231 mch_setmouse(g_fMouseActive);
1232}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001233# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001234
Christopher Plewright2a46f812022-10-16 19:47:45 +01001235/*
1236 * Win32 console mouse scroll event handler.
1237 * Loosely based on the _OnMouseWheel() function in gui_w32.c
1238 *
1239 * This encodes the mouse scroll direction and keyboard modifiers into
1240 * g_nMouseClick, and the mouse position into g_xMouse and g_yMouse
1241 *
1242 * The direction of the scroll is decoded from two fields of the win32 console
1243 * mouse event record;
1244 * 1. The axis - vertical or horizontal flag - from dwEventFlags, and
1245 * 2. The sign - positive or negative (aka delta flag) - from dwButtonState
1246 *
1247 * When scroll axis is HORIZONTAL
1248 * - If the high word of the dwButtonState member contains a positive
1249 * value, the wheel was rotated to the right.
1250 * - Otherwise, the wheel was rotated to the left.
1251 * When scroll axis is VERTICAL
1252 * - If the high word of the dwButtonState member contains a positive value,
1253 * the wheel was rotated forward, away from the user.
1254 * - Otherwise, the wheel was rotated backward, toward the user.
1255 */
1256 static void
1257decode_mouse_wheel(MOUSE_EVENT_RECORD *pmer)
1258{
Christopher Plewright2a46f812022-10-16 19:47:45 +01001259 int horizontal = (pmer->dwEventFlags == MOUSE_HWHEELED);
1260 int zDelta = pmer->dwButtonState;
1261
1262 g_xMouse = pmer->dwMousePosition.X;
1263 g_yMouse = pmer->dwMousePosition.Y;
1264
K.Takata161b6ac2022-11-14 15:31:07 +00001265# ifdef FEAT_PROP_POPUP
Christopher Plewright605d02a2022-10-19 11:54:46 +01001266 int lcol = g_xMouse;
1267 int lrow = g_yMouse;
Christopher Plewright38804d62022-11-09 23:55:52 +00001268 win_T *wp = mouse_find_win(&lrow, &lcol, FIND_POPUP);
Christopher Plewright2a46f812022-10-16 19:47:45 +01001269 if (wp != NULL && popup_is_popup(wp))
1270 {
1271 g_nMouseClick = -1;
1272 cmdarg_T cap;
1273 oparg_T oa;
1274 CLEAR_FIELD(cap);
1275 clear_oparg(&oa);
1276 cap.oap = &oa;
1277 if (horizontal)
1278 {
1279 cap.arg = zDelta < 0 ? MSCR_LEFT : MSCR_RIGHT;
1280 cap.cmdchar = zDelta < 0 ? K_MOUSELEFT : K_MOUSERIGHT;
1281 }
1282 else
1283 {
1284 cap.cmdchar = zDelta < 0 ? K_MOUSEUP : K_MOUSEDOWN;
1285 cap.arg = zDelta < 0 ? MSCR_UP : MSCR_DOWN;
1286 }
1287
1288 // Mouse hovers over popup window, scroll it if possible.
1289 mouse_row = wp->w_winrow;
1290 mouse_col = wp->w_wincol;
1291 nv_mousescroll(&cap);
1292 update_screen(0);
1293 setcursor();
1294 out_flush();
1295 return;
1296 }
K.Takata161b6ac2022-11-14 15:31:07 +00001297# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01001298 mouse_col = g_xMouse;
1299 mouse_row = g_yMouse;
1300
1301 char_u modifiers = 0;
1302 char_u direction = 0;
1303
1304 // Decode the direction into an event that Vim can process
1305 if (horizontal)
1306 direction = zDelta >= 0 ? KE_MOUSELEFT : KE_MOUSERIGHT;
1307 else
1308 direction = zDelta >= 0 ? KE_MOUSEDOWN : KE_MOUSEUP;
1309
dundargocc57b5bc2022-11-02 13:30:51 +00001310 // Decode the win32 console key modifiers into Vim mouse modifiers.
Christopher Plewright2a46f812022-10-16 19:47:45 +01001311 if (pmer->dwControlKeyState & SHIFT_PRESSED)
Christopher Plewright605d02a2022-10-19 11:54:46 +01001312 modifiers |= MOD_MASK_SHIFT; // MOUSE_SHIFT;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001313 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
Christopher Plewright605d02a2022-10-19 11:54:46 +01001314 modifiers |= MOD_MASK_CTRL; // MOUSE_CTRL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001315 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1316 modifiers |= MOD_MASK_ALT; // MOUSE_ALT;
1317
1318 // add (bitwise or) the scroll direction and the key modifier chars
1319 // together.
1320 g_nMouseClick = ((direction << 8) | modifiers);
1321
1322 return;
1323}
1324
Bram Moolenaar071d4272004-06-13 20:20:40 +00001325/*
1326 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1327 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1328 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1329 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1330 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1331 * and we return the mouse position in g_xMouse and g_yMouse.
1332 *
1333 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1334 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1335 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1336 *
1337 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1338 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1339 *
1340 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1341 * moves, even if it stays within the same character cell. We ignore
1342 * all MOUSE_MOVED messages if the position hasn't really changed, and
1343 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1344 * we're only interested in MOUSE_DRAG).
1345 *
1346 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1347 * 2-button mouses by pressing the left & right buttons simultaneously.
1348 * In practice, it's almost impossible to click both at the same time,
1349 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1350 * in such cases, if the user is clicking quickly.
1351 */
1352 static BOOL
1353decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001354 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001355{
1356 static int s_nOldButton = -1;
1357 static int s_nOldMouseClick = -1;
1358 static int s_xOldMouse = -1;
1359 static int s_yOldMouse = -1;
1360 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001361# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001362 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001363# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001364 static int s_cClicks = 1;
1365 static BOOL s_fReleased = TRUE;
1366 static DWORD s_dwLastClickTime = 0;
1367 static BOOL s_fNextIsMiddle = FALSE;
1368
Bram Moolenaar0f873732019-12-05 20:28:46 +01001369 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001370
1371 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1372 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1373 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1374 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1375
1376 int nButton;
1377
1378 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1379 cButtons = 2;
1380
1381 if (!g_fMouseAvail || !g_fMouseActive)
1382 {
1383 g_nMouseClick = -1;
1384 return FALSE;
1385 }
1386
Bram Moolenaar0f873732019-12-05 20:28:46 +01001387 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001388 if (g_fJustGotFocus)
1389 {
1390 g_fJustGotFocus = FALSE;
1391 return FALSE;
1392 }
1393
Christopher Plewright605d02a2022-10-19 11:54:46 +01001394 // If there is an unprocessed mouse click drop this one.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001395 if (g_nMouseClick != -1)
1396 return TRUE;
Christopher Plewright605d02a2022-10-19 11:54:46 +01001397
Christopher Plewright2a46f812022-10-16 19:47:45 +01001398 if (pmer->dwEventFlags == MOUSE_WHEELED
1399 || pmer->dwEventFlags == MOUSE_HWHEELED)
1400 {
1401 decode_mouse_wheel(pmer);
1402 return TRUE; // we now should have a mouse scroll in g_nMouseClick
1403 }
Christopher Plewright605d02a2022-10-19 11:54:46 +01001404
Bram Moolenaar071d4272004-06-13 20:20:40 +00001405 nButton = -1;
1406 g_xMouse = pmer->dwMousePosition.X;
1407 g_yMouse = pmer->dwMousePosition.Y;
1408
1409 if (pmer->dwEventFlags == MOUSE_MOVED)
1410 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001411 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1412 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001413 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1414 return FALSE;
1415 }
1416
Bram Moolenaar0f873732019-12-05 20:28:46 +01001417 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001418 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1419 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001420 nButton = MOUSE_RELEASE;
1421
Bram Moolenaar0f873732019-12-05 20:28:46 +01001422 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001423 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001424 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001425# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001426 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001427 if (p_bevalterm)
1428 nButton = MOUSE_DRAG;
1429 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001430# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001431 return FALSE;
1432 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001433
Bram Moolenaar071d4272004-06-13 20:20:40 +00001434 s_fReleased = TRUE;
1435 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001436 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001437 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001438 // on a 2-button mouse, hold down left and right buttons
1439 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001440
1441 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1442 {
1443 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1444
Bram Moolenaar0f873732019-12-05 20:28:46 +01001445 // if either left or right button only is pressed, see if the
1446 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001447 if (dwLR == LEFT || dwLR == RIGHT)
1448 {
1449 for (;;)
1450 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001451 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001452 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1453 != WAIT_OBJECT_0)
1454 break;
1455 else
1456 {
1457 DWORD cRecords = 0;
1458 INPUT_RECORD ir;
1459 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1460
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001461 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001462
1463 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1464 || !(pmer2->dwButtonState & LEFT_RIGHT))
1465 break;
1466 else
1467 {
1468 if (pmer2->dwEventFlags != MOUSE_MOVED)
1469 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001470 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001471
1472 return decode_mouse_event(pmer2);
1473 }
1474 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1475 s_yOldMouse == pmer2->dwMousePosition.Y)
1476 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001477 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001478 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001479
Bram Moolenaar0f873732019-12-05 20:28:46 +01001480 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001481 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001482
1483 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1484 break;
1485 }
1486 else
1487 break;
1488 }
1489 }
1490 }
1491 }
1492 }
1493
1494 if (s_fNextIsMiddle)
1495 {
1496 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1497 ? MOUSE_DRAG : MOUSE_MIDDLE;
1498 s_fNextIsMiddle = FALSE;
1499 }
1500 else if (cButtons == 2 &&
1501 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1502 {
1503 nButton = MOUSE_MIDDLE;
1504
1505 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1506 {
1507 s_fNextIsMiddle = TRUE;
1508 nButton = MOUSE_RELEASE;
1509 }
1510 }
1511 else if ((pmer->dwButtonState & LEFT) == LEFT)
1512 nButton = MOUSE_LEFT;
1513 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1514 nButton = MOUSE_MIDDLE;
1515 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1516 nButton = MOUSE_RIGHT;
1517
1518 if (! s_fReleased && ! s_fNextIsMiddle
1519 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1520 return FALSE;
1521
1522 s_fReleased = s_fNextIsMiddle;
1523 }
1524
1525 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1526 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001527 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001528 if (nButton != -1 && nButton != MOUSE_RELEASE)
1529 {
1530 DWORD dwCurrentTime = GetTickCount();
1531
1532 if (s_xOldMouse != g_xMouse
1533 || s_yOldMouse != g_yMouse
1534 || s_nOldButton != nButton
1535 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001536# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001537 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001538# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001539 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1540 {
1541 s_cClicks = 1;
1542 }
1543 else if (++s_cClicks > 4)
1544 {
1545 s_cClicks = 1;
1546 }
1547
1548 s_dwLastClickTime = dwCurrentTime;
1549 }
1550 }
1551 else if (pmer->dwEventFlags == MOUSE_MOVED)
1552 {
1553 if (nButton != -1 && nButton != MOUSE_RELEASE)
1554 nButton = MOUSE_DRAG;
1555
1556 s_cClicks = 1;
1557 }
1558
1559 if (nButton == -1)
1560 return FALSE;
1561
1562 if (nButton != MOUSE_RELEASE)
1563 s_nOldButton = nButton;
1564
1565 g_nMouseClick = nButton;
1566
1567 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1568 g_nMouseClick |= MOUSE_SHIFT;
1569 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1570 g_nMouseClick |= MOUSE_CTRL;
1571 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1572 g_nMouseClick |= MOUSE_ALT;
1573
1574 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1575 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1576
Bram Moolenaar0f873732019-12-05 20:28:46 +01001577 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001578 if (s_xOldMouse == g_xMouse
1579 && s_yOldMouse == g_yMouse
1580 && s_nOldMouseClick == g_nMouseClick)
1581 {
1582 g_nMouseClick = -1;
1583 return FALSE;
1584 }
1585
1586 s_xOldMouse = g_xMouse;
1587 s_yOldMouse = g_yMouse;
1588 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001589# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001590 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001591# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001592 s_nOldMouseClick = g_nMouseClick;
1593
1594 return TRUE;
1595}
1596
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001597#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001598
1599
1600#ifdef MCH_CURSOR_SHAPE
1601/*
1602 * Set the shape of the cursor.
1603 * 'thickness' can be from 1 (thin) to 99 (block)
1604 */
1605 static void
1606mch_set_cursor_shape(int thickness)
1607{
Christopher Plewright38804d62022-11-09 23:55:52 +00001608 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01001609 {
1610 if (*T_CSI == NUL)
1611 {
1612 // If 't_SI' is not set, use the default cursor styles.
1613 if (thickness < 50)
1614 vtp_printf("\033[3 q"); // underline
1615 else
1616 vtp_printf("\033[0 q"); // default
1617 }
1618 }
1619 else
1620 {
1621 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1622 ConsoleCursorInfo.dwSize = thickness;
1623 ConsoleCursorInfo.bVisible = s_cursor_visible;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001624
K.Takatadf5320c2022-09-01 13:20:16 +01001625 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1626 if (s_cursor_visible)
1627 SetConsoleCursorPosition(g_hConOut, g_coord);
1628 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001629}
1630
1631 void
1632mch_update_cursor(void)
1633{
1634 int idx;
1635 int thickness;
1636
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001637# ifdef VIMDLL
1638 if (gui.in_use)
1639 return;
1640# endif
1641
Bram Moolenaar071d4272004-06-13 20:20:40 +00001642 /*
1643 * How the cursor is drawn depends on the current mode.
1644 */
1645 idx = get_shape_idx(FALSE);
1646
1647 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001648 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00001649 else
1650 thickness = shape_table[idx].percentage;
1651 mch_set_cursor_shape(thickness);
1652}
1653#endif
1654
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001655#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001656/*
1657 * Handle FOCUS_EVENT.
1658 */
1659 static void
1660handle_focus_event(INPUT_RECORD ir)
1661{
1662 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1663 ui_focus_change((int)g_fJustGotFocus);
1664}
1665
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001666static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1667
Bram Moolenaar071d4272004-06-13 20:20:40 +00001668/*
1669 * Wait until console input from keyboard or mouse is available,
1670 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001671 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001672 * Return TRUE if something is available FALSE if not.
1673 */
1674 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001675WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001676{
1677 DWORD dwNow = 0, dwEndTime = 0;
1678 INPUT_RECORD ir;
1679 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001680 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001681# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001682 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001683# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001684
1685 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001686 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001687 dwEndTime = GetTickCount() + msec;
1688 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001689 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001690 dwEndTime = INFINITE;
1691
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001692 // We need to loop until the end of the time period, because
1693 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001694 for (;;)
1695 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001696 // Only process messages when waiting.
1697 if (msec != 0)
1698 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001699# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001700 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001701# endif
1702# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001703 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001704# endif
1705# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001706 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001707# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001708 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001709
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001710 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001711# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001712 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001713# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001714 )
1715 return TRUE;
1716
1717 if (msec > 0)
1718 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001719 // If the specified wait time has passed, return. Beware that
1720 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001721 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001722 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001723 break;
1724 }
1725 if (msec != 0)
1726 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001727 DWORD dwWaitTime = dwEndTime - dwNow;
1728
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001729 // Don't wait for more than 11 msec to avoid dropping characters,
1730 // check channel while waiting for input and handle a callback from
1731 // 'balloonexpr'.
1732 if (dwWaitTime > 11)
1733 dwWaitTime = 11;
1734
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001735# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001736 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001737 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001738# endif
1739# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001740 // When waiting very briefly don't trigger timers.
1741 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001742 {
1743 long due_time;
1744
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001745 // Trigger timers and then get the time in msec until the next
1746 // one is due. Wait up to that time.
1747 due_time = check_due_timer();
1748 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001749 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001750 // timer may have used feedkeys().
1751 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001752 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001753 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1754 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001755 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001756# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001757 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001758# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001759 // Wait for either an event on the console input or a
1760 // message in the client-server window.
1761 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1762 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001763# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001764 wait_for_single_object(g_hConIn, dwWaitTime)
1765 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001766# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001767 )
1768 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001769 }
1770
1771 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001772 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001773
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001774# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02001775 // May have to redraw if the cursor ends up in the wrong place.
1776 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01001777 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001778 {
1779 CONSOLE_SCREEN_BUFFER_INFO csbi;
1780
1781 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1782 {
1783 if (csbi.dwCursorPosition.Y != msg_row)
1784 {
matveyte08795e2021-05-07 15:00:17 +02001785 // The screen is now messed up, must redraw the command
1786 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01001787 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02001788 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001789 redrawcmd();
1790 }
1791 }
1792 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001793# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001794
1795 if (cRecords > 0)
1796 {
1797 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1798 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001799# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01001800 // Windows IME sends two '\n's with only one 'ENTER'. First:
1801 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00001802 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001803 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1804 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001805 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001806 continue;
1807 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001808# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001809 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1810 NULL, FALSE))
1811 return TRUE;
1812 }
1813
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001814 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001815
1816 if (ir.EventType == FOCUS_EVENT)
1817 handle_focus_event(ir);
1818 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001819 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001820 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1821
Bram Moolenaar36698e32019-12-11 22:57:40 +01001822 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001823 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001824 if (dwSize.X != Columns || dwSize.Y != Rows)
1825 {
1826 CONSOLE_SCREEN_BUFFER_INFO csbi;
1827 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01001828 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001829 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01001830 if (dwSize.X != Columns || dwSize.Y != Rows)
1831 {
1832 ResizeConBuf(g_hConOut, dwSize);
1833 shell_resized();
1834 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001835 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001836 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001837 else if (ir.EventType == MOUSE_EVENT
1838 && decode_mouse_event(&ir.Event.MouseEvent))
1839 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001840 }
1841 else if (msec == 0)
1842 break;
1843 }
1844
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001845# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01001846 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001847 if (input_available())
1848 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001849# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001850
Bram Moolenaar071d4272004-06-13 20:20:40 +00001851 return FALSE;
1852}
1853
Bram Moolenaar071d4272004-06-13 20:20:40 +00001854/*
1855 * return non-zero if a character is available
1856 */
1857 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001858mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001859{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001860# ifdef VIMDLL
1861 if (gui.in_use)
1862 return TRUE;
1863# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001864 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001865}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001866
1867# if defined(FEAT_TERMINAL) || defined(PROTO)
1868/*
1869 * Check for any pending input or messages.
1870 */
1871 int
1872mch_check_messages(void)
1873{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001874# ifdef VIMDLL
1875 if (gui.in_use)
1876 return TRUE;
1877# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001878 return WaitForChar(0L, TRUE);
1879}
1880# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001881
1882/*
1883 * Create the console input. Used when reading stdin doesn't work.
1884 */
1885 static void
1886create_conin(void)
1887{
1888 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1889 FILE_SHARE_READ|FILE_SHARE_WRITE,
1890 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001891 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001892 did_create_conin = TRUE;
1893}
1894
1895/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001896 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001897 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001898 static WCHAR
1899tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001900{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001901 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001902
1903 for (;;)
1904 {
1905 INPUT_RECORD ir;
1906 DWORD cRecords = 0;
1907
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001908# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001909 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001910 if (input_available())
1911 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001912 if (g_nMouseClick != -1)
1913 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001914# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001915 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001916 {
1917 if (did_create_conin)
1918 read_error_exit();
1919 create_conin();
1920 continue;
1921 }
1922
1923 if (ir.EventType == KEY_EVENT)
1924 {
1925 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1926 pmodifiers, TRUE))
1927 return ch;
1928 }
1929 else if (ir.EventType == FOCUS_EVENT)
1930 handle_focus_event(ir);
1931 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1932 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001933 else if (ir.EventType == MOUSE_EVENT)
1934 {
1935 if (decode_mouse_event(&ir.Event.MouseEvent))
1936 return 0;
1937 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001938 }
1939}
Bram Moolenaar0f873732019-12-05 20:28:46 +01001940#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001941
1942
1943/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001944 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001945 * Get one or more characters from the keyboard or the mouse.
1946 * If time == 0, do not wait for characters.
1947 * If time == n, wait a short time for characters.
1948 * If time == -1, wait forever for characters.
1949 * Returns the number of characters read into buf.
1950 */
1951 int
1952mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001953 char_u *buf UNUSED,
1954 int maxlen UNUSED,
1955 long time UNUSED,
1956 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001957{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001958#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001959
1960 int len;
1961 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001962# ifdef VIMDLL
1963// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
1964# define TYPEAHEADSPACE 6
1965# else
1966# define TYPEAHEADSPACE 0
1967# endif
1968# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001969 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001970 static int typeaheadlen = 0;
1971
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001972# ifdef VIMDLL
1973 if (gui.in_use)
1974 return 0;
1975# endif
1976
Bram Moolenaar0f873732019-12-05 20:28:46 +01001977 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001978 if (typeaheadlen > 0)
1979 goto theend;
1980
Bram Moolenaar071d4272004-06-13 20:20:40 +00001981 if (time >= 0)
1982 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001983 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00001984 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001985 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001986 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00001987 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001988 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00001989
Bram Moolenaar3918c952005-03-15 22:34:55 +00001990 /*
1991 * If there is no character available within 2 seconds (default)
1992 * write the autoscript file to disk. Or cause the CursorHold event
1993 * to be triggered.
1994 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001995 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001996 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001997 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001998 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001999 buf[0] = K_SPECIAL;
2000 buf[1] = KS_EXTRA;
2001 buf[2] = (int)KE_CURSORHOLD;
2002 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002003 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00002004 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002005 }
2006 }
2007
2008 /*
2009 * Try to read as many characters as there are, until the buffer is full.
2010 */
2011
Bram Moolenaar0f873732019-12-05 20:28:46 +01002012 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002013 g_fCBrkPressed = FALSE;
2014
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002015# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002016 if (fdDump)
2017 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002018# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002019
Bram Moolenaar0f873732019-12-05 20:28:46 +01002020 // Keep looping until there is something in the typeahead buffer and more
2021 // to get and still room in the buffer (up to two bytes for a char and
2022 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002023 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01002024 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002025 {
2026 if (typebuf_changed(tb_change_cnt))
2027 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002028 // "buf" may be invalid now if a client put something in the
2029 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002030 typeaheadlen = 0;
2031 break;
2032 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002033 if (g_nMouseClick != -1)
2034 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002035# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002036 if (fdDump)
2037 fprintf(fdDump, "{%02x @ %d, %d}",
2038 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002039# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01002040 char_u modifiers = ((char_u *)(&g_nMouseClick))[0];
2041 char_u scroll_dir = ((char_u *)(&g_nMouseClick))[1];
2042
2043 if (scroll_dir == KE_MOUSEDOWN
2044 || scroll_dir == KE_MOUSEUP
2045 || scroll_dir == KE_MOUSELEFT
2046 || scroll_dir == KE_MOUSERIGHT)
2047 {
2048 if (modifiers > 0)
2049 {
Christopher Plewright03193062022-11-22 12:58:27 +00002050 // use K_SPECIAL instead of CSI to make mappings work
2051 typeahead[typeaheadlen++] = K_SPECIAL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002052 typeahead[typeaheadlen++] = KS_MODIFIER;
2053 typeahead[typeaheadlen++] = modifiers;
2054 }
2055 typeahead[typeaheadlen++] = CSI;
2056 typeahead[typeaheadlen++] = KS_EXTRA;
2057 typeahead[typeaheadlen++] = scroll_dir;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002058 }
2059 else
2060 {
2061 typeahead[typeaheadlen++] = ESC + 128;
2062 typeahead[typeaheadlen++] = 'M';
2063 typeahead[typeaheadlen++] = g_nMouseClick;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002064 }
Christopher Plewright36446bb2022-11-23 22:28:08 +00002065
2066 // Pass the pointer coordinates of the mouse event in 2 bytes,
2067 // allowing for > 223 columns. Both for click and scroll events.
2068 // This is the same as what is used for the GUI.
2069 typeahead[typeaheadlen++] = (char_u)(g_xMouse / 128 + ' ' + 1);
2070 typeahead[typeaheadlen++] = (char_u)(g_xMouse % 128 + ' ' + 1);
2071 typeahead[typeaheadlen++] = (char_u)(g_yMouse / 128 + ' ' + 1);
2072 typeahead[typeaheadlen++] = (char_u)(g_yMouse % 128 + ' ' + 1);
2073
2074 g_nMouseClick = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002075 }
2076 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002077 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002078 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002079 int modifiers = 0;
2080
2081 c = tgetch(&modifiers, &ch2);
2082
2083 if (typebuf_changed(tb_change_cnt))
2084 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002085 // "buf" may be invalid now if a client put something in the
2086 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002087 typeaheadlen = 0;
2088 break;
2089 }
2090
2091 if (c == Ctrl_C && ctrl_c_interrupts)
2092 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002093# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002094 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002095# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002096 got_int = TRUE;
2097 }
2098
Bram Moolenaar071d4272004-06-13 20:20:40 +00002099 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002100 {
2101 int n = 1;
2102
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002103 if (ch2 == NUL)
2104 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002105 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002106 char_u *p;
2107 WCHAR ch[2];
2108
2109 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002110 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002111 {
2112 ch[1] = tgetch(&modifiers, &ch2);
2113 n++;
2114 }
2115 p = utf16_to_enc(ch, &n);
2116 if (p != NULL)
2117 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002118 for (i = 0, j = 0; i < n; i++)
2119 {
2120 typeahead[typeaheadlen + j++] = p[i];
2121# ifdef VIMDLL
2122 if (p[i] == CSI)
2123 {
2124 typeahead[typeaheadlen + j++] = KS_EXTRA;
2125 typeahead[typeaheadlen + j++] = KE_CSI;
2126 }
2127# endif
2128 }
2129 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002130 vim_free(p);
2131 }
2132 }
2133 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002134 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002135 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002136# ifdef VIMDLL
2137 if (c == CSI)
2138 {
2139 typeahead[typeaheadlen + 1] = KS_EXTRA;
2140 typeahead[typeaheadlen + 2] = KE_CSI;
2141 n = 3;
2142 }
2143# endif
2144 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002145 if (ch2 != NUL)
2146 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002147 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002148 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002149 switch (ch2)
2150 {
2151 case (WCHAR)'\324': // SHIFT+Insert
2152 case (WCHAR)'\325': // CTRL+Insert
2153 case (WCHAR)'\327': // SHIFT+Delete
2154 case (WCHAR)'\330': // CTRL+Delete
2155 typeahead[typeaheadlen + n] = (char_u)ch2;
2156 n++;
2157 break;
2158
2159 default:
2160 typeahead[typeaheadlen + n] = 3;
2161 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2162 n += 2;
2163 break;
2164 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002165 }
2166 else
2167 {
2168 typeahead[typeaheadlen + n] = 3;
2169 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2170 n += 2;
2171 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002172 }
2173
Bram Moolenaar0f873732019-12-05 20:28:46 +01002174 // Use the ALT key to set the 8th bit of the character
2175 // when it's one byte, the 8th bit isn't set yet and not
2176 // using a double-byte encoding (would become a lead
2177 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002178 if ((modifiers & MOD_MASK_ALT)
2179 && n == 1
2180 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002181 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002182 )
2183 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002184 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2185 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002186 modifiers &= ~MOD_MASK_ALT;
2187 }
2188
2189 if (modifiers != 0)
2190 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002191 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002192 mch_memmove(typeahead + typeaheadlen + 3,
2193 typeahead + typeaheadlen, n);
2194 typeahead[typeaheadlen++] = K_SPECIAL;
2195 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2196 typeahead[typeaheadlen++] = modifiers;
2197 }
2198
2199 typeaheadlen += n;
2200
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002201# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002202 if (fdDump)
2203 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002204# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002205 }
2206 }
2207 }
2208
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002209# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002210 if (fdDump)
2211 {
2212 fputs("]\n", fdDump);
2213 fflush(fdDump);
2214 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002215# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002216
Bram Moolenaar071d4272004-06-13 20:20:40 +00002217theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002218 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002219 len = 0;
2220 while (len < maxlen && typeaheadlen > 0)
2221 {
2222 buf[len++] = typeahead[0];
2223 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2224 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002225# ifdef FEAT_JOB_CHANNEL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002226 if (len > 0)
2227 {
2228 buf[len] = NUL;
2229 ch_log(NULL, "raw key input: \"%s\"", buf);
2230 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002231# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002232 return len;
2233
Bram Moolenaar0f873732019-12-05 20:28:46 +01002234#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002235 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002236#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002237}
2238
Bram Moolenaar82881492012-11-20 16:53:39 +01002239#ifndef PROTO
2240# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002241# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002242# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002243#endif
2244
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002245/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002246 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002247 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2248 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002249 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002250 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002251 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002252executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002253{
LemonBoy40fd7e62022-05-05 20:18:16 +01002254 int attrs = win32_getattrs((char_u *)name);
2255
2256 // The file doesn't exist or is a folder.
2257 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2258 return FALSE;
2259 // Check if the file is an AppExecLink, a special alias used by Windows
2260 // Store for its apps.
2261 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002262 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002263 char_u *res = resolve_appexeclink((char_u *)name);
2264 if (res == NULL)
2265 return FALSE;
2266 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002267 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002268 *path = res;
2269 else
2270 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002271 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002272 else if (path != NULL)
2273 *path = FullName_save((char_u *)name, FALSE);
2274 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002275}
2276
2277/*
2278 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2279 * If "use_path" is FALSE: Return TRUE if "name" exists.
2280 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2281 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2282 * the allocated memory.
2283 */
2284 static int
2285executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2286{
2287 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2288 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2289 // UTF-8.
2290 char_u buf[_MAX_PATH * 3];
2291 size_t len = STRLEN(name);
2292 size_t tmplen;
2293 char_u *p, *e, *e2;
2294 char_u *pathbuf = NULL;
2295 char_u *pathext = NULL;
2296 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002297 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002298 int noext = FALSE;
2299 int retval = FALSE;
2300
2301 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002302 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002303
2304 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002305 shname = gettail(p_sh);
2306 if (strstr((char *)shname, "sh") != NULL &&
2307 !(strstr((char *)shname, "powershell") != NULL
2308 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002309 noext = TRUE;
2310
2311 if (use_pathext)
2312 {
2313 pathext = mch_getenv("PATHEXT");
2314 if (pathext == NULL)
2315 pathext = (char_u *)".com;.exe;.bat;.cmd";
2316
2317 if (noext == FALSE)
2318 {
2319 /*
2320 * Loop over all extensions in $PATHEXT.
2321 * Check "name" ends with extension.
2322 */
2323 p = pathext;
2324 while (*p)
2325 {
2326 if (p[0] == ';'
2327 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2328 {
2329 // Skip empty or single ".".
2330 ++p;
2331 continue;
2332 }
2333 e = vim_strchr(p, ';');
2334 if (e == NULL)
2335 e = p + STRLEN(p);
2336 tmplen = e - p;
2337
2338 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2339 {
2340 noext = TRUE;
2341 break;
2342 }
2343
2344 p = e;
2345 }
2346 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002347 }
2348
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002349 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002350 if (pathext == NULL)
2351 pathext = (char_u *)".";
2352 else if (noext == TRUE)
2353 {
2354 if (pathextbuf == NULL)
2355 pathextbuf = alloc(STRLEN(pathext) + 3);
2356 if (pathextbuf == NULL)
2357 {
2358 retval = FALSE;
2359 goto theend;
2360 }
2361 STRCPY(pathextbuf, ".;");
2362 STRCAT(pathextbuf, pathext);
2363 pathext = pathextbuf;
2364 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002365
Bram Moolenaar95da1362020-05-30 18:37:55 +02002366 // Use $PATH when "use_path" is TRUE and "name" is basename.
2367 if (use_path && gettail((char_u *)name) == (char_u *)name)
2368 {
2369 p = mch_getenv("PATH");
2370 if (p != NULL)
2371 {
2372 pathbuf = alloc(STRLEN(p) + 3);
2373 if (pathbuf == NULL)
2374 {
2375 retval = FALSE;
2376 goto theend;
2377 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002378
2379 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2380 STRCPY(pathbuf, ".;");
2381 else
2382 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002383 STRCAT(pathbuf, p);
2384 }
2385 }
2386
2387 /*
2388 * Walk through all entries in $PATH to check if "name" exists there and
2389 * is an executable file.
2390 */
2391 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2392 while (*p)
2393 {
2394 if (*p == ';') // Skip empty entry
2395 {
2396 ++p;
2397 continue;
2398 }
2399 e = vim_strchr(p, ';');
2400 if (e == NULL)
2401 e = p + STRLEN(p);
2402
2403 if (e - p + len + 2 > sizeof(buf))
2404 {
2405 retval = FALSE;
2406 goto theend;
2407 }
2408 // A single "." that means current dir.
2409 if (e - p == 1 && *p == '.')
2410 STRCPY(buf, name);
2411 else
2412 {
2413 vim_strncpy(buf, p, e - p);
2414 add_pathsep(buf);
2415 STRCAT(buf, name);
2416 }
2417 tmplen = STRLEN(buf);
2418
2419 /*
2420 * Loop over all extensions in $PATHEXT.
2421 * Check "name" with extension added.
2422 */
2423 p = pathext;
2424 while (*p)
2425 {
2426 if (*p == ';')
2427 {
2428 // Skip empty entry
2429 ++p;
2430 continue;
2431 }
2432 e2 = vim_strchr(p, (int)';');
2433 if (e2 == NULL)
2434 e2 = p + STRLEN(p);
2435
2436 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2437 {
2438 // Not a single "." that means no extension is added.
2439 if (e2 - p + tmplen + 1 > sizeof(buf))
2440 {
2441 retval = FALSE;
2442 goto theend;
2443 }
2444 vim_strncpy(buf + tmplen, p, e2 - p);
2445 }
2446 if (executable_file((char *)buf, path))
2447 {
2448 retval = TRUE;
2449 goto theend;
2450 }
2451
2452 p = e2;
2453 }
2454
2455 p = e;
2456 }
2457
2458theend:
2459 free(pathextbuf);
2460 free(pathbuf);
2461 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002462}
2463
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002464#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2465 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002466/*
2467 * Bad parameter handler.
2468 *
2469 * Certain MS CRT functions will intentionally crash when passed invalid
2470 * parameters to highlight possible security holes. Setting this function as
2471 * the bad parameter handler will prevent the crash.
2472 *
2473 * In debug builds the parameters contain CRT information that might help track
2474 * down the source of a problem, but in non-debug builds the arguments are all
2475 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2476 * worth allowing these to make debugging of issues easier.
2477 */
2478 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002479bad_param_handler(const wchar_t *expression UNUSED,
2480 const wchar_t *function UNUSED,
2481 const wchar_t *file UNUSED,
2482 unsigned int line UNUSED,
2483 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002484{
2485}
2486
2487# define SET_INVALID_PARAM_HANDLER \
2488 ((void)_set_invalid_parameter_handler(bad_param_handler))
2489#else
2490# define SET_INVALID_PARAM_HANDLER
2491#endif
2492
Bram Moolenaar4f974752019-02-17 17:44:42 +01002493#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002494
2495/*
2496 * GUI version of mch_init().
2497 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002498 static void
2499mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002500{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002501# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002502 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002503# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002504
Bram Moolenaar0f873732019-12-05 20:28:46 +01002505 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002506 SET_INVALID_PARAM_HANDLER;
2507
Bram Moolenaar0f873732019-12-05 20:28:46 +01002508 // Let critical errors result in a failure, not in a dialog box. Required
2509 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002510 SetErrorMode(SEM_FAILCRITICALERRORS);
2511
Bram Moolenaar0f873732019-12-05 20:28:46 +01002512 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002513
Bram Moolenaar0f873732019-12-05 20:28:46 +01002514 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002515 Rows = 25;
2516 Columns = 80;
2517
Bram Moolenaar0f873732019-12-05 20:28:46 +01002518 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519 {
2520 char_u vimrun_location[_MAX_PATH + 4];
2521
Bram Moolenaar0f873732019-12-05 20:28:46 +01002522 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002523 STRCPY(vimrun_location, exe_name);
2524 STRCPY(gettail(vimrun_location), "vimrun.exe");
2525 if (mch_getperm(vimrun_location) >= 0)
2526 {
2527 if (*skiptowhite(vimrun_location) != NUL)
2528 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002529 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002530 mch_memmove(vimrun_location + 1, vimrun_location,
2531 STRLEN(vimrun_location) + 1);
2532 *vimrun_location = '"';
2533 STRCPY(gettail(vimrun_location), "vimrun\" ");
2534 }
2535 else
2536 STRCPY(gettail(vimrun_location), "vimrun ");
2537
2538 vimrun_path = (char *)vim_strsave(vimrun_location);
2539 s_dont_use_vimrun = FALSE;
2540 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002541 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002542 s_dont_use_vimrun = FALSE;
2543
Bram Moolenaar0f873732019-12-05 20:28:46 +01002544 // Don't give the warning for a missing vimrun.exe right now, but only
2545 // when vimrun was supposed to be used. Don't bother people that do
2546 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002547 if (s_dont_use_vimrun)
2548 need_vimrun_warning = TRUE;
2549 }
2550
2551 /*
2552 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2553 * Otherwise the default "findstr /n" is used.
2554 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002555 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01002556 set_option_value_give_err((char_u *)"grepprg",
2557 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002558
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002559# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002560 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002561# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002562
2563 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002564}
2565
2566
Bram Moolenaar0f873732019-12-05 20:28:46 +01002567#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002568
2569#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002570
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002571# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2572# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002573
2574/*
2575 * ClearConsoleBuffer()
2576 * Description:
2577 * Clears the entire contents of the console screen buffer, using the
2578 * specified attribute.
2579 * Returns:
2580 * TRUE on success
2581 */
2582 static BOOL
2583ClearConsoleBuffer(WORD wAttribute)
2584{
2585 CONSOLE_SCREEN_BUFFER_INFO csbi;
2586 COORD coord;
2587 DWORD NumCells, dummy;
2588
2589 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2590 return FALSE;
2591
2592 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2593 coord.X = 0;
2594 coord.Y = 0;
2595 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2596 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002597 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002598 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2599 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002600 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002601
2602 return TRUE;
2603}
2604
2605/*
2606 * FitConsoleWindow()
2607 * Description:
2608 * Checks if the console window will fit within given buffer dimensions.
2609 * Also, if requested, will shrink the window to fit.
2610 * Returns:
2611 * TRUE on success
2612 */
2613 static BOOL
2614FitConsoleWindow(
2615 COORD dwBufferSize,
2616 BOOL WantAdjust)
2617{
2618 CONSOLE_SCREEN_BUFFER_INFO csbi;
2619 COORD dwWindowSize;
2620 BOOL NeedAdjust = FALSE;
2621
2622 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2623 {
2624 /*
2625 * A buffer resize will fail if the current console window does
2626 * not lie completely within that buffer. To avoid this, we might
2627 * have to move and possibly shrink the window.
2628 */
2629 if (csbi.srWindow.Right >= dwBufferSize.X)
2630 {
2631 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2632 if (dwWindowSize.X > dwBufferSize.X)
2633 dwWindowSize.X = dwBufferSize.X;
2634 csbi.srWindow.Right = dwBufferSize.X - 1;
2635 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2636 NeedAdjust = TRUE;
2637 }
2638 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2639 {
2640 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2641 if (dwWindowSize.Y > dwBufferSize.Y)
2642 dwWindowSize.Y = dwBufferSize.Y;
2643 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2644 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2645 NeedAdjust = TRUE;
2646 }
2647 if (NeedAdjust && WantAdjust)
2648 {
2649 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2650 return FALSE;
2651 }
2652 return TRUE;
2653 }
2654
2655 return FALSE;
2656}
2657
2658typedef struct ConsoleBufferStruct
2659{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002660 BOOL IsValid;
2661 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002662 PCHAR_INFO Buffer;
2663 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002664 PSMALL_RECT Regions;
2665 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002666} ConsoleBuffer;
2667
2668/*
2669 * SaveConsoleBuffer()
2670 * Description:
2671 * Saves important information about the console buffer, including the
2672 * actual buffer contents. The saved information is suitable for later
2673 * restoration by RestoreConsoleBuffer().
2674 * Returns:
2675 * TRUE if all information was saved; FALSE otherwise
2676 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2677 */
2678 static BOOL
2679SaveConsoleBuffer(
2680 ConsoleBuffer *cb)
2681{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002682 DWORD NumCells;
2683 COORD BufferCoord;
2684 SMALL_RECT ReadRegion;
2685 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002686 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002687
Bram Moolenaar071d4272004-06-13 20:20:40 +00002688 if (cb == NULL)
2689 return FALSE;
2690
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002691 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002692 {
2693 cb->IsValid = FALSE;
2694 return FALSE;
2695 }
2696 cb->IsValid = TRUE;
2697
Christopher Plewright1140b512022-11-12 18:46:05 +00002698 // VTP uses alternate screen buffer.
2699 // No need to save buffer contents for restoration.
2700 if (win11_or_later && vtp_working)
2701 return TRUE;
2702
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002703 /*
2704 * Allocate a buffer large enough to hold the entire console screen
2705 * buffer. If this ConsoleBuffer structure has already been initialized
2706 * with a buffer of the correct size, then just use that one.
2707 */
2708 if (!cb->IsValid || cb->Buffer == NULL ||
2709 cb->BufferSize.X != cb->Info.dwSize.X ||
2710 cb->BufferSize.Y != cb->Info.dwSize.Y)
2711 {
2712 cb->BufferSize.X = cb->Info.dwSize.X;
2713 cb->BufferSize.Y = cb->Info.dwSize.Y;
2714 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2715 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002716 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002717 if (cb->Buffer == NULL)
2718 return FALSE;
2719 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002720
2721 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002722 * We will now copy the console screen buffer into our buffer.
2723 * ReadConsoleOutput() seems to be limited as far as how much you
2724 * can read at a time. Empirically, this number seems to be about
2725 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2726 * in chunks until it is all copied. The chunks will all have the
2727 * same horizontal characteristics, so initialize them now. The
2728 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002729 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002730 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002731 ReadRegion.Left = 0;
2732 ReadRegion.Right = cb->Info.dwSize.X - 1;
2733 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002734
2735 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2736 if (cb->Regions == NULL || numregions != cb->NumRegions)
2737 {
2738 cb->NumRegions = numregions;
2739 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002740 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002741 if (cb->Regions == NULL)
2742 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002743 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002744 return FALSE;
2745 }
2746 }
2747
2748 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002749 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002750 /*
2751 * Read into position (0, Y) in our buffer.
2752 */
2753 BufferCoord.Y = Y;
2754 /*
2755 * Read the region whose top left corner is (0, Y) and whose bottom
2756 * right corner is (width - 1, Y + Y_incr - 1). This should define
2757 * a region of size width by Y_incr. Don't worry if this region is
2758 * too large for the remaining buffer; it will be cropped.
2759 */
2760 ReadRegion.Top = Y;
2761 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002762 if (!ReadConsoleOutputW(g_hConOut, // output handle
2763 cb->Buffer, // our buffer
2764 cb->BufferSize, // dimensions of our buffer
2765 BufferCoord, // offset in our buffer
2766 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002767 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002768 VIM_CLEAR(cb->Buffer);
2769 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002770 return FALSE;
2771 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002772 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002773 }
2774
2775 return TRUE;
2776}
2777
2778/*
2779 * RestoreConsoleBuffer()
2780 * Description:
2781 * Restores important information about the console buffer, including the
2782 * actual buffer contents, if desired. The information to restore is in
2783 * the same format used by SaveConsoleBuffer().
2784 * Returns:
2785 * TRUE on success
2786 */
2787 static BOOL
2788RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002789 ConsoleBuffer *cb,
2790 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002791{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002792 COORD BufferCoord;
2793 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002794 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002795
Christopher Plewright1140b512022-11-12 18:46:05 +00002796 // VTP uses alternate screen buffer.
2797 // No need to restore buffer contents.
2798 if (win11_or_later && vtp_working)
2799 return TRUE;
2800
Bram Moolenaar071d4272004-06-13 20:20:40 +00002801 if (cb == NULL || !cb->IsValid)
2802 return FALSE;
2803
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002804 /*
2805 * Before restoring the buffer contents, clear the current buffer, and
2806 * restore the cursor position and window information. Doing this now
2807 * prevents old buffer contents from "flashing" onto the screen.
2808 */
2809 if (RestoreScreen)
2810 ClearConsoleBuffer(cb->Info.wAttributes);
2811
2812 FitConsoleWindow(cb->Info.dwSize, TRUE);
2813 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2814 return FALSE;
2815 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2816 return FALSE;
2817
2818 if (!RestoreScreen)
2819 {
2820 /*
2821 * No need to restore the screen buffer contents, so we're done.
2822 */
2823 return TRUE;
2824 }
2825
2826 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2827 return FALSE;
2828 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2829 return FALSE;
2830
2831 /*
2832 * Restore the screen buffer contents.
2833 */
2834 if (cb->Buffer != NULL)
2835 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002836 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002837 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002838 BufferCoord.X = cb->Regions[i].Left;
2839 BufferCoord.Y = cb->Regions[i].Top;
2840 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01002841 if (!WriteConsoleOutputW(g_hConOut, // output handle
2842 cb->Buffer, // our buffer
2843 cb->BufferSize, // dimensions of our buffer
2844 BufferCoord, // offset in our buffer
2845 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02002846 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002847 }
2848 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002849
2850 return TRUE;
2851}
2852
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002853# define FEAT_RESTORE_ORIG_SCREEN
2854# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002855static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002856# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002857static ConsoleBuffer g_cbNonTermcap = { 0 };
2858static ConsoleBuffer g_cbTermcap = { 0 };
2859
Bram Moolenaar071d4272004-06-13 20:20:40 +00002860char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01002861HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00002862static HICON g_hOrigIconSmall = NULL;
2863static HICON g_hOrigIcon = NULL;
2864static HICON g_hVimIcon = NULL;
2865static BOOL g_fCanChangeIcon = FALSE;
2866
Bram Moolenaar071d4272004-06-13 20:20:40 +00002867/*
2868 * GetConsoleIcon()
2869 * Description:
2870 * Attempts to retrieve the small icon and/or the big icon currently in
2871 * use by a given window.
2872 * Returns:
2873 * TRUE on success
2874 */
2875 static BOOL
2876GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002877 HWND hWnd,
2878 HICON *phIconSmall,
2879 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002880{
2881 if (hWnd == NULL)
2882 return FALSE;
2883
2884 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002885 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2886 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002887 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002888 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2889 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002890 return TRUE;
2891}
2892
2893/*
2894 * SetConsoleIcon()
2895 * Description:
2896 * Attempts to change the small icon and/or the big icon currently in
2897 * use by a given window.
2898 * Returns:
2899 * TRUE on success
2900 */
2901 static BOOL
2902SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002903 HWND hWnd,
2904 HICON hIconSmall,
2905 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002906{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002907 if (hWnd == NULL)
2908 return FALSE;
2909
2910 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002911 SendMessage(hWnd, WM_SETICON,
2912 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002913 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002914 SendMessage(hWnd, WM_SETICON,
2915 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002916 return TRUE;
2917}
2918
2919/*
2920 * SaveConsoleTitleAndIcon()
2921 * Description:
2922 * Saves the current console window title in g_szOrigTitle, for later
2923 * restoration. Also, attempts to obtain a handle to the console window,
2924 * and use it to save the small and big icons currently in use by the
2925 * console window. This is not always possible on some versions of Windows;
2926 * nor is it possible when running Vim remotely using Telnet (since the
2927 * console window the user sees is owned by a remote process).
2928 */
2929 static void
2930SaveConsoleTitleAndIcon(void)
2931{
Bram Moolenaar0f873732019-12-05 20:28:46 +01002932 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002933 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2934 return;
2935
2936 /*
2937 * Obtain a handle to the console window using GetConsoleWindow() from
2938 * KERNEL32.DLL; we need to handle in order to change the window icon.
2939 * This function only exists on NT-based Windows, starting with Windows
2940 * 2000. On older operating systems, we can't change the window icon
2941 * anyway.
2942 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002943 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002944 if (g_hWnd == NULL)
2945 return;
2946
Bram Moolenaar0f873732019-12-05 20:28:46 +01002947 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002948 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2949 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2950 return;
2951
Bram Moolenaar0f873732019-12-05 20:28:46 +01002952 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01002953 if (
2954# ifdef FEAT_LIBCALL
2955 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
2956# endif
2957 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002958 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002959 if (g_hVimIcon != NULL)
2960 g_fCanChangeIcon = TRUE;
2961}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002962
2963static int g_fWindInitCalled = FALSE;
2964static int g_fTermcapMode = FALSE;
2965static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002966
2967/*
2968 * non-GUI version of mch_init().
2969 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002970 static void
2971mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002972{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002973# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002974 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002975# endif
2976# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002977 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002978# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002979
Bram Moolenaar0f873732019-12-05 20:28:46 +01002980 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002981 SET_INVALID_PARAM_HANDLER;
2982
Bram Moolenaar0f873732019-12-05 20:28:46 +01002983 // Let critical errors result in a failure, not in a dialog box. Required
2984 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002985 SetErrorMode(SEM_FAILCRITICALERRORS);
2986
Bram Moolenaar0f873732019-12-05 20:28:46 +01002987 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002988 out_flush();
2989
Bram Moolenaar0f873732019-12-05 20:28:46 +01002990 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00002991 if (read_cmd_fd == 0)
2992 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2993 else
2994 create_conin();
2995 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2996
Christopher Plewright38804d62022-11-09 23:55:52 +00002997 wt_init();
2998 vtp_flag_init();
2999 vtp_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003000# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01003001 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003002 SaveConsoleBuffer(&g_cbOrig);
3003 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003004# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01003005 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003006 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
3007 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003008# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003009 if (cterm_normal_fg_color == 0)
3010 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
3011 if (cterm_normal_bg_color == 0)
3012 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
3013
Bram Moolenaarbdace832019-03-02 10:13:42 +01003014 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02003015 g_color_index_fg = g_attrDefault & 0xf;
3016 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
3017
Bram Moolenaar0f873732019-12-05 20:28:46 +01003018 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00003019 update_tcap(g_attrCurrent);
3020
3021 GetConsoleCursorInfo(g_hConOut, &g_cci);
3022 GetConsoleMode(g_hConIn, &g_cmodein);
3023 GetConsoleMode(g_hConOut, &g_cmodeout);
3024
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025 SaveConsoleTitleAndIcon();
3026 /*
3027 * Set both the small and big icons of the console window to Vim's icon.
3028 * Note that Vim presently only has one size of icon (32x32), but it
3029 * automatically gets scaled down to 16x16 when setting the small icon.
3030 */
3031 if (g_fCanChangeIcon)
3032 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003033
3034 ui_get_shellsize();
3035
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003036# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003037 fdDump = fopen("dump", "wt");
3038
3039 if (fdDump)
3040 {
3041 time_t t;
3042
3043 time(&t);
3044 fputs(ctime(&t), fdDump);
3045 fflush(fdDump);
3046 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003047# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048
3049 g_fWindInitCalled = TRUE;
3050
Bram Moolenaar071d4272004-06-13 20:20:40 +00003051 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003052
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003053# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003054 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003055# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003056}
3057
3058/*
3059 * non-GUI version of mch_exit().
3060 * Shut down and exit with status `r'
3061 * Careful: mch_exit() may be called before mch_init()!
3062 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003063 static void
3064mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003065{
Bram Moolenaar955f1982017-02-05 15:10:51 +01003066 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003067
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003068 vtp_exit();
3069
Bram Moolenaar955f1982017-02-05 15:10:51 +01003070 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003071 if (g_fWindInitCalled)
3072 settmode(TMODE_COOK);
3073
Bram Moolenaar0f873732019-12-05 20:28:46 +01003074 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00003075
3076 if (g_fWindInitCalled)
3077 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02003078 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003079 /*
3080 * Restore both the small and big icons of the console window to
3081 * what they were at startup. Don't do this when the window is
3082 * closed, Vim would hang here.
3083 */
3084 if (g_fCanChangeIcon && !g_fForceExit)
3085 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003086
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003087# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003088 if (fdDump)
3089 {
3090 time_t t;
3091
3092 time(&t);
3093 fputs(ctime(&t), fdDump);
3094 fclose(fdDump);
3095 }
3096 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003097# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003098 }
3099
3100 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003101 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003102 SetConsoleMode(g_hConOut, g_cmodeout);
3103
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003104# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003105 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003106# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003107
3108 exit(r);
3109}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003110#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003111
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003112 void
3113mch_init(void)
3114{
3115#ifdef VIMDLL
3116 if (gui.starting)
3117 mch_init_g();
3118 else
3119 mch_init_c();
3120#elif defined(FEAT_GUI_MSWIN)
3121 mch_init_g();
3122#else
3123 mch_init_c();
3124#endif
3125}
3126
3127 void
3128mch_exit(int r)
3129{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003130#ifdef FEAT_NETBEANS_INTG
3131 netbeans_send_disconnect();
3132#endif
3133
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003134#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003135 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003136 mch_exit_g(r);
3137 else
3138 mch_exit_c(r);
3139#elif defined(FEAT_GUI_MSWIN)
3140 mch_exit_g(r);
3141#else
3142 mch_exit_c(r);
3143#endif
3144}
3145
Bram Moolenaar071d4272004-06-13 20:20:40 +00003146/*
3147 * Do we have an interactive window?
3148 */
3149 int
3150mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003151 int argc UNUSED,
3152 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003153{
3154 get_exe_name();
3155
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003156#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003157 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003158#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003159# ifdef VIMDLL
3160 if (gui.in_use)
3161 return OK;
3162# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003163 if (isatty(1))
3164 return OK;
3165 return FAIL;
3166#endif
3167}
3168
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003169/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003170 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003171 * When "len" is > 0, also expand short to long filenames.
3172 */
3173 void
3174fname_case(
3175 char_u *name,
3176 int len)
3177{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003178 int flen;
3179 WCHAR *p;
3180 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003181
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003182 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003183 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003184 return;
3185
3186 slash_adjust(name);
3187
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003188 p = enc_to_utf16(name, NULL);
3189 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003190 return;
3191
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003192 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003193 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003194 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003195
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003196 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003197 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003198 if (len > 0 || flen >= (int)STRLEN(q))
3199 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3200 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003201 }
3202 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003203 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003204}
3205
3206
3207/*
3208 * Insert user name in s[len].
3209 */
3210 int
3211mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003212 char_u *s,
3213 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003214{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003215 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003216 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003217
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003218 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003219 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003220 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003221
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003222 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003223 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003224 vim_strncpy(s, p, len - 1);
3225 vim_free(p);
3226 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003227 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003228 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003229 s[0] = NUL;
3230 return FAIL;
3231}
3232
3233
3234/*
3235 * Insert host name in s[len].
3236 */
3237 void
3238mch_get_host_name(
3239 char_u *s,
3240 int len)
3241{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003242 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003243 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003244
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003245 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003246 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003247 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003248
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003249 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003250 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003251 vim_strncpy(s, p, len - 1);
3252 vim_free(p);
3253 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003254 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003255 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003256}
3257
3258
3259/*
3260 * return process ID
3261 */
3262 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003263mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003264{
3265 return (long)GetCurrentProcessId();
3266}
3267
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003268/*
3269 * return TRUE if process "pid" is still running
3270 */
3271 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003272mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003273{
3274 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3275 DWORD status = 0;
3276 int ret = FALSE;
3277
3278 if (hProcess == NULL)
3279 return FALSE; // might not have access
3280 if (GetExitCodeProcess(hProcess, &status) )
3281 ret = status == STILL_ACTIVE;
3282 CloseHandle(hProcess);
3283 return ret;
3284}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003285
3286/*
3287 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3288 * Return OK for success, FAIL for failure.
3289 */
3290 int
3291mch_dirname(
3292 char_u *buf,
3293 int len)
3294{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003295 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003296
Bram Moolenaar071d4272004-06-13 20:20:40 +00003297 /*
3298 * Originally this was:
3299 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3300 * But the Win32s known bug list says that getcwd() doesn't work
3301 * so use the Win32 system call instead. <Negri>
3302 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003303 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003304 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003305 WCHAR wcbuf[_MAX_PATH + 1];
3306 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003307
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003308 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003309 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003310 p = utf16_to_enc(wcbuf, NULL);
3311 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003312 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003313 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003314 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003315 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003316 }
3317 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003318 if (p == NULL)
3319 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003320
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003321 if (p != NULL)
3322 {
3323 vim_strncpy(buf, p, len - 1);
3324 vim_free(p);
3325 return OK;
3326 }
3327 }
3328 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003329}
3330
3331/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003332 * Get file permissions for "name".
3333 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003334 */
3335 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003336mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003337{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003338 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003339 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003340
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003341 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003342 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003343}
3344
3345
3346/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003347 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003348 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003349 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003350 */
3351 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003352mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003353{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003354 long n;
3355 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003356
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003357 p = enc_to_utf16(name, NULL);
3358 if (p == NULL)
3359 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003360
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003361 n = _wchmod(p, perm);
3362 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003363 if (n == -1)
3364 return FAIL;
3365
3366 win32_set_archive(name);
3367
3368 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003369}
3370
3371/*
3372 * Set hidden flag for "name".
3373 */
3374 void
3375mch_hide(char_u *name)
3376{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003377 int attrs = win32_getattrs(name);
3378 if (attrs == -1)
3379 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003380
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003381 attrs |= FILE_ATTRIBUTE_HIDDEN;
3382 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003383}
3384
3385/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003386 * Return TRUE if file "name" exists and is hidden.
3387 */
3388 int
3389mch_ishidden(char_u *name)
3390{
3391 int f = win32_getattrs(name);
3392
3393 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003394 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003395
3396 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3397}
3398
3399/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003400 * return TRUE if "name" is a directory
3401 * return FALSE if "name" is not a directory or upon error
3402 */
3403 int
3404mch_isdir(char_u *name)
3405{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003406 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003407
3408 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003409 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003410
3411 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3412}
3413
3414/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003415 * return TRUE if "name" is a directory, NOT a symlink to a directory
3416 * return FALSE if "name" is not a directory
3417 * return FALSE for error
3418 */
3419 int
3420mch_isrealdir(char_u *name)
3421{
3422 return mch_isdir(name) && !mch_is_symbolic_link(name);
3423}
3424
3425/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003426 * Create directory "name".
3427 * Return 0 on success, -1 on error.
3428 */
3429 int
3430mch_mkdir(char_u *name)
3431{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003432 WCHAR *p;
3433 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003434
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003435 p = enc_to_utf16(name, NULL);
3436 if (p == NULL)
3437 return -1;
3438 retval = _wmkdir(p);
3439 vim_free(p);
3440 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003441}
3442
3443/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003444 * Delete directory "name".
3445 * Return 0 on success, -1 on error.
3446 */
3447 int
3448mch_rmdir(char_u *name)
3449{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003450 WCHAR *p;
3451 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003452
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003453 p = enc_to_utf16(name, NULL);
3454 if (p == NULL)
3455 return -1;
3456 retval = _wrmdir(p);
3457 vim_free(p);
3458 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003459}
3460
3461/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003462 * Return TRUE if file "fname" has more than one link.
3463 */
3464 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003465mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003466{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003467 BY_HANDLE_FILE_INFORMATION info;
3468
3469 return win32_fileinfo(fname, &info) == FILEINFO_OK
3470 && info.nNumberOfLinks > 1;
3471}
3472
3473/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003474 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003475 */
3476 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003477mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003478{
3479 HANDLE hFind;
3480 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003481 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003482 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003483 WIN32_FIND_DATAW findDataW;
3484
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003485 wn = enc_to_utf16(name, NULL);
3486 if (wn == NULL)
3487 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003488
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003489 hFind = FindFirstFileW(wn, &findDataW);
3490 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003491 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003492 {
3493 fileFlags = findDataW.dwFileAttributes;
3494 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003495 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003496 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003497
3498 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003499 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3500 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003501 res = TRUE;
3502
3503 return res;
3504}
3505
3506/*
3507 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3508 * link.
3509 */
3510 int
3511mch_is_linked(char_u *fname)
3512{
3513 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3514 return TRUE;
3515 return FALSE;
3516}
3517
3518/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003519 * Get the by-handle-file-information for "fname".
3520 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003521 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003522 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3523 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3524 */
3525 int
3526win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3527{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003528 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003529 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003530 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003531
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003532 wn = enc_to_utf16(fname, NULL);
3533 if (wn == NULL)
3534 return FILEINFO_ENC_FAIL;
3535
3536 hFile = CreateFileW(wn, // file name
3537 GENERIC_READ, // access mode
3538 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3539 NULL, // security descriptor
3540 OPEN_EXISTING, // creation disposition
3541 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3542 NULL); // handle to template file
3543 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003544
3545 if (hFile != INVALID_HANDLE_VALUE)
3546 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003547 if (GetFileInformationByHandle(hFile, info) != 0)
3548 res = FILEINFO_OK;
3549 else
3550 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003551 CloseHandle(hFile);
3552 }
3553
Bram Moolenaar03f48552006-02-28 23:52:23 +00003554 return res;
3555}
3556
3557/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003558 * get file attributes for `name'
3559 * -1 : error
3560 * else FILE_ATTRIBUTE_* defined in winnt.h
3561 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003562 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003563win32_getattrs(char_u *name)
3564{
3565 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003566 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003567
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003568 p = enc_to_utf16(name, NULL);
3569 if (p == NULL)
3570 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003571
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003572 attr = GetFileAttributesW(p);
3573 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003574
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003575 return attr;
3576}
3577
3578/*
3579 * set file attributes for `name' to `attrs'
3580 *
3581 * return -1 for failure, 0 otherwise
3582 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003583 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003584win32_setattrs(char_u *name, int attrs)
3585{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003586 int res;
3587 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003588
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003589 p = enc_to_utf16(name, NULL);
3590 if (p == NULL)
3591 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003592
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003593 res = SetFileAttributesW(p, attrs);
3594 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003595
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003596 return res ? 0 : -1;
3597}
3598
3599/*
3600 * Set archive flag for "name".
3601 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003602 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003603win32_set_archive(char_u *name)
3604{
3605 int attrs = win32_getattrs(name);
3606 if (attrs == -1)
3607 return -1;
3608
3609 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3610 return win32_setattrs(name, attrs);
3611}
3612
3613/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003614 * Return TRUE if file or directory "name" is writable (not readonly).
3615 * Strange semantics of Win32: a readonly directory is writable, but you can't
3616 * delete a file. Let's say this means it is writable.
3617 */
3618 int
3619mch_writable(char_u *name)
3620{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003621 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003622
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003623 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3624 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003625}
3626
Bram Moolenaar071d4272004-06-13 20:20:40 +00003627/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003628 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003629 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003630 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3631 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003632 */
3633 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01003634mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003635{
Bram Moolenaar95da1362020-05-30 18:37:55 +02003636 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003637}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003638
3639/*
3640 * Check what "name" is:
3641 * NODE_NORMAL: file or directory (or doesn't exist)
3642 * NODE_WRITABLE: writable device, socket, fifo, etc.
3643 * NODE_OTHER: non-writable things
3644 */
3645 int
3646mch_nodetype(char_u *name)
3647{
3648 HANDLE hFile;
3649 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003650 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003651
Bram Moolenaar0f873732019-12-05 20:28:46 +01003652 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3653 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3654 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00003655 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3656 return NODE_WRITABLE;
3657
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003658 wn = enc_to_utf16(name, NULL);
3659 if (wn == NULL)
3660 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003661
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003662 hFile = CreateFileW(wn, // file name
3663 GENERIC_WRITE, // access mode
3664 0, // share mode
3665 NULL, // security descriptor
3666 OPEN_EXISTING, // creation disposition
3667 0, // file attributes
3668 NULL); // handle to template file
3669 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003670 if (hFile == INVALID_HANDLE_VALUE)
3671 return NODE_NORMAL;
3672
3673 type = GetFileType(hFile);
3674 CloseHandle(hFile);
3675 if (type == FILE_TYPE_CHAR)
3676 return NODE_WRITABLE;
3677 if (type == FILE_TYPE_DISK)
3678 return NODE_NORMAL;
3679 return NODE_OTHER;
3680}
3681
3682#ifdef HAVE_ACL
3683struct my_acl
3684{
3685 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3686 PSID pSidOwner;
3687 PSID pSidGroup;
3688 PACL pDacl;
3689 PACL pSacl;
3690};
3691#endif
3692
3693/*
3694 * Return a pointer to the ACL of file "fname" in allocated memory.
3695 * Return NULL if the ACL is not available for whatever reason.
3696 */
3697 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003698mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003699{
3700#ifndef HAVE_ACL
3701 return (vim_acl_T)NULL;
3702#else
3703 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003704 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003705
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003706 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003707 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003708 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003709 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003710
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003711 wn = enc_to_utf16(fname, NULL);
3712 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003713 {
3714 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003715 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003716 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003717
3718 // Try to retrieve the entire security descriptor.
3719 err = GetNamedSecurityInfoW(
3720 wn, // Abstract filename
3721 SE_FILE_OBJECT, // File Object
3722 OWNER_SECURITY_INFORMATION |
3723 GROUP_SECURITY_INFORMATION |
3724 DACL_SECURITY_INFORMATION |
3725 SACL_SECURITY_INFORMATION,
3726 &p->pSidOwner, // Ownership information.
3727 &p->pSidGroup, // Group membership.
3728 &p->pDacl, // Discretionary information.
3729 &p->pSacl, // For auditing purposes.
3730 &p->pSecurityDescriptor);
3731 if (err == ERROR_ACCESS_DENIED ||
3732 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003733 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003734 // Retrieve only DACL.
3735 (void)GetNamedSecurityInfoW(
3736 wn,
3737 SE_FILE_OBJECT,
3738 DACL_SECURITY_INFORMATION,
3739 NULL,
3740 NULL,
3741 &p->pDacl,
3742 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003743 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003744 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003745 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003746 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003747 mch_free_acl((vim_acl_T)p);
3748 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003749 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003750 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003751 }
3752
3753 return (vim_acl_T)p;
3754#endif
3755}
3756
Bram Moolenaar27515922013-06-29 15:36:26 +02003757#ifdef HAVE_ACL
3758/*
3759 * Check if "acl" contains inherited ACE.
3760 */
3761 static BOOL
3762is_acl_inherited(PACL acl)
3763{
3764 DWORD i;
3765 ACL_SIZE_INFORMATION acl_info;
3766 PACCESS_ALLOWED_ACE ace;
3767
3768 acl_info.AceCount = 0;
3769 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3770 for (i = 0; i < acl_info.AceCount; i++)
3771 {
3772 GetAce(acl, i, (LPVOID *)&ace);
3773 if (ace->Header.AceFlags & INHERITED_ACE)
3774 return TRUE;
3775 }
3776 return FALSE;
3777}
3778#endif
3779
Bram Moolenaar071d4272004-06-13 20:20:40 +00003780/*
3781 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3782 * Errors are ignored.
3783 * This must only be called with "acl" equal to what mch_get_acl() returned.
3784 */
3785 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003786mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003787{
3788#ifdef HAVE_ACL
3789 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003790 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003791 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003792
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003793 if (p == NULL)
3794 return;
3795
3796 wn = enc_to_utf16(fname, NULL);
3797 if (wn == NULL)
3798 return;
3799
3800 // Set security flags
3801 if (p->pSidOwner)
3802 sec_info |= OWNER_SECURITY_INFORMATION;
3803 if (p->pSidGroup)
3804 sec_info |= GROUP_SECURITY_INFORMATION;
3805 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003806 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003807 sec_info |= DACL_SECURITY_INFORMATION;
3808 // Do not inherit its parent's DACL.
3809 // If the DACL is inherited, Cygwin permissions would be changed.
3810 if (!is_acl_inherited(p->pDacl))
3811 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003812 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003813 if (p->pSacl)
3814 sec_info |= SACL_SECURITY_INFORMATION;
3815
3816 (void)SetNamedSecurityInfoW(
3817 wn, // Abstract filename
3818 SE_FILE_OBJECT, // File Object
3819 sec_info,
3820 p->pSidOwner, // Ownership information.
3821 p->pSidGroup, // Group membership.
3822 p->pDacl, // Discretionary information.
3823 p->pSacl // For auditing purposes.
3824 );
3825 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003826#endif
3827}
3828
3829 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003830mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003831{
3832#ifdef HAVE_ACL
3833 struct my_acl *p = (struct my_acl *)acl;
3834
3835 if (p != NULL)
3836 {
3837 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3838 vim_free(p);
3839 }
3840#endif
3841}
3842
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003843#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003844
3845/*
3846 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3847 */
3848 static BOOL WINAPI
3849handler_routine(
3850 DWORD dwCtrlType)
3851{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003852 INPUT_RECORD ir;
3853 DWORD out;
3854
Bram Moolenaar071d4272004-06-13 20:20:40 +00003855 switch (dwCtrlType)
3856 {
3857 case CTRL_C_EVENT:
3858 if (ctrl_c_interrupts)
3859 g_fCtrlCPressed = TRUE;
3860 return TRUE;
3861
3862 case CTRL_BREAK_EVENT:
3863 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003864 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003865 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02003866 ir.EventType = KEY_EVENT;
3867 ir.Event.KeyEvent.bKeyDown = TRUE;
3868 ir.Event.KeyEvent.wRepeatCount = 1;
3869 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3870 ir.Event.KeyEvent.wVirtualScanCode = 0;
3871 ir.Event.KeyEvent.dwControlKeyState = 0;
3872 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3873 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003874 return TRUE;
3875
Bram Moolenaar0f873732019-12-05 20:28:46 +01003876 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00003877 case CTRL_CLOSE_EVENT:
3878 case CTRL_LOGOFF_EVENT:
3879 case CTRL_SHUTDOWN_EVENT:
3880 windgoto((int)Rows - 1, 0);
3881 g_fForceExit = TRUE;
3882
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003883 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003884 (dwCtrlType == CTRL_CLOSE_EVENT
3885 ? _("close")
3886 : dwCtrlType == CTRL_LOGOFF_EVENT
3887 ? _("logoff")
3888 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003889# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00003890 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003891# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003892
Bram Moolenaar0f873732019-12-05 20:28:46 +01003893 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00003894
Bram Moolenaar0f873732019-12-05 20:28:46 +01003895 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00003896
3897 default:
3898 return FALSE;
3899 }
3900}
3901
3902
3903/*
3904 * set the tty in (raw) ? "raw" : "cooked" mode
3905 */
3906 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02003907mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003908{
3909 DWORD cmodein;
3910 DWORD cmodeout;
3911 BOOL bEnableHandler;
3912
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003913# ifdef VIMDLL
3914 if (gui.in_use)
3915 return;
3916# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003917 GetConsoleMode(g_hConIn, &cmodein);
3918 GetConsoleMode(g_hConOut, &cmodeout);
3919 if (tmode == TMODE_RAW)
3920 {
3921 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3922 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003923 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003924 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003925 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003926 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
3927 }
3928 else
3929 {
3930 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
3931 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003932 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003933# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01003934 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
3935 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003936 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003937# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003938 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003939# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003940 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003941 bEnableHandler = TRUE;
3942 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01003943 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00003944 {
3945 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3946 ENABLE_ECHO_INPUT);
3947 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3948 bEnableHandler = FALSE;
3949 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003950 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003951 SetConsoleMode(g_hConOut, cmodeout);
3952 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3953
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003954# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003955 if (fdDump)
3956 {
3957 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3958 tmode == TMODE_RAW ? "raw" :
3959 tmode == TMODE_COOK ? "cooked" : "normal",
3960 cmodein, cmodeout);
3961 fflush(fdDump);
3962 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003963# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003964}
3965
3966
3967/*
3968 * Get the size of the current window in `Rows' and `Columns'
3969 * Return OK when size could be determined, FAIL otherwise.
3970 */
3971 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003972mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003973{
3974 CONSOLE_SCREEN_BUFFER_INFO csbi;
3975
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003976# ifdef VIMDLL
3977 if (gui.in_use)
3978 return OK;
3979# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003980 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3981 {
3982 /*
3983 * For some reason, we are trying to get the screen dimensions
3984 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3985 * variables are really intended to mean the size of Vim screen
3986 * while in termcap mode.
3987 */
3988 Rows = g_cbTermcap.Info.dwSize.Y;
3989 Columns = g_cbTermcap.Info.dwSize.X;
3990 }
3991 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3992 {
3993 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3994 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3995 }
3996 else
3997 {
3998 Rows = 25;
3999 Columns = 80;
4000 }
4001 return OK;
4002}
4003
4004/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004005 * Resize console buffer to 'COORD'
4006 */
4007 static void
4008ResizeConBuf(
4009 HANDLE hConsole,
4010 COORD coordScreen)
4011{
4012 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4013 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004014# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004015 if (fdDump)
4016 {
4017 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4018 GetLastError());
4019 fflush(fdDump);
4020 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004021# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004022 }
4023}
4024
4025/*
4026 * Resize console window size to 'srWindowRect'
4027 */
4028 static void
4029ResizeWindow(
4030 HANDLE hConsole,
4031 SMALL_RECT srWindowRect)
4032{
4033 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4034 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004035# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004036 if (fdDump)
4037 {
4038 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4039 GetLastError());
4040 fflush(fdDump);
4041 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004042# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004043 }
4044}
4045
4046/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004047 * Set a console window to `xSize' * `ySize'
4048 */
4049 static void
4050ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004051 HANDLE hConsole,
4052 int xSize,
4053 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004054{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004055 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
4056 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004057 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004058 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004059 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004060
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004061# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004062 if (fdDump)
4063 {
4064 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4065 fflush(fdDump);
4066 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004067# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004068
Bram Moolenaar0f873732019-12-05 20:28:46 +01004069 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00004070 coordScreen = GetLargestConsoleWindowSize(hConsole);
4071
Bram Moolenaar0f873732019-12-05 20:28:46 +01004072 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00004073 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4074 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4075 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4076
4077 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4078 {
4079 int sx, sy;
4080
4081 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4082 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4083 if (sy < ySize || sx < xSize)
4084 {
4085 /*
4086 * Increasing number of lines/columns, do buffer first.
4087 * Use the maximal size in x and y direction.
4088 */
4089 if (sy < ySize)
4090 coordScreen.Y = ySize;
4091 else
4092 coordScreen.Y = sy;
4093 if (sx < xSize)
4094 coordScreen.X = xSize;
4095 else
4096 coordScreen.X = sx;
4097 SetConsoleScreenBufferSize(hConsole, coordScreen);
4098 }
4099 }
4100
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004101 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004102 coordScreen.X = xSize;
4103 coordScreen.Y = ySize;
4104
Bram Moolenaar2551c032018-08-23 22:38:31 +02004105 // In the new console call API, only the first time in reverse order
4106 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004107 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004108 ResizeWindow(hConsole, srWindowRect);
4109 ResizeConBuf(hConsole, coordScreen);
4110 }
4111 else
4112 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004113 // Workaround for a Windows 10 bug
4114 cursor.X = srWindowRect.Left;
4115 cursor.Y = srWindowRect.Top;
4116 SetConsoleCursorPosition(hConsole, cursor);
4117
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004118 ResizeConBuf(hConsole, coordScreen);
4119 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004120 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004121 }
4122}
4123
4124
4125/*
4126 * Set the console window to `Rows' * `Columns'
4127 */
4128 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004129mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004130{
4131 COORD coordScreen;
4132
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004133# ifdef VIMDLL
4134 if (gui.in_use)
4135 return;
4136# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004137 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004138 if (suppress_winsize != 0)
4139 {
4140 suppress_winsize = 2;
4141 return;
4142 }
4143
4144 if (term_console)
4145 {
4146 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4147
Bram Moolenaar0f873732019-12-05 20:28:46 +01004148 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004149 if (Rows > coordScreen.Y)
4150 Rows = coordScreen.Y;
4151 if (Columns > coordScreen.X)
4152 Columns = coordScreen.X;
4153
4154 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4155 }
4156}
4157
4158/*
4159 * Rows and/or Columns has changed.
4160 */
4161 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004162mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004163{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004164# ifdef VIMDLL
4165 if (gui.in_use)
4166 return;
4167# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004168 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4169}
4170
4171
4172/*
4173 * Called when started up, to set the winsize that was delayed.
4174 */
4175 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004176mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004177{
4178 if (suppress_winsize == 2)
4179 {
4180 suppress_winsize = 0;
4181 mch_set_shellsize();
4182 shell_resized();
4183 }
4184 suppress_winsize = 0;
4185}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004186#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004187
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004188 static BOOL
4189vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004190 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004191 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004192 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004193 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004194 PROCESS_INFORMATION *pi,
4195 LPVOID *env,
4196 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004197{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004198 BOOL ret = FALSE;
4199 WCHAR *wcmd, *wcwd = NULL;
4200
4201 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4202 if (wcmd == NULL)
4203 return FALSE;
4204 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004205 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004206 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4207 if (wcwd == NULL)
4208 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004209 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004210
4211 ret = CreateProcessW(
4212 NULL, // Executable name
4213 wcmd, // Command to execute
4214 NULL, // Process security attributes
4215 NULL, // Thread security attributes
4216 inherit_handles, // Inherit handles
4217 flags, // Creation flags
4218 env, // Environment
4219 wcwd, // Current directory
4220 (LPSTARTUPINFOW)si, // Startup information
4221 pi); // Process information
4222theend:
4223 vim_free(wcmd);
4224 vim_free(wcwd);
4225 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004226}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004227
4228
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004229 static HINSTANCE
4230vim_shell_execute(
4231 char *cmd,
4232 INT n_show_cmd)
4233{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004234 HINSTANCE ret;
4235 WCHAR *wcmd;
4236
4237 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4238 if (wcmd == NULL)
4239 return (HINSTANCE) 0;
4240
4241 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4242 vim_free(wcmd);
4243 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004244}
4245
4246
Bram Moolenaar4f974752019-02-17 17:44:42 +01004247#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004248
4249/*
4250 * Specialised version of system() for Win32 GUI mode.
4251 * This version proceeds as follows:
4252 * 1. Create a console window for use by the subprocess
4253 * 2. Run the subprocess (it gets the allocated console by default)
4254 * 3. Wait for the subprocess to terminate and get its exit code
4255 * 4. Prompt the user to press a key to close the console window
4256 */
4257 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004258mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004259{
4260 STARTUPINFO si;
4261 PROCESS_INFORMATION pi;
4262 DWORD ret = 0;
4263 HWND hwnd = GetFocus();
4264
4265 si.cb = sizeof(si);
4266 si.lpReserved = NULL;
4267 si.lpDesktop = NULL;
4268 si.lpTitle = NULL;
4269 si.dwFlags = STARTF_USESHOWWINDOW;
4270 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004271 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004272 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004273 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004274 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004275 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004276 else
4277 si.wShowWindow = SW_SHOWNORMAL;
4278 si.cbReserved2 = 0;
4279 si.lpReserved2 = NULL;
4280
Bram Moolenaar0f873732019-12-05 20:28:46 +01004281 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004282 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004283 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4284 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004285
Bram Moolenaar0f873732019-12-05 20:28:46 +01004286 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004287 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004288# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004289 int delay = 1;
4290
Bram Moolenaar0f873732019-12-05 20:28:46 +01004291 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004292 for (;;)
4293 {
4294 MSG msg;
4295
K.Takatab7057bd2022-01-21 11:37:07 +00004296 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004297 {
4298 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004299 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004300 delay = 1;
4301 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004302 }
4303 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4304 break;
4305
Bram Moolenaar0f873732019-12-05 20:28:46 +01004306 // We start waiting for a very short time and then increase it, so
4307 // that we respond quickly when the process is quick, and don't
4308 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004309 if (delay < 50)
4310 delay += 10;
4311 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004312# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004313 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004314# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004315
Bram Moolenaar0f873732019-12-05 20:28:46 +01004316 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004317 GetExitCodeProcess(pi.hProcess, &ret);
4318 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004319
Bram Moolenaar0f873732019-12-05 20:28:46 +01004320 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004321 CloseHandle(pi.hThread);
4322 CloseHandle(pi.hProcess);
4323
Bram Moolenaar0f873732019-12-05 20:28:46 +01004324 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004325 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4326
4327 return ret;
4328}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004329
4330/*
4331 * Thread launched by the gui to send the current buffer data to the
4332 * process. This way avoid to hang up vim totally if the children
4333 * process take a long time to process the lines.
4334 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004335 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004336sub_process_writer(LPVOID param)
4337{
4338 HANDLE g_hChildStd_IN_Wr = param;
4339 linenr_T lnum = curbuf->b_op_start.lnum;
4340 DWORD len = 0;
4341 DWORD l;
4342 char_u *lp = ml_get(lnum);
4343 char_u *s;
4344 int written = 0;
4345
4346 for (;;)
4347 {
4348 l = (DWORD)STRLEN(lp + written);
4349 if (l == 0)
4350 len = 0;
4351 else if (lp[written] == NL)
4352 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004353 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004354 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4355 }
4356 else
4357 {
4358 s = vim_strchr(lp + written, NL);
4359 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4360 s == NULL ? l : (DWORD)(s - (lp + written)),
4361 &len, NULL);
4362 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004363 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004364 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004365 // Finished a line, add a NL, unless this line should not have
4366 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004367 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004368 || (!curbuf->b_p_bin
4369 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004370 || (lnum != curbuf->b_no_eol_lnum
4371 && (lnum != curbuf->b_ml.ml_line_count
4372 || curbuf->b_p_eol)))
4373 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004374 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4375 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004376 }
4377
4378 ++lnum;
4379 if (lnum > curbuf->b_op_end.lnum)
4380 break;
4381
4382 lp = ml_get(lnum);
4383 written = 0;
4384 }
4385 else if (len > 0)
4386 written += len;
4387 }
4388
Bram Moolenaar0f873732019-12-05 20:28:46 +01004389 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004390 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004391 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004392}
4393
4394
Bram Moolenaar0f873732019-12-05 20:28:46 +01004395# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004396
4397/*
4398 * This function read from the children's stdout and write the
4399 * data on screen or in the buffer accordingly.
4400 */
4401 static void
4402dump_pipe(int options,
4403 HANDLE g_hChildStd_OUT_Rd,
4404 garray_T *ga,
4405 char_u buffer[],
4406 DWORD *buffer_off)
4407{
4408 DWORD availableBytes = 0;
4409 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004410 int ret;
4411 DWORD len;
4412 DWORD toRead;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004413
Bram Moolenaar0f873732019-12-05 20:28:46 +01004414 // we query the pipe to see if there is any data to read
4415 // to avoid to perform a blocking read
4416 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4417 NULL, // optional buffer
4418 0, // buffer size
4419 NULL, // number of read bytes
4420 &availableBytes, // available bytes total
4421 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004422
Bram Moolenaar0f873732019-12-05 20:28:46 +01004423 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004424 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004425 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01004426 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004427 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004428 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004429
Bram Moolenaar0f873732019-12-05 20:28:46 +01004430 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004431 if (len == 0)
4432 break;
4433
4434 availableBytes -= len;
4435
4436 if (options & SHELL_READ)
4437 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004438 // Do NUL -> NL translation, append NL separated
4439 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004440 for (i = 0; i < len; ++i)
4441 {
4442 if (buffer[i] == NL)
4443 append_ga_line(ga);
4444 else if (buffer[i] == NUL)
4445 ga_append(ga, NL);
4446 else
4447 ga_append(ga, buffer[i]);
4448 }
4449 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004450 else if (has_mbyte)
4451 {
4452 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004453 int c;
4454 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004455
4456 len += *buffer_off;
4457 buffer[len] = NUL;
4458
Bram Moolenaar0f873732019-12-05 20:28:46 +01004459 // Check if the last character in buffer[] is
4460 // incomplete, keep these bytes for the next
4461 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004462 for (p = buffer; p < buffer + len; p += l)
4463 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004464 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004465 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004466 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004467 else if (MB_BYTE2LEN(*p) != l)
4468 break;
4469 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004470 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004471 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004472 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004473 if (len >= 12)
4474 ++p;
4475 else
4476 {
4477 *buffer_off = len;
4478 return;
4479 }
4480 }
4481 c = *p;
4482 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004483 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004484 if (p < buffer + len)
4485 {
4486 *p = c;
4487 *buffer_off = (DWORD)((buffer + len) - p);
4488 mch_memmove(buffer, p, *buffer_off);
4489 return;
4490 }
4491 *buffer_off = 0;
4492 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004493 else
4494 {
4495 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004496 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004497 }
4498
4499 windgoto(msg_row, msg_col);
4500 cursor_on();
4501 out_flush();
4502 }
4503}
4504
4505/*
4506 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4507 * for communication and doesn't open any new window.
4508 */
4509 static int
4510mch_system_piped(char *cmd, int options)
4511{
4512 STARTUPINFO si;
4513 PROCESS_INFORMATION pi;
4514 DWORD ret = 0;
4515
4516 HANDLE g_hChildStd_IN_Rd = NULL;
4517 HANDLE g_hChildStd_IN_Wr = NULL;
4518 HANDLE g_hChildStd_OUT_Rd = NULL;
4519 HANDLE g_hChildStd_OUT_Wr = NULL;
4520
Bram Moolenaar0f873732019-12-05 20:28:46 +01004521 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004522 DWORD len;
4523
Bram Moolenaar0f873732019-12-05 20:28:46 +01004524 // buffer used to receive keys
4525 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4526 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004527
4528 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004529 int noread_cnt = 0;
4530 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004531 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004532 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004533 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004534
4535 SECURITY_ATTRIBUTES saAttr;
4536
Bram Moolenaar0f873732019-12-05 20:28:46 +01004537 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004538 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4539 saAttr.bInheritHandle = TRUE;
4540 saAttr.lpSecurityDescriptor = NULL;
4541
4542 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004543 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004544 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004545 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004546 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004547 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004548 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004549 {
4550 CloseHandle(g_hChildStd_IN_Rd);
4551 CloseHandle(g_hChildStd_IN_Wr);
4552 CloseHandle(g_hChildStd_OUT_Rd);
4553 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004554 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004555 }
4556
4557 si.cb = sizeof(si);
4558 si.lpReserved = NULL;
4559 si.lpDesktop = NULL;
4560 si.lpTitle = NULL;
4561 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4562
Bram Moolenaar0f873732019-12-05 20:28:46 +01004563 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004564 si.hStdError = g_hChildStd_OUT_Wr;
4565 si.hStdOutput = g_hChildStd_OUT_Wr;
4566 si.hStdInput = g_hChildStd_IN_Rd;
4567 si.wShowWindow = SW_HIDE;
4568 si.cbReserved2 = 0;
4569 si.lpReserved2 = NULL;
4570
4571 if (options & SHELL_READ)
4572 ga_init2(&ga, 1, BUFLEN);
4573
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004574 if (cmd != NULL)
4575 {
4576 p = (char *)vim_strsave((char_u *)cmd);
4577 if (p != NULL)
4578 unescape_shellxquote((char_u *)p, p_sxe);
4579 else
4580 p = cmd;
4581 }
4582
Bram Moolenaar0f873732019-12-05 20:28:46 +01004583 // Now, run the command.
4584 // About "Inherit handles" being TRUE: this command can be litigious,
4585 // handle inheritance was deactivated for pending temp file, but, if we
4586 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004587 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4588 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004589
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004590 if (p != cmd)
4591 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004592
Bram Moolenaar0f873732019-12-05 20:28:46 +01004593 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004594 CloseHandle(g_hChildStd_IN_Rd);
4595 CloseHandle(g_hChildStd_OUT_Wr);
4596
4597 if (options & SHELL_WRITE)
4598 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004599 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004600 _beginthreadex(NULL, // security attributes
4601 0, // default stack size
4602 sub_process_writer, // function to be executed
4603 g_hChildStd_IN_Wr, // parameter
4604 0, // creation flag, start immediately
4605 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004606 CloseHandle(thread);
4607 g_hChildStd_IN_Wr = NULL;
4608 }
4609
Bram Moolenaar0f873732019-12-05 20:28:46 +01004610 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004611 for (;;)
4612 {
4613 MSG msg;
4614
K.Takatab7057bd2022-01-21 11:37:07 +00004615 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004616 {
4617 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004618 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004619 }
4620
Bram Moolenaar0f873732019-12-05 20:28:46 +01004621 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004622 if ((options & (SHELL_READ|SHELL_WRITE))
4623# ifdef FEAT_GUI
4624 || gui.in_use
4625# endif
4626 )
4627 {
4628 len = 0;
4629 if (!(options & SHELL_EXPAND)
4630 && ((options &
4631 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4632 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4633# ifdef FEAT_GUI
4634 || gui.in_use
4635# endif
4636 )
4637 && (ta_len > 0 || noread_cnt > 4))
4638 {
4639 if (ta_len == 0)
4640 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004641 // Get extra characters when we don't have any. Reset the
4642 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004643 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004644 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4645 }
4646 if (ta_len > 0 || len > 0)
4647 {
4648 /*
4649 * For pipes: Check for CTRL-C: send interrupt signal to
4650 * child. Check for CTRL-D: EOF, close pipe to child.
4651 */
4652 if (len == 1 && cmd != NULL)
4653 {
4654 if (ta_buf[ta_len] == Ctrl_C)
4655 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004656 // Learn what exit code is expected, for
4657 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004658 TerminateProcess(pi.hProcess, 9);
4659 }
4660 if (ta_buf[ta_len] == Ctrl_D)
4661 {
4662 CloseHandle(g_hChildStd_IN_Wr);
4663 g_hChildStd_IN_Wr = NULL;
4664 }
4665 }
4666
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01004667 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004668
4669 /*
4670 * For pipes: echo the typed characters. For a pty this
4671 * does not seem to work.
4672 */
4673 for (i = ta_len; i < ta_len + len; ++i)
4674 {
4675 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4676 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004677 else if (has_mbyte)
4678 {
4679 int l = (*mb_ptr2len)(ta_buf + i);
4680
4681 msg_outtrans_len(ta_buf + i, l);
4682 i += l - 1;
4683 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004684 else
4685 msg_outtrans_len(ta_buf + i, 1);
4686 }
4687 windgoto(msg_row, msg_col);
4688 out_flush();
4689
4690 ta_len += len;
4691
4692 /*
4693 * Write the characters to the child, unless EOF has been
4694 * typed for pipes. Write one character at a time, to
4695 * avoid losing too much typeahead. When writing buffer
4696 * lines, drop the typed characters (only check for
4697 * CTRL-C).
4698 */
4699 if (options & SHELL_WRITE)
4700 ta_len = 0;
4701 else if (g_hChildStd_IN_Wr != NULL)
4702 {
4703 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4704 1, &len, NULL);
4705 // if we are typing in, we want to keep things reactive
4706 delay = 1;
4707 if (len > 0)
4708 {
4709 ta_len -= len;
4710 mch_memmove(ta_buf, ta_buf + len, ta_len);
4711 }
4712 }
4713 }
4714 }
4715 }
4716
4717 if (ta_len)
4718 ui_inchar_undo(ta_buf, ta_len);
4719
4720 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4721 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004722 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004723 break;
4724 }
4725
4726 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004727 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004728
Bram Moolenaar0f873732019-12-05 20:28:46 +01004729 // We start waiting for a very short time and then increase it, so
4730 // that we respond quickly when the process is quick, and don't
4731 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004732 if (delay < 50)
4733 delay += 10;
4734 }
4735
Bram Moolenaar0f873732019-12-05 20:28:46 +01004736 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004737 CloseHandle(g_hChildStd_OUT_Rd);
4738 if (g_hChildStd_IN_Wr != NULL)
4739 CloseHandle(g_hChildStd_IN_Wr);
4740
4741 WaitForSingleObject(pi.hProcess, INFINITE);
4742
Bram Moolenaar0f873732019-12-05 20:28:46 +01004743 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004744 GetExitCodeProcess(pi.hProcess, &ret);
4745
4746 if (options & SHELL_READ)
4747 {
4748 if (ga.ga_len > 0)
4749 {
4750 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01004751 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004752 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4753 }
4754 else
4755 curbuf->b_no_eol_lnum = 0;
4756 ga_clear(&ga);
4757 }
4758
Bram Moolenaar0f873732019-12-05 20:28:46 +01004759 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004760 CloseHandle(pi.hThread);
4761 CloseHandle(pi.hProcess);
4762
4763 return ret;
4764}
4765
4766 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004767mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004768{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004769 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004770 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004771 return mch_system_piped(cmd, options);
4772 else
4773 return mch_system_classic(cmd, options);
4774}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004775#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004776
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004777#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004778 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02004779mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004780{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004781 int ret;
4782 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004783 char_u *buf;
4784 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004785
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004786 // If the command starts and ends with double quotes, enclose the command
4787 // in parentheses.
4788 len = STRLEN(cmd);
4789 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
4790 {
4791 len += 3;
4792 buf = alloc(len);
4793 if (buf == NULL)
4794 return -1;
4795 vim_snprintf((char *)buf, len, "(%s)", cmd);
4796 wcmd = enc_to_utf16(buf, NULL);
4797 free(buf);
4798 }
4799 else
4800 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4801
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004802 if (wcmd == NULL)
4803 return -1;
4804
4805 ret = _wsystem(wcmd);
4806 vim_free(wcmd);
4807 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004808}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004809
4810#endif
4811
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004812 static int
4813mch_system(char *cmd, int options)
4814{
4815#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004816 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004817 return mch_system_g(cmd, options);
4818 else
4819 return mch_system_c(cmd, options);
4820#elif defined(FEAT_GUI_MSWIN)
4821 return mch_system_g(cmd, options);
4822#else
4823 return mch_system_c(cmd, options);
4824#endif
4825}
4826
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004827#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4828/*
4829 * Use a terminal window to run a shell command in.
4830 */
4831 static int
4832mch_call_shell_terminal(
4833 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004834 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004835{
4836 jobopt_T opt;
4837 char_u *newcmd = NULL;
4838 typval_T argvar[2];
4839 long_u cmdlen;
4840 int retval = -1;
4841 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004842 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004843 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004844 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004845
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004846 if (cmd == NULL)
4847 cmdlen = STRLEN(p_sh) + 1;
4848 else
4849 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004850 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004851 if (newcmd == NULL)
4852 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004853 if (cmd == NULL)
4854 {
4855 STRCPY(newcmd, p_sh);
4856 ch_log(NULL, "starting terminal to run a shell");
4857 }
4858 else
4859 {
4860 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4861 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4862 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004863
4864 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004865
4866 argvar[0].v_type = VAR_STRING;
4867 argvar[0].vval.v_string = newcmd;
4868 argvar[1].v_type = VAR_UNKNOWN;
4869 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004870 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004871 {
4872 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004873 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004874 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004875
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004876 job = term_getjob(buf->b_term);
4877 ++job->jv_refcount;
4878
Bram Moolenaar0f873732019-12-05 20:28:46 +01004879 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004880 aucmd_prepbuf(&aco, buf);
4881
4882 clear_oparg(&oa);
4883 while (term_use_loop())
4884 {
4885 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4886 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004887 // If terminal_loop() returns OK we got a key that is handled
4888 // in Normal model. We don't do redrawing anyway.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004889 if (terminal_loop(TRUE) == OK)
4890 normal_cmd(&oa, TRUE);
4891 }
4892 else
4893 normal_cmd(&oa, TRUE);
4894 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004895 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004896 ch_log(NULL, "system command finished");
4897
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004898 job_unref(job);
4899
Bram Moolenaar0f873732019-12-05 20:28:46 +01004900 // restore curwin/curbuf and a few other things
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004901 aucmd_restbuf(&aco);
4902
4903 wait_return(TRUE);
4904 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4905
4906 vim_free(newcmd);
4907 return retval;
4908}
4909#endif
4910
Bram Moolenaar071d4272004-06-13 20:20:40 +00004911/*
4912 * Either execute a command by calling the shell or start a new shell
4913 */
4914 int
4915mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004916 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004917 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00004918{
4919 int x = 0;
4920 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004921 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004922
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01004923#ifdef FEAT_JOB_CHANNEL
4924 ch_log(NULL, "executing shell command: %s", cmd);
4925#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004926 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02004927 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004928 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004929 if (cmd == NULL)
4930 wcscat(szShellTitle, L" :sh");
4931 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004932 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004933 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004934
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004935 if (wn != NULL)
4936 {
4937 wcscat(szShellTitle, L" - !");
4938 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02004939 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004940 wcscat(szShellTitle, wn);
4941 SetConsoleTitleW(szShellTitle);
4942 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004943 }
4944 }
4945 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004946
4947 out_flush();
4948
4949#ifdef MCH_WRITE_DUMP
4950 if (fdDump)
4951 {
4952 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4953 fflush(fdDump);
4954 }
4955#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004956#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004957 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004958 if (
4959# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004960 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004961# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004962 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004963 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4964 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004965 char_u *cmdbase = cmd;
4966
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004967 if (cmdbase != NULL)
4968 // Skip a leading quote and (.
4969 while (*cmdbase == '"' || *cmdbase == '(')
4970 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004971
4972 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01004973 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
4974 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004975 {
4976 // Use a terminal window to run the command in.
4977 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004978 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004979 return x;
4980 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004981 }
4982#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004983
4984 /*
4985 * Catch all deadly signals while running the external command, because a
4986 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4987 */
4988 signal(SIGINT, SIG_IGN);
4989#if defined(__GNUC__) && !defined(__MINGW32__)
4990 signal(SIGKILL, SIG_IGN);
4991#else
4992 signal(SIGBREAK, SIG_IGN);
4993#endif
4994 signal(SIGILL, SIG_IGN);
4995 signal(SIGFPE, SIG_IGN);
4996 signal(SIGSEGV, SIG_IGN);
4997 signal(SIGTERM, SIG_IGN);
4998 signal(SIGABRT, SIG_IGN);
4999
5000 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005001 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00005002
5003 if (cmd == NULL)
5004 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005005 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005006 }
5007 else
5008 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005009 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005010 char_u *newcmd = NULL;
5011 char_u *cmdbase = cmd;
5012 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005013
Bram Moolenaar0f873732019-12-05 20:28:46 +01005014 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005015 if (*cmdbase == '"' )
5016 ++cmdbase;
5017 if (*cmdbase == '(')
5018 ++cmdbase;
5019
Bram Moolenaar1c465442017-03-12 20:10:05 +01005020 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005021 {
5022 STARTUPINFO si;
5023 PROCESS_INFORMATION pi;
5024 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005025 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005026 char_u *p;
5027
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005028 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005029 si.cb = sizeof(si);
5030 si.lpReserved = NULL;
5031 si.lpDesktop = NULL;
5032 si.lpTitle = NULL;
5033 si.dwFlags = 0;
5034 si.cbReserved2 = 0;
5035 si.lpReserved2 = NULL;
5036
5037 cmdbase = skipwhite(cmdbase + 5);
5038 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005039 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005040 {
5041 cmdbase = skipwhite(cmdbase + 4);
5042 si.dwFlags = STARTF_USESHOWWINDOW;
5043 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005044 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005045 }
5046 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005047 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005048 {
5049 cmdbase = skipwhite(cmdbase + 2);
5050 flags = CREATE_NO_WINDOW;
5051 si.dwFlags = STARTF_USESTDHANDLES;
5052 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005053 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005054 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005055 NULL, // Security att.
5056 OPEN_EXISTING, // Open flags
5057 FILE_ATTRIBUTE_NORMAL, // File att.
5058 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005059 si.hStdOutput = si.hStdInput;
5060 si.hStdError = si.hStdInput;
5061 }
5062
Bram Moolenaar0f873732019-12-05 20:28:46 +01005063 // Remove a trailing ", ) and )" if they have a match
5064 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005065 if (cmdbase > cmd)
5066 {
5067 p = cmdbase + STRLEN(cmdbase);
5068 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5069 *--p = NUL;
5070 if (p > cmdbase && p[-1] == ')'
5071 && (*cmd =='(' || cmd[1] == '('))
5072 *--p = NUL;
5073 }
5074
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005075 newcmd = cmdbase;
5076 unescape_shellxquote(cmdbase, p_sxe);
5077
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005078 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005079 * If creating new console, arguments are passed to the
5080 * 'cmd.exe' as-is. If it's not, arguments are not treated
5081 * correctly for current 'cmd.exe'. So unescape characters in
5082 * shellxescape except '|' for avoiding to be treated as
5083 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005084 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005085 if (flags != CREATE_NEW_CONSOLE)
5086 {
5087 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005088 char_u *cmd_shell = mch_getenv("COMSPEC");
5089
5090 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005091 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005092
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005093 subcmd = vim_strsave_escaped_ext(cmdbase,
5094 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005095 if (subcmd != NULL)
5096 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005097 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005098 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005099 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005100 if (newcmd != NULL)
5101 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005102 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005103 else
5104 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005105 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005106 }
5107 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005108
5109 /*
5110 * Now, start the command as a process, so that it doesn't
5111 * inherit our handles which causes unpleasant dangling swap
5112 * files if we exit before the spawned process
5113 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005114 if (vim_create_process((char *)newcmd, FALSE, flags,
5115 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005116 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005117 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5118 > (HINSTANCE)32)
5119 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005120 else
5121 {
5122 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005123#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005124# ifdef VIMDLL
5125 if (gui.in_use)
5126# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005127 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005128#endif
5129 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005130
5131 if (newcmd != cmdbase)
5132 vim_free(newcmd);
5133
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005134 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005135 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005136 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005137 CloseHandle(si.hStdInput);
5138 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005139 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005140 CloseHandle(pi.hThread);
5141 CloseHandle(pi.hProcess);
5142 }
5143 else
5144 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005145 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005146#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005147 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005148 (!s_dont_use_vimrun && p_stmp ?
5149 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5150 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005151#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005152 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005153
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005154 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005155 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005156 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005157#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005158 if (
5159# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005160 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005161# endif
5162 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005163 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005164 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5165 "External commands will not pause after completion.\n"
5166 "See :help win32-vimrun for more information.");
5167 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005168 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5169 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005170
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005171 if (wmsg != NULL && wtitle != NULL)
5172 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5173 vim_free(wmsg);
5174 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005175 need_vimrun_warning = FALSE;
5176 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005177 if (
5178# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005179 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005180# endif
5181 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005182 // Use vimrun to execute the command. It opens a console
5183 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005184 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005185 vimrun_path,
5186 (msg_silent != 0 || (options & SHELL_DOOUT))
5187 ? "-s " : "",
5188 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005189 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005190# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005191 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005192# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005193 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005194 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005195 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5196 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005197 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005198#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005199 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005200 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005201 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005202 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005203 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005204 }
5205 }
5206
5207 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005208 {
5209 // The shell may have messed with the mode, always set it.
5210 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005211 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005212 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005213
Bram Moolenaar0f873732019-12-05 20:28:46 +01005214 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005215 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005216#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005217 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005218 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005219#endif
5220 )
5221 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005222 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005223 msg_putchar('\n');
5224 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005225 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005226
5227 signal(SIGINT, SIG_DFL);
5228#if defined(__GNUC__) && !defined(__MINGW32__)
5229 signal(SIGKILL, SIG_DFL);
5230#else
5231 signal(SIGBREAK, SIG_DFL);
5232#endif
5233 signal(SIGILL, SIG_DFL);
5234 signal(SIGFPE, SIG_DFL);
5235 signal(SIGSEGV, SIG_DFL);
5236 signal(SIGTERM, SIG_DFL);
5237 signal(SIGABRT, SIG_DFL);
5238
5239 return x;
5240}
5241
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005242#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005243 static HANDLE
5244job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005245 char_u *fname,
5246 DWORD dwDesiredAccess,
5247 DWORD dwShareMode,
5248 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5249 DWORD dwCreationDisposition,
5250 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005251{
5252 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005253 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005254
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005255 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005256 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005257 return INVALID_HANDLE_VALUE;
5258
5259 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5260 lpSecurityAttributes, dwCreationDisposition,
5261 dwFlagsAndAttributes, NULL);
5262 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005263 return h;
5264}
5265
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005266/*
5267 * Turn the dictionary "env" into a NUL separated list that can be used as the
5268 * environment argument of vim_create_process().
5269 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005270 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005271win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005272{
5273 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005274 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005275 LPVOID base = GetEnvironmentStringsW();
5276
Bram Moolenaar0f873732019-12-05 20:28:46 +01005277 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005278 if (ga_grow(gap, 1) == FAIL)
5279 return;
5280
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005281 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005282 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005283 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005284 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005285 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005286 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005287 typval_T *item = &dict_lookup(hi)->di_tv;
5288 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005289 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005290 --todo;
5291 if (wkey != NULL && wval != NULL)
5292 {
5293 size_t n;
5294 size_t lkey = wcslen(wkey);
5295 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005296
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005297 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5298 continue;
5299 for (n = 0; n < lkey; n++)
5300 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5301 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5302 for (n = 0; n < lval; n++)
5303 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5304 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5305 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005306 vim_free(wkey);
5307 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005308 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005309 }
5310 }
5311
Bram Moolenaar355757a2020-02-10 22:06:32 +01005312 if (base)
5313 {
5314 WCHAR *p = (WCHAR*) base;
5315
5316 // for last \0
5317 if (ga_grow(gap, 1) == FAIL)
5318 return;
5319
5320 while (*p != 0 || *(p + 1) != 0)
5321 {
5322 if (ga_grow(gap, 1) == OK)
5323 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5324 p++;
5325 }
5326 FreeEnvironmentStrings(base);
5327 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5328 }
5329
Bram Moolenaar493359e2018-06-12 20:25:52 +02005330# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005331 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005332# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005333 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005334 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005335# endif
5336# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005337 char_u *version = get_vim_var_str(VV_VERSION);
5338 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005339# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005340 // size of "VIM_SERVERNAME=" and value,
5341 // plus "VIM_TERMINAL=" and value,
5342 // plus two terminating NULs
5343 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005344# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005345 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005346# endif
5347# ifdef FEAT_TERMINAL
5348 + 13 + version_len + 2
5349# endif
5350 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005351
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005352 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005353 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005354# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005355 for (n = 0; n < 15; n++)
5356 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5357 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005358 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005359 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5360 (WCHAR)servername[n];
5361 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005362# endif
5363# ifdef FEAT_TERMINAL
5364 if (is_terminal)
5365 {
5366 for (n = 0; n < 13; n++)
5367 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5368 (WCHAR)"VIM_TERMINAL="[n];
5369 for (n = 0; n < version_len; n++)
5370 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5371 (WCHAR)version[n];
5372 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5373 }
5374# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005375 }
5376 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005377# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005378}
5379
Bram Moolenaarb091f302019-01-19 14:37:00 +01005380/*
5381 * Create a pair of pipes.
5382 * Return TRUE for success, FALSE for failure.
5383 */
5384 static BOOL
5385create_pipe_pair(HANDLE handles[2])
5386{
5387 static LONG s;
5388 char name[64];
5389 SECURITY_ATTRIBUTES sa;
5390
5391 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5392 GetCurrentProcessId(),
5393 InterlockedIncrement(&s));
5394
5395 // Create named pipe. Max size of named pipe is 65535.
5396 handles[1] = CreateNamedPipe(
5397 name,
5398 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5399 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005400 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005401
5402 if (handles[1] == INVALID_HANDLE_VALUE)
5403 return FALSE;
5404
5405 sa.nLength = sizeof(sa);
5406 sa.bInheritHandle = TRUE;
5407 sa.lpSecurityDescriptor = NULL;
5408
5409 handles[0] = CreateFile(name,
5410 FILE_GENERIC_READ,
5411 FILE_SHARE_READ, &sa,
5412 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5413
5414 if (handles[0] == INVALID_HANDLE_VALUE)
5415 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005416 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005417 return FALSE;
5418 }
5419
5420 return TRUE;
5421}
5422
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005423 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005424mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005425{
5426 STARTUPINFO si;
5427 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005428 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005429 SECURITY_ATTRIBUTES saAttr;
5430 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005431 HANDLE ifd[2];
5432 HANDLE ofd[2];
5433 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005434 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005435
5436 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5437 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5438 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5439 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5440 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5441 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5442 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5443
5444 if (use_out_for_err && use_null_for_out)
5445 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005446
5447 ifd[0] = INVALID_HANDLE_VALUE;
5448 ifd[1] = INVALID_HANDLE_VALUE;
5449 ofd[0] = INVALID_HANDLE_VALUE;
5450 ofd[1] = INVALID_HANDLE_VALUE;
5451 efd[0] = INVALID_HANDLE_VALUE;
5452 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005453 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005454
Bram Moolenaar14207f42016-10-27 21:13:10 +02005455 jo = CreateJobObject(NULL, NULL);
5456 if (jo == NULL)
5457 {
5458 job->jv_status = JOB_FAILED;
5459 goto failed;
5460 }
5461
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005462 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005463 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005464
Bram Moolenaar76467df2016-02-12 19:30:26 +01005465 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005466 ZeroMemory(&si, sizeof(si));
5467 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005468 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005469 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005470
Bram Moolenaard8070362016-02-15 21:56:54 +01005471 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5472 saAttr.bInheritHandle = TRUE;
5473 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005474
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005475 if (use_file_for_in)
5476 {
5477 char_u *fname = options->jo_io_name[PART_IN];
5478
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005479 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5480 FILE_SHARE_READ | FILE_SHARE_WRITE,
5481 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5482 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005483 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005484 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005485 goto failed;
5486 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005487 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005488 else if (!use_null_for_in
5489 && (!create_pipe_pair(ifd)
5490 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005491 goto failed;
5492
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005493 if (use_file_for_out)
5494 {
5495 char_u *fname = options->jo_io_name[PART_OUT];
5496
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005497 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5498 FILE_SHARE_READ | FILE_SHARE_WRITE,
5499 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5500 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005501 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005502 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005503 goto failed;
5504 }
5505 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005506 else if (!use_null_for_out &&
5507 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005508 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005509 goto failed;
5510
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005511 if (use_file_for_err)
5512 {
5513 char_u *fname = options->jo_io_name[PART_ERR];
5514
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005515 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5516 FILE_SHARE_READ | FILE_SHARE_WRITE,
5517 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5518 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005519 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005520 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005521 goto failed;
5522 }
5523 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005524 else if (!use_out_for_err && !use_null_for_err &&
5525 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005526 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005527 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005528
Bram Moolenaard8070362016-02-15 21:56:54 +01005529 si.dwFlags |= STARTF_USESTDHANDLES;
5530 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005531 si.hStdOutput = ofd[1];
5532 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5533
5534 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5535 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005536 if (options->jo_set & JO_CHANNEL)
5537 {
5538 channel = options->jo_channel;
5539 if (channel != NULL)
5540 ++channel->ch_refcount;
5541 }
5542 else
5543 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005544 if (channel == NULL)
5545 goto failed;
5546 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005547
5548 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005549 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005550 CREATE_DEFAULT_ERROR_MODE |
5551 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005552 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005553 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005554 &si, &pi,
5555 ga.ga_data,
5556 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005557 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005558 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005559 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005560 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005561 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005562
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005563 ga_clear(&ga);
5564
Bram Moolenaar14207f42016-10-27 21:13:10 +02005565 if (!AssignProcessToJobObject(jo, pi.hProcess))
5566 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005567 // if failing, switch the way to terminate
5568 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005569 CloseHandle(jo);
5570 jo = NULL;
5571 }
5572 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005573 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005574 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005575 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005576 job->jv_status = JOB_STARTED;
5577
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005578 CloseHandle(ifd[0]);
5579 CloseHandle(ofd[1]);
5580 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005581 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005582
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005583 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005584 if (channel != NULL)
5585 {
5586 channel_set_pipes(channel,
5587 use_file_for_in || use_null_for_in
5588 ? INVALID_FD : (sock_T)ifd[1],
5589 use_file_for_out || use_null_for_out
5590 ? INVALID_FD : (sock_T)ofd[0],
5591 use_out_for_err || use_file_for_err || use_null_for_err
5592 ? INVALID_FD : (sock_T)efd[0]);
5593 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005594 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005595 return;
5596
5597failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005598 CloseHandle(ifd[0]);
5599 CloseHandle(ofd[0]);
5600 CloseHandle(efd[0]);
5601 CloseHandle(ifd[1]);
5602 CloseHandle(ofd[1]);
5603 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005604 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005605 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005606}
5607
5608 char *
5609mch_job_status(job_T *job)
5610{
5611 DWORD dwExitCode = 0;
5612
Bram Moolenaar76467df2016-02-12 19:30:26 +01005613 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5614 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005615 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005616 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005617 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005618 {
5619 ch_log(job->jv_channel, "Job ended");
5620 job->jv_status = JOB_ENDED;
5621 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005622 return "dead";
5623 }
5624 return "run";
5625}
5626
Bram Moolenaar97792de2016-10-15 18:36:49 +02005627 job_T *
5628mch_detect_ended_job(job_T *job_list)
5629{
5630 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5631 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5632 job_T *job = job_list;
5633
5634 while (job != NULL)
5635 {
5636 DWORD n;
5637 DWORD result;
5638
5639 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5640 && job != NULL; job = job->jv_next)
5641 {
5642 if (job->jv_status == JOB_STARTED)
5643 {
5644 jobHandles[n] = job->jv_proc_info.hProcess;
5645 jobArray[n] = job;
5646 ++n;
5647 }
5648 }
5649 if (n == 0)
5650 continue;
5651 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5652 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5653 {
5654 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5655
5656 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5657 return wait_job;
5658 }
5659 }
5660 return NULL;
5661}
5662
Bram Moolenaarfb630902016-10-29 14:55:00 +02005663 static BOOL
5664terminate_all(HANDLE process, int code)
5665{
5666 PROCESSENTRY32 pe;
5667 HANDLE h = INVALID_HANDLE_VALUE;
5668 DWORD pid = GetProcessId(process);
5669
5670 if (pid != 0)
5671 {
5672 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5673 if (h != INVALID_HANDLE_VALUE)
5674 {
5675 pe.dwSize = sizeof(PROCESSENTRY32);
5676 if (!Process32First(h, &pe))
5677 goto theend;
5678
5679 do
5680 {
5681 if (pe.th32ParentProcessID == pid)
5682 {
5683 HANDLE ph = OpenProcess(
5684 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5685 if (ph != NULL)
5686 {
5687 terminate_all(ph, code);
5688 CloseHandle(ph);
5689 }
5690 }
5691 } while (Process32Next(h, &pe));
5692
5693 CloseHandle(h);
5694 }
5695 }
5696
5697theend:
5698 return TerminateProcess(process, code);
5699}
5700
5701/*
5702 * Send a (deadly) signal to "job".
5703 * Return FAIL if it didn't work.
5704 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005705 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005706mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005707{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005708 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005709
Bram Moolenaar923d9262016-02-25 20:56:01 +01005710 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005711 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005712 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02005713 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005714 {
5715 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5716 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00005717 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005718 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01005719 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005720 }
5721
5722 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5723 return FAIL;
5724 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005725 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5726 job->jv_proc_info.dwProcessId)
5727 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005728 FreeConsole();
5729 return ret;
5730}
5731
5732/*
5733 * Clear the data related to "job".
5734 */
5735 void
5736mch_clear_job(job_T *job)
5737{
5738 if (job->jv_status != JOB_FAILED)
5739 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005740 if (job->jv_job_object != NULL)
5741 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005742 CloseHandle(job->jv_proc_info.hProcess);
5743 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005744}
5745#endif
5746
Bram Moolenaar071d4272004-06-13 20:20:40 +00005747
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005748#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005749
5750/*
5751 * Start termcap mode
5752 */
5753 static void
5754termcap_mode_start(void)
5755{
5756 DWORD cmodein;
5757
5758 if (g_fTermcapMode)
5759 return;
5760
Christopher Plewright1140b512022-11-12 18:46:05 +00005761 // VTP uses alternate screen buffer.
5762 // Switch to a new alternate screen buffer.
5763 if (win11_or_later && p_rs && vtp_working)
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005764 vtp_printf("\033[?1049h");
5765
Bram Moolenaar071d4272004-06-13 20:20:40 +00005766 SaveConsoleBuffer(&g_cbNonTermcap);
5767
5768 if (g_cbTermcap.IsValid)
5769 {
5770 /*
5771 * We've been in termcap mode before. Restore certain screen
5772 * characteristics, including the buffer size and the window
5773 * size. Since we will be redrawing the screen, we don't need
5774 * to restore the actual contents of the buffer.
5775 */
5776 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005777 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005778 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5779 Rows = g_cbTermcap.Info.dwSize.Y;
5780 Columns = g_cbTermcap.Info.dwSize.X;
5781 }
5782 else
5783 {
5784 /*
5785 * This is our first time entering termcap mode. Clear the console
5786 * screen buffer, and resize the buffer to match the current window
5787 * size. We will use this as the size of our editing environment.
5788 */
5789 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005790 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005791 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5792 }
5793
Bram Moolenaar071d4272004-06-13 20:20:40 +00005794 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005795
5796 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005797 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005798 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005799 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005800 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
5801 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005802 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005803 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005804 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005805 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5806 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005807 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005808 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005809
5810 redraw_later_clear();
5811 g_fTermcapMode = TRUE;
5812}
5813
5814
5815/*
5816 * End termcap mode
5817 */
5818 static void
5819termcap_mode_end(void)
5820{
5821 DWORD cmodein;
5822 ConsoleBuffer *cb;
5823 COORD coord;
5824 DWORD dwDummy;
5825
5826 if (!g_fTermcapMode)
5827 return;
5828
5829 SaveConsoleBuffer(&g_cbTermcap);
5830
5831 GetConsoleMode(g_hConIn, &cmodein);
5832 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005833 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5834 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005835
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005836# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005837 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005838# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005839 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005840# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005841 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01005842 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005843
Christopher Plewright1140b512022-11-12 18:46:05 +00005844 // VTP uses alternate screen buffer.
5845 // Switch back to main screen buffer.
5846 if (exiting && win11_or_later && p_rs && vtp_working)
5847 vtp_printf("\033[?1049l");
5848
5849 if (!USE_WT && (p_rs || exiting))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005850 {
5851 /*
5852 * Clear anything that happens to be on the current line.
5853 */
5854 coord.X = 0;
5855 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
Christopher Plewright1140b512022-11-12 18:46:05 +00005856 if (!vtp_working)
5857 FillConsoleOutputCharacter(g_hConOut, ' ',
5858 cb->Info.dwSize.X, coord, &dwDummy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005859 /*
5860 * The following is just for aesthetics. If we are exiting without
5861 * restoring the screen, then we want to have a prompt string
5862 * appear at the bottom line. However, the command interpreter
5863 * seems to always advance the cursor one line before displaying
5864 * the prompt string, which causes the screen to scroll. To
5865 * counter this, move the cursor up one line before exiting.
5866 */
5867 if (exiting && !p_rs)
5868 coord.Y--;
5869 /*
5870 * Position the cursor at the leftmost column of the desired row.
5871 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005872 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005873 }
Christopher Plewright1140b512022-11-12 18:46:05 +00005874 SetConsoleCursorInfo(g_hConOut, &g_cci);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005875 g_fTermcapMode = FALSE;
5876}
Christopher Plewright38804d62022-11-09 23:55:52 +00005877#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00005878
5879
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005880#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005881 void
5882mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005883 char_u *s UNUSED,
5884 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005885{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005886 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00005887}
5888
5889#else
5890
5891/*
5892 * clear `n' chars, starting from `coord'
5893 */
5894 static void
5895clear_chars(
5896 COORD coord,
5897 DWORD n)
5898{
Christopher Plewright38804d62022-11-09 23:55:52 +00005899 if (!vtp_working)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02005900 {
5901 DWORD dwDummy;
5902
5903 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5904 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
5905 &dwDummy);
5906 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005907 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005908 {
5909 set_console_color_rgb();
5910 gotoxy(coord.X + 1, coord.Y + 1);
5911 vtp_printf("\033[%dX", n);
5912 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005913}
5914
5915
5916/*
5917 * Clear the screen
5918 */
5919 static void
5920clear_screen(void)
5921{
5922 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005923
Christopher Plewright38804d62022-11-09 23:55:52 +00005924 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005925 clear_chars(g_coord, Rows * Columns);
5926 else
5927 {
5928 set_console_color_rgb();
5929 gotoxy(1, 1);
5930 vtp_printf("\033[2J");
5931 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005932}
5933
5934
5935/*
5936 * Clear to end of display
5937 */
5938 static void
5939clear_to_end_of_display(void)
5940{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005941 COORD save = g_coord;
5942
Christopher Plewright38804d62022-11-09 23:55:52 +00005943 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005944 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005945 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005946 else
5947 {
5948 set_console_color_rgb();
5949 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5950 vtp_printf("\033[0J");
5951
5952 gotoxy(save.X + 1, save.Y + 1);
5953 g_coord = save;
5954 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005955}
5956
5957
5958/*
5959 * Clear to end of line
5960 */
5961 static void
5962clear_to_end_of_line(void)
5963{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005964 COORD save = g_coord;
5965
Christopher Plewright38804d62022-11-09 23:55:52 +00005966 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005967 clear_chars(g_coord, Columns - g_coord.X);
5968 else
5969 {
5970 set_console_color_rgb();
5971 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5972 vtp_printf("\033[0K");
5973
5974 gotoxy(save.X + 1, save.Y + 1);
5975 g_coord = save;
5976 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005977}
5978
5979
5980/*
5981 * Scroll the scroll region up by `cLines' lines
5982 */
5983 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005984scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005985{
5986 COORD oldcoord = g_coord;
5987
5988 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5989 delete_lines(cLines);
5990
5991 g_coord = oldcoord;
5992}
5993
5994
5995/*
5996 * Set the scroll region
5997 */
5998 static void
5999set_scroll_region(
6000 unsigned left,
6001 unsigned top,
6002 unsigned right,
6003 unsigned bottom)
6004{
6005 if (left >= right
6006 || top >= bottom
6007 || right > (unsigned) Columns - 1
6008 || bottom > (unsigned) Rows - 1)
6009 return;
6010
6011 g_srScrollRegion.Left = left;
6012 g_srScrollRegion.Top = top;
6013 g_srScrollRegion.Right = right;
6014 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006015}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006016
Bram Moolenaar6982f422019-02-16 16:48:01 +01006017 static void
6018set_scroll_region_tb(
6019 unsigned top,
6020 unsigned bottom)
6021{
6022 if (top >= bottom || bottom > (unsigned)Rows - 1)
6023 return;
6024
6025 g_srScrollRegion.Top = top;
6026 g_srScrollRegion.Bottom = bottom;
6027}
6028
6029 static void
6030set_scroll_region_lr(
6031 unsigned left,
6032 unsigned right)
6033{
6034 if (left >= right || right > (unsigned)Columns - 1)
6035 return;
6036
6037 g_srScrollRegion.Left = left;
6038 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006039}
6040
6041
6042/*
6043 * Insert `cLines' lines at the current cursor position
6044 */
6045 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006046insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006047{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006048 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006049 COORD dest;
6050 CHAR_INFO fill;
6051
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006052 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6053
Bram Moolenaar6982f422019-02-16 16:48:01 +01006054 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006055 dest.Y = g_coord.Y + cLines;
6056
Bram Moolenaar6982f422019-02-16 16:48:01 +01006057 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006058 source.Top = g_coord.Y;
6059 source.Right = g_srScrollRegion.Right;
6060 source.Bottom = g_srScrollRegion.Bottom - cLines;
6061
Bram Moolenaar6982f422019-02-16 16:48:01 +01006062 clip.Left = g_srScrollRegion.Left;
6063 clip.Top = g_coord.Y;
6064 clip.Right = g_srScrollRegion.Right;
6065 clip.Bottom = g_srScrollRegion.Bottom;
6066
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006067 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006068 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006069# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006070 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006071# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006072 ))
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006073 fill.Attributes = g_attrCurrent;
6074 else
6075 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006076
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006077 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006078
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006079 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6080
Bram Moolenaar6982f422019-02-16 16:48:01 +01006081 // Here we have to deal with a win32 console flake: If the scroll
6082 // region looks like abc and we scroll c to a and fill with d we get
6083 // cbd... if we scroll block c one line at a time to a, we get cdd...
6084 // vim expects cdd consistently... So we have to deal with that
6085 // here... (this also occurs scrolling the same way in the other
6086 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006087
6088 if (source.Bottom < dest.Y)
6089 {
6090 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006091 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006092
Bram Moolenaar6982f422019-02-16 16:48:01 +01006093 coord.X = source.Left;
6094 for (i = clip.Top; i < dest.Y; ++i)
6095 {
6096 coord.Y = i;
6097 clear_chars(coord, source.Right - source.Left + 1);
6098 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006099 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006100
Christopher Plewright38804d62022-11-09 23:55:52 +00006101 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006102 {
6103 COORD coord;
6104 int i;
6105
6106 coord.X = source.Left;
6107 for (i = source.Top; i < dest.Y; ++i)
6108 {
6109 coord.Y = i;
6110 clear_chars(coord, source.Right - source.Left + 1);
6111 }
6112 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006113}
6114
6115
6116/*
6117 * Delete `cLines' lines at the current cursor position
6118 */
6119 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006120delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006121{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006122 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006123 COORD dest;
6124 CHAR_INFO fill;
6125 int nb;
6126
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006127 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6128
Bram Moolenaar6982f422019-02-16 16:48:01 +01006129 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006130 dest.Y = g_coord.Y;
6131
Bram Moolenaar6982f422019-02-16 16:48:01 +01006132 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006133 source.Top = g_coord.Y + cLines;
6134 source.Right = g_srScrollRegion.Right;
6135 source.Bottom = g_srScrollRegion.Bottom;
6136
Bram Moolenaar6982f422019-02-16 16:48:01 +01006137 clip.Left = g_srScrollRegion.Left;
6138 clip.Top = g_coord.Y;
6139 clip.Right = g_srScrollRegion.Right;
6140 clip.Bottom = g_srScrollRegion.Bottom;
6141
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006142 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006143 if (!vtp_working)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006144 fill.Attributes = g_attrCurrent;
6145 else
6146 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006147
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006148 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006149
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006150 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6151
Bram Moolenaar6982f422019-02-16 16:48:01 +01006152 // Here we have to deal with a win32 console flake; See insert_lines()
6153 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006154
6155 nb = dest.Y + (source.Bottom - source.Top) + 1;
6156
6157 if (nb < source.Top)
6158 {
6159 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006160 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006161
Bram Moolenaar6982f422019-02-16 16:48:01 +01006162 coord.X = source.Left;
6163 for (i = nb; i < clip.Bottom; ++i)
6164 {
6165 coord.Y = i;
6166 clear_chars(coord, source.Right - source.Left + 1);
6167 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006168 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006169
Christopher Plewright38804d62022-11-09 23:55:52 +00006170 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006171 {
6172 COORD coord;
6173 int i;
6174
6175 coord.X = source.Left;
6176 for (i = nb; i <= source.Bottom; ++i)
6177 {
6178 coord.Y = i;
6179 clear_chars(coord, source.Right - source.Left + 1);
6180 }
6181 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006182}
6183
6184
6185/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006186 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006187 */
6188 static void
6189gotoxy(
6190 unsigned x,
6191 unsigned y)
6192{
6193 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6194 return;
6195
Christopher Plewright38804d62022-11-09 23:55:52 +00006196 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006197# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006198 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006199# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006200 ))
Bram Moolenaar2313b612019-09-27 14:14:32 +02006201 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006202 // There are reports of double-width characters not displayed
6203 // correctly. This workaround should fix it, similar to how it's done
6204 // for VTP.
6205 g_coord.X = 0;
6206 SetConsoleCursorPosition(g_hConOut, g_coord);
6207
Bram Moolenaar2313b612019-09-27 14:14:32 +02006208 // external cursor coords are 1-based; internal are 0-based
6209 g_coord.X = x - 1;
6210 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006211 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006212 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006213 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006214 {
6215 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006216 // destruction. Insider build bug. Always enabled because it's cheap
6217 // and avoids mistakes with recognizing the build.
6218 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006219
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006220 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006221
6222 g_coord.X = x - 1;
6223 g_coord.Y = y - 1;
6224 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006225}
6226
6227
6228/*
6229 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006230 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006231 */
6232 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006233textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006234{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006235 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006236
6237 SetConsoleTextAttribute(g_hConOut, wAttr);
6238}
6239
6240
6241 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006242textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006243{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006244 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006245
Christopher Plewright38804d62022-11-09 23:55:52 +00006246 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006247 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6248 else
6249 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006250}
6251
6252
6253 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006254textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006255{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006256 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006257
Christopher Plewright38804d62022-11-09 23:55:52 +00006258 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006259 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6260 else
6261 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006262}
6263
6264
6265/*
6266 * restore the default text attribute (whatever we started with)
6267 */
6268 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006269normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006270{
Christopher Plewright38804d62022-11-09 23:55:52 +00006271 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006272 textattr(g_attrDefault);
6273 else
6274 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006275}
6276
6277
6278static WORD g_attrPreStandout = 0;
6279
6280/*
6281 * Make the text standout, by brightening it
6282 */
6283 static void
6284standout(void)
6285{
6286 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006287
Bram Moolenaar071d4272004-06-13 20:20:40 +00006288 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6289}
6290
6291
6292/*
6293 * Turn off standout mode
6294 */
6295 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006296standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006297{
6298 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006299 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006300
6301 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006302}
6303
6304
6305/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006306 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006307 */
6308 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006309mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006310{
6311 char_u *p;
6312 int n;
6313
6314 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6315 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006316 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006317# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006318 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006319# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006320 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006321 {
6322 p = T_ME + 2;
6323 n = getdigits(&p);
6324 if (*p == 'm' && n > 0)
6325 {
6326 cterm_normal_fg_color = (n & 0xf) + 1;
6327 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6328 }
6329 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006330# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006331 cterm_normal_fg_gui_color = INVALCOLOR;
6332 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006333# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006334}
6335
6336
6337/*
6338 * visual bell: flash the screen
6339 */
6340 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006341visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006342{
6343 COORD coordOrigin = {0, 0};
6344 WORD attrFlash = ~g_attrCurrent & 0xff;
6345
6346 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006347 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006348
6349 if (oldattrs == NULL)
6350 return;
6351 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6352 coordOrigin, &dwDummy);
6353 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6354 coordOrigin, &dwDummy);
6355
Bram Moolenaar0f873732019-12-05 20:28:46 +01006356 Sleep(15); // wait for 15 msec
Christopher Plewright38804d62022-11-09 23:55:52 +00006357 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006358 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006359 coordOrigin, &dwDummy);
6360 vim_free(oldattrs);
6361}
6362
6363
6364/*
6365 * Make the cursor visible or invisible
6366 */
6367 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006368cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006369{
6370 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006371
Christopher Plewright38804d62022-11-09 23:55:52 +00006372 if (vtp_working)
Bram Moolenaar2695de62020-04-17 21:13:01 +02006373 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6374
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006375# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006376 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006377# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006378}
6379
6380
6381/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006382 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006383 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006384 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006385 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006386write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006387 char_u *pchBuf,
6388 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006389{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006390 COORD coord = g_coord;
6391 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006392 DWORD n, cchwritten;
6393 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006394 static WCHAR *unicodebuf = NULL;
6395 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006396 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006397 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006398 static WCHAR *utf8spbuf = NULL;
6399 static int utf8splength;
6400 static DWORD utf8spcells;
6401 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006402
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006403 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006404 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006405 utf8usingbuf = &unicodebuf;
6406 do
6407 {
6408 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6409 unicodebuf, unibuflen);
6410 if (length && length <= unibuflen)
6411 break;
6412 vim_free(unicodebuf);
6413 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6414 unibuflen = unibuflen ? 0 : length;
6415 } while(1);
6416 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006417 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006418 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6419 {
6420 if (utf8usingbuf != &utf8spbuf)
6421 {
6422 if (utf8spbuf == NULL)
6423 {
6424 cells = mb_string2cells((char_u *)" ", 1);
6425 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6426 utf8spbuf = LALLOC_MULT(WCHAR, length);
6427 if (utf8spbuf != NULL)
6428 {
6429 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6430 utf8usingbuf = &utf8spbuf;
6431 utf8splength = length;
6432 utf8spcells = cells;
6433 }
6434 }
6435 else
6436 {
6437 utf8usingbuf = &utf8spbuf;
6438 length = utf8splength;
6439 cells = utf8spcells;
6440 }
6441 }
6442 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006443
Christopher Plewright38804d62022-11-09 23:55:52 +00006444 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006445# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006446 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006447# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006448 ))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006449 {
6450 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6451 coord, &written);
6452 // When writing fails or didn't write a single character, pretend one
6453 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006454 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006455 coord, &cchwritten) == 0
6456 || cchwritten == 0 || cchwritten == (DWORD)-1)
6457 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006458 }
6459 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006460 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006461 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006462 NULL) == 0 || cchwritten == 0)
6463 cchwritten = 1;
6464 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006465
K.Takata135e1522022-01-29 15:27:58 +00006466 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006467 {
6468 written = cbToWrite;
6469 g_coord.X += (SHORT)cells;
6470 }
6471 else
6472 {
6473 char_u *p = pchBuf;
6474 for (n = 0; n < cchwritten; n++)
6475 MB_CPTR_ADV(p);
6476 written = p - pchBuf;
6477 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006478 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006479
6480 while (g_coord.X > g_srScrollRegion.Right)
6481 {
6482 g_coord.X -= (SHORT) Columns;
6483 if (g_coord.Y < g_srScrollRegion.Bottom)
6484 g_coord.Y++;
6485 }
6486
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006487 // Cursor under VTP is always in the correct position, no need to reset.
Christopher Plewright38804d62022-11-09 23:55:52 +00006488 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006489# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006490 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006491# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006492 ))
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006493 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006494
6495 return written;
6496}
6497
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006498 static char_u *
6499get_seq(
6500 int *args,
6501 int *count,
6502 char_u *head)
6503{
6504 int argc;
6505 char_u *p;
6506
6507 if (head == NULL || *head != '\033')
6508 return NULL;
6509
6510 argc = 0;
6511 p = head;
6512 ++p;
6513 do
6514 {
6515 ++p;
6516 args[argc] = getdigits(&p);
6517 argc += (argc < 15) ? 1 : 0;
6518 } while (*p == ';');
6519 *count = argc;
6520
6521 return p;
6522}
6523
6524 static char_u *
6525get_sgr(
6526 int *args,
6527 int *count,
6528 char_u *head)
6529{
6530 char_u *p = get_seq(args, count, head);
6531
6532 return (p && *p == 'm') ? ++p : NULL;
6533}
6534
6535/*
6536 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6537 */
6538 static char_u *
6539sgrn2(
6540 char_u *head,
6541 int n)
6542{
6543 int argc;
6544 int args[16];
6545 char_u *p = get_sgr(args, &argc, head);
6546
6547 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6548}
6549
6550/*
6551 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6552 */
6553 static char_u *
6554sgrnc(
6555 char_u *head,
6556 int n)
6557{
6558 int argc;
6559 int args[16];
6560 char_u *p = get_sgr(args, &argc, head);
6561
6562 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6563 ? p : NULL;
6564}
6565
6566 static char_u *
6567skipblank(char_u *q)
6568{
6569 char_u *p = q;
6570
6571 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6572 ++p;
6573 return p;
6574}
6575
6576/*
6577 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6578 * NULL.
6579 */
6580 static char_u *
6581sgrn2c(
6582 char_u *head,
6583 int n)
6584{
6585 char_u *p = sgrn2(head, n);
6586
6587 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6588}
6589
6590/*
6591 * If there is only a newline between the sequence immediately following it,
6592 * a pointer to the character following the newline is returned.
6593 * Otherwise NULL.
6594 */
6595 static char_u *
6596sgrn2cn(
6597 char_u *head,
6598 int n)
6599{
6600 char_u *p = sgrn2(head, n);
6601
6602 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6603}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006604
6605/*
6606 * mch_write(): write the output buffer to the screen, translating ESC
6607 * sequences into calls to console output routines.
6608 */
6609 void
6610mch_write(
6611 char_u *s,
6612 int len)
6613{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006614 char_u *end = s + len;
6615
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006616# ifdef VIMDLL
6617 if (gui.in_use)
6618 return;
6619# endif
6620
Bram Moolenaar071d4272004-06-13 20:20:40 +00006621 if (!term_console)
6622 {
6623 write(1, s, (unsigned)len);
6624 return;
6625 }
6626
Bram Moolenaar0f873732019-12-05 20:28:46 +01006627 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00006628 while (len--)
6629 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006630 int prefix = -1;
6631 char_u ch;
6632
6633 // While processing a sequence, on rare occasions it seems that another
6634 // sequence may be inserted asynchronously.
6635 if (len < 0)
6636 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006637 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006638 return;
6639 }
6640
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006641 while (s + ++prefix < end)
6642 {
6643 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006644 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6645 && ch != '\a' && ch != '\033'))
6646 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006647 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006648
6649 if (p_wd)
6650 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006651 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006652 if (prefix != 0)
6653 prefix = 1;
6654 }
6655
6656 if (prefix != 0)
6657 {
6658 DWORD nWritten;
6659
6660 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006661# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006662 if (fdDump)
6663 {
6664 fputc('>', fdDump);
6665 fwrite(s, sizeof(char_u), nWritten, fdDump);
6666 fputs("<\n", fdDump);
6667 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006668# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006669 len -= (nWritten - 1);
6670 s += nWritten;
6671 }
6672 else if (s[0] == '\n')
6673 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006674 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00006675 if (g_coord.Y == g_srScrollRegion.Bottom)
6676 {
6677 scroll(1);
6678 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6679 }
6680 else
6681 {
6682 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6683 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006684# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006685 if (fdDump)
6686 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006687# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006688 s++;
6689 }
6690 else if (s[0] == '\r')
6691 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006692 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00006693 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006694# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006695 if (fdDump)
6696 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006697# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006698 s++;
6699 }
6700 else if (s[0] == '\b')
6701 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006702 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00006703 if (g_coord.X > g_srScrollRegion.Left)
6704 g_coord.X--;
6705 else if (g_coord.Y > g_srScrollRegion.Top)
6706 {
6707 g_coord.X = g_srScrollRegion.Right;
6708 g_coord.Y--;
6709 }
6710 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006711# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006712 if (fdDump)
6713 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006714# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006715 s++;
6716 }
6717 else if (s[0] == '\a')
6718 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006719 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00006720 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006721# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006722 if (fdDump)
6723 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006724# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006725 s++;
6726 }
6727 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6728 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006729# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006730 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006731# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006732 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006733 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006734 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006735
6736 switch (s[2])
6737 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006738 case '0': case '1': case '2': case '3': case '4':
6739 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006740 if (*(p = get_seq(args, &argc, s)) != 'm')
6741 goto notsgr;
6742
6743 p = s;
6744
6745 // Handling frequent optional sequences. Output to the screen
6746 // takes too long, so do not output as much as possible.
6747
6748 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
6749 // resetFG,FG,BG are omitted.
6750 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006751 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006752 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
6753 len = len + 1 - (int)(p - s);
6754 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006755 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006756 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006757
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006758 // If FG,BG,BG,FG of SGR are connected, the first FG can be
6759 // omitted.
6760 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
6761 p = sp;
6762
6763 // If FG,BG,FG,BG of SGR are connected, the first FG can be
6764 // omitted.
6765 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
6766 p = sp;
6767
6768 // If BG,BG of SGR are connected, the first BG can be omitted.
6769 if (sgrn2((sp = sgrn2(p, 48)), 48))
6770 p = sp;
6771
6772 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01006773 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006774 if (sgrn2((sp = sgrnc(p, 39)), 38))
6775 p = sp;
6776
6777 p = get_seq(args, &argc, p);
6778
6779notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006780 arg1 = args[0];
6781 arg2 = args[1];
6782 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006783 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006784 if (argc == 1 && args[0] == 0)
6785 normvideo();
6786 else if (argc == 1)
6787 {
Christopher Plewright38804d62022-11-09 23:55:52 +00006788 if (vtp_working
6789# ifdef FEAT_TERMGUICOLORS
6790 && (p_tgc || t_colors >= 256)
6791# endif
6792 )
6793 textcolor((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006794 else
Christopher Plewright38804d62022-11-09 23:55:52 +00006795 textattr((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006796 }
Christopher Plewright38804d62022-11-09 23:55:52 +00006797 else if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006798 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006799 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006800 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006801 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006802 gotoxy(arg2, arg1);
6803 }
6804 else if (argc == 2 && *p == 'r')
6805 {
6806 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6807 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006808 else if (argc == 2 && *p == 'R')
6809 {
6810 set_scroll_region_tb(arg1, arg2);
6811 }
6812 else if (argc == 2 && *p == 'V')
6813 {
6814 set_scroll_region_lr(arg1, arg2);
6815 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006816 else if (argc == 1 && *p == 'A')
6817 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006818 gotoxy(g_coord.X + 1,
6819 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6820 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006821 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006822 {
6823 textbackground((WORD) arg1);
6824 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006825 else if (argc == 1 && *p == 'C')
6826 {
6827 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6828 g_coord.Y + 1);
6829 }
6830 else if (argc == 1 && *p == 'f')
6831 {
6832 textcolor((WORD) arg1);
6833 }
6834 else if (argc == 1 && *p == 'H')
6835 {
6836 gotoxy(1, arg1);
6837 }
6838 else if (argc == 1 && *p == 'L')
6839 {
6840 insert_lines(arg1);
6841 }
6842 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006843 {
6844 delete_lines(arg1);
6845 }
6846
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006847 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006848 s = p + 1;
6849 break;
6850
Bram Moolenaar071d4272004-06-13 20:20:40 +00006851 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006852 gotoxy(g_coord.X + 1,
6853 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6854 goto got3;
6855
6856 case 'B':
6857 visual_bell();
6858 goto got3;
6859
6860 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006861 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6862 g_coord.Y + 1);
6863 goto got3;
6864
6865 case 'E':
6866 termcap_mode_end();
6867 goto got3;
6868
6869 case 'F':
6870 standout();
6871 goto got3;
6872
6873 case 'f':
6874 standend();
6875 goto got3;
6876
6877 case 'H':
6878 gotoxy(1, 1);
6879 goto got3;
6880
6881 case 'j':
6882 clear_to_end_of_display();
6883 goto got3;
6884
6885 case 'J':
6886 clear_screen();
6887 goto got3;
6888
6889 case 'K':
6890 clear_to_end_of_line();
6891 goto got3;
6892
6893 case 'L':
6894 insert_lines(1);
6895 goto got3;
6896
6897 case 'M':
6898 delete_lines(1);
6899 goto got3;
6900
6901 case 'S':
6902 termcap_mode_start();
6903 goto got3;
6904
6905 case 'V':
6906 cursor_visible(TRUE);
6907 goto got3;
6908
6909 case 'v':
6910 cursor_visible(FALSE);
6911 goto got3;
6912
6913 got3:
6914 s += 3;
6915 len -= 2;
6916 }
6917
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006918# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006919 if (fdDump)
6920 {
6921 fputs("ESC | ", fdDump);
6922 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6923 fputc('\n', fdDump);
6924 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006925# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006926 }
K.Takatadf5320c2022-09-01 13:20:16 +01006927 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
6928 {
6929 int l = 2;
6930
6931 if (isdigit(s[l]))
6932 l++;
6933 if (s[l] == ' ' && s[l + 1] == 'q')
6934 {
6935 // DECSCUSR (cursor style) sequences
Christopher Plewright38804d62022-11-09 23:55:52 +00006936 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01006937 vtp_printf("%.*s", l + 2, s); // Pass through
6938 s += l + 2;
6939 len -= l + 1;
6940 }
6941 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006942 else
6943 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006944 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00006945 DWORD nWritten;
6946
6947 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006948# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006949 if (fdDump)
6950 {
6951 fputc('>', fdDump);
6952 fwrite(s, sizeof(char_u), nWritten, fdDump);
6953 fputs("<\n", fdDump);
6954 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006955# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006956
6957 len -= (nWritten - 1);
6958 s += nWritten;
6959 }
6960 }
6961
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006962# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006963 if (fdDump)
6964 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006965# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006966}
6967
Bram Moolenaar0f873732019-12-05 20:28:46 +01006968#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006969
6970
6971/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006972 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006973 */
6974 void
6975mch_delay(
6976 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02006977 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006978{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006979#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006980 Sleep((int)msec); // never wait for input
6981#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006982# ifdef VIMDLL
6983 if (gui.in_use)
6984 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006985 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006986 return;
6987 }
6988# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02006989 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006990# ifdef FEAT_MZSCHEME
6991 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6992 {
6993 int towait = p_mzq;
6994
Bram Moolenaar0f873732019-12-05 20:28:46 +01006995 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006996 while (msec > 0)
6997 {
6998 mzvim_check_threads();
6999 if (msec < towait)
7000 towait = msec;
7001 Sleep(towait);
7002 msec -= towait;
7003 }
7004 }
7005 else
7006# endif
7007 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007008 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007009 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007010#endif
7011}
7012
7013
7014/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01007015 * This version of remove is not scared by a readonly (backup) file.
7016 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007017 * Return 0 for success, -1 for failure.
7018 */
7019 int
7020mch_remove(char_u *name)
7021{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007022 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007023 int n;
7024
Bram Moolenaar203258c2016-01-17 22:15:16 +01007025 /*
7026 * On Windows, deleting a directory's symbolic link is done by
7027 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
7028 */
7029 if (mch_isdir(name) && mch_is_symbolic_link(name))
7030 return mch_rmdir(name);
7031
Bram Moolenaar12b559e2013-06-12 22:41:37 +02007032 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
7033
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007034 wn = enc_to_utf16(name, NULL);
7035 if (wn == NULL)
7036 return -1;
7037
7038 n = DeleteFileW(wn) ? 0 : -1;
7039 vim_free(wn);
7040 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007041}
7042
7043
7044/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007045 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007046 */
7047 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007048mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007049{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007050#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7051# ifdef VIMDLL
7052 if (!gui.in_use)
7053# endif
7054 if (g_fCtrlCPressed || g_fCBrkPressed)
7055 {
7056 ctrl_break_was_pressed = g_fCBrkPressed;
7057 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7058 got_int = TRUE;
7059 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007060#endif
7061}
7062
Bram Moolenaar0f873732019-12-05 20:28:46 +01007063// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007064#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007065
7066/*
7067 * How much main memory in KiB that can be used by VIM.
7068 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007069 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007070mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007071{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007072 MEMORYSTATUSEX ms;
7073
Bram Moolenaar0f873732019-12-05 20:28:46 +01007074 // Need to use GlobalMemoryStatusEx() when there is more memory than
7075 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007076 ms.dwLength = sizeof(MEMORYSTATUSEX);
7077 GlobalMemoryStatusEx(&ms);
7078 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007079 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007080 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007081 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007082 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007083 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007084 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007085 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007086 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007087 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007088 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007089 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007090}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007091
Bram Moolenaar071d4272004-06-13 20:20:40 +00007092/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007093 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00007094 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
7095 * file whose short file name is "FOO.BAR" (its long file name will
7096 * be correct: "foo.bar~"). Because a file can be accessed by
7097 * either its SFN or its LFN, "foo.bar" has effectively been
7098 * renamed to "foo.bar", which is not at all what was wanted. This
7099 * seems to happen only when renaming files with three-character
7100 * extensions by appending a suffix that does not include ".".
7101 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
7102 *
7103 * There is another problem, which isn't really a bug but isn't right either:
7104 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
7105 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
7106 * service pack 6. Doesn't seem to happen on Windows 98.
7107 *
7108 * Like rename(), returns 0 upon success, non-zero upon failure.
7109 * Should probably set errno appropriately when errors occur.
7110 */
7111 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007112mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007113{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007114 WCHAR *p;
7115 int i;
7116 WCHAR szTempFile[_MAX_PATH + 1];
7117 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007118 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007119
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007120 // No need to play tricks unless the file name contains a "~" as the
7121 // seventh character.
7122 p = wold;
7123 for (i = 0; wold[i] != NUL; ++i)
7124 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
7125 && wold[i + 1] != 0)
7126 p = wold + i + 1;
7127 if ((int)(wold + i - p) < 8 || p[6] != '~')
7128 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007129
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007130 // Get base path of new file name. Undocumented feature: If pszNewFile is
7131 // a directory, no error is returned and pszFilePart will be NULL.
7132 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007133 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007134 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007135
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007136 // Get (and create) a unique temporary file name in directory of new file
7137 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007138 return -2;
7139
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007140 // blow the temp file away
7141 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007142 return -3;
7143
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007144 // rename old file to the temp file
7145 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007146 return -4;
7147
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007148 // now create an empty file called pszOldFile; this prevents the operating
7149 // system using pszOldFile as an alias (SFN) if we're renaming within the
7150 // same directory. For example, we're editing a file called
7151 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7152 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7153 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7154 // cause all sorts of problems later in buf_write(). So, we create an
7155 // empty file called filena~1.txt and the system will have to find some
7156 // other SFN for filena~1.txt~, such as filena~2.txt
7157 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007158 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7159 return -5;
7160 if (!CloseHandle(hf))
7161 return -6;
7162
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007163 // rename the temp file to the new file
7164 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007165 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007166 // Renaming failed. Rename the file back to its old name, so that it
7167 // looks like nothing happened.
7168 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007169 return -7;
7170 }
7171
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007172 // Seems to be left around on Novell filesystems
7173 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007174
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007175 // finally, remove the empty old file
7176 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007177 return -8;
7178
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007179 return 0;
7180}
7181
7182
7183/*
7184 * Converts the filenames to UTF-16, then call mch_wrename().
7185 * Like rename(), returns 0 upon success, non-zero upon failure.
7186 */
7187 int
7188mch_rename(
7189 const char *pszOldFile,
7190 const char *pszNewFile)
7191{
7192 WCHAR *wold = NULL;
7193 WCHAR *wnew = NULL;
7194 int retval = -1;
7195
7196 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7197 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7198 if (wold != NULL && wnew != NULL)
7199 retval = mch_wrename(wold, wnew);
7200 vim_free(wold);
7201 vim_free(wnew);
7202 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007203}
7204
7205/*
7206 * Get the default shell for the current hardware platform
7207 */
7208 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007209default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007210{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007211 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007212}
7213
7214/*
7215 * mch_access() extends access() to do more detailed check on network drives.
7216 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7217 */
7218 int
7219mch_access(char *n, int p)
7220{
7221 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007222 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007223 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007224
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007225 wn = enc_to_utf16((char_u *)n, NULL);
7226 if (wn == NULL)
7227 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007228
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007229 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007230 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007231 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007232
7233 if (p & R_OK)
7234 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007235 // Read check is performed by seeing if we can do a find file on
7236 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007237 int i;
7238 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007239
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007240 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7241 TempNameW[i] = wn[i];
7242 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7243 TempNameW[i++] = '\\';
7244 TempNameW[i++] = '*';
7245 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007246
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007247 hFile = FindFirstFileW(TempNameW, &d);
7248 if (hFile == INVALID_HANDLE_VALUE)
7249 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007250 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007251 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007252 }
7253
7254 if (p & W_OK)
7255 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007256 // Trying to create a temporary file in the directory should catch
7257 // directories on read-only network shares. However, in
7258 // directories whose ACL allows writes but denies deletes will end
7259 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007260 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7261 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007262 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007263 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007264 }
7265 }
7266 else
7267 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007268 // Don't consider a file read-only if another process has opened it.
7269 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7270
Bram Moolenaar0f873732019-12-05 20:28:46 +01007271 // Trying to open the file for the required access does ACL, read-only
7272 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007273 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7274 | ((p & R_OK) ? GENERIC_READ : 0);
7275
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007276 hFile = CreateFileW(wn, access_mode, share_mode,
7277 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007278 if (hFile == INVALID_HANDLE_VALUE)
7279 goto getout;
7280 CloseHandle(hFile);
7281 }
7282
Bram Moolenaar0f873732019-12-05 20:28:46 +01007283 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007284getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007285 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007286 return retval;
7287}
7288
Bram Moolenaar071d4272004-06-13 20:20:40 +00007289/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007290 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007291 */
7292 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007293mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007294{
7295 WCHAR *wn;
7296 int f;
7297
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007298 wn = enc_to_utf16((char_u *)name, NULL);
7299 if (wn == NULL)
7300 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007301
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007302 f = _wopen(wn, flags, mode);
7303 vim_free(wn);
7304 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007305}
7306
7307/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007308 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007309 */
7310 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007311mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007312{
7313 WCHAR *wn, *wm;
7314 FILE *f = NULL;
7315
Bram Moolenaara12a1612019-01-24 16:39:02 +01007316#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007317 // Work around an annoying assertion in the Microsoft debug CRT
7318 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007319 char newMode = mode[strlen(mode) - 1];
7320 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007321
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007322 _get_fmode(&oldMode);
7323 if (newMode == 't')
7324 _set_fmode(_O_TEXT);
7325 else if (newMode == 'b')
7326 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007327#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007328 wn = enc_to_utf16((char_u *)name, NULL);
7329 wm = enc_to_utf16((char_u *)mode, NULL);
7330 if (wn != NULL && wm != NULL)
7331 f = _wfopen(wn, wm);
7332 vim_free(wn);
7333 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007334
Bram Moolenaara12a1612019-01-24 16:39:02 +01007335#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007336 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007337#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007338 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007339}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007340
Bram Moolenaar071d4272004-06-13 20:20:40 +00007341/*
7342 * SUB STREAM (aka info stream) handling:
7343 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007344 * NTFS can have sub streams for each file. The normal contents of a file is
7345 * stored in the main stream, and extra contents (author information, title and
7346 * so on) can be stored in a sub stream. After Windows 2000, the user can
7347 * access and store this information in sub streams via an explorer's property
7348 * menu item in the right click menu. This information in sub streams was lost
7349 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007350 *
7351 * Incomplete explanation:
7352 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7353 * More useful info and an example:
7354 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7355 */
7356
7357/*
7358 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7359 * and write to stream "substream" of file "to".
7360 * Errors are ignored.
7361 */
7362 static void
7363copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7364{
7365 HANDLE hTo;
7366 WCHAR *to_name;
7367
7368 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7369 wcscpy(to_name, to);
7370 wcscat(to_name, substream);
7371
7372 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7373 FILE_ATTRIBUTE_NORMAL, NULL);
7374 if (hTo != INVALID_HANDLE_VALUE)
7375 {
7376 long done;
7377 DWORD todo;
7378 DWORD readcnt, written;
7379 char buf[4096];
7380
Bram Moolenaar0f873732019-12-05 20:28:46 +01007381 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007382 for (done = 0; done < len; done += written)
7383 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007384 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007385 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7386 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007387 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7388 FALSE, FALSE, context)
7389 || readcnt != todo
7390 || !WriteFile(hTo, buf, todo, &written, NULL)
7391 || written != todo)
7392 break;
7393 }
7394 CloseHandle(hTo);
7395 }
7396
7397 free(to_name);
7398}
7399
7400/*
7401 * Copy info streams from file "from" to file "to".
7402 */
7403 static void
7404copy_infostreams(char_u *from, char_u *to)
7405{
7406 WCHAR *fromw;
7407 WCHAR *tow;
7408 HANDLE sh;
7409 WIN32_STREAM_ID sid;
7410 int headersize;
7411 WCHAR streamname[_MAX_PATH];
7412 DWORD readcount;
7413 void *context = NULL;
7414 DWORD lo, hi;
7415 int len;
7416
Bram Moolenaar0f873732019-12-05 20:28:46 +01007417 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007418 fromw = enc_to_utf16(from, NULL);
7419 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007420 if (fromw != NULL && tow != NULL)
7421 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007422 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007423 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7424 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7425 if (sh != INVALID_HANDLE_VALUE)
7426 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007427 // Use BackupRead() to find the info streams. Repeat until we
7428 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007429 for (;;)
7430 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007431 // Get the header to find the length of the stream name. If
7432 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007433 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007434 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007435 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7436 &readcount, FALSE, FALSE, &context)
7437 || readcount == 0)
7438 break;
7439
Bram Moolenaar0f873732019-12-05 20:28:46 +01007440 // We only deal with streams that have a name. The normal
7441 // file data appears to be without a name, even though docs
7442 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007443 if (sid.dwStreamNameSize > 0)
7444 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007445 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007446 if (!BackupRead(sh, (LPBYTE)streamname,
7447 sid.dwStreamNameSize,
7448 &readcount, FALSE, FALSE, &context))
7449 break;
7450
Bram Moolenaar0f873732019-12-05 20:28:46 +01007451 // Copy an info stream with a name ":anything:$DATA".
7452 // Skip "::$DATA", it has no stream name (examples suggest
7453 // it might be used for the normal file contents).
7454 // Note that BackupRead() counts bytes, but the name is in
7455 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007456 len = readcount / sizeof(WCHAR);
7457 streamname[len] = 0;
7458 if (len > 7 && wcsicmp(streamname + len - 6,
7459 L":$DATA") == 0)
7460 {
7461 streamname[len - 6] = 0;
7462 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007463 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007464 }
7465 }
7466
Bram Moolenaar0f873732019-12-05 20:28:46 +01007467 // Advance to the next stream. We might try seeking too far,
7468 // but BackupSeek() doesn't skip over stream borders, thus
7469 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007470 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007471 &lo, &hi, &context);
7472 }
7473
Bram Moolenaar0f873732019-12-05 20:28:46 +01007474 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007475 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7476
7477 CloseHandle(sh);
7478 }
7479 }
7480 vim_free(fromw);
7481 vim_free(tow);
7482}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007483
7484/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007485 * ntdll.dll definitions
7486 */
7487#define FileEaInformation 7
7488#ifndef STATUS_SUCCESS
7489# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7490#endif
7491
7492typedef struct _FILE_FULL_EA_INFORMATION_ {
7493 ULONG NextEntryOffset;
7494 UCHAR Flags;
7495 UCHAR EaNameLength;
7496 USHORT EaValueLength;
7497 CHAR EaName[1];
7498} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7499
7500typedef struct _FILE_EA_INFORMATION_ {
7501 ULONG EaSize;
7502} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7503
Paul Ollis65745772022-06-05 16:55:54 +01007504#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007505typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7506 PHANDLE FileHandle,
7507 ACCESS_MASK DesiredAccess,
7508 POBJECT_ATTRIBUTES ObjectAttributes,
7509 PIO_STATUS_BLOCK IoStatusBlock,
7510 ULONG ShareAccess,
7511 ULONG OpenOptions);
7512typedef NTSTATUS (NTAPI *PfnNtClose)(
7513 HANDLE Handle);
7514typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007515 HANDLE FileHandle,
7516 PIO_STATUS_BLOCK IoStatusBlock,
7517 PVOID Buffer,
7518 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007519typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7520 HANDLE FileHandle,
7521 PIO_STATUS_BLOCK IoStatusBlock,
7522 PVOID Buffer,
7523 ULONG Length,
7524 BOOLEAN ReturnSingleEntry,
7525 PVOID EaList,
7526 ULONG EaListLength,
7527 PULONG EaIndex,
7528 BOOLEAN RestartScan);
7529typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007530 HANDLE FileHandle,
7531 PIO_STATUS_BLOCK IoStatusBlock,
7532 PVOID FileInformation,
7533 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007534 FILE_INFORMATION_CLASS FileInformationClass);
7535typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7536 PUNICODE_STRING DestinationString,
7537 PCWSTR SourceString);
7538
7539PfnNtOpenFile pNtOpenFile = NULL;
7540PfnNtClose pNtClose = NULL;
7541PfnNtSetEaFile pNtSetEaFile = NULL;
7542PfnNtQueryEaFile pNtQueryEaFile = NULL;
7543PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7544PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01007545#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007546
7547/*
7548 * Load ntdll.dll functions.
7549 */
7550 static BOOL
7551load_ntdll(void)
7552{
7553 static int loaded = -1;
7554
7555 if (loaded == -1)
7556 {
7557 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7558 if (hNtdll != NULL)
7559 {
7560 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7561 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7562 pNtSetEaFile = (PfnNtSetEaFile)
7563 GetProcAddress(hNtdll, "NtSetEaFile");
7564 pNtQueryEaFile = (PfnNtQueryEaFile)
7565 GetProcAddress(hNtdll, "NtQueryEaFile");
7566 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7567 GetProcAddress(hNtdll, "NtQueryInformationFile");
7568 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7569 GetProcAddress(hNtdll, "RtlInitUnicodeString");
7570 }
7571 if (pNtOpenFile == NULL
7572 || pNtClose == NULL
7573 || pNtSetEaFile == NULL
7574 || pNtQueryEaFile == NULL
7575 || pNtQueryInformationFile == NULL
7576 || pRtlInitUnicodeString == NULL)
7577 loaded = FALSE;
7578 else
7579 loaded = TRUE;
7580 }
7581 return (BOOL) loaded;
7582}
7583
7584/*
7585 * Copy extended attributes (EA) from file "from" to file "to".
7586 */
7587 static void
7588copy_extattr(char_u *from, char_u *to)
7589{
7590 char_u *fromf = NULL;
7591 char_u *tof = NULL;
7592 WCHAR *fromw = NULL;
7593 WCHAR *tow = NULL;
7594 UNICODE_STRING u;
7595 HANDLE h;
7596 OBJECT_ATTRIBUTES oa;
7597 IO_STATUS_BLOCK iosb;
7598 FILE_EA_INFORMATION_ eainfo = {0};
7599 void *ea = NULL;
7600
7601 if (!load_ntdll())
7602 return;
7603
7604 // Convert the file names to the fully qualified object names.
7605 fromf = alloc(STRLEN(from) + 5);
7606 tof = alloc(STRLEN(to) + 5);
7607 if (fromf == NULL || tof == NULL)
7608 goto theend;
7609 STRCPY(fromf, "\\??\\");
7610 STRCAT(fromf, from);
7611 STRCPY(tof, "\\??\\");
7612 STRCAT(tof, to);
7613
7614 // Convert the names to wide characters.
7615 fromw = enc_to_utf16(fromf, NULL);
7616 tow = enc_to_utf16(tof, NULL);
7617 if (fromw == NULL || tow == NULL)
7618 goto theend;
7619
7620 // Get the EA.
7621 pRtlInitUnicodeString(&u, fromw);
7622 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7623 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7624 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7625 goto theend;
7626 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7627 FileEaInformation);
7628 if (eainfo.EaSize != 0)
7629 {
7630 ea = alloc(eainfo.EaSize);
7631 if (ea != NULL)
7632 {
7633 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7634 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7635 {
7636 vim_free(ea);
7637 ea = NULL;
7638 }
7639 }
7640 }
7641 pNtClose(h);
7642
7643 // Set the EA.
7644 if (ea != NULL)
7645 {
7646 pRtlInitUnicodeString(&u, tow);
7647 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7648 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7649 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7650 goto theend;
7651
7652 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
7653 pNtClose(h);
7654 }
7655
7656theend:
7657 vim_free(fromf);
7658 vim_free(tof);
7659 vim_free(fromw);
7660 vim_free(tow);
7661 vim_free(ea);
7662}
7663
7664/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007665 * Copy file attributes from file "from" to file "to".
7666 * For Windows NT and later we copy info streams.
7667 * Always returns zero, errors are ignored.
7668 */
7669 int
7670mch_copy_file_attribute(char_u *from, char_u *to)
7671{
Bram Moolenaar0f873732019-12-05 20:28:46 +01007672 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007673 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007674 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007675 return 0;
7676}
7677
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007678
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007679/*
K.Takatadc73b4b2021-06-08 18:32:36 +02007680 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007681 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007682static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007683static LPWSTR *ArglistW = NULL;
7684static int global_argc = 0;
7685static char **global_argv;
7686
Bram Moolenaar0f873732019-12-05 20:28:46 +01007687static int used_file_argc = 0; // last argument in global_argv[] used
7688 // for the argument list.
7689static int *used_file_indexes = NULL; // indexes in global_argv[] for
7690 // command line arguments added to
7691 // the argument list
7692static int used_file_count = 0; // nr of entries in used_file_indexes
7693static int used_file_literal = FALSE; // take file names literally
7694static int used_file_full_path = FALSE; // file name was full path
7695static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007696static int used_alist_count = 0;
7697
7698
7699/*
7700 * Get the command line arguments. Unicode version.
7701 * Returns argc. Zero when something fails.
7702 */
7703 int
7704get_cmd_argsW(char ***argvp)
7705{
7706 char **argv = NULL;
7707 int argc = 0;
7708 int i;
7709
Bram Moolenaar14993322014-09-09 12:25:33 +02007710 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007711 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7712 if (ArglistW != NULL)
7713 {
7714 argv = malloc((nArgsW + 1) * sizeof(char *));
7715 if (argv != NULL)
7716 {
7717 argc = nArgsW;
7718 argv[argc] = NULL;
7719 for (i = 0; i < argc; ++i)
7720 {
7721 int len;
7722
K.Takatadc73b4b2021-06-08 18:32:36 +02007723 // Convert each Unicode argument to UTF-8.
7724 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007725 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007726 (LPSTR *)&argv[i], &len, 0, 0);
7727 if (argv[i] == NULL)
7728 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007729 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007730 while (i > 0)
7731 free(argv[--i]);
7732 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007733 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007734 argc = 0;
7735 }
7736 }
7737 }
7738 }
7739
7740 global_argc = argc;
7741 global_argv = argv;
7742 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007743 {
7744 if (used_file_indexes != NULL)
7745 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007746 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007747 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007748
7749 if (argvp != NULL)
7750 *argvp = argv;
7751 return argc;
7752}
7753
7754 void
7755free_cmd_argsW(void)
7756{
7757 if (ArglistW != NULL)
7758 {
7759 GlobalFree(ArglistW);
7760 ArglistW = NULL;
7761 }
7762}
7763
7764/*
7765 * Remember "name" is an argument that was added to the argument list.
7766 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7767 * is called.
7768 */
7769 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007770used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007771{
7772 int i;
7773
7774 if (used_file_indexes == NULL)
7775 return;
7776 for (i = used_file_argc + 1; i < global_argc; ++i)
7777 if (STRCMP(global_argv[i], name) == 0)
7778 {
7779 used_file_argc = i;
7780 used_file_indexes[used_file_count++] = i;
7781 break;
7782 }
7783 used_file_literal = literal;
7784 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007785 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007786}
7787
7788/*
7789 * Remember the length of the argument list as it was. If it changes then we
7790 * leave it alone when 'encoding' is set.
7791 */
7792 void
7793set_alist_count(void)
7794{
7795 used_alist_count = GARGCOUNT;
7796}
7797
7798/*
7799 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02007800 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007801 * and convert them to 'encoding'.
7802 */
7803 void
7804fix_arg_enc(void)
7805{
7806 int i;
7807 int idx;
7808 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007809 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007810
Bram Moolenaar0f873732019-12-05 20:28:46 +01007811 // Safety checks:
7812 // - if argument count differs between the wide and non-wide argument
7813 // list, something must be wrong.
7814 // - the file name arguments must have been located.
7815 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007816 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007817 || ArglistW == NULL
7818 || used_file_indexes == NULL
7819 || used_file_count == 0
7820 || used_alist_count != GARGCOUNT)
7821 return;
7822
Bram Moolenaar0f873732019-12-05 20:28:46 +01007823 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007824 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007825 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007826 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00007827 for (i = 0; i < GARGCOUNT; ++i)
7828 fnum_list[i] = GARGLIST[i].ae_fnum;
7829
Bram Moolenaar0f873732019-12-05 20:28:46 +01007830 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007831 alist_clear(&global_alist);
7832 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007833 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007834
7835 for (i = 0; i < used_file_count; ++i)
7836 {
7837 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007838 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007839 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007840 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007841 int literal = used_file_literal;
7842
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007843#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01007844 // When using diff mode may need to concatenate file name to
7845 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007846 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7847 && !mch_isdir(alist_name(&GARGLIST[0])))
7848 {
7849 char_u *r;
7850
7851 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7852 if (r != NULL)
7853 {
7854 vim_free(str);
7855 str = r;
7856 }
7857 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007858#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01007859 // Re-use the old buffer by renaming it. When not using literal
7860 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00007861 if (used_file_literal)
7862 buf_set_name(fnum_list[i], str);
7863
Bram Moolenaar0f873732019-12-05 20:28:46 +01007864 // Check backtick literal. backtick literal is already expanded in
7865 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007866 if (literal == FALSE)
7867 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007868 size_t len = STRLEN(str);
7869
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007870 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7871 literal = TRUE;
7872 }
7873 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007874 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007875 }
7876
7877 if (!used_file_literal)
7878 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007879 // Now expand wildcards in the arguments.
7880 // Temporarily add '(' and ')' to 'isfname'. These are valid
7881 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00007882 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01007883 // Also, unset wildignore to not be influenced by this option.
7884 // The arguments specified in command-line should be kept even if
7885 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00007886 // Use :legacy so that it also works when in Vim9 script.
7887 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
7888 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007889 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00007890 do_cmdline_cmd(
7891 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
7892 do_cmdline_cmd(
7893 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007894 }
7895
Bram Moolenaar0f873732019-12-05 20:28:46 +01007896 // If wildcard expansion failed, we are editing the first file of the
7897 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007898 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7899 {
7900 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00007901 if (GARGCOUNT == 1 && used_file_full_path
7902 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
7903 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007904 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007905
7906 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007907}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007908
7909 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007910mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007911{
7912 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007913 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007914
Bram Moolenaar964b3742019-05-24 18:54:09 +02007915 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007916 if (envbuf == NULL)
7917 return -1;
7918
7919 sprintf((char *)envbuf, "%s=%s", var, value);
7920
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007921 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007922
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007923 vim_free(envbuf);
7924 if (p == NULL)
7925 return -1;
7926 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007927#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007928 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007929#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007930 // Unlike Un*x systems, we can free the string for _wputenv().
7931 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007932
7933 return 0;
7934}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007935
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007936/*
7937 * Support for 256 colors and 24-bit colors was added in Windows 10
7938 * version 1703 (Creators update).
7939 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007940#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7941
7942/*
7943 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02007944 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007945 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007946#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007947
7948/*
7949 * ConPTY differences between versions, need different logic.
7950 * version 1903 (May 2019 update).
7951 */
7952#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
7953
7954/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007955 * version 1909 (November 2019 update).
7956 */
7957#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
7958
7959/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007960 * Stay ahead of the next update, and when it's done, fix this.
7961 * version ? (2020 update, temporarily use the build number of insider preview)
7962 */
7963#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
7964
7965/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02007966 * Confirm until this version. Also the logic changes.
7967 * insider preview.
7968 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02007969#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007970
7971/*
7972 * Not stable now.
7973 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007974#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Christopher Plewright1140b512022-11-12 18:46:05 +00007975// Notes:
7976// Win 10 22H2 Final is build 19045, it's conpty is widely used.
7977// Strangely, 19045 is newer but is a lower build number than the 2020 insider
7978// preview which had a build 19587. And, not sure how stable that was?
7979// Win Server 2022 (May 10, 2022) is build 20348, its conpty is widely used.
7980// Win 11 starts from build 22000, even though the major version says 10!
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007981
7982 static void
7983vtp_flag_init(void)
7984{
7985 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007986#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007987 DWORD mode;
7988 HANDLE out;
7989
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007990# ifdef VIMDLL
7991 if (!gui.in_use)
7992# endif
7993 {
7994 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007995
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007996 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7997 GetConsoleMode(out, &mode);
7998 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7999 if (SetConsoleMode(out, mode) == 0)
8000 vtp_working = 0;
8001 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008002#endif
8003
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008004 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008005 conpty_working = 1;
8006 if (ver >= CONPTY_STABLE_BUILD)
8007 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008008
Bram Moolenaar57da6982019-09-13 22:30:11 +02008009 if (ver <= CONPTY_INSIDER_BUILD)
8010 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008011 if (ver <= CONPTY_1909_BUILD)
8012 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02008013 if (ver <= CONPTY_1903_BUILD)
8014 conpty_type = 2;
8015 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
8016 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008017
8018 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
8019 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008020}
8021
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008022#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008023
8024 static void
8025vtp_init(void)
8026{
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008027# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00008028 if (!vtp_working)
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008029 {
Christopher Plewright38804d62022-11-09 23:55:52 +00008030 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8031 csbi.cbSize = sizeof(csbi);
8032 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8033 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
8034 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
8035 store_console_bg_rgb = save_console_bg_rgb;
8036 store_console_fg_rgb = save_console_fg_rgb;
8037
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008038 COLORREF bg;
8039 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
8040 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8041 default_console_color_bg = bg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008042
8043 COLORREF fg;
8044 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
8045 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8046 default_console_color_fg = fg;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008047 }
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008048# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008049
8050 set_console_color_rgb();
8051}
8052
8053 static void
8054vtp_exit(void)
8055{
Bram Moolenaardf543822020-01-30 11:53:59 +01008056 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008057}
8058
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008059 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008060vtp_printf(
8061 char *format,
8062 ...)
8063{
8064 char_u buf[100];
8065 va_list list;
8066 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008067 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008068
8069 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008070 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008071 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008072 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008073 return (int)result;
8074}
8075
8076 static void
8077vtp_sgr_bulk(
8078 int arg)
8079{
8080 int args[1];
8081
8082 args[0] = arg;
8083 vtp_sgr_bulks(1, args);
8084}
8085
K.Takata6e1d31e2022-02-03 13:05:32 +00008086# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008087 if ((*p-- = "0123456789"[(n = x % 10)]) \
8088 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8089 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8090
K.Takata6e1d31e2022-02-03 13:05:32 +00008091# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008092 case x: \
8093 FAST256(newargs[x - 1]);
8094
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008095 static void
8096vtp_sgr_bulks(
8097 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008098 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008099{
K.Takata6e1d31e2022-02-03 13:05:32 +00008100# define MAXSGR 16
8101# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008102 char_u buf[SGRBUFSIZE];
8103 char_u *p;
8104 int in, out;
8105 int newargs[16];
8106 static int sgrfgr = -1, sgrfgg, sgrfgb;
8107 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008108
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008109 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008110 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008111 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008112 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008113 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008114 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008115
8116 in = out = 0;
8117 while (in < argc)
8118 {
8119 int s = args[in];
8120 int copylen = 1;
8121
8122 if (s == 38)
8123 {
8124 if (argc - in >= 5 && args[in + 1] == 2)
8125 {
8126 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8127 && sgrfgb == args[in + 4])
8128 {
8129 in += 5;
8130 copylen = 0;
8131 }
8132 else
8133 {
8134 sgrfgr = args[in + 2];
8135 sgrfgg = args[in + 3];
8136 sgrfgb = args[in + 4];
8137 copylen = 5;
8138 }
8139 }
8140 else if (argc - in >= 3 && args[in + 1] == 5)
8141 {
8142 sgrfgr = -1;
8143 copylen = 3;
8144 }
8145 }
8146 else if (s == 48)
8147 {
8148 if (argc - in >= 5 && args[in + 1] == 2)
8149 {
8150 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8151 && sgrbgb == args[in + 4])
8152 {
8153 in += 5;
8154 copylen = 0;
8155 }
8156 else
8157 {
8158 sgrbgr = args[in + 2];
8159 sgrbgg = args[in + 3];
8160 sgrbgb = args[in + 4];
8161 copylen = 5;
8162 }
8163 }
8164 else if (argc - in >= 3 && args[in + 1] == 5)
8165 {
8166 sgrbgr = -1;
8167 copylen = 3;
8168 }
8169 }
8170 else if (30 <= s && s <= 39)
8171 sgrfgr = -1;
8172 else if (90 <= s && s <= 97)
8173 sgrfgr = -1;
8174 else if (40 <= s && s <= 49)
8175 sgrbgr = -1;
8176 else if (100 <= s && s <= 107)
8177 sgrbgr = -1;
8178 else if (s == 0)
8179 sgrfgr = sgrbgr = -1;
8180
8181 while (copylen--)
8182 newargs[out++] = args[in++];
8183 }
8184
8185 p = &buf[sizeof(buf) - 1];
8186 *p-- = 'm';
8187
8188 switch (out)
8189 {
8190 int n, m;
8191 DWORD r;
8192
8193 FAST256CASE(16);
8194 *p-- = ';';
8195 FAST256CASE(15);
8196 *p-- = ';';
8197 FAST256CASE(14);
8198 *p-- = ';';
8199 FAST256CASE(13);
8200 *p-- = ';';
8201 FAST256CASE(12);
8202 *p-- = ';';
8203 FAST256CASE(11);
8204 *p-- = ';';
8205 FAST256CASE(10);
8206 *p-- = ';';
8207 FAST256CASE(9);
8208 *p-- = ';';
8209 FAST256CASE(8);
8210 *p-- = ';';
8211 FAST256CASE(7);
8212 *p-- = ';';
8213 FAST256CASE(6);
8214 *p-- = ';';
8215 FAST256CASE(5);
8216 *p-- = ';';
8217 FAST256CASE(4);
8218 *p-- = ';';
8219 FAST256CASE(3);
8220 *p-- = ';';
8221 FAST256CASE(2);
8222 *p-- = ';';
8223 FAST256CASE(1);
8224 *p-- = '[';
8225 *p = '\033';
8226 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8227 default:
8228 break;
8229 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008230}
8231
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008232 static void
8233wt_init(void)
8234{
Christopher Plewright1140b512022-11-12 18:46:05 +00008235 wt_working = mch_getenv("WT_SESSION") != NULL;
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008236}
8237
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008238# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008239 static int
8240ctermtoxterm(
8241 int cterm)
8242{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008243 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008244
8245 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8246 return (((int)r << 16) | ((int)g << 8) | (int)b);
8247}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008248# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008249
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008250 static void
8251set_console_color_rgb(void)
8252{
8253# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008254 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008255 guicolor_T fg, bg;
8256 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008257
Christopher Plewright38804d62022-11-09 23:55:52 +00008258 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008259 return;
8260
Bram Moolenaara050b942019-12-02 21:35:31 +01008261 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8262
Christopher Plewright38804d62022-11-09 23:55:52 +00008263 if (p_tgc || t_colors >= 256)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008264 {
8265 term_fg_rgb_color(fg);
8266 term_bg_rgb_color(bg);
8267 return;
8268 }
8269
Christopher Plewright38804d62022-11-09 23:55:52 +00008270 if (!conpty_working)
8271 {
8272 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8273 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008274
Christopher Plewright38804d62022-11-09 23:55:52 +00008275 csbi.cbSize = sizeof(csbi);
8276 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008277
Christopher Plewright38804d62022-11-09 23:55:52 +00008278 csbi.cbSize = sizeof(csbi);
8279 csbi.srWindow.Right += 1;
8280 csbi.srWindow.Bottom += 1;
8281 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8282 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
8283 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8284 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
8285 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8286 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008287# endif
8288}
8289
Bram Moolenaara050b942019-12-02 21:35:31 +01008290# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8291 void
8292get_default_console_color(
8293 int *cterm_fg,
8294 int *cterm_bg,
8295 guicolor_T *gui_fg,
8296 guicolor_T *gui_bg)
8297{
8298 int id;
8299 guicolor_T guifg = INVALCOLOR;
8300 guicolor_T guibg = INVALCOLOR;
8301 int ctermfg = 0;
8302 int ctermbg = 0;
Christopher Plewright38804d62022-11-09 23:55:52 +00008303 int dummynull = 0;
Bram Moolenaara050b942019-12-02 21:35:31 +01008304
8305 id = syn_name2id((char_u *)"Normal");
8306 if (id > 0 && p_tgc)
8307 syn_id2colors(id, &guifg, &guibg);
8308 if (guifg == INVALCOLOR)
8309 {
8310 ctermfg = -1;
8311 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008312 syn_id2cterm_bg(id, &ctermfg, &dummynull);
8313 if (vtp_working)
8314 {
8315 cterm_normal_fg_gui_color = guifg =
8316 ctermfg != -1 ? ctermtoxterm(ctermfg) : INVALCOLOR;
8317 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8318 }
8319 else
8320 {
8321 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
Bram Moolenaara050b942019-12-02 21:35:31 +01008322 : default_console_color_fg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008323 cterm_normal_fg_gui_color = guifg;
8324 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8325 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008326 }
8327 if (guibg == INVALCOLOR)
8328 {
8329 ctermbg = -1;
8330 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008331 syn_id2cterm_bg(id, &dummynull, &ctermbg);
8332 if (vtp_working)
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008333 {
8334 cterm_normal_bg_gui_color = guibg =
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01008335 ctermbg != -1 ? ctermtoxterm(ctermbg) : INVALCOLOR;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008336 if (ctermbg < 0)
8337 ctermbg = 0;
8338 }
K.Takatae53a0d42022-09-05 21:45:11 +01008339 else
8340 {
8341 guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8342 : default_console_color_bg;
8343 cterm_normal_bg_gui_color = guibg;
8344 ctermbg = ctermbg < 0 ? 0 : ctermbg;
8345 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008346 }
8347
8348 *cterm_fg = ctermfg;
8349 *cterm_bg = ctermbg;
8350 *gui_fg = guifg;
8351 *gui_bg = guibg;
8352}
8353# endif
8354
Bram Moolenaardf543822020-01-30 11:53:59 +01008355/*
8356 * Set the console colors to the original colors or the last set colors.
8357 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008358 static void
8359reset_console_color_rgb(void)
8360{
8361# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008362
Christopher Plewright38804d62022-11-09 23:55:52 +00008363 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008364 return;
8365
Christopher Plewright38804d62022-11-09 23:55:52 +00008366 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8367
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008368 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008369 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008370
8371 csbi.cbSize = sizeof(csbi);
8372 csbi.srWindow.Right += 1;
8373 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008374 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8375 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008376 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008377# endif
8378}
8379
8380/*
8381 * Set the console colors to the original colors.
8382 */
8383 static void
8384restore_console_color_rgb(void)
8385{
8386# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00008387 if (vtp_working)
8388 return;
8389
K.Takata27b53be2022-09-18 12:25:49 +01008390 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008391
8392 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008393 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008394
8395 csbi.cbSize = sizeof(csbi);
8396 csbi.srWindow.Right += 1;
8397 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008398 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8399 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008400 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008401# endif
8402}
8403
8404 void
8405control_console_color_rgb(void)
8406{
Christopher Plewright38804d62022-11-09 23:55:52 +00008407 if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008408 set_console_color_rgb();
8409 else
8410 reset_console_color_rgb();
8411}
8412
8413 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008414use_vtp(void)
8415{
8416 return USE_VTP;
8417}
8418
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008419 int
8420is_term_win32(void)
8421{
8422 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8423}
8424
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008425 int
8426has_vtp_working(void)
8427{
8428 return vtp_working;
8429}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008430
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008431#endif
8432
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008433 int
8434has_conpty_working(void)
8435{
8436 return conpty_working;
8437}
8438
8439 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008440get_conpty_type(void)
8441{
8442 return conpty_type;
8443}
8444
8445 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008446is_conpty_stable(void)
8447{
8448 return conpty_stable;
8449}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008450
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008451 int
8452get_conpty_fix_type(void)
8453{
8454 return conpty_fix_type;
8455}
8456
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008457#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008458 void
8459resize_console_buf(void)
8460{
8461 CONSOLE_SCREEN_BUFFER_INFO csbi;
8462 COORD coord;
8463 SMALL_RECT newsize;
8464
8465 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8466 {
8467 coord.X = SRWIDTH(csbi.srWindow);
8468 coord.Y = SRHEIGHT(csbi.srWindow);
8469 SetConsoleScreenBufferSize(g_hConOut, coord);
8470
8471 newsize.Left = 0;
8472 newsize.Top = 0;
8473 newsize.Right = coord.X - 1;
8474 newsize.Bottom = coord.Y - 1;
8475 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8476
8477 SetConsoleScreenBufferSize(g_hConOut, coord);
8478 }
8479}
8480#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008481
8482 char *
8483GetWin32Error(void)
8484{
K.Takatad68b2fc2022-02-12 11:18:37 +00008485 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008486 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008487
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008488 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8489 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008490 if (oldmsg != NULL)
8491 LocalFree(oldmsg);
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008492 if (msg != NULL)
8493 {
8494 // remove trailing \r\n
8495 char *pcrlf = strstr(msg, "\r\n");
8496 if (pcrlf != NULL)
8497 *pcrlf = '\0';
K.Takatad68b2fc2022-02-12 11:18:37 +00008498 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008499 }
8500 return msg;
8501}
Paul Ollis65745772022-06-05 16:55:54 +01008502
8503#if defined(FEAT_RELTIME) || defined(PROTO)
8504static HANDLE timer_handle;
8505static int timer_active = FALSE;
8506
8507/*
8508 * Calls to start_timeout alternate the return value pointer between the two
8509 * entries in timeout_flags. If the previously active timeout is very close to
8510 * expiring when start_timeout() is called then a race condition means that the
8511 * set_flag() function may still be invoked after the previous timer is
8512 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8513 * timeouts.
8514 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008515static sig_atomic_t timeout_flags[2];
8516static int timeout_flag_idx = 0;
8517static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01008518
8519
8520 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01008521set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01008522{
8523 int *timeout_flag = (int *)param;
8524
8525 *timeout_flag = TRUE;
8526}
8527
8528/*
8529 * Stop any active timeout.
8530 */
8531 void
8532stop_timeout(void)
8533{
8534 if (timer_active)
8535 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01008536 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01008537 timer_active = FALSE;
8538 if (!ret && GetLastError() != ERROR_IO_PENDING)
8539 {
8540 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
8541 }
8542 }
8543 *timeout_flag = FALSE;
8544}
8545
8546/*
8547 * Start the timeout timer.
8548 *
8549 * The period is defined in milliseconds.
8550 *
8551 * The return value is a pointer to a flag that is initialised to 0. If the
8552 * timeout expires, the flag is set to 1. This will only return pointers to
8553 * static memory; i.e. any pointer returned by this function may always be
8554 * safely dereferenced.
8555 *
8556 * This function is not expected to fail, but if it does it still returns a
8557 * valid flag pointer; the flag will remain stuck at zero.
8558 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008559 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01008560start_timeout(long msec)
8561{
Paul Ollis65745772022-06-05 16:55:54 +01008562 BOOL ret;
8563
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008564 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01008565
8566 stop_timeout();
8567 ret = CreateTimerQueueTimer(
8568 &timer_handle, NULL, set_flag, timeout_flag,
8569 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
8570 if (!ret)
8571 {
8572 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
8573 }
8574 else
8575 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008576 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01008577 timer_active = TRUE;
8578 *timeout_flag = FALSE;
8579 }
8580 return timeout_flag;
8581}
8582#endif