blob: f06227f10ac0845ff095fc4fbb3b549dc3ba779c [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
12 * Used for both the console version and the Win32 GUI. A lot of code is for
Bram Moolenaar4f974752019-02-17 17:44:42 +010013 * the console version only, so there is a lot of "#ifndef FEAT_GUI_MSWIN".
Bram Moolenaar071d4272004-06-13 20:20:40 +000014 *
15 * Win32 (Windows NT and Windows 95) system-dependent routines.
16 * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17 * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18 *
19 * George V. Reilly <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
Bram Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010032
Bram Moolenaar0f873732019-12-05 20:28:46 +010033// cproto fails on missing include files
Bram Moolenaar82881492012-11-20 16:53:39 +010034#ifndef PROTO
35# include <process.h>
Bram Moolenaare7bebc42021-02-01 20:50:37 +010036# include <winternl.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010037#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000038
39#undef chdir
40#ifdef __GNUC__
41# ifndef __MINGW32__
42# include <dirent.h>
43# endif
44#else
45# include <direct.h>
46#endif
47
Bram Moolenaar82881492012-11-20 16:53:39 +010048#ifndef PROTO
Bram Moolenaar651fca82021-11-29 20:39:38 +000049# if !defined(FEAT_GUI_MSWIN)
Bram Moolenaar82881492012-11-20 16:53:39 +010050# include <shellapi.h>
51# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000052#endif
53
Bram Moolenaarfb630902016-10-29 14:55:00 +020054#ifdef FEAT_JOB_CHANNEL
55# include <tlhelp32.h>
56#endif
57
Bram Moolenaar071d4272004-06-13 20:20:40 +000058#ifdef __MINGW32__
59# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
60# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
61# endif
62# ifndef RIGHTMOST_BUTTON_PRESSED
63# define RIGHTMOST_BUTTON_PRESSED 0x0002
64# endif
65# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
66# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
67# endif
68# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
69# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
70# endif
71# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
72# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
73# endif
74
75/*
76 * EventFlags
77 */
78# ifndef MOUSE_MOVED
79# define MOUSE_MOVED 0x0001
80# endif
81# ifndef DOUBLE_CLICK
82# define DOUBLE_CLICK 0x0002
83# endif
84#endif
85
Bram Moolenaar0f873732019-12-05 20:28:46 +010086// Record all output and all keyboard & mouse input
87// #define MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +000088
89#ifdef MCH_WRITE_DUMP
90FILE* fdDump = NULL;
91#endif
92
93/*
94 * When generating prototypes for Win32 on Unix, these lines make the syntax
95 * errors disappear. They do not need to be correct.
96 */
97#ifdef PROTO
Bram Moolenaar912bc4a2019-12-01 18:58:11 +010098# define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000099typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000100typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000101typedef int ACCESS_MASK;
102typedef int BOOL;
Paul Ollis65745772022-06-05 16:55:54 +0100103typedef int BOOLEAN;
104typedef int CALLBACK;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000105typedef int COLORREF;
106typedef int CONSOLE_CURSOR_INFO;
107typedef int COORD;
108typedef int DWORD;
109typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100110typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000111typedef int HDC;
112typedef int HFONT;
113typedef int HICON;
114typedef int HINSTANCE;
115typedef int HWND;
116typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200117typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000118typedef int KEY_EVENT_RECORD;
119typedef int LOGFONT;
120typedef int LPBOOL;
121typedef int LPCTSTR;
122typedef int LPDWORD;
123typedef int LPSTR;
124typedef int LPTSTR;
125typedef int LPVOID;
126typedef int MOUSE_EVENT_RECORD;
127typedef int PACL;
128typedef int PDWORD;
129typedef int PHANDLE;
130typedef int PRINTDLG;
131typedef int PSECURITY_DESCRIPTOR;
132typedef int PSID;
133typedef int SECURITY_INFORMATION;
134typedef int SHORT;
135typedef int SMALL_RECT;
136typedef int TEXTMETRIC;
137typedef int TOKEN_INFORMATION_CLASS;
138typedef int TRUSTEE;
139typedef int WORD;
140typedef int WCHAR;
141typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100142typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200143typedef int SE_OBJECT_TYPE;
144typedef int PSNSECINFO;
145typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100146typedef int STARTUPINFO;
147typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200148typedef int LPSECURITY_ATTRIBUTES;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100149# define __stdcall // empty
Bram Moolenaar071d4272004-06-13 20:20:40 +0000150#endif
151
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200152#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100153// Win32 Console handles for input and output
Bram Moolenaar071d4272004-06-13 20:20:40 +0000154static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
155static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
156
Bram Moolenaar0f873732019-12-05 20:28:46 +0100157// Win32 Screen buffer,coordinate,console I/O information
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158static SMALL_RECT g_srScrollRegion;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100159static COORD g_coord; // 0-based, but external coords are 1-based
Bram Moolenaar071d4272004-06-13 20:20:40 +0000160
Bram Moolenaar0f873732019-12-05 20:28:46 +0100161// The attribute of the screen when the editor was started
162static WORD g_attrDefault = 7; // lightgray text on black background
Bram Moolenaar071d4272004-06-13 20:20:40 +0000163static WORD g_attrCurrent;
164
Bram Moolenaar0f873732019-12-05 20:28:46 +0100165static int g_fCBrkPressed = FALSE; // set by ctrl-break interrupt
166static int g_fCtrlCPressed = FALSE; // set when ctrl-C or ctrl-break detected
167static int g_fForceExit = FALSE; // set when forcefully exiting
Bram Moolenaar071d4272004-06-13 20:20:40 +0000168
Bram Moolenaar071d4272004-06-13 20:20:40 +0000169static void scroll(unsigned cLines);
170static void set_scroll_region(unsigned left, unsigned top,
171 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100172static void set_scroll_region_tb(unsigned top, unsigned bottom);
173static void set_scroll_region_lr(unsigned left, unsigned right);
174static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000175static void delete_lines(unsigned cLines);
176static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000177static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000178static int s_cursor_visible = TRUE;
179static int did_create_conin = FALSE;
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200180#endif
181#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000182static int s_dont_use_vimrun = TRUE;
183static int need_vimrun_warning = FALSE;
184static char *vimrun_path = "vimrun ";
185#endif
186
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200187static int win32_getattrs(char_u *name);
188static int win32_setattrs(char_u *name, int attrs);
189static int win32_set_archive(char_u *name);
190
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100191static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200192static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100193static int conpty_stable = 0;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +0200194static int conpty_fix_type = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100195static void vtp_flag_init();
196
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200197#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100198static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100199static void vtp_init();
200static void vtp_exit();
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100201static void vtp_sgr_bulk(int arg);
202static void vtp_sgr_bulks(int argc, int *argv);
203
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200204static int wt_working = 0;
205static void wt_init();
206
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100207static guicolor_T save_console_bg_rgb;
208static guicolor_T save_console_fg_rgb;
Bram Moolenaardf543822020-01-30 11:53:59 +0100209static guicolor_T store_console_bg_rgb;
210static guicolor_T store_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100211
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200212static int g_color_index_bg = 0;
213static int g_color_index_fg = 7;
214
215# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200216static int default_console_color_fg = 0xc0c0c0; // white
217# endif
218
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100219# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200220# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200221# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100222# else
223# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200224# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100225# endif
226
227static void set_console_color_rgb(void);
228static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100229static void restore_console_color_rgb(void);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100230#endif
231
Bram Moolenaar0f873732019-12-05 20:28:46 +0100232// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100233#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
234# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
235#endif
236
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200237#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100238static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000239#endif
240
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200241static char_u *exe_path = NULL;
242
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100243static BOOL win8_or_later = FALSE;
244
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200245#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100246// Dynamic loading for portability
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100247typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
248{
249 ULONG cbSize;
250 COORD dwSize;
251 COORD dwCursorPosition;
252 WORD wAttributes;
253 SMALL_RECT srWindow;
254 COORD dwMaximumWindowSize;
255 WORD wPopupAttributes;
256 BOOL bFullscreenSupported;
257 COLORREF ColorTable[16];
258} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
259typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
260static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
261typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
262static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
263static BOOL has_csbiex = FALSE;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100264#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100265
266/*
267 * Get version number including build number
268 */
269typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100270#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100271 (((major) << 24) | ((minor) << 16) | (build))
272
273 static DWORD
274get_build_number(void)
275{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100276 OSVERSIONINFOW osver;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100277 HMODULE hNtdll;
278 PfnRtlGetVersion pRtlGetVersion;
279 DWORD ver = MAKE_VER(0, 0, 0);
280
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100281 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100282 hNtdll = GetModuleHandle("ntdll.dll");
283 if (hNtdll != NULL)
284 {
285 pRtlGetVersion =
286 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
287 pRtlGetVersion(&osver);
288 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
289 min(osver.dwMinorVersion, 255),
290 min(osver.dwBuildNumber, 32767));
291 }
292 return ver;
293}
294
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200295#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200296 static BOOL
297is_ambiwidth_event(
298 INPUT_RECORD *ir)
299{
300 return ir->EventType == KEY_EVENT
301 && ir->Event.KeyEvent.bKeyDown
302 && ir->Event.KeyEvent.wRepeatCount == 1
303 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
304 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000305 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200306 && ir->Event.KeyEvent.dwControlKeyState == 2;
307}
308
309 static void
310make_ambiwidth_event(
311 INPUT_RECORD *down,
312 INPUT_RECORD *up)
313{
314 down->Event.KeyEvent.wVirtualKeyCode = 0;
315 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000316 down->Event.KeyEvent.uChar.UnicodeChar
317 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200318 down->Event.KeyEvent.dwControlKeyState = 0;
319}
320
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100321/*
322 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100323 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100324 */
325 static BOOL
326read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100327 HANDLE hInput,
328 INPUT_RECORD *lpBuffer,
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100329 int nLength,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100330 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100331{
332 enum
333 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100334 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100335 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100336 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100337 static DWORD s_dwIndex = 0;
338 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100339 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100340 int head;
341 int tail;
342 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200343 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100344
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200345 if (nLength == -2)
346 return (s_dwMax > 0) ? TRUE : FALSE;
347
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100348 if (!win8_or_later)
349 {
350 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200351 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
352 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100353 }
354
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100355 if (s_dwMax == 0)
356 {
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200357 if (!USE_WT && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200358 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200359 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
360 if (dwEvents == 0 && nLength == -1)
361 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
362 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100363 s_dwIndex = 0;
364 s_dwMax = dwEvents;
365 if (dwEvents == 0)
366 {
367 *lpEvents = 0;
368 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100369 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100370
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200371 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
372 if (is_ambiwidth_event(&s_irCache[i]))
373 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
374
Bram Moolenaardd415a62014-02-05 14:02:27 +0100375 if (s_dwMax > 1)
376 {
377 head = 0;
378 tail = s_dwMax - 1;
379 while (head != tail)
380 {
381 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
382 && s_irCache[head + 1].EventType
383 == WINDOW_BUFFER_SIZE_EVENT)
384 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100385 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100386 for (i = head; i < tail; ++i)
387 s_irCache[i] = s_irCache[i + 1];
388 --tail;
389 continue;
390 }
391 head++;
392 }
393 s_dwMax = tail + 1;
394 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100395 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100396
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200397 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
398 {
399 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
400 {
401 s_irPseudo = s_irCache[s_dwIndex];
402 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
403 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
404 *lpBuffer = s_irPseudo;
405 *lpEvents = 1;
406 return TRUE;
407 }
408 }
409
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100410 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200411 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100412 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100413 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100414 return TRUE;
415}
416
417/*
418 * Version of PeekConsoleInput() that works with IME.
419 */
420 static BOOL
421peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100422 HANDLE hInput,
423 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200424 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100425 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100426{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100427 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100428}
429
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100430# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200431 static DWORD
432msg_wait_for_multiple_objects(
433 DWORD nCount,
434 LPHANDLE pHandles,
435 BOOL fWaitAll,
436 DWORD dwMilliseconds,
437 DWORD dwWakeMask)
438{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100439 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200440 return WAIT_OBJECT_0;
441 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
442 dwMilliseconds, dwWakeMask);
443}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100444# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200445
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100446# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200447 static DWORD
448wait_for_single_object(
449 HANDLE hHandle,
450 DWORD dwMilliseconds)
451{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100452 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200453 return WAIT_OBJECT_0;
454 return WaitForSingleObject(hHandle, dwMilliseconds);
455}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100456# endif
457#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200458
Bram Moolenaar071d4272004-06-13 20:20:40 +0000459 static void
460get_exe_name(void)
461{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100462 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
463 // as the maximum length that works (plus a NUL byte).
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100464#define MAX_ENV_PATH_LEN 8192
465 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200466 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000467
468 if (exe_name == NULL)
469 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100470 // store the name of the executable, may be used for $VIM
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100471 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000472 if (*temp != NUL)
473 exe_name = FullName_save((char_u *)temp, FALSE);
474 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000475
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200476 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000477 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200478 exe_path = vim_strnsave(exe_name, gettail_sep(exe_name) - exe_name);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200479 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000480 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100481 // Append our starting directory to $PATH, so that when doing
482 // "!xxd" it's found in our starting directory. Needed because
483 // SearchPath() also looks there.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200484 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100485 if (p == NULL
486 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200487 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100488 if (p == NULL || *p == NUL)
489 temp[0] = NUL;
490 else
491 {
492 STRCPY(temp, p);
493 STRCAT(temp, ";");
494 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200495 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100496 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200497 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000498 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000499 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000500}
501
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200502/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100503 * Unescape characters in "p" that appear in "escaped".
504 */
505 static void
506unescape_shellxquote(char_u *p, char_u *escaped)
507{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100508 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100509 int n;
510
511 while (*p != NUL)
512 {
513 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
514 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100515 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100516 p += n;
517 l -= n;
518 }
519}
520
521/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200522 * Load library "name".
523 */
524 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000525vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200526{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200527 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200528
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200529 // No need to load any library when registering OLE.
530 if (found_register_arg)
531 return dll;
532
Bram Moolenaar0f873732019-12-05 20:28:46 +0100533 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
534 // vimLoadLib() recursively, which causes a stack overflow.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200535 if (exe_path == NULL)
536 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200537 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200538 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200539 WCHAR old_dirw[MAXPATHL];
540
541 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
542 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100543 // Change directory to where the executable is, both to make
544 // sure we find a .dll there and to avoid looking for a .dll
545 // in the current directory.
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100546 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200547 dll = LoadLibrary(name);
548 SetCurrentDirectoryW(old_dirw);
549 return dll;
550 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200551 }
552 return dll;
553}
554
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200555#if defined(VIMDLL) || defined(PROTO)
556/*
557 * Check if the current executable file is for the GUI subsystem.
558 */
559 int
560mch_is_gui_executable(void)
561{
562 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
563 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
564 PIMAGE_NT_HEADERS pPE;
565
566 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
567 return FALSE;
568 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
569 if (pPE->Signature != IMAGE_NT_SIGNATURE)
570 return FALSE;
571 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
572 return TRUE;
573 return FALSE;
574}
575#endif
576
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000577#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
578 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100579/*
580 * Get related information about 'funcname' which is imported by 'hInst'.
581 * If 'info' is 0, return the function address.
582 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000583 * If 'info' is 2, hook the function with 'ptr', and return the original
584 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100585 */
586 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000587get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
588 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100589{
590 PBYTE pImage = (PBYTE)hInst;
591 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
592 PIMAGE_NT_HEADERS pPE;
593 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100594 PIMAGE_THUNK_DATA pIAT; // Import Address Table
595 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100596 PIMAGE_IMPORT_BY_NAME pImpName;
597
598 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
599 return NULL;
600 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
601 if (pPE->Signature != IMAGE_NT_SIGNATURE)
602 return NULL;
603 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
604 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
605 .VirtualAddress);
606 for (; pImpDesc->FirstThunk; ++pImpDesc)
607 {
608 if (!pImpDesc->OriginalFirstThunk)
609 continue;
610 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
611 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
612 for (; pIAT->u1.Function; ++pIAT, ++pINT)
613 {
614 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
615 continue;
616 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
617 + (UINT_PTR)(pINT->u1.AddressOfData));
618 if (strcmp((char *)pImpName->Name, funcname) == 0)
619 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000620 void *original;
621 DWORD old, new = PAGE_READWRITE;
622
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100623 switch (info)
624 {
625 case 0:
626 return (void *)pIAT->u1.Function;
627 case 1:
628 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000629 case 2:
630 original = (void *)pIAT->u1.Function;
631 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
632 new, &old);
633 pIAT->u1.Function = (UINT_PTR)ptr;
634 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
635 old, &new);
636 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100637 default:
638 return NULL;
639 }
640 }
641 }
642 }
643 return NULL;
644}
645
646/*
647 * Get the module handle which 'funcname' in 'hInst' is imported from.
648 */
649 HINSTANCE
650find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
651{
652 char *modulename;
653
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000654 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100655 if (modulename != NULL)
656 return GetModuleHandleA(modulename);
657 return NULL;
658}
659
660/*
661 * Get the address of 'funcname' which is imported by 'hInst' DLL.
662 */
663 void *
664get_dll_import_func(HINSTANCE hInst, const char *funcname)
665{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000666 return get_imported_func_info(hInst, funcname, 0, NULL);
667}
668
669/*
670 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
671 * and return the original function address.
672 */
673 void *
674hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
675{
676 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100677}
678#endif
679
Bram Moolenaar071d4272004-06-13 20:20:40 +0000680#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
681# ifndef GETTEXT_DLL
682# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200683# define GETTEXT_DLL_ALT1 "libintl-8.dll"
684# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000685# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100686// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000687static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200688static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000689static char *null_libintl_textdomain(const char *);
690static char *null_libintl_bindtextdomain(const char *, const char *);
691static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100692static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000693
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200694static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000695char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200696char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
697 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000698char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
699char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000700 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000701char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
702 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100703int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000704
705 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100706dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000707{
708 int i;
709 static struct
710 {
711 char *name;
712 FARPROC *ptr;
713 } libintl_entry[] =
714 {
715 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200716 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000717 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
718 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
719 {NULL, NULL}
720 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100721 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000722
Bram Moolenaar7554c542018-10-06 15:03:15 +0200723 // No need to initialize twice.
724 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000725 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200726 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100727 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100728# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100729 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200730 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100731# endif
732# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200733 if (!hLibintlDLL)
734 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100735# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100736 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000737 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200738 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000739 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200740 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000741 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200742 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000743 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200744 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000745 }
746 for (i = 0; libintl_entry[i].name != NULL
747 && libintl_entry[i].ptr != NULL; ++i)
748 {
K.Takata54119102022-02-03 13:33:03 +0000749 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000750 libintl_entry[i].name)) == NULL)
751 {
752 dyn_libintl_end();
753 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000754 {
755 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000756 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000757 verbose_leave();
758 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000759 return 0;
760 }
761 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000762
Bram Moolenaar0f873732019-12-05 20:28:46 +0100763 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100764 dyn_libintl_bind_textdomain_codeset = (char *(*)(const char *, const char *))
765 GetProcAddress(hLibintlDLL, "bind_textdomain_codeset");
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000766 if (dyn_libintl_bind_textdomain_codeset == NULL)
767 dyn_libintl_bind_textdomain_codeset =
768 null_libintl_bind_textdomain_codeset;
769
Bram Moolenaar0f873732019-12-05 20:28:46 +0100770 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100771 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
772 if (hmsvcrt != NULL)
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100773 dyn_libintl_wputenv = (int (*)(const wchar_t *))
774 GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100775 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
776 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100777
Bram Moolenaar071d4272004-06-13 20:20:40 +0000778 return 1;
779}
780
781 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100782dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000783{
784 if (hLibintlDLL)
785 FreeLibrary(hLibintlDLL);
786 hLibintlDLL = NULL;
787 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200788 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000789 dyn_libintl_textdomain = null_libintl_textdomain;
790 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000791 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100792 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000793}
794
795 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000796null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000797{
798 return (char*)msgid;
799}
800
801 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200802null_libintl_ngettext(
803 const char *msgid,
804 const char *msgid_plural,
805 unsigned long n)
806{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200807 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200808}
809
Bram Moolenaaree695f72016-08-03 22:08:45 +0200810 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100811null_libintl_bindtextdomain(
812 const char *domainname UNUSED,
813 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000814{
815 return NULL;
816}
817
818 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100819null_libintl_bind_textdomain_codeset(
820 const char *domainname UNUSED,
821 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000822{
823 return NULL;
824}
825
826 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100827null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000828{
829 return NULL;
830}
831
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200832 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100833null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100834{
835 return 0;
836}
837
Bram Moolenaar0f873732019-12-05 20:28:46 +0100838#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000839
Bram Moolenaar0f873732019-12-05 20:28:46 +0100840// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000841
842#ifndef VER_PLATFORM_WIN32_WINDOWS
843# define VER_PLATFORM_WIN32_WINDOWS 1
844#endif
845
Bram Moolenaar071d4272004-06-13 20:20:40 +0000846#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100847# ifndef PROTO
848# include <aclapi.h>
849# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200850# ifndef PROTECTED_DACL_SECURITY_INFORMATION
851# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
852# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000853#endif
854
Bram Moolenaar27515922013-06-29 15:36:26 +0200855#ifdef HAVE_ACL
856/*
857 * Enables or disables the specified privilege.
858 */
859 static BOOL
860win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
861{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100862 BOOL bResult;
863 LUID luid;
864 HANDLE hToken;
865 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200866
867 if (!OpenProcessToken(GetCurrentProcess(),
868 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
869 return FALSE;
870
871 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
872 {
873 CloseHandle(hToken);
874 return FALSE;
875 }
876
Bram Moolenaar45500912014-07-09 20:51:07 +0200877 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200878 tokenPrivileges.Privileges[0].Luid = luid;
879 tokenPrivileges.Privileges[0].Attributes = bEnable ?
880 SE_PRIVILEGE_ENABLED : 0;
881
882 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
883 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
884
885 CloseHandle(hToken);
886
887 return bResult && GetLastError() == ERROR_SUCCESS;
888}
889#endif
890
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100891#ifdef _MSC_VER
892// Suppress the deprecation warning for using GetVersionEx().
893// It is needed for implementing "windowsversion()".
894# pragma warning(push)
895# pragma warning(disable: 4996)
896#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000897/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200898 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000899 */
900 void
901PlatformId(void)
902{
903 static int done = FALSE;
904
905 if (!done)
906 {
907 OSVERSIONINFO ovi;
908
909 ovi.dwOSVersionInfoSize = sizeof(ovi);
910 GetVersionEx(&ovi);
911
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200912#ifdef FEAT_EVAL
Bram Moolenaar0c1e3742019-12-27 13:49:24 +0100913 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
914 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200915#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100916 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
917 || ovi.dwMajorVersion > 6)
918 win8_or_later = TRUE;
919
Bram Moolenaar071d4272004-06-13 20:20:40 +0000920#ifdef HAVE_ACL
Bram Moolenaar0f873732019-12-05 20:28:46 +0100921 // Enable privilege for getting or setting SACLs.
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200922 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000923#endif
924 done = TRUE;
925 }
926}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100927#ifdef _MSC_VER
928# pragma warning(pop)
929#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000930
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200931#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000932
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100933# define SHIFT (SHIFT_PRESSED)
934# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
935# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
936# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000937
938
Bram Moolenaar0f873732019-12-05 20:28:46 +0100939// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
940// We map function keys to their ANSI terminal equivalents, as produced
941// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
942// ANSI key with a value >= '\300' is nonstandard, but provided anyway
943// so that the user can have access to all SHIFT-, CTRL-, and ALT-
944// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000945
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000946static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000947{
948 WORD wVirtKey;
949 BOOL fAnsiKey;
950 int chAlone;
951 int chShift;
952 int chCtrl;
953 int chAlt;
954} VirtKeyMap[] =
955{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200956// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000957 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
958
959 { VK_F1, TRUE, ';', 'T', '^', 'h', },
960 { VK_F2, TRUE, '<', 'U', '_', 'i', },
961 { VK_F3, TRUE, '=', 'V', '`', 'j', },
962 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
963 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
964 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
965 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
966 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
967 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
968 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200969 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
970 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000971
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200972 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
973 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
974 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
975 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
976 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
977 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
978 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
979 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
980 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
981 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100982 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000983
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200984 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000985
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100986# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200987 // Most people don't have F13-F20, but what the hell...
988 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
989 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
990 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
991 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
992 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
993 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
994 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
995 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100996# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200997 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
998 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
999 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
1000 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001001
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001002 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
1003 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
1004 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
1005 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
1006 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
1007 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
1008 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
1009 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
1010 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
1011 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001012 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001013};
1014
1015
Bram Moolenaar0f873732019-12-05 20:28:46 +01001016/*
1017 * The return code indicates key code size.
1018 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001019 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001020win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001021 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001022{
1023 UINT uMods = pker->dwControlKeyState;
1024 static int s_iIsDead = 0;
1025 static WORD awAnsiCode[2];
1026 static BYTE abKeystate[256];
1027
1028
1029 if (s_iIsDead == 2)
1030 {
K.Takata972db232022-02-04 10:45:38 +00001031 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001032 s_iIsDead = 0;
1033 return 1;
1034 }
1035
K.Takata972db232022-02-04 10:45:38 +00001036 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001037 return 1;
1038
Bram Moolenaara80faa82020-04-12 19:37:17 +02001039 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001040
Bram Moolenaar0f873732019-12-05 20:28:46 +01001041 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001042 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001043
1044 if (uMods & SHIFT_PRESSED)
1045 abKeystate[VK_SHIFT] = 0x80;
1046 if (uMods & CAPSLOCK_ON)
1047 abKeystate[VK_CAPITAL] = 1;
1048
1049 if ((uMods & ALT_GR) == ALT_GR)
1050 {
1051 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1052 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1053 }
1054
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001055 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1056 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001057
1058 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001059 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001060
1061 return s_iIsDead;
1062}
1063
Bram Moolenaar071d4272004-06-13 20:20:40 +00001064static BOOL g_fJustGotFocus = FALSE;
1065
1066/*
1067 * Decode a KEY_EVENT into one or two keystrokes
1068 */
1069 static BOOL
1070decode_key_event(
1071 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001072 WCHAR *pch,
1073 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001074 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001075 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001076{
1077 int i;
1078 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1079
1080 *pch = *pch2 = NUL;
1081 g_fJustGotFocus = FALSE;
1082
Bram Moolenaar0f873732019-12-05 20:28:46 +01001083 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001084 if (!pker->bKeyDown)
1085 return FALSE;
1086
Bram Moolenaar0f873732019-12-05 20:28:46 +01001087 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001088 switch (pker->wVirtualKeyCode)
1089 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001090 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001091 case VK_SHIFT:
1092 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001093 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001094 return FALSE;
1095
1096 default:
1097 break;
1098 }
1099
Bram Moolenaar0f873732019-12-05 20:28:46 +01001100 // special cases
K.Takata972db232022-02-04 10:45:38 +00001101 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0
1102 && pker->uChar.UnicodeChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001103 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001104 // Ctrl-6 is Ctrl-^
Bram Moolenaar071d4272004-06-13 20:20:40 +00001105 if (pker->wVirtualKeyCode == '6')
1106 {
1107 *pch = Ctrl_HAT;
1108 return TRUE;
1109 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001110 // Ctrl-2 is Ctrl-@
Bram Moolenaar071d4272004-06-13 20:20:40 +00001111 else if (pker->wVirtualKeyCode == '2')
1112 {
1113 *pch = NUL;
1114 return TRUE;
1115 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001116 // Ctrl-- is Ctrl-_
Bram Moolenaar071d4272004-06-13 20:20:40 +00001117 else if (pker->wVirtualKeyCode == 0xBD)
1118 {
1119 *pch = Ctrl__;
1120 return TRUE;
1121 }
1122 }
1123
Bram Moolenaar0f873732019-12-05 20:28:46 +01001124 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001125 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1126 {
1127 *pch = K_NUL;
1128 *pch2 = '\017';
1129 return TRUE;
1130 }
1131
K.Takataeeec2542021-06-02 13:28:16 +02001132 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001133 {
1134 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1135 {
1136 if (nModifs == 0)
1137 *pch = VirtKeyMap[i].chAlone;
1138 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1139 *pch = VirtKeyMap[i].chShift;
1140 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1141 *pch = VirtKeyMap[i].chCtrl;
1142 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1143 *pch = VirtKeyMap[i].chAlt;
1144
1145 if (*pch != 0)
1146 {
1147 if (VirtKeyMap[i].fAnsiKey)
1148 {
1149 *pch2 = *pch;
1150 *pch = K_NUL;
1151 }
1152
1153 return TRUE;
1154 }
1155 }
1156 }
1157
1158 i = win32_kbd_patch_key(pker);
1159
1160 if (i < 0)
1161 *pch = NUL;
1162 else
1163 {
K.Takata972db232022-02-04 10:45:38 +00001164 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001165
1166 if (pmodifiers != NULL)
1167 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001168 // Pass on the ALT key as a modifier, but only when not combined
1169 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001170 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1171 *pmodifiers |= MOD_MASK_ALT;
1172
Bram Moolenaar0f873732019-12-05 20:28:46 +01001173 // Pass on SHIFT only for special keys, because we don't know when
1174 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001175 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1176 *pmodifiers |= MOD_MASK_SHIFT;
1177
Bram Moolenaar0f873732019-12-05 20:28:46 +01001178 // Pass on CTRL only for non-special keys, because we don't know
1179 // when it's already included with the character. And not when
1180 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001181 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1182 && *pch >= 0x20 && *pch < 0x80)
1183 *pmodifiers |= MOD_MASK_CTRL;
1184 }
1185 }
1186
1187 return (*pch != NUL);
1188}
1189
Bram Moolenaar0f873732019-12-05 20:28:46 +01001190#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001191
1192
Bram Moolenaar071d4272004-06-13 20:20:40 +00001193/*
1194 * For the GUI the mouse handling is in gui_w32.c.
1195 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001196#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001197 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001198mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001199{
1200}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001201#else
Bram Moolenaar0f873732019-12-05 20:28:46 +01001202static int g_fMouseAvail = FALSE; // mouse present
1203static int g_fMouseActive = FALSE; // mouse enabled
1204static int g_nMouseClick = -1; // mouse status
1205static int g_xMouse; // mouse x coordinate
1206static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001207static DWORD g_cmodein = 0; // Original console input mode
1208static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001209
1210/*
1211 * Enable or disable mouse input
1212 */
1213 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001214mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001215{
1216 DWORD cmodein;
1217
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001218# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001219 if (gui.in_use)
1220 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001221# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001222 if (!g_fMouseAvail)
1223 return;
1224
1225 g_fMouseActive = on;
1226 GetConsoleMode(g_hConIn, &cmodein);
1227
1228 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001229 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001230 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001231 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1232 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001233 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001234 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001235 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001236 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1237 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001238
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001239 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001240}
1241
Bram Moolenaar157d8132018-03-06 17:09:20 +01001242
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001243# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001244/*
1245 * Called when 'balloonevalterm' changed.
1246 */
1247 void
1248mch_bevalterm_changed(void)
1249{
1250 mch_setmouse(g_fMouseActive);
1251}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001252# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001253
Bram Moolenaar071d4272004-06-13 20:20:40 +00001254/*
1255 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1256 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1257 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1258 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1259 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1260 * and we return the mouse position in g_xMouse and g_yMouse.
1261 *
1262 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1263 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1264 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1265 *
1266 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1267 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1268 *
1269 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1270 * moves, even if it stays within the same character cell. We ignore
1271 * all MOUSE_MOVED messages if the position hasn't really changed, and
1272 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1273 * we're only interested in MOUSE_DRAG).
1274 *
1275 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1276 * 2-button mouses by pressing the left & right buttons simultaneously.
1277 * In practice, it's almost impossible to click both at the same time,
1278 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1279 * in such cases, if the user is clicking quickly.
1280 */
1281 static BOOL
1282decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001283 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001284{
1285 static int s_nOldButton = -1;
1286 static int s_nOldMouseClick = -1;
1287 static int s_xOldMouse = -1;
1288 static int s_yOldMouse = -1;
1289 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001290# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001291 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001292# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001293 static int s_cClicks = 1;
1294 static BOOL s_fReleased = TRUE;
1295 static DWORD s_dwLastClickTime = 0;
1296 static BOOL s_fNextIsMiddle = FALSE;
1297
Bram Moolenaar0f873732019-12-05 20:28:46 +01001298 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001299
1300 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1301 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1302 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1303 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1304
1305 int nButton;
1306
1307 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1308 cButtons = 2;
1309
1310 if (!g_fMouseAvail || !g_fMouseActive)
1311 {
1312 g_nMouseClick = -1;
1313 return FALSE;
1314 }
1315
Bram Moolenaar0f873732019-12-05 20:28:46 +01001316 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001317 if (g_fJustGotFocus)
1318 {
1319 g_fJustGotFocus = FALSE;
1320 return FALSE;
1321 }
1322
Bram Moolenaar0f873732019-12-05 20:28:46 +01001323 // unprocessed mouse click?
Bram Moolenaar071d4272004-06-13 20:20:40 +00001324 if (g_nMouseClick != -1)
1325 return TRUE;
1326
1327 nButton = -1;
1328 g_xMouse = pmer->dwMousePosition.X;
1329 g_yMouse = pmer->dwMousePosition.Y;
1330
1331 if (pmer->dwEventFlags == MOUSE_MOVED)
1332 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001333 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1334 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001335 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1336 return FALSE;
1337 }
1338
Bram Moolenaar0f873732019-12-05 20:28:46 +01001339 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001340 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1341 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001342 nButton = MOUSE_RELEASE;
1343
Bram Moolenaar0f873732019-12-05 20:28:46 +01001344 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001345 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001346 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001347# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001348 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001349 if (p_bevalterm)
1350 nButton = MOUSE_DRAG;
1351 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001352# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001353 return FALSE;
1354 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001355
Bram Moolenaar071d4272004-06-13 20:20:40 +00001356 s_fReleased = TRUE;
1357 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001358 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001359 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001360 // on a 2-button mouse, hold down left and right buttons
1361 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001362
1363 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1364 {
1365 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1366
Bram Moolenaar0f873732019-12-05 20:28:46 +01001367 // if either left or right button only is pressed, see if the
1368 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001369 if (dwLR == LEFT || dwLR == RIGHT)
1370 {
1371 for (;;)
1372 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001373 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001374 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1375 != WAIT_OBJECT_0)
1376 break;
1377 else
1378 {
1379 DWORD cRecords = 0;
1380 INPUT_RECORD ir;
1381 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1382
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001383 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001384
1385 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1386 || !(pmer2->dwButtonState & LEFT_RIGHT))
1387 break;
1388 else
1389 {
1390 if (pmer2->dwEventFlags != MOUSE_MOVED)
1391 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001392 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001393
1394 return decode_mouse_event(pmer2);
1395 }
1396 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1397 s_yOldMouse == pmer2->dwMousePosition.Y)
1398 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001399 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001400 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001401
Bram Moolenaar0f873732019-12-05 20:28:46 +01001402 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001403 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001404
1405 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1406 break;
1407 }
1408 else
1409 break;
1410 }
1411 }
1412 }
1413 }
1414 }
1415
1416 if (s_fNextIsMiddle)
1417 {
1418 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1419 ? MOUSE_DRAG : MOUSE_MIDDLE;
1420 s_fNextIsMiddle = FALSE;
1421 }
1422 else if (cButtons == 2 &&
1423 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1424 {
1425 nButton = MOUSE_MIDDLE;
1426
1427 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1428 {
1429 s_fNextIsMiddle = TRUE;
1430 nButton = MOUSE_RELEASE;
1431 }
1432 }
1433 else if ((pmer->dwButtonState & LEFT) == LEFT)
1434 nButton = MOUSE_LEFT;
1435 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1436 nButton = MOUSE_MIDDLE;
1437 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1438 nButton = MOUSE_RIGHT;
1439
1440 if (! s_fReleased && ! s_fNextIsMiddle
1441 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1442 return FALSE;
1443
1444 s_fReleased = s_fNextIsMiddle;
1445 }
1446
1447 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1448 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001449 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001450 if (nButton != -1 && nButton != MOUSE_RELEASE)
1451 {
1452 DWORD dwCurrentTime = GetTickCount();
1453
1454 if (s_xOldMouse != g_xMouse
1455 || s_yOldMouse != g_yMouse
1456 || s_nOldButton != nButton
1457 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001458# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001459 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001460# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001461 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1462 {
1463 s_cClicks = 1;
1464 }
1465 else if (++s_cClicks > 4)
1466 {
1467 s_cClicks = 1;
1468 }
1469
1470 s_dwLastClickTime = dwCurrentTime;
1471 }
1472 }
1473 else if (pmer->dwEventFlags == MOUSE_MOVED)
1474 {
1475 if (nButton != -1 && nButton != MOUSE_RELEASE)
1476 nButton = MOUSE_DRAG;
1477
1478 s_cClicks = 1;
1479 }
1480
1481 if (nButton == -1)
1482 return FALSE;
1483
1484 if (nButton != MOUSE_RELEASE)
1485 s_nOldButton = nButton;
1486
1487 g_nMouseClick = nButton;
1488
1489 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1490 g_nMouseClick |= MOUSE_SHIFT;
1491 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1492 g_nMouseClick |= MOUSE_CTRL;
1493 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1494 g_nMouseClick |= MOUSE_ALT;
1495
1496 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1497 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1498
Bram Moolenaar0f873732019-12-05 20:28:46 +01001499 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001500 if (s_xOldMouse == g_xMouse
1501 && s_yOldMouse == g_yMouse
1502 && s_nOldMouseClick == g_nMouseClick)
1503 {
1504 g_nMouseClick = -1;
1505 return FALSE;
1506 }
1507
1508 s_xOldMouse = g_xMouse;
1509 s_yOldMouse = g_yMouse;
1510 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001511# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001512 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001513# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001514 s_nOldMouseClick = g_nMouseClick;
1515
1516 return TRUE;
1517}
1518
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001519#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001520
1521
1522#ifdef MCH_CURSOR_SHAPE
1523/*
1524 * Set the shape of the cursor.
1525 * 'thickness' can be from 1 (thin) to 99 (block)
1526 */
1527 static void
1528mch_set_cursor_shape(int thickness)
1529{
1530 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1531 ConsoleCursorInfo.dwSize = thickness;
1532 ConsoleCursorInfo.bVisible = s_cursor_visible;
1533
1534 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1535 if (s_cursor_visible)
1536 SetConsoleCursorPosition(g_hConOut, g_coord);
1537}
1538
1539 void
1540mch_update_cursor(void)
1541{
1542 int idx;
1543 int thickness;
1544
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001545# ifdef VIMDLL
1546 if (gui.in_use)
1547 return;
1548# endif
1549
Bram Moolenaar071d4272004-06-13 20:20:40 +00001550 /*
1551 * How the cursor is drawn depends on the current mode.
1552 */
1553 idx = get_shape_idx(FALSE);
1554
1555 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001556 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00001557 else
1558 thickness = shape_table[idx].percentage;
1559 mch_set_cursor_shape(thickness);
1560}
1561#endif
1562
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001563#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001564/*
1565 * Handle FOCUS_EVENT.
1566 */
1567 static void
1568handle_focus_event(INPUT_RECORD ir)
1569{
1570 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1571 ui_focus_change((int)g_fJustGotFocus);
1572}
1573
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001574static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1575
Bram Moolenaar071d4272004-06-13 20:20:40 +00001576/*
1577 * Wait until console input from keyboard or mouse is available,
1578 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001579 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001580 * Return TRUE if something is available FALSE if not.
1581 */
1582 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001583WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001584{
1585 DWORD dwNow = 0, dwEndTime = 0;
1586 INPUT_RECORD ir;
1587 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001588 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001589# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001590 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001591# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001592
1593 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001594 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001595 dwEndTime = GetTickCount() + msec;
1596 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001597 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001598 dwEndTime = INFINITE;
1599
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001600 // We need to loop until the end of the time period, because
1601 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001602 for (;;)
1603 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001604 // Only process messages when waiting.
1605 if (msec != 0)
1606 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001607# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001608 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001609# endif
1610# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001611 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001612# endif
1613# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001614 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001615# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001616 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001617
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001618 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001619# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001620 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001621# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001622 )
1623 return TRUE;
1624
1625 if (msec > 0)
1626 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001627 // If the specified wait time has passed, return. Beware that
1628 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001629 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001630 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001631 break;
1632 }
1633 if (msec != 0)
1634 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001635 DWORD dwWaitTime = dwEndTime - dwNow;
1636
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001637 // Don't wait for more than 11 msec to avoid dropping characters,
1638 // check channel while waiting for input and handle a callback from
1639 // 'balloonexpr'.
1640 if (dwWaitTime > 11)
1641 dwWaitTime = 11;
1642
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001643# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001644 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001645 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001646# endif
1647# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001648 // When waiting very briefly don't trigger timers.
1649 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001650 {
1651 long due_time;
1652
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001653 // Trigger timers and then get the time in msec until the next
1654 // one is due. Wait up to that time.
1655 due_time = check_due_timer();
1656 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001657 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001658 // timer may have used feedkeys().
1659 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001660 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001661 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1662 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001663 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001664# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001665 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001666# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001667 // Wait for either an event on the console input or a
1668 // message in the client-server window.
1669 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1670 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001671# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001672 wait_for_single_object(g_hConIn, dwWaitTime)
1673 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001674# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001675 )
1676 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001677 }
1678
1679 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001680 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001681
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001682# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02001683 // May have to redraw if the cursor ends up in the wrong place.
1684 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01001685 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001686 {
1687 CONSOLE_SCREEN_BUFFER_INFO csbi;
1688
1689 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1690 {
1691 if (csbi.dwCursorPosition.Y != msg_row)
1692 {
matveyte08795e2021-05-07 15:00:17 +02001693 // The screen is now messed up, must redraw the command
1694 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01001695 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02001696 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001697 redrawcmd();
1698 }
1699 }
1700 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001701# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001702
1703 if (cRecords > 0)
1704 {
1705 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1706 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001707# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01001708 // Windows IME sends two '\n's with only one 'ENTER'. First:
1709 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00001710 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001711 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1712 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001713 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001714 continue;
1715 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001716# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1718 NULL, FALSE))
1719 return TRUE;
1720 }
1721
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001722 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001723
1724 if (ir.EventType == FOCUS_EVENT)
1725 handle_focus_event(ir);
1726 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001727 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001728 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1729
Bram Moolenaar36698e32019-12-11 22:57:40 +01001730 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001731 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001732 if (dwSize.X != Columns || dwSize.Y != Rows)
1733 {
1734 CONSOLE_SCREEN_BUFFER_INFO csbi;
1735 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01001736 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001737 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01001738 if (dwSize.X != Columns || dwSize.Y != Rows)
1739 {
1740 ResizeConBuf(g_hConOut, dwSize);
1741 shell_resized();
1742 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001743 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001744 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001745 else if (ir.EventType == MOUSE_EVENT
1746 && decode_mouse_event(&ir.Event.MouseEvent))
1747 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001748 }
1749 else if (msec == 0)
1750 break;
1751 }
1752
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001753# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01001754 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001755 if (input_available())
1756 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001757# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001758
Bram Moolenaar071d4272004-06-13 20:20:40 +00001759 return FALSE;
1760}
1761
Bram Moolenaar071d4272004-06-13 20:20:40 +00001762/*
1763 * return non-zero if a character is available
1764 */
1765 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001766mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001767{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001768# ifdef VIMDLL
1769 if (gui.in_use)
1770 return TRUE;
1771# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001772 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001773}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001774
1775# if defined(FEAT_TERMINAL) || defined(PROTO)
1776/*
1777 * Check for any pending input or messages.
1778 */
1779 int
1780mch_check_messages(void)
1781{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001782# ifdef VIMDLL
1783 if (gui.in_use)
1784 return TRUE;
1785# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001786 return WaitForChar(0L, TRUE);
1787}
1788# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001789
1790/*
1791 * Create the console input. Used when reading stdin doesn't work.
1792 */
1793 static void
1794create_conin(void)
1795{
1796 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1797 FILE_SHARE_READ|FILE_SHARE_WRITE,
1798 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001799 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001800 did_create_conin = TRUE;
1801}
1802
1803/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001804 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001805 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001806 static WCHAR
1807tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001808{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001809 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001810
1811 for (;;)
1812 {
1813 INPUT_RECORD ir;
1814 DWORD cRecords = 0;
1815
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001816# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001817 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001818 if (input_available())
1819 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001820 if (g_nMouseClick != -1)
1821 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001822# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001823 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001824 {
1825 if (did_create_conin)
1826 read_error_exit();
1827 create_conin();
1828 continue;
1829 }
1830
1831 if (ir.EventType == KEY_EVENT)
1832 {
1833 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1834 pmodifiers, TRUE))
1835 return ch;
1836 }
1837 else if (ir.EventType == FOCUS_EVENT)
1838 handle_focus_event(ir);
1839 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1840 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001841 else if (ir.EventType == MOUSE_EVENT)
1842 {
1843 if (decode_mouse_event(&ir.Event.MouseEvent))
1844 return 0;
1845 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001846 }
1847}
Bram Moolenaar0f873732019-12-05 20:28:46 +01001848#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001849
1850
1851/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001852 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001853 * Get one or more characters from the keyboard or the mouse.
1854 * If time == 0, do not wait for characters.
1855 * If time == n, wait a short time for characters.
1856 * If time == -1, wait forever for characters.
1857 * Returns the number of characters read into buf.
1858 */
1859 int
1860mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001861 char_u *buf UNUSED,
1862 int maxlen UNUSED,
1863 long time UNUSED,
1864 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001865{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001866#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001867
1868 int len;
1869 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001870# ifdef VIMDLL
1871// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
1872# define TYPEAHEADSPACE 6
1873# else
1874# define TYPEAHEADSPACE 0
1875# endif
1876# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001877 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001878 static int typeaheadlen = 0;
1879
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001880# ifdef VIMDLL
1881 if (gui.in_use)
1882 return 0;
1883# endif
1884
Bram Moolenaar0f873732019-12-05 20:28:46 +01001885 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001886 if (typeaheadlen > 0)
1887 goto theend;
1888
Bram Moolenaar071d4272004-06-13 20:20:40 +00001889 if (time >= 0)
1890 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001891 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00001892 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001893 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001894 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00001895 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001896 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00001897
Bram Moolenaar3918c952005-03-15 22:34:55 +00001898 /*
1899 * If there is no character available within 2 seconds (default)
1900 * write the autoscript file to disk. Or cause the CursorHold event
1901 * to be triggered.
1902 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001903 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001904 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001905 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001906 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001907 buf[0] = K_SPECIAL;
1908 buf[1] = KS_EXTRA;
1909 buf[2] = (int)KE_CURSORHOLD;
1910 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001911 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001912 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001913 }
1914 }
1915
1916 /*
1917 * Try to read as many characters as there are, until the buffer is full.
1918 */
1919
Bram Moolenaar0f873732019-12-05 20:28:46 +01001920 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001921 g_fCBrkPressed = FALSE;
1922
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001923# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001924 if (fdDump)
1925 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001926# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001927
Bram Moolenaar0f873732019-12-05 20:28:46 +01001928 // Keep looping until there is something in the typeahead buffer and more
1929 // to get and still room in the buffer (up to two bytes for a char and
1930 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001931 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001932 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001933 {
1934 if (typebuf_changed(tb_change_cnt))
1935 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001936 // "buf" may be invalid now if a client put something in the
1937 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001938 typeaheadlen = 0;
1939 break;
1940 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001941 if (g_nMouseClick != -1)
1942 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001943# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001944 if (fdDump)
1945 fprintf(fdDump, "{%02x @ %d, %d}",
1946 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001947# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001948 typeahead[typeaheadlen++] = ESC + 128;
1949 typeahead[typeaheadlen++] = 'M';
1950 typeahead[typeaheadlen++] = g_nMouseClick;
1951 typeahead[typeaheadlen++] = g_xMouse + '!';
1952 typeahead[typeaheadlen++] = g_yMouse + '!';
1953 g_nMouseClick = -1;
1954 }
1955 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001956 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001957 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001958 int modifiers = 0;
1959
1960 c = tgetch(&modifiers, &ch2);
1961
1962 if (typebuf_changed(tb_change_cnt))
1963 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001964 // "buf" may be invalid now if a client put something in the
1965 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001966 typeaheadlen = 0;
1967 break;
1968 }
1969
1970 if (c == Ctrl_C && ctrl_c_interrupts)
1971 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001972# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001973 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001974# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001975 got_int = TRUE;
1976 }
1977
Bram Moolenaar071d4272004-06-13 20:20:40 +00001978 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001979 {
1980 int n = 1;
1981
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001982 if (ch2 == NUL)
1983 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001984 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001985 char_u *p;
1986 WCHAR ch[2];
1987
1988 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01001989 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001990 {
1991 ch[1] = tgetch(&modifiers, &ch2);
1992 n++;
1993 }
1994 p = utf16_to_enc(ch, &n);
1995 if (p != NULL)
1996 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001997 for (i = 0, j = 0; i < n; i++)
1998 {
1999 typeahead[typeaheadlen + j++] = p[i];
2000# ifdef VIMDLL
2001 if (p[i] == CSI)
2002 {
2003 typeahead[typeaheadlen + j++] = KS_EXTRA;
2004 typeahead[typeaheadlen + j++] = KE_CSI;
2005 }
2006# endif
2007 }
2008 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002009 vim_free(p);
2010 }
2011 }
2012 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002013 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002014 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002015# ifdef VIMDLL
2016 if (c == CSI)
2017 {
2018 typeahead[typeaheadlen + 1] = KS_EXTRA;
2019 typeahead[typeaheadlen + 2] = KE_CSI;
2020 n = 3;
2021 }
2022# endif
2023 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002024 if (ch2 != NUL)
2025 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002026 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002027 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002028 switch (ch2)
2029 {
2030 case (WCHAR)'\324': // SHIFT+Insert
2031 case (WCHAR)'\325': // CTRL+Insert
2032 case (WCHAR)'\327': // SHIFT+Delete
2033 case (WCHAR)'\330': // CTRL+Delete
2034 typeahead[typeaheadlen + n] = (char_u)ch2;
2035 n++;
2036 break;
2037
2038 default:
2039 typeahead[typeaheadlen + n] = 3;
2040 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2041 n += 2;
2042 break;
2043 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002044 }
2045 else
2046 {
2047 typeahead[typeaheadlen + n] = 3;
2048 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2049 n += 2;
2050 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002051 }
2052
Bram Moolenaar0f873732019-12-05 20:28:46 +01002053 // Use the ALT key to set the 8th bit of the character
2054 // when it's one byte, the 8th bit isn't set yet and not
2055 // using a double-byte encoding (would become a lead
2056 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057 if ((modifiers & MOD_MASK_ALT)
2058 && n == 1
2059 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002060 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002061 )
2062 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002063 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2064 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002065 modifiers &= ~MOD_MASK_ALT;
2066 }
2067
2068 if (modifiers != 0)
2069 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002070 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002071 mch_memmove(typeahead + typeaheadlen + 3,
2072 typeahead + typeaheadlen, n);
2073 typeahead[typeaheadlen++] = K_SPECIAL;
2074 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2075 typeahead[typeaheadlen++] = modifiers;
2076 }
2077
2078 typeaheadlen += n;
2079
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002080# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002081 if (fdDump)
2082 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002083# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002084 }
2085 }
2086 }
2087
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002088# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002089 if (fdDump)
2090 {
2091 fputs("]\n", fdDump);
2092 fflush(fdDump);
2093 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002094# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002095
Bram Moolenaar071d4272004-06-13 20:20:40 +00002096theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002097 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002098 len = 0;
2099 while (len < maxlen && typeaheadlen > 0)
2100 {
2101 buf[len++] = typeahead[0];
2102 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2103 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002104# ifdef FEAT_JOB_CHANNEL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002105 if (len > 0)
2106 {
2107 buf[len] = NUL;
2108 ch_log(NULL, "raw key input: \"%s\"", buf);
2109 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002110# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002111 return len;
2112
Bram Moolenaar0f873732019-12-05 20:28:46 +01002113#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002114 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002115#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002116}
2117
Bram Moolenaar82881492012-11-20 16:53:39 +01002118#ifndef PROTO
2119# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002120# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002121# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002122#endif
2123
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002124/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002125 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002126 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2127 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002128 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002129 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002130 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002131executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002132{
LemonBoy40fd7e62022-05-05 20:18:16 +01002133 int attrs = win32_getattrs((char_u *)name);
2134
2135 // The file doesn't exist or is a folder.
2136 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2137 return FALSE;
2138 // Check if the file is an AppExecLink, a special alias used by Windows
2139 // Store for its apps.
2140 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002141 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002142 char_u *res = resolve_appexeclink((char_u *)name);
2143 if (res == NULL)
2144 return FALSE;
2145 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002146 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002147 *path = res;
2148 else
2149 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002150 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002151 else if (path != NULL)
2152 *path = FullName_save((char_u *)name, FALSE);
2153 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002154}
2155
2156/*
2157 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2158 * If "use_path" is FALSE: Return TRUE if "name" exists.
2159 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2160 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2161 * the allocated memory.
2162 */
2163 static int
2164executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2165{
2166 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2167 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2168 // UTF-8.
2169 char_u buf[_MAX_PATH * 3];
2170 size_t len = STRLEN(name);
2171 size_t tmplen;
2172 char_u *p, *e, *e2;
2173 char_u *pathbuf = NULL;
2174 char_u *pathext = NULL;
2175 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002176 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002177 int noext = FALSE;
2178 int retval = FALSE;
2179
2180 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002181 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002182
2183 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002184 shname = gettail(p_sh);
2185 if (strstr((char *)shname, "sh") != NULL &&
2186 !(strstr((char *)shname, "powershell") != NULL
2187 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002188 noext = TRUE;
2189
2190 if (use_pathext)
2191 {
2192 pathext = mch_getenv("PATHEXT");
2193 if (pathext == NULL)
2194 pathext = (char_u *)".com;.exe;.bat;.cmd";
2195
2196 if (noext == FALSE)
2197 {
2198 /*
2199 * Loop over all extensions in $PATHEXT.
2200 * Check "name" ends with extension.
2201 */
2202 p = pathext;
2203 while (*p)
2204 {
2205 if (p[0] == ';'
2206 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2207 {
2208 // Skip empty or single ".".
2209 ++p;
2210 continue;
2211 }
2212 e = vim_strchr(p, ';');
2213 if (e == NULL)
2214 e = p + STRLEN(p);
2215 tmplen = e - p;
2216
2217 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2218 {
2219 noext = TRUE;
2220 break;
2221 }
2222
2223 p = e;
2224 }
2225 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002226 }
2227
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002228 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002229 if (pathext == NULL)
2230 pathext = (char_u *)".";
2231 else if (noext == TRUE)
2232 {
2233 if (pathextbuf == NULL)
2234 pathextbuf = alloc(STRLEN(pathext) + 3);
2235 if (pathextbuf == NULL)
2236 {
2237 retval = FALSE;
2238 goto theend;
2239 }
2240 STRCPY(pathextbuf, ".;");
2241 STRCAT(pathextbuf, pathext);
2242 pathext = pathextbuf;
2243 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002244
Bram Moolenaar95da1362020-05-30 18:37:55 +02002245 // Use $PATH when "use_path" is TRUE and "name" is basename.
2246 if (use_path && gettail((char_u *)name) == (char_u *)name)
2247 {
2248 p = mch_getenv("PATH");
2249 if (p != NULL)
2250 {
2251 pathbuf = alloc(STRLEN(p) + 3);
2252 if (pathbuf == NULL)
2253 {
2254 retval = FALSE;
2255 goto theend;
2256 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002257
2258 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2259 STRCPY(pathbuf, ".;");
2260 else
2261 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002262 STRCAT(pathbuf, p);
2263 }
2264 }
2265
2266 /*
2267 * Walk through all entries in $PATH to check if "name" exists there and
2268 * is an executable file.
2269 */
2270 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2271 while (*p)
2272 {
2273 if (*p == ';') // Skip empty entry
2274 {
2275 ++p;
2276 continue;
2277 }
2278 e = vim_strchr(p, ';');
2279 if (e == NULL)
2280 e = p + STRLEN(p);
2281
2282 if (e - p + len + 2 > sizeof(buf))
2283 {
2284 retval = FALSE;
2285 goto theend;
2286 }
2287 // A single "." that means current dir.
2288 if (e - p == 1 && *p == '.')
2289 STRCPY(buf, name);
2290 else
2291 {
2292 vim_strncpy(buf, p, e - p);
2293 add_pathsep(buf);
2294 STRCAT(buf, name);
2295 }
2296 tmplen = STRLEN(buf);
2297
2298 /*
2299 * Loop over all extensions in $PATHEXT.
2300 * Check "name" with extension added.
2301 */
2302 p = pathext;
2303 while (*p)
2304 {
2305 if (*p == ';')
2306 {
2307 // Skip empty entry
2308 ++p;
2309 continue;
2310 }
2311 e2 = vim_strchr(p, (int)';');
2312 if (e2 == NULL)
2313 e2 = p + STRLEN(p);
2314
2315 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2316 {
2317 // Not a single "." that means no extension is added.
2318 if (e2 - p + tmplen + 1 > sizeof(buf))
2319 {
2320 retval = FALSE;
2321 goto theend;
2322 }
2323 vim_strncpy(buf + tmplen, p, e2 - p);
2324 }
2325 if (executable_file((char *)buf, path))
2326 {
2327 retval = TRUE;
2328 goto theend;
2329 }
2330
2331 p = e2;
2332 }
2333
2334 p = e;
2335 }
2336
2337theend:
2338 free(pathextbuf);
2339 free(pathbuf);
2340 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002341}
2342
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002343#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2344 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002345/*
2346 * Bad parameter handler.
2347 *
2348 * Certain MS CRT functions will intentionally crash when passed invalid
2349 * parameters to highlight possible security holes. Setting this function as
2350 * the bad parameter handler will prevent the crash.
2351 *
2352 * In debug builds the parameters contain CRT information that might help track
2353 * down the source of a problem, but in non-debug builds the arguments are all
2354 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2355 * worth allowing these to make debugging of issues easier.
2356 */
2357 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002358bad_param_handler(const wchar_t *expression UNUSED,
2359 const wchar_t *function UNUSED,
2360 const wchar_t *file UNUSED,
2361 unsigned int line UNUSED,
2362 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002363{
2364}
2365
2366# define SET_INVALID_PARAM_HANDLER \
2367 ((void)_set_invalid_parameter_handler(bad_param_handler))
2368#else
2369# define SET_INVALID_PARAM_HANDLER
2370#endif
2371
Bram Moolenaar4f974752019-02-17 17:44:42 +01002372#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002373
2374/*
2375 * GUI version of mch_init().
2376 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002377 static void
2378mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002379{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002380# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002381 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002382# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002383
Bram Moolenaar0f873732019-12-05 20:28:46 +01002384 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002385 SET_INVALID_PARAM_HANDLER;
2386
Bram Moolenaar0f873732019-12-05 20:28:46 +01002387 // Let critical errors result in a failure, not in a dialog box. Required
2388 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002389 SetErrorMode(SEM_FAILCRITICALERRORS);
2390
Bram Moolenaar0f873732019-12-05 20:28:46 +01002391 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002392
Bram Moolenaar0f873732019-12-05 20:28:46 +01002393 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002394 Rows = 25;
2395 Columns = 80;
2396
Bram Moolenaar0f873732019-12-05 20:28:46 +01002397 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002398 {
2399 char_u vimrun_location[_MAX_PATH + 4];
2400
Bram Moolenaar0f873732019-12-05 20:28:46 +01002401 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002402 STRCPY(vimrun_location, exe_name);
2403 STRCPY(gettail(vimrun_location), "vimrun.exe");
2404 if (mch_getperm(vimrun_location) >= 0)
2405 {
2406 if (*skiptowhite(vimrun_location) != NUL)
2407 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002408 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002409 mch_memmove(vimrun_location + 1, vimrun_location,
2410 STRLEN(vimrun_location) + 1);
2411 *vimrun_location = '"';
2412 STRCPY(gettail(vimrun_location), "vimrun\" ");
2413 }
2414 else
2415 STRCPY(gettail(vimrun_location), "vimrun ");
2416
2417 vimrun_path = (char *)vim_strsave(vimrun_location);
2418 s_dont_use_vimrun = FALSE;
2419 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002420 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002421 s_dont_use_vimrun = FALSE;
2422
Bram Moolenaar0f873732019-12-05 20:28:46 +01002423 // Don't give the warning for a missing vimrun.exe right now, but only
2424 // when vimrun was supposed to be used. Don't bother people that do
2425 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002426 if (s_dont_use_vimrun)
2427 need_vimrun_warning = TRUE;
2428 }
2429
2430 /*
2431 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2432 * Otherwise the default "findstr /n" is used.
2433 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002434 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01002435 set_option_value_give_err((char_u *)"grepprg",
2436 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002437
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002438# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002439 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002440# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002441
2442 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002443}
2444
2445
Bram Moolenaar0f873732019-12-05 20:28:46 +01002446#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002447
2448#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002449
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002450# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2451# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002452
2453/*
2454 * ClearConsoleBuffer()
2455 * Description:
2456 * Clears the entire contents of the console screen buffer, using the
2457 * specified attribute.
2458 * Returns:
2459 * TRUE on success
2460 */
2461 static BOOL
2462ClearConsoleBuffer(WORD wAttribute)
2463{
2464 CONSOLE_SCREEN_BUFFER_INFO csbi;
2465 COORD coord;
2466 DWORD NumCells, dummy;
2467
2468 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2469 return FALSE;
2470
2471 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2472 coord.X = 0;
2473 coord.Y = 0;
2474 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2475 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002476 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002477 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2478 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002479 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002480
2481 return TRUE;
2482}
2483
2484/*
2485 * FitConsoleWindow()
2486 * Description:
2487 * Checks if the console window will fit within given buffer dimensions.
2488 * Also, if requested, will shrink the window to fit.
2489 * Returns:
2490 * TRUE on success
2491 */
2492 static BOOL
2493FitConsoleWindow(
2494 COORD dwBufferSize,
2495 BOOL WantAdjust)
2496{
2497 CONSOLE_SCREEN_BUFFER_INFO csbi;
2498 COORD dwWindowSize;
2499 BOOL NeedAdjust = FALSE;
2500
2501 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2502 {
2503 /*
2504 * A buffer resize will fail if the current console window does
2505 * not lie completely within that buffer. To avoid this, we might
2506 * have to move and possibly shrink the window.
2507 */
2508 if (csbi.srWindow.Right >= dwBufferSize.X)
2509 {
2510 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2511 if (dwWindowSize.X > dwBufferSize.X)
2512 dwWindowSize.X = dwBufferSize.X;
2513 csbi.srWindow.Right = dwBufferSize.X - 1;
2514 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2515 NeedAdjust = TRUE;
2516 }
2517 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2518 {
2519 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2520 if (dwWindowSize.Y > dwBufferSize.Y)
2521 dwWindowSize.Y = dwBufferSize.Y;
2522 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2523 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2524 NeedAdjust = TRUE;
2525 }
2526 if (NeedAdjust && WantAdjust)
2527 {
2528 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2529 return FALSE;
2530 }
2531 return TRUE;
2532 }
2533
2534 return FALSE;
2535}
2536
2537typedef struct ConsoleBufferStruct
2538{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002539 BOOL IsValid;
2540 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002541 PCHAR_INFO Buffer;
2542 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002543 PSMALL_RECT Regions;
2544 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002545} ConsoleBuffer;
2546
2547/*
2548 * SaveConsoleBuffer()
2549 * Description:
2550 * Saves important information about the console buffer, including the
2551 * actual buffer contents. The saved information is suitable for later
2552 * restoration by RestoreConsoleBuffer().
2553 * Returns:
2554 * TRUE if all information was saved; FALSE otherwise
2555 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2556 */
2557 static BOOL
2558SaveConsoleBuffer(
2559 ConsoleBuffer *cb)
2560{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002561 DWORD NumCells;
2562 COORD BufferCoord;
2563 SMALL_RECT ReadRegion;
2564 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002565 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002566
Bram Moolenaar071d4272004-06-13 20:20:40 +00002567 if (cb == NULL)
2568 return FALSE;
2569
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002570 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002571 {
2572 cb->IsValid = FALSE;
2573 return FALSE;
2574 }
2575 cb->IsValid = TRUE;
2576
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002577 /*
2578 * Allocate a buffer large enough to hold the entire console screen
2579 * buffer. If this ConsoleBuffer structure has already been initialized
2580 * with a buffer of the correct size, then just use that one.
2581 */
2582 if (!cb->IsValid || cb->Buffer == NULL ||
2583 cb->BufferSize.X != cb->Info.dwSize.X ||
2584 cb->BufferSize.Y != cb->Info.dwSize.Y)
2585 {
2586 cb->BufferSize.X = cb->Info.dwSize.X;
2587 cb->BufferSize.Y = cb->Info.dwSize.Y;
2588 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2589 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002590 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002591 if (cb->Buffer == NULL)
2592 return FALSE;
2593 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002594
2595 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002596 * We will now copy the console screen buffer into our buffer.
2597 * ReadConsoleOutput() seems to be limited as far as how much you
2598 * can read at a time. Empirically, this number seems to be about
2599 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2600 * in chunks until it is all copied. The chunks will all have the
2601 * same horizontal characteristics, so initialize them now. The
2602 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002603 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002604 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002605 ReadRegion.Left = 0;
2606 ReadRegion.Right = cb->Info.dwSize.X - 1;
2607 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002608
2609 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2610 if (cb->Regions == NULL || numregions != cb->NumRegions)
2611 {
2612 cb->NumRegions = numregions;
2613 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002614 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002615 if (cb->Regions == NULL)
2616 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002617 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002618 return FALSE;
2619 }
2620 }
2621
2622 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002623 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002624 /*
2625 * Read into position (0, Y) in our buffer.
2626 */
2627 BufferCoord.Y = Y;
2628 /*
2629 * Read the region whose top left corner is (0, Y) and whose bottom
2630 * right corner is (width - 1, Y + Y_incr - 1). This should define
2631 * a region of size width by Y_incr. Don't worry if this region is
2632 * too large for the remaining buffer; it will be cropped.
2633 */
2634 ReadRegion.Top = Y;
2635 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002636 if (!ReadConsoleOutputW(g_hConOut, // output handle
2637 cb->Buffer, // our buffer
2638 cb->BufferSize, // dimensions of our buffer
2639 BufferCoord, // offset in our buffer
2640 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002641 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002642 VIM_CLEAR(cb->Buffer);
2643 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002644 return FALSE;
2645 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002646 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002647 }
2648
2649 return TRUE;
2650}
2651
2652/*
2653 * RestoreConsoleBuffer()
2654 * Description:
2655 * Restores important information about the console buffer, including the
2656 * actual buffer contents, if desired. The information to restore is in
2657 * the same format used by SaveConsoleBuffer().
2658 * Returns:
2659 * TRUE on success
2660 */
2661 static BOOL
2662RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002663 ConsoleBuffer *cb,
2664 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002665{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002666 COORD BufferCoord;
2667 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002668 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002669
2670 if (cb == NULL || !cb->IsValid)
2671 return FALSE;
2672
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002673 /*
2674 * Before restoring the buffer contents, clear the current buffer, and
2675 * restore the cursor position and window information. Doing this now
2676 * prevents old buffer contents from "flashing" onto the screen.
2677 */
2678 if (RestoreScreen)
2679 ClearConsoleBuffer(cb->Info.wAttributes);
2680
2681 FitConsoleWindow(cb->Info.dwSize, TRUE);
2682 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2683 return FALSE;
2684 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2685 return FALSE;
2686
2687 if (!RestoreScreen)
2688 {
2689 /*
2690 * No need to restore the screen buffer contents, so we're done.
2691 */
2692 return TRUE;
2693 }
2694
2695 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2696 return FALSE;
2697 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2698 return FALSE;
2699
2700 /*
2701 * Restore the screen buffer contents.
2702 */
2703 if (cb->Buffer != NULL)
2704 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002705 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002706 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002707 BufferCoord.X = cb->Regions[i].Left;
2708 BufferCoord.Y = cb->Regions[i].Top;
2709 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01002710 if (!WriteConsoleOutputW(g_hConOut, // output handle
2711 cb->Buffer, // our buffer
2712 cb->BufferSize, // dimensions of our buffer
2713 BufferCoord, // offset in our buffer
2714 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02002715 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002716 }
2717 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002718
2719 return TRUE;
2720}
2721
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002722# define FEAT_RESTORE_ORIG_SCREEN
2723# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002724static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002725# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002726static ConsoleBuffer g_cbNonTermcap = { 0 };
2727static ConsoleBuffer g_cbTermcap = { 0 };
2728
Bram Moolenaar071d4272004-06-13 20:20:40 +00002729char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01002730HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00002731static HICON g_hOrigIconSmall = NULL;
2732static HICON g_hOrigIcon = NULL;
2733static HICON g_hVimIcon = NULL;
2734static BOOL g_fCanChangeIcon = FALSE;
2735
Bram Moolenaar071d4272004-06-13 20:20:40 +00002736/*
2737 * GetConsoleIcon()
2738 * Description:
2739 * Attempts to retrieve the small icon and/or the big icon currently in
2740 * use by a given window.
2741 * Returns:
2742 * TRUE on success
2743 */
2744 static BOOL
2745GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002746 HWND hWnd,
2747 HICON *phIconSmall,
2748 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002749{
2750 if (hWnd == NULL)
2751 return FALSE;
2752
2753 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002754 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2755 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002756 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002757 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2758 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002759 return TRUE;
2760}
2761
2762/*
2763 * SetConsoleIcon()
2764 * Description:
2765 * Attempts to change the small icon and/or the big icon currently in
2766 * use by a given window.
2767 * Returns:
2768 * TRUE on success
2769 */
2770 static BOOL
2771SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002772 HWND hWnd,
2773 HICON hIconSmall,
2774 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002775{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002776 if (hWnd == NULL)
2777 return FALSE;
2778
2779 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002780 SendMessage(hWnd, WM_SETICON,
2781 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002782 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002783 SendMessage(hWnd, WM_SETICON,
2784 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002785 return TRUE;
2786}
2787
2788/*
2789 * SaveConsoleTitleAndIcon()
2790 * Description:
2791 * Saves the current console window title in g_szOrigTitle, for later
2792 * restoration. Also, attempts to obtain a handle to the console window,
2793 * and use it to save the small and big icons currently in use by the
2794 * console window. This is not always possible on some versions of Windows;
2795 * nor is it possible when running Vim remotely using Telnet (since the
2796 * console window the user sees is owned by a remote process).
2797 */
2798 static void
2799SaveConsoleTitleAndIcon(void)
2800{
Bram Moolenaar0f873732019-12-05 20:28:46 +01002801 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002802 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2803 return;
2804
2805 /*
2806 * Obtain a handle to the console window using GetConsoleWindow() from
2807 * KERNEL32.DLL; we need to handle in order to change the window icon.
2808 * This function only exists on NT-based Windows, starting with Windows
2809 * 2000. On older operating systems, we can't change the window icon
2810 * anyway.
2811 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002812 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002813 if (g_hWnd == NULL)
2814 return;
2815
Bram Moolenaar0f873732019-12-05 20:28:46 +01002816 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002817 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2818 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2819 return;
2820
Bram Moolenaar0f873732019-12-05 20:28:46 +01002821 // Extract the first icon contained in the Vim executable.
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002822 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002823 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002824 if (g_hVimIcon != NULL)
2825 g_fCanChangeIcon = TRUE;
2826}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002827
2828static int g_fWindInitCalled = FALSE;
2829static int g_fTermcapMode = FALSE;
2830static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002831
2832/*
2833 * non-GUI version of mch_init().
2834 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002835 static void
2836mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002837{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002838# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002839 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002840# endif
2841# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002842 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002843# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002844
Bram Moolenaar0f873732019-12-05 20:28:46 +01002845 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002846 SET_INVALID_PARAM_HANDLER;
2847
Bram Moolenaar0f873732019-12-05 20:28:46 +01002848 // Let critical errors result in a failure, not in a dialog box. Required
2849 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002850 SetErrorMode(SEM_FAILCRITICALERRORS);
2851
Bram Moolenaar0f873732019-12-05 20:28:46 +01002852 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002853 out_flush();
2854
Bram Moolenaar0f873732019-12-05 20:28:46 +01002855 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00002856 if (read_cmd_fd == 0)
2857 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2858 else
2859 create_conin();
2860 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2861
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002862# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01002863 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002864 SaveConsoleBuffer(&g_cbOrig);
2865 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002866# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01002867 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002868 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2869 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002870# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002871 if (cterm_normal_fg_color == 0)
2872 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2873 if (cterm_normal_bg_color == 0)
2874 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2875
Bram Moolenaarbdace832019-03-02 10:13:42 +01002876 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002877 g_color_index_fg = g_attrDefault & 0xf;
2878 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2879
Bram Moolenaar0f873732019-12-05 20:28:46 +01002880 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00002881 update_tcap(g_attrCurrent);
2882
2883 GetConsoleCursorInfo(g_hConOut, &g_cci);
2884 GetConsoleMode(g_hConIn, &g_cmodein);
2885 GetConsoleMode(g_hConOut, &g_cmodeout);
2886
Bram Moolenaar071d4272004-06-13 20:20:40 +00002887 SaveConsoleTitleAndIcon();
2888 /*
2889 * Set both the small and big icons of the console window to Vim's icon.
2890 * Note that Vim presently only has one size of icon (32x32), but it
2891 * automatically gets scaled down to 16x16 when setting the small icon.
2892 */
2893 if (g_fCanChangeIcon)
2894 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002895
2896 ui_get_shellsize();
2897
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002898# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002899 fdDump = fopen("dump", "wt");
2900
2901 if (fdDump)
2902 {
2903 time_t t;
2904
2905 time(&t);
2906 fputs(ctime(&t), fdDump);
2907 fflush(fdDump);
2908 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002909# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002910
2911 g_fWindInitCalled = TRUE;
2912
Bram Moolenaar071d4272004-06-13 20:20:40 +00002913 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002914
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002915# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002916 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002917# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002918
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02002919 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002920 vtp_init();
Bram Moolenaar06b7b582020-05-30 17:49:25 +02002921 wt_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002922}
2923
2924/*
2925 * non-GUI version of mch_exit().
2926 * Shut down and exit with status `r'
2927 * Careful: mch_exit() may be called before mch_init()!
2928 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002929 static void
2930mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002931{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002932 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002933
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002934 vtp_exit();
2935
Bram Moolenaar955f1982017-02-05 15:10:51 +01002936 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002937 if (g_fWindInitCalled)
2938 settmode(TMODE_COOK);
2939
Bram Moolenaar0f873732019-12-05 20:28:46 +01002940 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00002941
2942 if (g_fWindInitCalled)
2943 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02002944 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002945 /*
2946 * Restore both the small and big icons of the console window to
2947 * what they were at startup. Don't do this when the window is
2948 * closed, Vim would hang here.
2949 */
2950 if (g_fCanChangeIcon && !g_fForceExit)
2951 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002952
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002953# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002954 if (fdDump)
2955 {
2956 time_t t;
2957
2958 time(&t);
2959 fputs(ctime(&t), fdDump);
2960 fclose(fdDump);
2961 }
2962 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002963# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002964 }
2965
2966 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02002967 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002968 SetConsoleMode(g_hConOut, g_cmodeout);
2969
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002970# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00002971 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002972# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002973
2974 exit(r);
2975}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002976#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002977
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002978 void
2979mch_init(void)
2980{
2981#ifdef VIMDLL
2982 if (gui.starting)
2983 mch_init_g();
2984 else
2985 mch_init_c();
2986#elif defined(FEAT_GUI_MSWIN)
2987 mch_init_g();
2988#else
2989 mch_init_c();
2990#endif
2991}
2992
2993 void
2994mch_exit(int r)
2995{
Bram Moolenaar173d8412020-04-19 14:02:26 +02002996#ifdef FEAT_NETBEANS_INTG
2997 netbeans_send_disconnect();
2998#endif
2999
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003000#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003001 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003002 mch_exit_g(r);
3003 else
3004 mch_exit_c(r);
3005#elif defined(FEAT_GUI_MSWIN)
3006 mch_exit_g(r);
3007#else
3008 mch_exit_c(r);
3009#endif
3010}
3011
Bram Moolenaar071d4272004-06-13 20:20:40 +00003012/*
3013 * Do we have an interactive window?
3014 */
3015 int
3016mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003017 int argc UNUSED,
3018 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003019{
3020 get_exe_name();
3021
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003022#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003023 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003024#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003025# ifdef VIMDLL
3026 if (gui.in_use)
3027 return OK;
3028# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003029 if (isatty(1))
3030 return OK;
3031 return FAIL;
3032#endif
3033}
3034
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003035/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003036 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003037 * When "len" is > 0, also expand short to long filenames.
3038 */
3039 void
3040fname_case(
3041 char_u *name,
3042 int len)
3043{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003044 int flen;
3045 WCHAR *p;
3046 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003047
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003048 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003049 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003050 return;
3051
3052 slash_adjust(name);
3053
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003054 p = enc_to_utf16(name, NULL);
3055 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003056 return;
3057
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003058 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003059 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003060 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003061
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003062 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003063 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003064 if (len > 0 || flen >= (int)STRLEN(q))
3065 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3066 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003067 }
3068 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003069 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003070}
3071
3072
3073/*
3074 * Insert user name in s[len].
3075 */
3076 int
3077mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003078 char_u *s,
3079 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003080{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003081 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003082 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003083
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003084 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003085 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003086 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003087
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003088 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003089 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003090 vim_strncpy(s, p, len - 1);
3091 vim_free(p);
3092 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003093 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003094 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003095 s[0] = NUL;
3096 return FAIL;
3097}
3098
3099
3100/*
3101 * Insert host name in s[len].
3102 */
3103 void
3104mch_get_host_name(
3105 char_u *s,
3106 int len)
3107{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003108 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003109 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003110
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003111 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003112 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003113 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003114
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003115 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003116 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003117 vim_strncpy(s, p, len - 1);
3118 vim_free(p);
3119 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003120 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003121 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003122}
3123
3124
3125/*
3126 * return process ID
3127 */
3128 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003129mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003130{
3131 return (long)GetCurrentProcessId();
3132}
3133
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003134/*
3135 * return TRUE if process "pid" is still running
3136 */
3137 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003138mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003139{
3140 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3141 DWORD status = 0;
3142 int ret = FALSE;
3143
3144 if (hProcess == NULL)
3145 return FALSE; // might not have access
3146 if (GetExitCodeProcess(hProcess, &status) )
3147 ret = status == STILL_ACTIVE;
3148 CloseHandle(hProcess);
3149 return ret;
3150}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003151
3152/*
3153 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3154 * Return OK for success, FAIL for failure.
3155 */
3156 int
3157mch_dirname(
3158 char_u *buf,
3159 int len)
3160{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003161 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003162
Bram Moolenaar071d4272004-06-13 20:20:40 +00003163 /*
3164 * Originally this was:
3165 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3166 * But the Win32s known bug list says that getcwd() doesn't work
3167 * so use the Win32 system call instead. <Negri>
3168 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003169 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003170 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003171 WCHAR wcbuf[_MAX_PATH + 1];
3172 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003173
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003174 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003175 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003176 p = utf16_to_enc(wcbuf, NULL);
3177 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003178 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003179 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003180 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003181 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003182 }
3183 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003184 if (p == NULL)
3185 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003186
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003187 if (p != NULL)
3188 {
3189 vim_strncpy(buf, p, len - 1);
3190 vim_free(p);
3191 return OK;
3192 }
3193 }
3194 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003195}
3196
3197/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003198 * Get file permissions for "name".
3199 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003200 */
3201 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003202mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003203{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003204 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003205 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003206
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003207 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003208 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003209}
3210
3211
3212/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003213 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003214 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003215 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003216 */
3217 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003218mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003219{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003220 long n;
3221 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003222
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003223 p = enc_to_utf16(name, NULL);
3224 if (p == NULL)
3225 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003226
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003227 n = _wchmod(p, perm);
3228 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003229 if (n == -1)
3230 return FAIL;
3231
3232 win32_set_archive(name);
3233
3234 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003235}
3236
3237/*
3238 * Set hidden flag for "name".
3239 */
3240 void
3241mch_hide(char_u *name)
3242{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003243 int attrs = win32_getattrs(name);
3244 if (attrs == -1)
3245 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003246
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003247 attrs |= FILE_ATTRIBUTE_HIDDEN;
3248 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003249}
3250
3251/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003252 * Return TRUE if file "name" exists and is hidden.
3253 */
3254 int
3255mch_ishidden(char_u *name)
3256{
3257 int f = win32_getattrs(name);
3258
3259 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003260 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003261
3262 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3263}
3264
3265/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003266 * return TRUE if "name" is a directory
3267 * return FALSE if "name" is not a directory or upon error
3268 */
3269 int
3270mch_isdir(char_u *name)
3271{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003272 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003273
3274 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003275 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003276
3277 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3278}
3279
3280/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003281 * return TRUE if "name" is a directory, NOT a symlink to a directory
3282 * return FALSE if "name" is not a directory
3283 * return FALSE for error
3284 */
3285 int
3286mch_isrealdir(char_u *name)
3287{
3288 return mch_isdir(name) && !mch_is_symbolic_link(name);
3289}
3290
3291/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003292 * Create directory "name".
3293 * Return 0 on success, -1 on error.
3294 */
3295 int
3296mch_mkdir(char_u *name)
3297{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003298 WCHAR *p;
3299 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003300
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003301 p = enc_to_utf16(name, NULL);
3302 if (p == NULL)
3303 return -1;
3304 retval = _wmkdir(p);
3305 vim_free(p);
3306 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003307}
3308
3309/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003310 * Delete directory "name".
3311 * Return 0 on success, -1 on error.
3312 */
3313 int
3314mch_rmdir(char_u *name)
3315{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003316 WCHAR *p;
3317 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003318
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003319 p = enc_to_utf16(name, NULL);
3320 if (p == NULL)
3321 return -1;
3322 retval = _wrmdir(p);
3323 vim_free(p);
3324 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003325}
3326
3327/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003328 * Return TRUE if file "fname" has more than one link.
3329 */
3330 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003331mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003332{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003333 BY_HANDLE_FILE_INFORMATION info;
3334
3335 return win32_fileinfo(fname, &info) == FILEINFO_OK
3336 && info.nNumberOfLinks > 1;
3337}
3338
3339/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003340 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003341 */
3342 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003343mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003344{
3345 HANDLE hFind;
3346 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003347 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003348 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003349 WIN32_FIND_DATAW findDataW;
3350
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003351 wn = enc_to_utf16(name, NULL);
3352 if (wn == NULL)
3353 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003354
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003355 hFind = FindFirstFileW(wn, &findDataW);
3356 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003357 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003358 {
3359 fileFlags = findDataW.dwFileAttributes;
3360 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003361 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003362 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003363
3364 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003365 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3366 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003367 res = TRUE;
3368
3369 return res;
3370}
3371
3372/*
3373 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3374 * link.
3375 */
3376 int
3377mch_is_linked(char_u *fname)
3378{
3379 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3380 return TRUE;
3381 return FALSE;
3382}
3383
3384/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003385 * Get the by-handle-file-information for "fname".
3386 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003387 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003388 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3389 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3390 */
3391 int
3392win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3393{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003394 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003395 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003396 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003397
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003398 wn = enc_to_utf16(fname, NULL);
3399 if (wn == NULL)
3400 return FILEINFO_ENC_FAIL;
3401
3402 hFile = CreateFileW(wn, // file name
3403 GENERIC_READ, // access mode
3404 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3405 NULL, // security descriptor
3406 OPEN_EXISTING, // creation disposition
3407 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3408 NULL); // handle to template file
3409 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003410
3411 if (hFile != INVALID_HANDLE_VALUE)
3412 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003413 if (GetFileInformationByHandle(hFile, info) != 0)
3414 res = FILEINFO_OK;
3415 else
3416 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003417 CloseHandle(hFile);
3418 }
3419
Bram Moolenaar03f48552006-02-28 23:52:23 +00003420 return res;
3421}
3422
3423/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003424 * get file attributes for `name'
3425 * -1 : error
3426 * else FILE_ATTRIBUTE_* defined in winnt.h
3427 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003428 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003429win32_getattrs(char_u *name)
3430{
3431 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003432 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003433
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003434 p = enc_to_utf16(name, NULL);
3435 if (p == NULL)
3436 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003437
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003438 attr = GetFileAttributesW(p);
3439 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003440
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003441 return attr;
3442}
3443
3444/*
3445 * set file attributes for `name' to `attrs'
3446 *
3447 * return -1 for failure, 0 otherwise
3448 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003449 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003450win32_setattrs(char_u *name, int attrs)
3451{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003452 int res;
3453 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003454
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003455 p = enc_to_utf16(name, NULL);
3456 if (p == NULL)
3457 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003458
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003459 res = SetFileAttributesW(p, attrs);
3460 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003461
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003462 return res ? 0 : -1;
3463}
3464
3465/*
3466 * Set archive flag for "name".
3467 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003468 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003469win32_set_archive(char_u *name)
3470{
3471 int attrs = win32_getattrs(name);
3472 if (attrs == -1)
3473 return -1;
3474
3475 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3476 return win32_setattrs(name, attrs);
3477}
3478
3479/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003480 * Return TRUE if file or directory "name" is writable (not readonly).
3481 * Strange semantics of Win32: a readonly directory is writable, but you can't
3482 * delete a file. Let's say this means it is writable.
3483 */
3484 int
3485mch_writable(char_u *name)
3486{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003487 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003488
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003489 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3490 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003491}
3492
Bram Moolenaar071d4272004-06-13 20:20:40 +00003493/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003494 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003495 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003496 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3497 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003498 */
3499 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01003500mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003501{
Bram Moolenaar95da1362020-05-30 18:37:55 +02003502 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003503}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003504
3505/*
3506 * Check what "name" is:
3507 * NODE_NORMAL: file or directory (or doesn't exist)
3508 * NODE_WRITABLE: writable device, socket, fifo, etc.
3509 * NODE_OTHER: non-writable things
3510 */
3511 int
3512mch_nodetype(char_u *name)
3513{
3514 HANDLE hFile;
3515 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003516 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003517
Bram Moolenaar0f873732019-12-05 20:28:46 +01003518 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3519 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3520 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00003521 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3522 return NODE_WRITABLE;
3523
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003524 wn = enc_to_utf16(name, NULL);
3525 if (wn == NULL)
3526 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003527
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003528 hFile = CreateFileW(wn, // file name
3529 GENERIC_WRITE, // access mode
3530 0, // share mode
3531 NULL, // security descriptor
3532 OPEN_EXISTING, // creation disposition
3533 0, // file attributes
3534 NULL); // handle to template file
3535 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003536 if (hFile == INVALID_HANDLE_VALUE)
3537 return NODE_NORMAL;
3538
3539 type = GetFileType(hFile);
3540 CloseHandle(hFile);
3541 if (type == FILE_TYPE_CHAR)
3542 return NODE_WRITABLE;
3543 if (type == FILE_TYPE_DISK)
3544 return NODE_NORMAL;
3545 return NODE_OTHER;
3546}
3547
3548#ifdef HAVE_ACL
3549struct my_acl
3550{
3551 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3552 PSID pSidOwner;
3553 PSID pSidGroup;
3554 PACL pDacl;
3555 PACL pSacl;
3556};
3557#endif
3558
3559/*
3560 * Return a pointer to the ACL of file "fname" in allocated memory.
3561 * Return NULL if the ACL is not available for whatever reason.
3562 */
3563 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003564mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003565{
3566#ifndef HAVE_ACL
3567 return (vim_acl_T)NULL;
3568#else
3569 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003570 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003571
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003572 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003573 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003574 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003575 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003576
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003577 wn = enc_to_utf16(fname, NULL);
3578 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003579 {
3580 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003581 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003582 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003583
3584 // Try to retrieve the entire security descriptor.
3585 err = GetNamedSecurityInfoW(
3586 wn, // Abstract filename
3587 SE_FILE_OBJECT, // File Object
3588 OWNER_SECURITY_INFORMATION |
3589 GROUP_SECURITY_INFORMATION |
3590 DACL_SECURITY_INFORMATION |
3591 SACL_SECURITY_INFORMATION,
3592 &p->pSidOwner, // Ownership information.
3593 &p->pSidGroup, // Group membership.
3594 &p->pDacl, // Discretionary information.
3595 &p->pSacl, // For auditing purposes.
3596 &p->pSecurityDescriptor);
3597 if (err == ERROR_ACCESS_DENIED ||
3598 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003599 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003600 // Retrieve only DACL.
3601 (void)GetNamedSecurityInfoW(
3602 wn,
3603 SE_FILE_OBJECT,
3604 DACL_SECURITY_INFORMATION,
3605 NULL,
3606 NULL,
3607 &p->pDacl,
3608 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003609 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003610 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003611 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003612 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003613 mch_free_acl((vim_acl_T)p);
3614 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003615 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003616 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003617 }
3618
3619 return (vim_acl_T)p;
3620#endif
3621}
3622
Bram Moolenaar27515922013-06-29 15:36:26 +02003623#ifdef HAVE_ACL
3624/*
3625 * Check if "acl" contains inherited ACE.
3626 */
3627 static BOOL
3628is_acl_inherited(PACL acl)
3629{
3630 DWORD i;
3631 ACL_SIZE_INFORMATION acl_info;
3632 PACCESS_ALLOWED_ACE ace;
3633
3634 acl_info.AceCount = 0;
3635 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3636 for (i = 0; i < acl_info.AceCount; i++)
3637 {
3638 GetAce(acl, i, (LPVOID *)&ace);
3639 if (ace->Header.AceFlags & INHERITED_ACE)
3640 return TRUE;
3641 }
3642 return FALSE;
3643}
3644#endif
3645
Bram Moolenaar071d4272004-06-13 20:20:40 +00003646/*
3647 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3648 * Errors are ignored.
3649 * This must only be called with "acl" equal to what mch_get_acl() returned.
3650 */
3651 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003652mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003653{
3654#ifdef HAVE_ACL
3655 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003656 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003657 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003658
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003659 if (p == NULL)
3660 return;
3661
3662 wn = enc_to_utf16(fname, NULL);
3663 if (wn == NULL)
3664 return;
3665
3666 // Set security flags
3667 if (p->pSidOwner)
3668 sec_info |= OWNER_SECURITY_INFORMATION;
3669 if (p->pSidGroup)
3670 sec_info |= GROUP_SECURITY_INFORMATION;
3671 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003672 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003673 sec_info |= DACL_SECURITY_INFORMATION;
3674 // Do not inherit its parent's DACL.
3675 // If the DACL is inherited, Cygwin permissions would be changed.
3676 if (!is_acl_inherited(p->pDacl))
3677 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003678 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003679 if (p->pSacl)
3680 sec_info |= SACL_SECURITY_INFORMATION;
3681
3682 (void)SetNamedSecurityInfoW(
3683 wn, // Abstract filename
3684 SE_FILE_OBJECT, // File Object
3685 sec_info,
3686 p->pSidOwner, // Ownership information.
3687 p->pSidGroup, // Group membership.
3688 p->pDacl, // Discretionary information.
3689 p->pSacl // For auditing purposes.
3690 );
3691 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003692#endif
3693}
3694
3695 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003696mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003697{
3698#ifdef HAVE_ACL
3699 struct my_acl *p = (struct my_acl *)acl;
3700
3701 if (p != NULL)
3702 {
3703 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3704 vim_free(p);
3705 }
3706#endif
3707}
3708
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003709#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003710
3711/*
3712 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3713 */
3714 static BOOL WINAPI
3715handler_routine(
3716 DWORD dwCtrlType)
3717{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003718 INPUT_RECORD ir;
3719 DWORD out;
3720
Bram Moolenaar071d4272004-06-13 20:20:40 +00003721 switch (dwCtrlType)
3722 {
3723 case CTRL_C_EVENT:
3724 if (ctrl_c_interrupts)
3725 g_fCtrlCPressed = TRUE;
3726 return TRUE;
3727
3728 case CTRL_BREAK_EVENT:
3729 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003730 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003731 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02003732 ir.EventType = KEY_EVENT;
3733 ir.Event.KeyEvent.bKeyDown = TRUE;
3734 ir.Event.KeyEvent.wRepeatCount = 1;
3735 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3736 ir.Event.KeyEvent.wVirtualScanCode = 0;
3737 ir.Event.KeyEvent.dwControlKeyState = 0;
3738 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3739 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003740 return TRUE;
3741
Bram Moolenaar0f873732019-12-05 20:28:46 +01003742 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00003743 case CTRL_CLOSE_EVENT:
3744 case CTRL_LOGOFF_EVENT:
3745 case CTRL_SHUTDOWN_EVENT:
3746 windgoto((int)Rows - 1, 0);
3747 g_fForceExit = TRUE;
3748
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003749 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003750 (dwCtrlType == CTRL_CLOSE_EVENT
3751 ? _("close")
3752 : dwCtrlType == CTRL_LOGOFF_EVENT
3753 ? _("logoff")
3754 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003755# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00003756 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003757# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003758
Bram Moolenaar0f873732019-12-05 20:28:46 +01003759 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00003760
Bram Moolenaar0f873732019-12-05 20:28:46 +01003761 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00003762
3763 default:
3764 return FALSE;
3765 }
3766}
3767
3768
3769/*
3770 * set the tty in (raw) ? "raw" : "cooked" mode
3771 */
3772 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02003773mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003774{
3775 DWORD cmodein;
3776 DWORD cmodeout;
3777 BOOL bEnableHandler;
3778
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003779# ifdef VIMDLL
3780 if (gui.in_use)
3781 return;
3782# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003783 GetConsoleMode(g_hConIn, &cmodein);
3784 GetConsoleMode(g_hConOut, &cmodeout);
3785 if (tmode == TMODE_RAW)
3786 {
3787 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3788 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003789 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003790 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003791 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003792 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
3793 }
3794 else
3795 {
3796 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
3797 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003798 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003799# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01003800 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
3801 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003802 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003803# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003804 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003805# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003806 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003807 bEnableHandler = TRUE;
3808 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01003809 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00003810 {
3811 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3812 ENABLE_ECHO_INPUT);
3813 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3814 bEnableHandler = FALSE;
3815 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003816 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003817 SetConsoleMode(g_hConOut, cmodeout);
3818 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3819
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003820# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003821 if (fdDump)
3822 {
3823 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3824 tmode == TMODE_RAW ? "raw" :
3825 tmode == TMODE_COOK ? "cooked" : "normal",
3826 cmodein, cmodeout);
3827 fflush(fdDump);
3828 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003829# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003830}
3831
3832
3833/*
3834 * Get the size of the current window in `Rows' and `Columns'
3835 * Return OK when size could be determined, FAIL otherwise.
3836 */
3837 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003838mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003839{
3840 CONSOLE_SCREEN_BUFFER_INFO csbi;
3841
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003842# ifdef VIMDLL
3843 if (gui.in_use)
3844 return OK;
3845# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003846 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3847 {
3848 /*
3849 * For some reason, we are trying to get the screen dimensions
3850 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3851 * variables are really intended to mean the size of Vim screen
3852 * while in termcap mode.
3853 */
3854 Rows = g_cbTermcap.Info.dwSize.Y;
3855 Columns = g_cbTermcap.Info.dwSize.X;
3856 }
3857 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3858 {
3859 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3860 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3861 }
3862 else
3863 {
3864 Rows = 25;
3865 Columns = 80;
3866 }
3867 return OK;
3868}
3869
3870/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003871 * Resize console buffer to 'COORD'
3872 */
3873 static void
3874ResizeConBuf(
3875 HANDLE hConsole,
3876 COORD coordScreen)
3877{
3878 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3879 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003880# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003881 if (fdDump)
3882 {
3883 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3884 GetLastError());
3885 fflush(fdDump);
3886 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003887# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003888 }
3889}
3890
3891/*
3892 * Resize console window size to 'srWindowRect'
3893 */
3894 static void
3895ResizeWindow(
3896 HANDLE hConsole,
3897 SMALL_RECT srWindowRect)
3898{
3899 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
3900 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003901# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003902 if (fdDump)
3903 {
3904 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3905 GetLastError());
3906 fflush(fdDump);
3907 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003908# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003909 }
3910}
3911
3912/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003913 * Set a console window to `xSize' * `ySize'
3914 */
3915 static void
3916ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003917 HANDLE hConsole,
3918 int xSize,
3919 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003920{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003921 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
3922 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003923 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003924 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02003925 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003926
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003927# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003928 if (fdDump)
3929 {
3930 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3931 fflush(fdDump);
3932 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003933# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003934
Bram Moolenaar0f873732019-12-05 20:28:46 +01003935 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00003936 coordScreen = GetLargestConsoleWindowSize(hConsole);
3937
Bram Moolenaar0f873732019-12-05 20:28:46 +01003938 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00003939 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3940 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3941 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3942
3943 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3944 {
3945 int sx, sy;
3946
3947 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3948 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3949 if (sy < ySize || sx < xSize)
3950 {
3951 /*
3952 * Increasing number of lines/columns, do buffer first.
3953 * Use the maximal size in x and y direction.
3954 */
3955 if (sy < ySize)
3956 coordScreen.Y = ySize;
3957 else
3958 coordScreen.Y = sy;
3959 if (sx < xSize)
3960 coordScreen.X = xSize;
3961 else
3962 coordScreen.X = sx;
3963 SetConsoleScreenBufferSize(hConsole, coordScreen);
3964 }
3965 }
3966
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003967 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003968 coordScreen.X = xSize;
3969 coordScreen.Y = ySize;
3970
Bram Moolenaar2551c032018-08-23 22:38:31 +02003971 // In the new console call API, only the first time in reverse order
3972 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003973 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003974 ResizeWindow(hConsole, srWindowRect);
3975 ResizeConBuf(hConsole, coordScreen);
3976 }
3977 else
3978 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003979 // Workaround for a Windows 10 bug
3980 cursor.X = srWindowRect.Left;
3981 cursor.Y = srWindowRect.Top;
3982 SetConsoleCursorPosition(hConsole, cursor);
3983
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003984 ResizeConBuf(hConsole, coordScreen);
3985 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02003986 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003987 }
3988}
3989
3990
3991/*
3992 * Set the console window to `Rows' * `Columns'
3993 */
3994 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003995mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003996{
3997 COORD coordScreen;
3998
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003999# ifdef VIMDLL
4000 if (gui.in_use)
4001 return;
4002# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004003 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004004 if (suppress_winsize != 0)
4005 {
4006 suppress_winsize = 2;
4007 return;
4008 }
4009
4010 if (term_console)
4011 {
4012 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4013
Bram Moolenaar0f873732019-12-05 20:28:46 +01004014 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004015 if (Rows > coordScreen.Y)
4016 Rows = coordScreen.Y;
4017 if (Columns > coordScreen.X)
4018 Columns = coordScreen.X;
4019
4020 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4021 }
4022}
4023
4024/*
4025 * Rows and/or Columns has changed.
4026 */
4027 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004028mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004029{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004030# ifdef VIMDLL
4031 if (gui.in_use)
4032 return;
4033# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004034 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4035}
4036
4037
4038/*
4039 * Called when started up, to set the winsize that was delayed.
4040 */
4041 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004042mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004043{
4044 if (suppress_winsize == 2)
4045 {
4046 suppress_winsize = 0;
4047 mch_set_shellsize();
4048 shell_resized();
4049 }
4050 suppress_winsize = 0;
4051}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004052#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004053
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004054 static BOOL
4055vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004056 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004057 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004058 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004059 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004060 PROCESS_INFORMATION *pi,
4061 LPVOID *env,
4062 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004063{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004064 BOOL ret = FALSE;
4065 WCHAR *wcmd, *wcwd = NULL;
4066
4067 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4068 if (wcmd == NULL)
4069 return FALSE;
4070 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004071 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004072 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4073 if (wcwd == NULL)
4074 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004075 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004076
4077 ret = CreateProcessW(
4078 NULL, // Executable name
4079 wcmd, // Command to execute
4080 NULL, // Process security attributes
4081 NULL, // Thread security attributes
4082 inherit_handles, // Inherit handles
4083 flags, // Creation flags
4084 env, // Environment
4085 wcwd, // Current directory
4086 (LPSTARTUPINFOW)si, // Startup information
4087 pi); // Process information
4088theend:
4089 vim_free(wcmd);
4090 vim_free(wcwd);
4091 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004092}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004093
4094
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004095 static HINSTANCE
4096vim_shell_execute(
4097 char *cmd,
4098 INT n_show_cmd)
4099{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004100 HINSTANCE ret;
4101 WCHAR *wcmd;
4102
4103 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4104 if (wcmd == NULL)
4105 return (HINSTANCE) 0;
4106
4107 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4108 vim_free(wcmd);
4109 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004110}
4111
4112
Bram Moolenaar4f974752019-02-17 17:44:42 +01004113#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004114
4115/*
4116 * Specialised version of system() for Win32 GUI mode.
4117 * This version proceeds as follows:
4118 * 1. Create a console window for use by the subprocess
4119 * 2. Run the subprocess (it gets the allocated console by default)
4120 * 3. Wait for the subprocess to terminate and get its exit code
4121 * 4. Prompt the user to press a key to close the console window
4122 */
4123 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004124mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004125{
4126 STARTUPINFO si;
4127 PROCESS_INFORMATION pi;
4128 DWORD ret = 0;
4129 HWND hwnd = GetFocus();
4130
4131 si.cb = sizeof(si);
4132 si.lpReserved = NULL;
4133 si.lpDesktop = NULL;
4134 si.lpTitle = NULL;
4135 si.dwFlags = STARTF_USESHOWWINDOW;
4136 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004137 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004138 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004139 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004140 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004141 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004142 else
4143 si.wShowWindow = SW_SHOWNORMAL;
4144 si.cbReserved2 = 0;
4145 si.lpReserved2 = NULL;
4146
Bram Moolenaar0f873732019-12-05 20:28:46 +01004147 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004148 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004149 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4150 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004151
Bram Moolenaar0f873732019-12-05 20:28:46 +01004152 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004153 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004154# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004155 int delay = 1;
4156
Bram Moolenaar0f873732019-12-05 20:28:46 +01004157 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004158 for (;;)
4159 {
4160 MSG msg;
4161
K.Takatab7057bd2022-01-21 11:37:07 +00004162 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004163 {
4164 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004165 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004166 delay = 1;
4167 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004168 }
4169 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4170 break;
4171
Bram Moolenaar0f873732019-12-05 20:28:46 +01004172 // We start waiting for a very short time and then increase it, so
4173 // that we respond quickly when the process is quick, and don't
4174 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004175 if (delay < 50)
4176 delay += 10;
4177 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004178# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004179 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004180# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004181
Bram Moolenaar0f873732019-12-05 20:28:46 +01004182 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004183 GetExitCodeProcess(pi.hProcess, &ret);
4184 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004185
Bram Moolenaar0f873732019-12-05 20:28:46 +01004186 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004187 CloseHandle(pi.hThread);
4188 CloseHandle(pi.hProcess);
4189
Bram Moolenaar0f873732019-12-05 20:28:46 +01004190 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004191 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4192
4193 return ret;
4194}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004195
4196/*
4197 * Thread launched by the gui to send the current buffer data to the
4198 * process. This way avoid to hang up vim totally if the children
4199 * process take a long time to process the lines.
4200 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004201 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004202sub_process_writer(LPVOID param)
4203{
4204 HANDLE g_hChildStd_IN_Wr = param;
4205 linenr_T lnum = curbuf->b_op_start.lnum;
4206 DWORD len = 0;
4207 DWORD l;
4208 char_u *lp = ml_get(lnum);
4209 char_u *s;
4210 int written = 0;
4211
4212 for (;;)
4213 {
4214 l = (DWORD)STRLEN(lp + written);
4215 if (l == 0)
4216 len = 0;
4217 else if (lp[written] == NL)
4218 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004219 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004220 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4221 }
4222 else
4223 {
4224 s = vim_strchr(lp + written, NL);
4225 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4226 s == NULL ? l : (DWORD)(s - (lp + written)),
4227 &len, NULL);
4228 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004229 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004230 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004231 // Finished a line, add a NL, unless this line should not have
4232 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004233 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004234 || (!curbuf->b_p_bin
4235 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004236 || (lnum != curbuf->b_no_eol_lnum
4237 && (lnum != curbuf->b_ml.ml_line_count
4238 || curbuf->b_p_eol)))
4239 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004240 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4241 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004242 }
4243
4244 ++lnum;
4245 if (lnum > curbuf->b_op_end.lnum)
4246 break;
4247
4248 lp = ml_get(lnum);
4249 written = 0;
4250 }
4251 else if (len > 0)
4252 written += len;
4253 }
4254
Bram Moolenaar0f873732019-12-05 20:28:46 +01004255 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004256 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004257 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004258}
4259
4260
Bram Moolenaar0f873732019-12-05 20:28:46 +01004261# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004262
4263/*
4264 * This function read from the children's stdout and write the
4265 * data on screen or in the buffer accordingly.
4266 */
4267 static void
4268dump_pipe(int options,
4269 HANDLE g_hChildStd_OUT_Rd,
4270 garray_T *ga,
4271 char_u buffer[],
4272 DWORD *buffer_off)
4273{
4274 DWORD availableBytes = 0;
4275 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004276 int ret;
4277 DWORD len;
4278 DWORD toRead;
4279 int repeatCount;
4280
Bram Moolenaar0f873732019-12-05 20:28:46 +01004281 // we query the pipe to see if there is any data to read
4282 // to avoid to perform a blocking read
4283 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4284 NULL, // optional buffer
4285 0, // buffer size
4286 NULL, // number of read bytes
4287 &availableBytes, // available bytes total
4288 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004289
4290 repeatCount = 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004291 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004292 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004293 {
4294 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004295 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004296 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004297 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004298
Bram Moolenaar0f873732019-12-05 20:28:46 +01004299 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004300 if (len == 0)
4301 break;
4302
4303 availableBytes -= len;
4304
4305 if (options & SHELL_READ)
4306 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004307 // Do NUL -> NL translation, append NL separated
4308 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004309 for (i = 0; i < len; ++i)
4310 {
4311 if (buffer[i] == NL)
4312 append_ga_line(ga);
4313 else if (buffer[i] == NUL)
4314 ga_append(ga, NL);
4315 else
4316 ga_append(ga, buffer[i]);
4317 }
4318 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004319 else if (has_mbyte)
4320 {
4321 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004322 int c;
4323 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004324
4325 len += *buffer_off;
4326 buffer[len] = NUL;
4327
Bram Moolenaar0f873732019-12-05 20:28:46 +01004328 // Check if the last character in buffer[] is
4329 // incomplete, keep these bytes for the next
4330 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004331 for (p = buffer; p < buffer + len; p += l)
4332 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004333 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004334 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004335 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004336 else if (MB_BYTE2LEN(*p) != l)
4337 break;
4338 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004339 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004340 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004341 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004342 if (len >= 12)
4343 ++p;
4344 else
4345 {
4346 *buffer_off = len;
4347 return;
4348 }
4349 }
4350 c = *p;
4351 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004352 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004353 if (p < buffer + len)
4354 {
4355 *p = c;
4356 *buffer_off = (DWORD)((buffer + len) - p);
4357 mch_memmove(buffer, p, *buffer_off);
4358 return;
4359 }
4360 *buffer_off = 0;
4361 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004362 else
4363 {
4364 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004365 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004366 }
4367
4368 windgoto(msg_row, msg_col);
4369 cursor_on();
4370 out_flush();
4371 }
4372}
4373
4374/*
4375 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4376 * for communication and doesn't open any new window.
4377 */
4378 static int
4379mch_system_piped(char *cmd, int options)
4380{
4381 STARTUPINFO si;
4382 PROCESS_INFORMATION pi;
4383 DWORD ret = 0;
4384
4385 HANDLE g_hChildStd_IN_Rd = NULL;
4386 HANDLE g_hChildStd_IN_Wr = NULL;
4387 HANDLE g_hChildStd_OUT_Rd = NULL;
4388 HANDLE g_hChildStd_OUT_Wr = NULL;
4389
Bram Moolenaar0f873732019-12-05 20:28:46 +01004390 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004391 DWORD len;
4392
Bram Moolenaar0f873732019-12-05 20:28:46 +01004393 // buffer used to receive keys
4394 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4395 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004396
4397 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004398 int noread_cnt = 0;
4399 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004400 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004401 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004402 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004403
4404 SECURITY_ATTRIBUTES saAttr;
4405
Bram Moolenaar0f873732019-12-05 20:28:46 +01004406 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004407 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4408 saAttr.bInheritHandle = TRUE;
4409 saAttr.lpSecurityDescriptor = NULL;
4410
4411 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004412 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004413 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004414 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004415 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004416 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004417 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004418 {
4419 CloseHandle(g_hChildStd_IN_Rd);
4420 CloseHandle(g_hChildStd_IN_Wr);
4421 CloseHandle(g_hChildStd_OUT_Rd);
4422 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004423 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004424 }
4425
4426 si.cb = sizeof(si);
4427 si.lpReserved = NULL;
4428 si.lpDesktop = NULL;
4429 si.lpTitle = NULL;
4430 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4431
Bram Moolenaar0f873732019-12-05 20:28:46 +01004432 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004433 si.hStdError = g_hChildStd_OUT_Wr;
4434 si.hStdOutput = g_hChildStd_OUT_Wr;
4435 si.hStdInput = g_hChildStd_IN_Rd;
4436 si.wShowWindow = SW_HIDE;
4437 si.cbReserved2 = 0;
4438 si.lpReserved2 = NULL;
4439
4440 if (options & SHELL_READ)
4441 ga_init2(&ga, 1, BUFLEN);
4442
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004443 if (cmd != NULL)
4444 {
4445 p = (char *)vim_strsave((char_u *)cmd);
4446 if (p != NULL)
4447 unescape_shellxquote((char_u *)p, p_sxe);
4448 else
4449 p = cmd;
4450 }
4451
Bram Moolenaar0f873732019-12-05 20:28:46 +01004452 // Now, run the command.
4453 // About "Inherit handles" being TRUE: this command can be litigious,
4454 // handle inheritance was deactivated for pending temp file, but, if we
4455 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004456 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4457 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004458
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004459 if (p != cmd)
4460 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004461
Bram Moolenaar0f873732019-12-05 20:28:46 +01004462 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004463 CloseHandle(g_hChildStd_IN_Rd);
4464 CloseHandle(g_hChildStd_OUT_Wr);
4465
4466 if (options & SHELL_WRITE)
4467 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004468 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004469 _beginthreadex(NULL, // security attributes
4470 0, // default stack size
4471 sub_process_writer, // function to be executed
4472 g_hChildStd_IN_Wr, // parameter
4473 0, // creation flag, start immediately
4474 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004475 CloseHandle(thread);
4476 g_hChildStd_IN_Wr = NULL;
4477 }
4478
Bram Moolenaar0f873732019-12-05 20:28:46 +01004479 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004480 for (;;)
4481 {
4482 MSG msg;
4483
K.Takatab7057bd2022-01-21 11:37:07 +00004484 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004485 {
4486 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004487 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004488 }
4489
Bram Moolenaar0f873732019-12-05 20:28:46 +01004490 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004491 if ((options & (SHELL_READ|SHELL_WRITE))
4492# ifdef FEAT_GUI
4493 || gui.in_use
4494# endif
4495 )
4496 {
4497 len = 0;
4498 if (!(options & SHELL_EXPAND)
4499 && ((options &
4500 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4501 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4502# ifdef FEAT_GUI
4503 || gui.in_use
4504# endif
4505 )
4506 && (ta_len > 0 || noread_cnt > 4))
4507 {
4508 if (ta_len == 0)
4509 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004510 // Get extra characters when we don't have any. Reset the
4511 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004512 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004513 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4514 }
4515 if (ta_len > 0 || len > 0)
4516 {
4517 /*
4518 * For pipes: Check for CTRL-C: send interrupt signal to
4519 * child. Check for CTRL-D: EOF, close pipe to child.
4520 */
4521 if (len == 1 && cmd != NULL)
4522 {
4523 if (ta_buf[ta_len] == Ctrl_C)
4524 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004525 // Learn what exit code is expected, for
4526 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004527 TerminateProcess(pi.hProcess, 9);
4528 }
4529 if (ta_buf[ta_len] == Ctrl_D)
4530 {
4531 CloseHandle(g_hChildStd_IN_Wr);
4532 g_hChildStd_IN_Wr = NULL;
4533 }
4534 }
4535
Bram Moolenaarf4140482020-02-15 23:06:45 +01004536 term_replace_bs_del_keycode(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004537
4538 /*
4539 * For pipes: echo the typed characters. For a pty this
4540 * does not seem to work.
4541 */
4542 for (i = ta_len; i < ta_len + len; ++i)
4543 {
4544 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4545 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004546 else if (has_mbyte)
4547 {
4548 int l = (*mb_ptr2len)(ta_buf + i);
4549
4550 msg_outtrans_len(ta_buf + i, l);
4551 i += l - 1;
4552 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004553 else
4554 msg_outtrans_len(ta_buf + i, 1);
4555 }
4556 windgoto(msg_row, msg_col);
4557 out_flush();
4558
4559 ta_len += len;
4560
4561 /*
4562 * Write the characters to the child, unless EOF has been
4563 * typed for pipes. Write one character at a time, to
4564 * avoid losing too much typeahead. When writing buffer
4565 * lines, drop the typed characters (only check for
4566 * CTRL-C).
4567 */
4568 if (options & SHELL_WRITE)
4569 ta_len = 0;
4570 else if (g_hChildStd_IN_Wr != NULL)
4571 {
4572 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4573 1, &len, NULL);
4574 // if we are typing in, we want to keep things reactive
4575 delay = 1;
4576 if (len > 0)
4577 {
4578 ta_len -= len;
4579 mch_memmove(ta_buf, ta_buf + len, ta_len);
4580 }
4581 }
4582 }
4583 }
4584 }
4585
4586 if (ta_len)
4587 ui_inchar_undo(ta_buf, ta_len);
4588
4589 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4590 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004591 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004592 break;
4593 }
4594
4595 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004596 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004597
Bram Moolenaar0f873732019-12-05 20:28:46 +01004598 // We start waiting for a very short time and then increase it, so
4599 // that we respond quickly when the process is quick, and don't
4600 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004601 if (delay < 50)
4602 delay += 10;
4603 }
4604
Bram Moolenaar0f873732019-12-05 20:28:46 +01004605 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004606 CloseHandle(g_hChildStd_OUT_Rd);
4607 if (g_hChildStd_IN_Wr != NULL)
4608 CloseHandle(g_hChildStd_IN_Wr);
4609
4610 WaitForSingleObject(pi.hProcess, INFINITE);
4611
Bram Moolenaar0f873732019-12-05 20:28:46 +01004612 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004613 GetExitCodeProcess(pi.hProcess, &ret);
4614
4615 if (options & SHELL_READ)
4616 {
4617 if (ga.ga_len > 0)
4618 {
4619 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01004620 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004621 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4622 }
4623 else
4624 curbuf->b_no_eol_lnum = 0;
4625 ga_clear(&ga);
4626 }
4627
Bram Moolenaar0f873732019-12-05 20:28:46 +01004628 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004629 CloseHandle(pi.hThread);
4630 CloseHandle(pi.hProcess);
4631
4632 return ret;
4633}
4634
4635 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004636mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004637{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004638 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004639 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004640 return mch_system_piped(cmd, options);
4641 else
4642 return mch_system_classic(cmd, options);
4643}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004644#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004645
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004646#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004647 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02004648mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004649{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004650 int ret;
4651 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004652 char_u *buf;
4653 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004654
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004655 // If the command starts and ends with double quotes, enclose the command
4656 // in parentheses.
4657 len = STRLEN(cmd);
4658 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
4659 {
4660 len += 3;
4661 buf = alloc(len);
4662 if (buf == NULL)
4663 return -1;
4664 vim_snprintf((char *)buf, len, "(%s)", cmd);
4665 wcmd = enc_to_utf16(buf, NULL);
4666 free(buf);
4667 }
4668 else
4669 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4670
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004671 if (wcmd == NULL)
4672 return -1;
4673
4674 ret = _wsystem(wcmd);
4675 vim_free(wcmd);
4676 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004677}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004678
4679#endif
4680
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004681 static int
4682mch_system(char *cmd, int options)
4683{
4684#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004685 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004686 return mch_system_g(cmd, options);
4687 else
4688 return mch_system_c(cmd, options);
4689#elif defined(FEAT_GUI_MSWIN)
4690 return mch_system_g(cmd, options);
4691#else
4692 return mch_system_c(cmd, options);
4693#endif
4694}
4695
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004696#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4697/*
4698 * Use a terminal window to run a shell command in.
4699 */
4700 static int
4701mch_call_shell_terminal(
4702 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004703 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004704{
4705 jobopt_T opt;
4706 char_u *newcmd = NULL;
4707 typval_T argvar[2];
4708 long_u cmdlen;
4709 int retval = -1;
4710 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004711 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004712 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004713 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004714
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004715 if (cmd == NULL)
4716 cmdlen = STRLEN(p_sh) + 1;
4717 else
4718 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004719 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004720 if (newcmd == NULL)
4721 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004722 if (cmd == NULL)
4723 {
4724 STRCPY(newcmd, p_sh);
4725 ch_log(NULL, "starting terminal to run a shell");
4726 }
4727 else
4728 {
4729 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4730 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4731 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004732
4733 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004734
4735 argvar[0].v_type = VAR_STRING;
4736 argvar[0].vval.v_string = newcmd;
4737 argvar[1].v_type = VAR_UNKNOWN;
4738 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004739 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004740 {
4741 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004742 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004743 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004744
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004745 job = term_getjob(buf->b_term);
4746 ++job->jv_refcount;
4747
Bram Moolenaar0f873732019-12-05 20:28:46 +01004748 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004749 aucmd_prepbuf(&aco, buf);
4750
4751 clear_oparg(&oa);
4752 while (term_use_loop())
4753 {
4754 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4755 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004756 // If terminal_loop() returns OK we got a key that is handled
4757 // in Normal model. We don't do redrawing anyway.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004758 if (terminal_loop(TRUE) == OK)
4759 normal_cmd(&oa, TRUE);
4760 }
4761 else
4762 normal_cmd(&oa, TRUE);
4763 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004764 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004765 ch_log(NULL, "system command finished");
4766
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004767 job_unref(job);
4768
Bram Moolenaar0f873732019-12-05 20:28:46 +01004769 // restore curwin/curbuf and a few other things
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004770 aucmd_restbuf(&aco);
4771
4772 wait_return(TRUE);
4773 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4774
4775 vim_free(newcmd);
4776 return retval;
4777}
4778#endif
4779
Bram Moolenaar071d4272004-06-13 20:20:40 +00004780/*
4781 * Either execute a command by calling the shell or start a new shell
4782 */
4783 int
4784mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004785 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004786 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00004787{
4788 int x = 0;
4789 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004790 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004791
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01004792#ifdef FEAT_JOB_CHANNEL
4793 ch_log(NULL, "executing shell command: %s", cmd);
4794#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004795 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02004796 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004797 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004798 if (cmd == NULL)
4799 wcscat(szShellTitle, L" :sh");
4800 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004801 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004802 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004803
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004804 if (wn != NULL)
4805 {
4806 wcscat(szShellTitle, L" - !");
4807 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02004808 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004809 wcscat(szShellTitle, wn);
4810 SetConsoleTitleW(szShellTitle);
4811 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004812 }
4813 }
4814 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004815
4816 out_flush();
4817
4818#ifdef MCH_WRITE_DUMP
4819 if (fdDump)
4820 {
4821 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4822 fflush(fdDump);
4823 }
4824#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004825#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004826 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004827 if (
4828# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004829 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004830# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004831 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004832 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4833 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004834 char_u *cmdbase = cmd;
4835
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004836 if (cmdbase != NULL)
4837 // Skip a leading quote and (.
4838 while (*cmdbase == '"' || *cmdbase == '(')
4839 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004840
4841 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01004842 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
4843 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004844 {
4845 // Use a terminal window to run the command in.
4846 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004847 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004848 return x;
4849 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004850 }
4851#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004852
4853 /*
4854 * Catch all deadly signals while running the external command, because a
4855 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4856 */
4857 signal(SIGINT, SIG_IGN);
4858#if defined(__GNUC__) && !defined(__MINGW32__)
4859 signal(SIGKILL, SIG_IGN);
4860#else
4861 signal(SIGBREAK, SIG_IGN);
4862#endif
4863 signal(SIGILL, SIG_IGN);
4864 signal(SIGFPE, SIG_IGN);
4865 signal(SIGSEGV, SIG_IGN);
4866 signal(SIGTERM, SIG_IGN);
4867 signal(SIGABRT, SIG_IGN);
4868
4869 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004870 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00004871
4872 if (cmd == NULL)
4873 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004874 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004875 }
4876 else
4877 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004878 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004879 char_u *newcmd = NULL;
4880 char_u *cmdbase = cmd;
4881 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004882
Bram Moolenaar0f873732019-12-05 20:28:46 +01004883 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004884 if (*cmdbase == '"' )
4885 ++cmdbase;
4886 if (*cmdbase == '(')
4887 ++cmdbase;
4888
Bram Moolenaar1c465442017-03-12 20:10:05 +01004889 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004890 {
4891 STARTUPINFO si;
4892 PROCESS_INFORMATION pi;
4893 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004894 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004895 char_u *p;
4896
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004897 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004898 si.cb = sizeof(si);
4899 si.lpReserved = NULL;
4900 si.lpDesktop = NULL;
4901 si.lpTitle = NULL;
4902 si.dwFlags = 0;
4903 si.cbReserved2 = 0;
4904 si.lpReserved2 = NULL;
4905
4906 cmdbase = skipwhite(cmdbase + 5);
4907 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004908 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004909 {
4910 cmdbase = skipwhite(cmdbase + 4);
4911 si.dwFlags = STARTF_USESHOWWINDOW;
4912 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004913 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004914 }
4915 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004916 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004917 {
4918 cmdbase = skipwhite(cmdbase + 2);
4919 flags = CREATE_NO_WINDOW;
4920 si.dwFlags = STARTF_USESTDHANDLES;
4921 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004922 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004923 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004924 NULL, // Security att.
4925 OPEN_EXISTING, // Open flags
4926 FILE_ATTRIBUTE_NORMAL, // File att.
4927 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004928 si.hStdOutput = si.hStdInput;
4929 si.hStdError = si.hStdInput;
4930 }
4931
Bram Moolenaar0f873732019-12-05 20:28:46 +01004932 // Remove a trailing ", ) and )" if they have a match
4933 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004934 if (cmdbase > cmd)
4935 {
4936 p = cmdbase + STRLEN(cmdbase);
4937 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4938 *--p = NUL;
4939 if (p > cmdbase && p[-1] == ')'
4940 && (*cmd =='(' || cmd[1] == '('))
4941 *--p = NUL;
4942 }
4943
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004944 newcmd = cmdbase;
4945 unescape_shellxquote(cmdbase, p_sxe);
4946
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004947 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004948 * If creating new console, arguments are passed to the
4949 * 'cmd.exe' as-is. If it's not, arguments are not treated
4950 * correctly for current 'cmd.exe'. So unescape characters in
4951 * shellxescape except '|' for avoiding to be treated as
4952 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004953 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004954 if (flags != CREATE_NEW_CONSOLE)
4955 {
4956 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004957 char_u *cmd_shell = mch_getenv("COMSPEC");
4958
4959 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004960 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004961
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004962 subcmd = vim_strsave_escaped_ext(cmdbase,
4963 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004964 if (subcmd != NULL)
4965 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004966 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004967 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004968 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004969 if (newcmd != NULL)
4970 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004971 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004972 else
4973 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004974 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004975 }
4976 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004977
4978 /*
4979 * Now, start the command as a process, so that it doesn't
4980 * inherit our handles which causes unpleasant dangling swap
4981 * files if we exit before the spawned process
4982 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004983 if (vim_create_process((char *)newcmd, FALSE, flags,
4984 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004985 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004986 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4987 > (HINSTANCE)32)
4988 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004989 else
4990 {
4991 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01004992#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004993# ifdef VIMDLL
4994 if (gui.in_use)
4995# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00004996 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004997#endif
4998 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004999
5000 if (newcmd != cmdbase)
5001 vim_free(newcmd);
5002
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005003 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005004 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005005 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005006 CloseHandle(si.hStdInput);
5007 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005008 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005009 CloseHandle(pi.hThread);
5010 CloseHandle(pi.hProcess);
5011 }
5012 else
5013 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005014 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005015#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005016 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005017 (!s_dont_use_vimrun && p_stmp ?
5018 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5019 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005020#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005021 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005022
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005023 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005024 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005025 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005026#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005027 if (
5028# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005029 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005030# endif
5031 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005032 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005033 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5034 "External commands will not pause after completion.\n"
5035 "See :help win32-vimrun for more information.");
5036 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005037 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5038 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005039
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005040 if (wmsg != NULL && wtitle != NULL)
5041 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5042 vim_free(wmsg);
5043 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005044 need_vimrun_warning = FALSE;
5045 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005046 if (
5047# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005048 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005049# endif
5050 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005051 // Use vimrun to execute the command. It opens a console
5052 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005053 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005054 vimrun_path,
5055 (msg_silent != 0 || (options & SHELL_DOOUT))
5056 ? "-s " : "",
5057 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005058 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005059# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005060 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005061# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005062 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005063 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005064 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5065 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005066 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005067#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005068 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005069 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005070 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005071 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005072 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005073 }
5074 }
5075
5076 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005077 {
5078 // The shell may have messed with the mode, always set it.
5079 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005080 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005081 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005082
Bram Moolenaar0f873732019-12-05 20:28:46 +01005083 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005084 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005085#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005086 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005087 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005088#endif
5089 )
5090 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005091 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005092 msg_putchar('\n');
5093 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005094 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005095
5096 signal(SIGINT, SIG_DFL);
5097#if defined(__GNUC__) && !defined(__MINGW32__)
5098 signal(SIGKILL, SIG_DFL);
5099#else
5100 signal(SIGBREAK, SIG_DFL);
5101#endif
5102 signal(SIGILL, SIG_DFL);
5103 signal(SIGFPE, SIG_DFL);
5104 signal(SIGSEGV, SIG_DFL);
5105 signal(SIGTERM, SIG_DFL);
5106 signal(SIGABRT, SIG_DFL);
5107
5108 return x;
5109}
5110
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005111#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005112 static HANDLE
5113job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005114 char_u *fname,
5115 DWORD dwDesiredAccess,
5116 DWORD dwShareMode,
5117 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5118 DWORD dwCreationDisposition,
5119 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005120{
5121 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005122 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005123
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005124 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005125 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005126 return INVALID_HANDLE_VALUE;
5127
5128 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5129 lpSecurityAttributes, dwCreationDisposition,
5130 dwFlagsAndAttributes, NULL);
5131 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005132 return h;
5133}
5134
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005135/*
5136 * Turn the dictionary "env" into a NUL separated list that can be used as the
5137 * environment argument of vim_create_process().
5138 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005139 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005140win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005141{
5142 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005143 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005144 LPVOID base = GetEnvironmentStringsW();
5145
Bram Moolenaar0f873732019-12-05 20:28:46 +01005146 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005147 if (ga_grow(gap, 1) == FAIL)
5148 return;
5149
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005150 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005151 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005152 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005153 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005154 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005155 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005156 typval_T *item = &dict_lookup(hi)->di_tv;
5157 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005158 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005159 --todo;
5160 if (wkey != NULL && wval != NULL)
5161 {
5162 size_t n;
5163 size_t lkey = wcslen(wkey);
5164 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005165
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005166 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5167 continue;
5168 for (n = 0; n < lkey; n++)
5169 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5170 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5171 for (n = 0; n < lval; n++)
5172 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5173 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5174 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005175 vim_free(wkey);
5176 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005177 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005178 }
5179 }
5180
Bram Moolenaar355757a2020-02-10 22:06:32 +01005181 if (base)
5182 {
5183 WCHAR *p = (WCHAR*) base;
5184
5185 // for last \0
5186 if (ga_grow(gap, 1) == FAIL)
5187 return;
5188
5189 while (*p != 0 || *(p + 1) != 0)
5190 {
5191 if (ga_grow(gap, 1) == OK)
5192 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5193 p++;
5194 }
5195 FreeEnvironmentStrings(base);
5196 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5197 }
5198
Bram Moolenaar493359e2018-06-12 20:25:52 +02005199# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005200 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005201# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005202 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005203 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005204# endif
5205# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005206 char_u *version = get_vim_var_str(VV_VERSION);
5207 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005208# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005209 // size of "VIM_SERVERNAME=" and value,
5210 // plus "VIM_TERMINAL=" and value,
5211 // plus two terminating NULs
5212 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005213# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005214 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005215# endif
5216# ifdef FEAT_TERMINAL
5217 + 13 + version_len + 2
5218# endif
5219 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005220
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005221 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005222 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005223# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005224 for (n = 0; n < 15; n++)
5225 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5226 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005227 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005228 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5229 (WCHAR)servername[n];
5230 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005231# endif
5232# ifdef FEAT_TERMINAL
5233 if (is_terminal)
5234 {
5235 for (n = 0; n < 13; n++)
5236 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5237 (WCHAR)"VIM_TERMINAL="[n];
5238 for (n = 0; n < version_len; n++)
5239 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5240 (WCHAR)version[n];
5241 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5242 }
5243# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005244 }
5245 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005246# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005247}
5248
Bram Moolenaarb091f302019-01-19 14:37:00 +01005249/*
5250 * Create a pair of pipes.
5251 * Return TRUE for success, FALSE for failure.
5252 */
5253 static BOOL
5254create_pipe_pair(HANDLE handles[2])
5255{
5256 static LONG s;
5257 char name[64];
5258 SECURITY_ATTRIBUTES sa;
5259
5260 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5261 GetCurrentProcessId(),
5262 InterlockedIncrement(&s));
5263
5264 // Create named pipe. Max size of named pipe is 65535.
5265 handles[1] = CreateNamedPipe(
5266 name,
5267 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5268 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005269 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005270
5271 if (handles[1] == INVALID_HANDLE_VALUE)
5272 return FALSE;
5273
5274 sa.nLength = sizeof(sa);
5275 sa.bInheritHandle = TRUE;
5276 sa.lpSecurityDescriptor = NULL;
5277
5278 handles[0] = CreateFile(name,
5279 FILE_GENERIC_READ,
5280 FILE_SHARE_READ, &sa,
5281 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5282
5283 if (handles[0] == INVALID_HANDLE_VALUE)
5284 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005285 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005286 return FALSE;
5287 }
5288
5289 return TRUE;
5290}
5291
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005292 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005293mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005294{
5295 STARTUPINFO si;
5296 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005297 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005298 SECURITY_ATTRIBUTES saAttr;
5299 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005300 HANDLE ifd[2];
5301 HANDLE ofd[2];
5302 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005303 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005304
5305 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5306 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5307 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5308 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5309 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5310 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5311 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5312
5313 if (use_out_for_err && use_null_for_out)
5314 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005315
5316 ifd[0] = INVALID_HANDLE_VALUE;
5317 ifd[1] = INVALID_HANDLE_VALUE;
5318 ofd[0] = INVALID_HANDLE_VALUE;
5319 ofd[1] = INVALID_HANDLE_VALUE;
5320 efd[0] = INVALID_HANDLE_VALUE;
5321 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005322 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005323
Bram Moolenaar14207f42016-10-27 21:13:10 +02005324 jo = CreateJobObject(NULL, NULL);
5325 if (jo == NULL)
5326 {
5327 job->jv_status = JOB_FAILED;
5328 goto failed;
5329 }
5330
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005331 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005332 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005333
Bram Moolenaar76467df2016-02-12 19:30:26 +01005334 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005335 ZeroMemory(&si, sizeof(si));
5336 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005337 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005338 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005339
Bram Moolenaard8070362016-02-15 21:56:54 +01005340 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5341 saAttr.bInheritHandle = TRUE;
5342 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005343
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005344 if (use_file_for_in)
5345 {
5346 char_u *fname = options->jo_io_name[PART_IN];
5347
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005348 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5349 FILE_SHARE_READ | FILE_SHARE_WRITE,
5350 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5351 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005352 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005353 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005354 goto failed;
5355 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005356 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005357 else if (!use_null_for_in
5358 && (!create_pipe_pair(ifd)
5359 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005360 goto failed;
5361
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005362 if (use_file_for_out)
5363 {
5364 char_u *fname = options->jo_io_name[PART_OUT];
5365
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005366 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5367 FILE_SHARE_READ | FILE_SHARE_WRITE,
5368 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5369 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005370 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005371 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005372 goto failed;
5373 }
5374 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005375 else if (!use_null_for_out &&
5376 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005377 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005378 goto failed;
5379
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005380 if (use_file_for_err)
5381 {
5382 char_u *fname = options->jo_io_name[PART_ERR];
5383
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005384 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5385 FILE_SHARE_READ | FILE_SHARE_WRITE,
5386 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5387 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005388 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005389 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005390 goto failed;
5391 }
5392 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005393 else if (!use_out_for_err && !use_null_for_err &&
5394 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005395 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005396 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005397
Bram Moolenaard8070362016-02-15 21:56:54 +01005398 si.dwFlags |= STARTF_USESTDHANDLES;
5399 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005400 si.hStdOutput = ofd[1];
5401 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5402
5403 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5404 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005405 if (options->jo_set & JO_CHANNEL)
5406 {
5407 channel = options->jo_channel;
5408 if (channel != NULL)
5409 ++channel->ch_refcount;
5410 }
5411 else
5412 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005413 if (channel == NULL)
5414 goto failed;
5415 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005416
5417 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005418 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005419 CREATE_DEFAULT_ERROR_MODE |
5420 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005421 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005422 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005423 &si, &pi,
5424 ga.ga_data,
5425 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005426 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005427 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005428 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005429 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005430 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005431
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005432 ga_clear(&ga);
5433
Bram Moolenaar14207f42016-10-27 21:13:10 +02005434 if (!AssignProcessToJobObject(jo, pi.hProcess))
5435 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005436 // if failing, switch the way to terminate
5437 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005438 CloseHandle(jo);
5439 jo = NULL;
5440 }
5441 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005442 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005443 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005444 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005445 job->jv_status = JOB_STARTED;
5446
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005447 CloseHandle(ifd[0]);
5448 CloseHandle(ofd[1]);
5449 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005450 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005451
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005452 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005453 if (channel != NULL)
5454 {
5455 channel_set_pipes(channel,
5456 use_file_for_in || use_null_for_in
5457 ? INVALID_FD : (sock_T)ifd[1],
5458 use_file_for_out || use_null_for_out
5459 ? INVALID_FD : (sock_T)ofd[0],
5460 use_out_for_err || use_file_for_err || use_null_for_err
5461 ? INVALID_FD : (sock_T)efd[0]);
5462 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005463 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005464 return;
5465
5466failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005467 CloseHandle(ifd[0]);
5468 CloseHandle(ofd[0]);
5469 CloseHandle(efd[0]);
5470 CloseHandle(ifd[1]);
5471 CloseHandle(ofd[1]);
5472 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005473 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005474 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005475}
5476
5477 char *
5478mch_job_status(job_T *job)
5479{
5480 DWORD dwExitCode = 0;
5481
Bram Moolenaar76467df2016-02-12 19:30:26 +01005482 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5483 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005484 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005485 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005486 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005487 {
5488 ch_log(job->jv_channel, "Job ended");
5489 job->jv_status = JOB_ENDED;
5490 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005491 return "dead";
5492 }
5493 return "run";
5494}
5495
Bram Moolenaar97792de2016-10-15 18:36:49 +02005496 job_T *
5497mch_detect_ended_job(job_T *job_list)
5498{
5499 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5500 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5501 job_T *job = job_list;
5502
5503 while (job != NULL)
5504 {
5505 DWORD n;
5506 DWORD result;
5507
5508 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5509 && job != NULL; job = job->jv_next)
5510 {
5511 if (job->jv_status == JOB_STARTED)
5512 {
5513 jobHandles[n] = job->jv_proc_info.hProcess;
5514 jobArray[n] = job;
5515 ++n;
5516 }
5517 }
5518 if (n == 0)
5519 continue;
5520 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5521 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5522 {
5523 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5524
5525 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5526 return wait_job;
5527 }
5528 }
5529 return NULL;
5530}
5531
Bram Moolenaarfb630902016-10-29 14:55:00 +02005532 static BOOL
5533terminate_all(HANDLE process, int code)
5534{
5535 PROCESSENTRY32 pe;
5536 HANDLE h = INVALID_HANDLE_VALUE;
5537 DWORD pid = GetProcessId(process);
5538
5539 if (pid != 0)
5540 {
5541 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5542 if (h != INVALID_HANDLE_VALUE)
5543 {
5544 pe.dwSize = sizeof(PROCESSENTRY32);
5545 if (!Process32First(h, &pe))
5546 goto theend;
5547
5548 do
5549 {
5550 if (pe.th32ParentProcessID == pid)
5551 {
5552 HANDLE ph = OpenProcess(
5553 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5554 if (ph != NULL)
5555 {
5556 terminate_all(ph, code);
5557 CloseHandle(ph);
5558 }
5559 }
5560 } while (Process32Next(h, &pe));
5561
5562 CloseHandle(h);
5563 }
5564 }
5565
5566theend:
5567 return TerminateProcess(process, code);
5568}
5569
5570/*
5571 * Send a (deadly) signal to "job".
5572 * Return FAIL if it didn't work.
5573 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005574 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005575mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005576{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005577 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005578
Bram Moolenaar923d9262016-02-25 20:56:01 +01005579 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005580 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005581 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02005582 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005583 {
5584 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5585 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00005586 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005587 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01005588 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005589 }
5590
5591 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5592 return FAIL;
5593 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005594 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5595 job->jv_proc_info.dwProcessId)
5596 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005597 FreeConsole();
5598 return ret;
5599}
5600
5601/*
5602 * Clear the data related to "job".
5603 */
5604 void
5605mch_clear_job(job_T *job)
5606{
5607 if (job->jv_status != JOB_FAILED)
5608 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005609 if (job->jv_job_object != NULL)
5610 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005611 CloseHandle(job->jv_proc_info.hProcess);
5612 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005613}
5614#endif
5615
Bram Moolenaar071d4272004-06-13 20:20:40 +00005616
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005617#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005618
5619/*
5620 * Start termcap mode
5621 */
5622 static void
5623termcap_mode_start(void)
5624{
5625 DWORD cmodein;
5626
5627 if (g_fTermcapMode)
5628 return;
5629
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005630 if (!p_rs && USE_VTP)
5631 vtp_printf("\033[?1049h");
5632
Bram Moolenaar071d4272004-06-13 20:20:40 +00005633 SaveConsoleBuffer(&g_cbNonTermcap);
5634
5635 if (g_cbTermcap.IsValid)
5636 {
5637 /*
5638 * We've been in termcap mode before. Restore certain screen
5639 * characteristics, including the buffer size and the window
5640 * size. Since we will be redrawing the screen, we don't need
5641 * to restore the actual contents of the buffer.
5642 */
5643 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005644 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005645 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5646 Rows = g_cbTermcap.Info.dwSize.Y;
5647 Columns = g_cbTermcap.Info.dwSize.X;
5648 }
5649 else
5650 {
5651 /*
5652 * This is our first time entering termcap mode. Clear the console
5653 * screen buffer, and resize the buffer to match the current window
5654 * size. We will use this as the size of our editing environment.
5655 */
5656 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005657 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005658 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5659 }
5660
Bram Moolenaar071d4272004-06-13 20:20:40 +00005661 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005662
5663 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005664 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005665 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005666 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005667 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
5668 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005669 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005670 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005671 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005672 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5673 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005674 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005675 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005676
5677 redraw_later_clear();
5678 g_fTermcapMode = TRUE;
5679}
5680
5681
5682/*
5683 * End termcap mode
5684 */
5685 static void
5686termcap_mode_end(void)
5687{
5688 DWORD cmodein;
5689 ConsoleBuffer *cb;
5690 COORD coord;
5691 DWORD dwDummy;
5692
5693 if (!g_fTermcapMode)
5694 return;
5695
5696 SaveConsoleBuffer(&g_cbTermcap);
5697
5698 GetConsoleMode(g_hConIn, &cmodein);
5699 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005700 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5701 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005702
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005703# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005704 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005705# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005706 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005707# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005708 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01005709 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005710 SetConsoleCursorInfo(g_hConOut, &g_cci);
5711
5712 if (p_rs || exiting)
5713 {
5714 /*
5715 * Clear anything that happens to be on the current line.
5716 */
5717 coord.X = 0;
5718 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5719 FillConsoleOutputCharacter(g_hConOut, ' ',
5720 cb->Info.dwSize.X, coord, &dwDummy);
5721 /*
5722 * The following is just for aesthetics. If we are exiting without
5723 * restoring the screen, then we want to have a prompt string
5724 * appear at the bottom line. However, the command interpreter
5725 * seems to always advance the cursor one line before displaying
5726 * the prompt string, which causes the screen to scroll. To
5727 * counter this, move the cursor up one line before exiting.
5728 */
5729 if (exiting && !p_rs)
5730 coord.Y--;
5731 /*
5732 * Position the cursor at the leftmost column of the desired row.
5733 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005734 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005735 }
5736
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005737 if (!p_rs && USE_VTP)
Bram Moolenaar0afdcf82020-04-01 18:29:10 +02005738 vtp_printf("\033[?1049l");
5739
Bram Moolenaar071d4272004-06-13 20:20:40 +00005740 g_fTermcapMode = FALSE;
5741}
Bram Moolenaar0f873732019-12-05 20:28:46 +01005742#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005743
5744
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005745#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005746 void
5747mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005748 char_u *s UNUSED,
5749 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005750{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005751 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00005752}
5753
5754#else
5755
5756/*
5757 * clear `n' chars, starting from `coord'
5758 */
5759 static void
5760clear_chars(
5761 COORD coord,
5762 DWORD n)
5763{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005764 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02005765 {
5766 DWORD dwDummy;
5767
5768 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5769 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
5770 &dwDummy);
5771 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005772 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005773 {
5774 set_console_color_rgb();
5775 gotoxy(coord.X + 1, coord.Y + 1);
5776 vtp_printf("\033[%dX", n);
5777 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005778}
5779
5780
5781/*
5782 * Clear the screen
5783 */
5784 static void
5785clear_screen(void)
5786{
5787 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005788
5789 if (!USE_VTP)
5790 clear_chars(g_coord, Rows * Columns);
5791 else
5792 {
5793 set_console_color_rgb();
5794 gotoxy(1, 1);
5795 vtp_printf("\033[2J");
5796 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005797}
5798
5799
5800/*
5801 * Clear to end of display
5802 */
5803 static void
5804clear_to_end_of_display(void)
5805{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005806 COORD save = g_coord;
5807
5808 if (!USE_VTP)
5809 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005810 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005811 else
5812 {
5813 set_console_color_rgb();
5814 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5815 vtp_printf("\033[0J");
5816
5817 gotoxy(save.X + 1, save.Y + 1);
5818 g_coord = save;
5819 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005820}
5821
5822
5823/*
5824 * Clear to end of line
5825 */
5826 static void
5827clear_to_end_of_line(void)
5828{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005829 COORD save = g_coord;
5830
5831 if (!USE_VTP)
5832 clear_chars(g_coord, Columns - g_coord.X);
5833 else
5834 {
5835 set_console_color_rgb();
5836 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5837 vtp_printf("\033[0K");
5838
5839 gotoxy(save.X + 1, save.Y + 1);
5840 g_coord = save;
5841 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005842}
5843
5844
5845/*
5846 * Scroll the scroll region up by `cLines' lines
5847 */
5848 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005849scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005850{
5851 COORD oldcoord = g_coord;
5852
5853 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5854 delete_lines(cLines);
5855
5856 g_coord = oldcoord;
5857}
5858
5859
5860/*
5861 * Set the scroll region
5862 */
5863 static void
5864set_scroll_region(
5865 unsigned left,
5866 unsigned top,
5867 unsigned right,
5868 unsigned bottom)
5869{
5870 if (left >= right
5871 || top >= bottom
5872 || right > (unsigned) Columns - 1
5873 || bottom > (unsigned) Rows - 1)
5874 return;
5875
5876 g_srScrollRegion.Left = left;
5877 g_srScrollRegion.Top = top;
5878 g_srScrollRegion.Right = right;
5879 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005880}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005881
Bram Moolenaar6982f422019-02-16 16:48:01 +01005882 static void
5883set_scroll_region_tb(
5884 unsigned top,
5885 unsigned bottom)
5886{
5887 if (top >= bottom || bottom > (unsigned)Rows - 1)
5888 return;
5889
5890 g_srScrollRegion.Top = top;
5891 g_srScrollRegion.Bottom = bottom;
5892}
5893
5894 static void
5895set_scroll_region_lr(
5896 unsigned left,
5897 unsigned right)
5898{
5899 if (left >= right || right > (unsigned)Columns - 1)
5900 return;
5901
5902 g_srScrollRegion.Left = left;
5903 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005904}
5905
5906
5907/*
5908 * Insert `cLines' lines at the current cursor position
5909 */
5910 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005911insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005912{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005913 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005914 COORD dest;
5915 CHAR_INFO fill;
5916
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005917 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5918
Bram Moolenaar6982f422019-02-16 16:48:01 +01005919 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005920 dest.Y = g_coord.Y + cLines;
5921
Bram Moolenaar6982f422019-02-16 16:48:01 +01005922 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005923 source.Top = g_coord.Y;
5924 source.Right = g_srScrollRegion.Right;
5925 source.Bottom = g_srScrollRegion.Bottom - cLines;
5926
Bram Moolenaar6982f422019-02-16 16:48:01 +01005927 clip.Left = g_srScrollRegion.Left;
5928 clip.Top = g_coord.Y;
5929 clip.Right = g_srScrollRegion.Right;
5930 clip.Bottom = g_srScrollRegion.Bottom;
5931
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005932 fill.Char.AsciiChar = ' ';
5933 if (!USE_VTP)
5934 fill.Attributes = g_attrCurrent;
5935 else
5936 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005937
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005938 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005939
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005940 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5941
Bram Moolenaar6982f422019-02-16 16:48:01 +01005942 // Here we have to deal with a win32 console flake: If the scroll
5943 // region looks like abc and we scroll c to a and fill with d we get
5944 // cbd... if we scroll block c one line at a time to a, we get cdd...
5945 // vim expects cdd consistently... So we have to deal with that
5946 // here... (this also occurs scrolling the same way in the other
5947 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005948
5949 if (source.Bottom < dest.Y)
5950 {
5951 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005952 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005953
Bram Moolenaar6982f422019-02-16 16:48:01 +01005954 coord.X = source.Left;
5955 for (i = clip.Top; i < dest.Y; ++i)
5956 {
5957 coord.Y = i;
5958 clear_chars(coord, source.Right - source.Left + 1);
5959 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005960 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02005961
5962 if (USE_WT)
5963 {
5964 COORD coord;
5965 int i;
5966
5967 coord.X = source.Left;
5968 for (i = source.Top; i < dest.Y; ++i)
5969 {
5970 coord.Y = i;
5971 clear_chars(coord, source.Right - source.Left + 1);
5972 }
5973 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005974}
5975
5976
5977/*
5978 * Delete `cLines' lines at the current cursor position
5979 */
5980 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005981delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005982{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005983 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005984 COORD dest;
5985 CHAR_INFO fill;
5986 int nb;
5987
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005988 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5989
Bram Moolenaar6982f422019-02-16 16:48:01 +01005990 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005991 dest.Y = g_coord.Y;
5992
Bram Moolenaar6982f422019-02-16 16:48:01 +01005993 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005994 source.Top = g_coord.Y + cLines;
5995 source.Right = g_srScrollRegion.Right;
5996 source.Bottom = g_srScrollRegion.Bottom;
5997
Bram Moolenaar6982f422019-02-16 16:48:01 +01005998 clip.Left = g_srScrollRegion.Left;
5999 clip.Top = g_coord.Y;
6000 clip.Right = g_srScrollRegion.Right;
6001 clip.Bottom = g_srScrollRegion.Bottom;
6002
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006003 fill.Char.AsciiChar = ' ';
6004 if (!USE_VTP)
6005 fill.Attributes = g_attrCurrent;
6006 else
6007 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006008
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006009 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006010
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006011 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6012
Bram Moolenaar6982f422019-02-16 16:48:01 +01006013 // Here we have to deal with a win32 console flake; See insert_lines()
6014 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006015
6016 nb = dest.Y + (source.Bottom - source.Top) + 1;
6017
6018 if (nb < source.Top)
6019 {
6020 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006021 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006022
Bram Moolenaar6982f422019-02-16 16:48:01 +01006023 coord.X = source.Left;
6024 for (i = nb; i < clip.Bottom; ++i)
6025 {
6026 coord.Y = i;
6027 clear_chars(coord, source.Right - source.Left + 1);
6028 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006029 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006030
6031 if (USE_WT)
6032 {
6033 COORD coord;
6034 int i;
6035
6036 coord.X = source.Left;
6037 for (i = nb; i <= source.Bottom; ++i)
6038 {
6039 coord.Y = i;
6040 clear_chars(coord, source.Right - source.Left + 1);
6041 }
6042 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006043}
6044
6045
6046/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006047 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006048 */
6049 static void
6050gotoxy(
6051 unsigned x,
6052 unsigned y)
6053{
6054 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6055 return;
6056
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006057 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006058 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006059 // There are reports of double-width characters not displayed
6060 // correctly. This workaround should fix it, similar to how it's done
6061 // for VTP.
6062 g_coord.X = 0;
6063 SetConsoleCursorPosition(g_hConOut, g_coord);
6064
Bram Moolenaar2313b612019-09-27 14:14:32 +02006065 // external cursor coords are 1-based; internal are 0-based
6066 g_coord.X = x - 1;
6067 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006068 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006069 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006070 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006071 {
6072 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006073 // destruction. Insider build bug. Always enabled because it's cheap
6074 // and avoids mistakes with recognizing the build.
6075 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006076
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006077 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006078
6079 g_coord.X = x - 1;
6080 g_coord.Y = y - 1;
6081 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006082}
6083
6084
6085/*
6086 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006087 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006088 */
6089 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006090textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006091{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006092 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006093
6094 SetConsoleTextAttribute(g_hConOut, wAttr);
6095}
6096
6097
6098 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006099textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006100{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006101 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006102
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006103 if (!USE_VTP)
6104 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6105 else
6106 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006107}
6108
6109
6110 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006111textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006112{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006113 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006114
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006115 if (!USE_VTP)
6116 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6117 else
6118 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006119}
6120
6121
6122/*
6123 * restore the default text attribute (whatever we started with)
6124 */
6125 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006126normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006127{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006128 if (!USE_VTP)
6129 textattr(g_attrDefault);
6130 else
6131 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006132}
6133
6134
6135static WORD g_attrPreStandout = 0;
6136
6137/*
6138 * Make the text standout, by brightening it
6139 */
6140 static void
6141standout(void)
6142{
6143 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006144
Bram Moolenaar071d4272004-06-13 20:20:40 +00006145 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6146}
6147
6148
6149/*
6150 * Turn off standout mode
6151 */
6152 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006153standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006154{
6155 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006156 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006157
6158 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006159}
6160
6161
6162/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006163 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006164 */
6165 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006166mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006167{
6168 char_u *p;
6169 int n;
6170
6171 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6172 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006173 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006174# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006175 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006176# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006177 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006178 {
6179 p = T_ME + 2;
6180 n = getdigits(&p);
6181 if (*p == 'm' && n > 0)
6182 {
6183 cterm_normal_fg_color = (n & 0xf) + 1;
6184 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6185 }
6186 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006187# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006188 cterm_normal_fg_gui_color = INVALCOLOR;
6189 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006190# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006191}
6192
6193
6194/*
6195 * visual bell: flash the screen
6196 */
6197 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006198visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006199{
6200 COORD coordOrigin = {0, 0};
6201 WORD attrFlash = ~g_attrCurrent & 0xff;
6202
6203 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006204 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006205
6206 if (oldattrs == NULL)
6207 return;
6208 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6209 coordOrigin, &dwDummy);
6210 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6211 coordOrigin, &dwDummy);
6212
Bram Moolenaar0f873732019-12-05 20:28:46 +01006213 Sleep(15); // wait for 15 msec
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006214 if (!USE_VTP)
6215 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006216 coordOrigin, &dwDummy);
6217 vim_free(oldattrs);
6218}
6219
6220
6221/*
6222 * Make the cursor visible or invisible
6223 */
6224 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006225cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006226{
6227 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006228
6229 if (USE_VTP)
6230 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6231
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006232# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006233 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006234# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006235}
6236
6237
6238/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006239 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006240 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006241 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006242 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006243write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006244 char_u *pchBuf,
6245 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006246{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006247 COORD coord = g_coord;
6248 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006249 DWORD n, cchwritten;
6250 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006251 static WCHAR *unicodebuf = NULL;
6252 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006253 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006254 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006255 static WCHAR *utf8spbuf = NULL;
6256 static int utf8splength;
6257 static DWORD utf8spcells;
6258 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006259
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006260 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006261 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006262 utf8usingbuf = &unicodebuf;
6263 do
6264 {
6265 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6266 unicodebuf, unibuflen);
6267 if (length && length <= unibuflen)
6268 break;
6269 vim_free(unicodebuf);
6270 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6271 unibuflen = unibuflen ? 0 : length;
6272 } while(1);
6273 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006274 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006275 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6276 {
6277 if (utf8usingbuf != &utf8spbuf)
6278 {
6279 if (utf8spbuf == NULL)
6280 {
6281 cells = mb_string2cells((char_u *)" ", 1);
6282 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6283 utf8spbuf = LALLOC_MULT(WCHAR, length);
6284 if (utf8spbuf != NULL)
6285 {
6286 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6287 utf8usingbuf = &utf8spbuf;
6288 utf8splength = length;
6289 utf8spcells = cells;
6290 }
6291 }
6292 else
6293 {
6294 utf8usingbuf = &utf8spbuf;
6295 length = utf8splength;
6296 cells = utf8spcells;
6297 }
6298 }
6299 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006300
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006301 if (!USE_VTP)
6302 {
6303 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6304 coord, &written);
6305 // When writing fails or didn't write a single character, pretend one
6306 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006307 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006308 coord, &cchwritten) == 0
6309 || cchwritten == 0 || cchwritten == (DWORD)-1)
6310 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006311 }
6312 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006313 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006314 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006315 NULL) == 0 || cchwritten == 0)
6316 cchwritten = 1;
6317 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006318
K.Takata135e1522022-01-29 15:27:58 +00006319 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006320 {
6321 written = cbToWrite;
6322 g_coord.X += (SHORT)cells;
6323 }
6324 else
6325 {
6326 char_u *p = pchBuf;
6327 for (n = 0; n < cchwritten; n++)
6328 MB_CPTR_ADV(p);
6329 written = p - pchBuf;
6330 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006331 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006332
6333 while (g_coord.X > g_srScrollRegion.Right)
6334 {
6335 g_coord.X -= (SHORT) Columns;
6336 if (g_coord.Y < g_srScrollRegion.Bottom)
6337 g_coord.Y++;
6338 }
6339
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006340 // Cursor under VTP is always in the correct position, no need to reset.
6341 if (!USE_VTP)
6342 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006343
6344 return written;
6345}
6346
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006347 static char_u *
6348get_seq(
6349 int *args,
6350 int *count,
6351 char_u *head)
6352{
6353 int argc;
6354 char_u *p;
6355
6356 if (head == NULL || *head != '\033')
6357 return NULL;
6358
6359 argc = 0;
6360 p = head;
6361 ++p;
6362 do
6363 {
6364 ++p;
6365 args[argc] = getdigits(&p);
6366 argc += (argc < 15) ? 1 : 0;
6367 } while (*p == ';');
6368 *count = argc;
6369
6370 return p;
6371}
6372
6373 static char_u *
6374get_sgr(
6375 int *args,
6376 int *count,
6377 char_u *head)
6378{
6379 char_u *p = get_seq(args, count, head);
6380
6381 return (p && *p == 'm') ? ++p : NULL;
6382}
6383
6384/*
6385 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6386 */
6387 static char_u *
6388sgrn2(
6389 char_u *head,
6390 int n)
6391{
6392 int argc;
6393 int args[16];
6394 char_u *p = get_sgr(args, &argc, head);
6395
6396 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6397}
6398
6399/*
6400 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6401 */
6402 static char_u *
6403sgrnc(
6404 char_u *head,
6405 int n)
6406{
6407 int argc;
6408 int args[16];
6409 char_u *p = get_sgr(args, &argc, head);
6410
6411 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6412 ? p : NULL;
6413}
6414
6415 static char_u *
6416skipblank(char_u *q)
6417{
6418 char_u *p = q;
6419
6420 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6421 ++p;
6422 return p;
6423}
6424
6425/*
6426 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6427 * NULL.
6428 */
6429 static char_u *
6430sgrn2c(
6431 char_u *head,
6432 int n)
6433{
6434 char_u *p = sgrn2(head, n);
6435
6436 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6437}
6438
6439/*
6440 * If there is only a newline between the sequence immediately following it,
6441 * a pointer to the character following the newline is returned.
6442 * Otherwise NULL.
6443 */
6444 static char_u *
6445sgrn2cn(
6446 char_u *head,
6447 int n)
6448{
6449 char_u *p = sgrn2(head, n);
6450
6451 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6452}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006453
6454/*
6455 * mch_write(): write the output buffer to the screen, translating ESC
6456 * sequences into calls to console output routines.
6457 */
6458 void
6459mch_write(
6460 char_u *s,
6461 int len)
6462{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006463 char_u *end = s + len;
6464
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006465# ifdef VIMDLL
6466 if (gui.in_use)
6467 return;
6468# endif
6469
Bram Moolenaar071d4272004-06-13 20:20:40 +00006470 if (!term_console)
6471 {
6472 write(1, s, (unsigned)len);
6473 return;
6474 }
6475
Bram Moolenaar0f873732019-12-05 20:28:46 +01006476 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00006477 while (len--)
6478 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006479 int prefix = -1;
6480 char_u ch;
6481
6482 // While processing a sequence, on rare occasions it seems that another
6483 // sequence may be inserted asynchronously.
6484 if (len < 0)
6485 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006486 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006487 return;
6488 }
6489
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006490 while (s + ++prefix < end)
6491 {
6492 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006493 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6494 && ch != '\a' && ch != '\033'))
6495 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006496 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006497
6498 if (p_wd)
6499 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006500 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006501 if (prefix != 0)
6502 prefix = 1;
6503 }
6504
6505 if (prefix != 0)
6506 {
6507 DWORD nWritten;
6508
6509 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006510# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006511 if (fdDump)
6512 {
6513 fputc('>', fdDump);
6514 fwrite(s, sizeof(char_u), nWritten, fdDump);
6515 fputs("<\n", fdDump);
6516 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006517# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006518 len -= (nWritten - 1);
6519 s += nWritten;
6520 }
6521 else if (s[0] == '\n')
6522 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006523 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00006524 if (g_coord.Y == g_srScrollRegion.Bottom)
6525 {
6526 scroll(1);
6527 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6528 }
6529 else
6530 {
6531 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6532 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006533# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006534 if (fdDump)
6535 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006536# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006537 s++;
6538 }
6539 else if (s[0] == '\r')
6540 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006541 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00006542 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006543# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006544 if (fdDump)
6545 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006546# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006547 s++;
6548 }
6549 else if (s[0] == '\b')
6550 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006551 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00006552 if (g_coord.X > g_srScrollRegion.Left)
6553 g_coord.X--;
6554 else if (g_coord.Y > g_srScrollRegion.Top)
6555 {
6556 g_coord.X = g_srScrollRegion.Right;
6557 g_coord.Y--;
6558 }
6559 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006560# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006561 if (fdDump)
6562 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006563# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006564 s++;
6565 }
6566 else if (s[0] == '\a')
6567 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006568 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00006569 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006570# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006571 if (fdDump)
6572 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006573# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006574 s++;
6575 }
6576 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6577 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006578# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006579 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006580# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006581 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006582 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006583 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006584
6585 switch (s[2])
6586 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006587 case '0': case '1': case '2': case '3': case '4':
6588 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006589 if (*(p = get_seq(args, &argc, s)) != 'm')
6590 goto notsgr;
6591
6592 p = s;
6593
6594 // Handling frequent optional sequences. Output to the screen
6595 // takes too long, so do not output as much as possible.
6596
6597 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
6598 // resetFG,FG,BG are omitted.
6599 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006600 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006601 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
6602 len = len + 1 - (int)(p - s);
6603 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006604 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006605 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006606
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006607 // If FG,BG,BG,FG of SGR are connected, the first FG can be
6608 // omitted.
6609 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
6610 p = sp;
6611
6612 // If FG,BG,FG,BG of SGR are connected, the first FG can be
6613 // omitted.
6614 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
6615 p = sp;
6616
6617 // If BG,BG of SGR are connected, the first BG can be omitted.
6618 if (sgrn2((sp = sgrn2(p, 48)), 48))
6619 p = sp;
6620
6621 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01006622 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006623 if (sgrn2((sp = sgrnc(p, 39)), 38))
6624 p = sp;
6625
6626 p = get_seq(args, &argc, p);
6627
6628notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006629 arg1 = args[0];
6630 arg2 = args[1];
6631 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006632 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006633 if (argc == 1 && args[0] == 0)
6634 normvideo();
6635 else if (argc == 1)
6636 {
6637 if (USE_VTP)
6638 textcolor((WORD) arg1);
6639 else
6640 textattr((WORD) arg1);
6641 }
6642 else if (USE_VTP)
6643 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006644 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006645 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006646 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006647 gotoxy(arg2, arg1);
6648 }
6649 else if (argc == 2 && *p == 'r')
6650 {
6651 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6652 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006653 else if (argc == 2 && *p == 'R')
6654 {
6655 set_scroll_region_tb(arg1, arg2);
6656 }
6657 else if (argc == 2 && *p == 'V')
6658 {
6659 set_scroll_region_lr(arg1, arg2);
6660 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006661 else if (argc == 1 && *p == 'A')
6662 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006663 gotoxy(g_coord.X + 1,
6664 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6665 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006666 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006667 {
6668 textbackground((WORD) arg1);
6669 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006670 else if (argc == 1 && *p == 'C')
6671 {
6672 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6673 g_coord.Y + 1);
6674 }
6675 else if (argc == 1 && *p == 'f')
6676 {
6677 textcolor((WORD) arg1);
6678 }
6679 else if (argc == 1 && *p == 'H')
6680 {
6681 gotoxy(1, arg1);
6682 }
6683 else if (argc == 1 && *p == 'L')
6684 {
6685 insert_lines(arg1);
6686 }
6687 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006688 {
6689 delete_lines(arg1);
6690 }
6691
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006692 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006693 s = p + 1;
6694 break;
6695
Bram Moolenaar071d4272004-06-13 20:20:40 +00006696 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006697 gotoxy(g_coord.X + 1,
6698 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6699 goto got3;
6700
6701 case 'B':
6702 visual_bell();
6703 goto got3;
6704
6705 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006706 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6707 g_coord.Y + 1);
6708 goto got3;
6709
6710 case 'E':
6711 termcap_mode_end();
6712 goto got3;
6713
6714 case 'F':
6715 standout();
6716 goto got3;
6717
6718 case 'f':
6719 standend();
6720 goto got3;
6721
6722 case 'H':
6723 gotoxy(1, 1);
6724 goto got3;
6725
6726 case 'j':
6727 clear_to_end_of_display();
6728 goto got3;
6729
6730 case 'J':
6731 clear_screen();
6732 goto got3;
6733
6734 case 'K':
6735 clear_to_end_of_line();
6736 goto got3;
6737
6738 case 'L':
6739 insert_lines(1);
6740 goto got3;
6741
6742 case 'M':
6743 delete_lines(1);
6744 goto got3;
6745
6746 case 'S':
6747 termcap_mode_start();
6748 goto got3;
6749
6750 case 'V':
6751 cursor_visible(TRUE);
6752 goto got3;
6753
6754 case 'v':
6755 cursor_visible(FALSE);
6756 goto got3;
6757
6758 got3:
6759 s += 3;
6760 len -= 2;
6761 }
6762
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006763# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006764 if (fdDump)
6765 {
6766 fputs("ESC | ", fdDump);
6767 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6768 fputc('\n', fdDump);
6769 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006770# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006771 }
6772 else
6773 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006774 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00006775 DWORD nWritten;
6776
6777 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006778# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006779 if (fdDump)
6780 {
6781 fputc('>', fdDump);
6782 fwrite(s, sizeof(char_u), nWritten, fdDump);
6783 fputs("<\n", fdDump);
6784 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006785# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006786
6787 len -= (nWritten - 1);
6788 s += nWritten;
6789 }
6790 }
6791
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006792# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006793 if (fdDump)
6794 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006795# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006796}
6797
Bram Moolenaar0f873732019-12-05 20:28:46 +01006798#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006799
6800
6801/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006802 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006803 */
6804 void
6805mch_delay(
6806 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02006807 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006808{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006809#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006810 Sleep((int)msec); // never wait for input
6811#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006812# ifdef VIMDLL
6813 if (gui.in_use)
6814 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006815 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006816 return;
6817 }
6818# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02006819 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006820# ifdef FEAT_MZSCHEME
6821 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6822 {
6823 int towait = p_mzq;
6824
Bram Moolenaar0f873732019-12-05 20:28:46 +01006825 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006826 while (msec > 0)
6827 {
6828 mzvim_check_threads();
6829 if (msec < towait)
6830 towait = msec;
6831 Sleep(towait);
6832 msec -= towait;
6833 }
6834 }
6835 else
6836# endif
6837 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006838 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006839 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006840#endif
6841}
6842
6843
6844/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006845 * This version of remove is not scared by a readonly (backup) file.
6846 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006847 * Return 0 for success, -1 for failure.
6848 */
6849 int
6850mch_remove(char_u *name)
6851{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006852 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006853 int n;
6854
Bram Moolenaar203258c2016-01-17 22:15:16 +01006855 /*
6856 * On Windows, deleting a directory's symbolic link is done by
6857 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6858 */
6859 if (mch_isdir(name) && mch_is_symbolic_link(name))
6860 return mch_rmdir(name);
6861
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006862 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6863
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006864 wn = enc_to_utf16(name, NULL);
6865 if (wn == NULL)
6866 return -1;
6867
6868 n = DeleteFileW(wn) ? 0 : -1;
6869 vim_free(wn);
6870 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006871}
6872
6873
6874/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006875 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006876 */
6877 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006878mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006879{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006880#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
6881# ifdef VIMDLL
6882 if (!gui.in_use)
6883# endif
6884 if (g_fCtrlCPressed || g_fCBrkPressed)
6885 {
6886 ctrl_break_was_pressed = g_fCBrkPressed;
6887 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6888 got_int = TRUE;
6889 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006890#endif
6891}
6892
Bram Moolenaar0f873732019-12-05 20:28:46 +01006893// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01006894#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006895
6896/*
6897 * How much main memory in KiB that can be used by VIM.
6898 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006899 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006900mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006901{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006902 MEMORYSTATUSEX ms;
6903
Bram Moolenaar0f873732019-12-05 20:28:46 +01006904 // Need to use GlobalMemoryStatusEx() when there is more memory than
6905 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006906 ms.dwLength = sizeof(MEMORYSTATUSEX);
6907 GlobalMemoryStatusEx(&ms);
6908 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006909 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006910 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006911 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006912 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006913 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006914 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006915 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006916 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006917 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01006918 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006919 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006920}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006921
Bram Moolenaar071d4272004-06-13 20:20:40 +00006922/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006923 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00006924 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6925 * file whose short file name is "FOO.BAR" (its long file name will
6926 * be correct: "foo.bar~"). Because a file can be accessed by
6927 * either its SFN or its LFN, "foo.bar" has effectively been
6928 * renamed to "foo.bar", which is not at all what was wanted. This
6929 * seems to happen only when renaming files with three-character
6930 * extensions by appending a suffix that does not include ".".
6931 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6932 *
6933 * There is another problem, which isn't really a bug but isn't right either:
6934 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6935 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6936 * service pack 6. Doesn't seem to happen on Windows 98.
6937 *
6938 * Like rename(), returns 0 upon success, non-zero upon failure.
6939 * Should probably set errno appropriately when errors occur.
6940 */
6941 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006942mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006943{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006944 WCHAR *p;
6945 int i;
6946 WCHAR szTempFile[_MAX_PATH + 1];
6947 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006948 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006949
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006950 // No need to play tricks unless the file name contains a "~" as the
6951 // seventh character.
6952 p = wold;
6953 for (i = 0; wold[i] != NUL; ++i)
6954 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6955 && wold[i + 1] != 0)
6956 p = wold + i + 1;
6957 if ((int)(wold + i - p) < 8 || p[6] != '~')
6958 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006959
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006960 // Get base path of new file name. Undocumented feature: If pszNewFile is
6961 // a directory, no error is returned and pszFilePart will be NULL.
6962 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006963 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006964 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006965
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006966 // Get (and create) a unique temporary file name in directory of new file
6967 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006968 return -2;
6969
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006970 // blow the temp file away
6971 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006972 return -3;
6973
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006974 // rename old file to the temp file
6975 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006976 return -4;
6977
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006978 // now create an empty file called pszOldFile; this prevents the operating
6979 // system using pszOldFile as an alias (SFN) if we're renaming within the
6980 // same directory. For example, we're editing a file called
6981 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6982 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
6983 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
6984 // cause all sorts of problems later in buf_write(). So, we create an
6985 // empty file called filena~1.txt and the system will have to find some
6986 // other SFN for filena~1.txt~, such as filena~2.txt
6987 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006988 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6989 return -5;
6990 if (!CloseHandle(hf))
6991 return -6;
6992
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006993 // rename the temp file to the new file
6994 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006995 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006996 // Renaming failed. Rename the file back to its old name, so that it
6997 // looks like nothing happened.
6998 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006999 return -7;
7000 }
7001
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007002 // Seems to be left around on Novell filesystems
7003 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007004
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007005 // finally, remove the empty old file
7006 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007007 return -8;
7008
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007009 return 0;
7010}
7011
7012
7013/*
7014 * Converts the filenames to UTF-16, then call mch_wrename().
7015 * Like rename(), returns 0 upon success, non-zero upon failure.
7016 */
7017 int
7018mch_rename(
7019 const char *pszOldFile,
7020 const char *pszNewFile)
7021{
7022 WCHAR *wold = NULL;
7023 WCHAR *wnew = NULL;
7024 int retval = -1;
7025
7026 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7027 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7028 if (wold != NULL && wnew != NULL)
7029 retval = mch_wrename(wold, wnew);
7030 vim_free(wold);
7031 vim_free(wnew);
7032 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007033}
7034
7035/*
7036 * Get the default shell for the current hardware platform
7037 */
7038 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007039default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007040{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007041 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007042}
7043
7044/*
7045 * mch_access() extends access() to do more detailed check on network drives.
7046 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7047 */
7048 int
7049mch_access(char *n, int p)
7050{
7051 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007052 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007053 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007054
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007055 wn = enc_to_utf16((char_u *)n, NULL);
7056 if (wn == NULL)
7057 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007058
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007059 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007060 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007061 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007062
7063 if (p & R_OK)
7064 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007065 // Read check is performed by seeing if we can do a find file on
7066 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007067 int i;
7068 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007069
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007070 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7071 TempNameW[i] = wn[i];
7072 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7073 TempNameW[i++] = '\\';
7074 TempNameW[i++] = '*';
7075 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007076
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007077 hFile = FindFirstFileW(TempNameW, &d);
7078 if (hFile == INVALID_HANDLE_VALUE)
7079 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007080 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007081 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007082 }
7083
7084 if (p & W_OK)
7085 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007086 // Trying to create a temporary file in the directory should catch
7087 // directories on read-only network shares. However, in
7088 // directories whose ACL allows writes but denies deletes will end
7089 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007090 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7091 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007092 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007093 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007094 }
7095 }
7096 else
7097 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007098 // Don't consider a file read-only if another process has opened it.
7099 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7100
Bram Moolenaar0f873732019-12-05 20:28:46 +01007101 // Trying to open the file for the required access does ACL, read-only
7102 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007103 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7104 | ((p & R_OK) ? GENERIC_READ : 0);
7105
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007106 hFile = CreateFileW(wn, access_mode, share_mode,
7107 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007108 if (hFile == INVALID_HANDLE_VALUE)
7109 goto getout;
7110 CloseHandle(hFile);
7111 }
7112
Bram Moolenaar0f873732019-12-05 20:28:46 +01007113 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007114getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007115 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007116 return retval;
7117}
7118
Bram Moolenaar071d4272004-06-13 20:20:40 +00007119/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007120 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007121 */
7122 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007123mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007124{
7125 WCHAR *wn;
7126 int f;
7127
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007128 wn = enc_to_utf16((char_u *)name, NULL);
7129 if (wn == NULL)
7130 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007131
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007132 f = _wopen(wn, flags, mode);
7133 vim_free(wn);
7134 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007135}
7136
7137/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007138 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007139 */
7140 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007141mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007142{
7143 WCHAR *wn, *wm;
7144 FILE *f = NULL;
7145
Bram Moolenaara12a1612019-01-24 16:39:02 +01007146#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007147 // Work around an annoying assertion in the Microsoft debug CRT
7148 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007149 char newMode = mode[strlen(mode) - 1];
7150 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007151
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007152 _get_fmode(&oldMode);
7153 if (newMode == 't')
7154 _set_fmode(_O_TEXT);
7155 else if (newMode == 'b')
7156 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007157#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007158 wn = enc_to_utf16((char_u *)name, NULL);
7159 wm = enc_to_utf16((char_u *)mode, NULL);
7160 if (wn != NULL && wm != NULL)
7161 f = _wfopen(wn, wm);
7162 vim_free(wn);
7163 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007164
Bram Moolenaara12a1612019-01-24 16:39:02 +01007165#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007166 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007167#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007168 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007169}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007170
Bram Moolenaar071d4272004-06-13 20:20:40 +00007171/*
7172 * SUB STREAM (aka info stream) handling:
7173 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007174 * NTFS can have sub streams for each file. The normal contents of a file is
7175 * stored in the main stream, and extra contents (author information, title and
7176 * so on) can be stored in a sub stream. After Windows 2000, the user can
7177 * access and store this information in sub streams via an explorer's property
7178 * menu item in the right click menu. This information in sub streams was lost
7179 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007180 *
7181 * Incomplete explanation:
7182 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7183 * More useful info and an example:
7184 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7185 */
7186
7187/*
7188 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7189 * and write to stream "substream" of file "to".
7190 * Errors are ignored.
7191 */
7192 static void
7193copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7194{
7195 HANDLE hTo;
7196 WCHAR *to_name;
7197
7198 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7199 wcscpy(to_name, to);
7200 wcscat(to_name, substream);
7201
7202 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7203 FILE_ATTRIBUTE_NORMAL, NULL);
7204 if (hTo != INVALID_HANDLE_VALUE)
7205 {
7206 long done;
7207 DWORD todo;
7208 DWORD readcnt, written;
7209 char buf[4096];
7210
Bram Moolenaar0f873732019-12-05 20:28:46 +01007211 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007212 for (done = 0; done < len; done += written)
7213 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007214 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007215 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7216 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007217 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7218 FALSE, FALSE, context)
7219 || readcnt != todo
7220 || !WriteFile(hTo, buf, todo, &written, NULL)
7221 || written != todo)
7222 break;
7223 }
7224 CloseHandle(hTo);
7225 }
7226
7227 free(to_name);
7228}
7229
7230/*
7231 * Copy info streams from file "from" to file "to".
7232 */
7233 static void
7234copy_infostreams(char_u *from, char_u *to)
7235{
7236 WCHAR *fromw;
7237 WCHAR *tow;
7238 HANDLE sh;
7239 WIN32_STREAM_ID sid;
7240 int headersize;
7241 WCHAR streamname[_MAX_PATH];
7242 DWORD readcount;
7243 void *context = NULL;
7244 DWORD lo, hi;
7245 int len;
7246
Bram Moolenaar0f873732019-12-05 20:28:46 +01007247 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007248 fromw = enc_to_utf16(from, NULL);
7249 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007250 if (fromw != NULL && tow != NULL)
7251 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007252 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007253 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7254 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7255 if (sh != INVALID_HANDLE_VALUE)
7256 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007257 // Use BackupRead() to find the info streams. Repeat until we
7258 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007259 for (;;)
7260 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007261 // Get the header to find the length of the stream name. If
7262 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007263 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007264 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007265 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7266 &readcount, FALSE, FALSE, &context)
7267 || readcount == 0)
7268 break;
7269
Bram Moolenaar0f873732019-12-05 20:28:46 +01007270 // We only deal with streams that have a name. The normal
7271 // file data appears to be without a name, even though docs
7272 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007273 if (sid.dwStreamNameSize > 0)
7274 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007275 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007276 if (!BackupRead(sh, (LPBYTE)streamname,
7277 sid.dwStreamNameSize,
7278 &readcount, FALSE, FALSE, &context))
7279 break;
7280
Bram Moolenaar0f873732019-12-05 20:28:46 +01007281 // Copy an info stream with a name ":anything:$DATA".
7282 // Skip "::$DATA", it has no stream name (examples suggest
7283 // it might be used for the normal file contents).
7284 // Note that BackupRead() counts bytes, but the name is in
7285 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007286 len = readcount / sizeof(WCHAR);
7287 streamname[len] = 0;
7288 if (len > 7 && wcsicmp(streamname + len - 6,
7289 L":$DATA") == 0)
7290 {
7291 streamname[len - 6] = 0;
7292 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007293 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007294 }
7295 }
7296
Bram Moolenaar0f873732019-12-05 20:28:46 +01007297 // Advance to the next stream. We might try seeking too far,
7298 // but BackupSeek() doesn't skip over stream borders, thus
7299 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007300 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007301 &lo, &hi, &context);
7302 }
7303
Bram Moolenaar0f873732019-12-05 20:28:46 +01007304 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007305 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7306
7307 CloseHandle(sh);
7308 }
7309 }
7310 vim_free(fromw);
7311 vim_free(tow);
7312}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007313
7314/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007315 * ntdll.dll definitions
7316 */
7317#define FileEaInformation 7
7318#ifndef STATUS_SUCCESS
7319# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7320#endif
7321
7322typedef struct _FILE_FULL_EA_INFORMATION_ {
7323 ULONG NextEntryOffset;
7324 UCHAR Flags;
7325 UCHAR EaNameLength;
7326 USHORT EaValueLength;
7327 CHAR EaName[1];
7328} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7329
7330typedef struct _FILE_EA_INFORMATION_ {
7331 ULONG EaSize;
7332} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7333
Paul Ollis65745772022-06-05 16:55:54 +01007334#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007335typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7336 PHANDLE FileHandle,
7337 ACCESS_MASK DesiredAccess,
7338 POBJECT_ATTRIBUTES ObjectAttributes,
7339 PIO_STATUS_BLOCK IoStatusBlock,
7340 ULONG ShareAccess,
7341 ULONG OpenOptions);
7342typedef NTSTATUS (NTAPI *PfnNtClose)(
7343 HANDLE Handle);
7344typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007345 HANDLE FileHandle,
7346 PIO_STATUS_BLOCK IoStatusBlock,
7347 PVOID Buffer,
7348 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007349typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7350 HANDLE FileHandle,
7351 PIO_STATUS_BLOCK IoStatusBlock,
7352 PVOID Buffer,
7353 ULONG Length,
7354 BOOLEAN ReturnSingleEntry,
7355 PVOID EaList,
7356 ULONG EaListLength,
7357 PULONG EaIndex,
7358 BOOLEAN RestartScan);
7359typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007360 HANDLE FileHandle,
7361 PIO_STATUS_BLOCK IoStatusBlock,
7362 PVOID FileInformation,
7363 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007364 FILE_INFORMATION_CLASS FileInformationClass);
7365typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7366 PUNICODE_STRING DestinationString,
7367 PCWSTR SourceString);
7368
7369PfnNtOpenFile pNtOpenFile = NULL;
7370PfnNtClose pNtClose = NULL;
7371PfnNtSetEaFile pNtSetEaFile = NULL;
7372PfnNtQueryEaFile pNtQueryEaFile = NULL;
7373PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7374PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01007375#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007376
7377/*
7378 * Load ntdll.dll functions.
7379 */
7380 static BOOL
7381load_ntdll(void)
7382{
7383 static int loaded = -1;
7384
7385 if (loaded == -1)
7386 {
7387 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7388 if (hNtdll != NULL)
7389 {
7390 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7391 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7392 pNtSetEaFile = (PfnNtSetEaFile)
7393 GetProcAddress(hNtdll, "NtSetEaFile");
7394 pNtQueryEaFile = (PfnNtQueryEaFile)
7395 GetProcAddress(hNtdll, "NtQueryEaFile");
7396 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7397 GetProcAddress(hNtdll, "NtQueryInformationFile");
7398 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7399 GetProcAddress(hNtdll, "RtlInitUnicodeString");
7400 }
7401 if (pNtOpenFile == NULL
7402 || pNtClose == NULL
7403 || pNtSetEaFile == NULL
7404 || pNtQueryEaFile == NULL
7405 || pNtQueryInformationFile == NULL
7406 || pRtlInitUnicodeString == NULL)
7407 loaded = FALSE;
7408 else
7409 loaded = TRUE;
7410 }
7411 return (BOOL) loaded;
7412}
7413
7414/*
7415 * Copy extended attributes (EA) from file "from" to file "to".
7416 */
7417 static void
7418copy_extattr(char_u *from, char_u *to)
7419{
7420 char_u *fromf = NULL;
7421 char_u *tof = NULL;
7422 WCHAR *fromw = NULL;
7423 WCHAR *tow = NULL;
7424 UNICODE_STRING u;
7425 HANDLE h;
7426 OBJECT_ATTRIBUTES oa;
7427 IO_STATUS_BLOCK iosb;
7428 FILE_EA_INFORMATION_ eainfo = {0};
7429 void *ea = NULL;
7430
7431 if (!load_ntdll())
7432 return;
7433
7434 // Convert the file names to the fully qualified object names.
7435 fromf = alloc(STRLEN(from) + 5);
7436 tof = alloc(STRLEN(to) + 5);
7437 if (fromf == NULL || tof == NULL)
7438 goto theend;
7439 STRCPY(fromf, "\\??\\");
7440 STRCAT(fromf, from);
7441 STRCPY(tof, "\\??\\");
7442 STRCAT(tof, to);
7443
7444 // Convert the names to wide characters.
7445 fromw = enc_to_utf16(fromf, NULL);
7446 tow = enc_to_utf16(tof, NULL);
7447 if (fromw == NULL || tow == NULL)
7448 goto theend;
7449
7450 // Get the EA.
7451 pRtlInitUnicodeString(&u, fromw);
7452 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7453 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7454 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7455 goto theend;
7456 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7457 FileEaInformation);
7458 if (eainfo.EaSize != 0)
7459 {
7460 ea = alloc(eainfo.EaSize);
7461 if (ea != NULL)
7462 {
7463 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7464 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7465 {
7466 vim_free(ea);
7467 ea = NULL;
7468 }
7469 }
7470 }
7471 pNtClose(h);
7472
7473 // Set the EA.
7474 if (ea != NULL)
7475 {
7476 pRtlInitUnicodeString(&u, tow);
7477 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7478 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7479 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7480 goto theend;
7481
7482 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
7483 pNtClose(h);
7484 }
7485
7486theend:
7487 vim_free(fromf);
7488 vim_free(tof);
7489 vim_free(fromw);
7490 vim_free(tow);
7491 vim_free(ea);
7492}
7493
7494/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007495 * Copy file attributes from file "from" to file "to".
7496 * For Windows NT and later we copy info streams.
7497 * Always returns zero, errors are ignored.
7498 */
7499 int
7500mch_copy_file_attribute(char_u *from, char_u *to)
7501{
Bram Moolenaar0f873732019-12-05 20:28:46 +01007502 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007503 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007504 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007505 return 0;
7506}
7507
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007508
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007509/*
K.Takatadc73b4b2021-06-08 18:32:36 +02007510 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007511 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007512static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007513static LPWSTR *ArglistW = NULL;
7514static int global_argc = 0;
7515static char **global_argv;
7516
Bram Moolenaar0f873732019-12-05 20:28:46 +01007517static int used_file_argc = 0; // last argument in global_argv[] used
7518 // for the argument list.
7519static int *used_file_indexes = NULL; // indexes in global_argv[] for
7520 // command line arguments added to
7521 // the argument list
7522static int used_file_count = 0; // nr of entries in used_file_indexes
7523static int used_file_literal = FALSE; // take file names literally
7524static int used_file_full_path = FALSE; // file name was full path
7525static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007526static int used_alist_count = 0;
7527
7528
7529/*
7530 * Get the command line arguments. Unicode version.
7531 * Returns argc. Zero when something fails.
7532 */
7533 int
7534get_cmd_argsW(char ***argvp)
7535{
7536 char **argv = NULL;
7537 int argc = 0;
7538 int i;
7539
Bram Moolenaar14993322014-09-09 12:25:33 +02007540 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007541 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7542 if (ArglistW != NULL)
7543 {
7544 argv = malloc((nArgsW + 1) * sizeof(char *));
7545 if (argv != NULL)
7546 {
7547 argc = nArgsW;
7548 argv[argc] = NULL;
7549 for (i = 0; i < argc; ++i)
7550 {
7551 int len;
7552
K.Takatadc73b4b2021-06-08 18:32:36 +02007553 // Convert each Unicode argument to UTF-8.
7554 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007555 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007556 (LPSTR *)&argv[i], &len, 0, 0);
7557 if (argv[i] == NULL)
7558 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007559 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007560 while (i > 0)
7561 free(argv[--i]);
7562 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007563 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007564 argc = 0;
7565 }
7566 }
7567 }
7568 }
7569
7570 global_argc = argc;
7571 global_argv = argv;
7572 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007573 {
7574 if (used_file_indexes != NULL)
7575 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007576 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007577 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007578
7579 if (argvp != NULL)
7580 *argvp = argv;
7581 return argc;
7582}
7583
7584 void
7585free_cmd_argsW(void)
7586{
7587 if (ArglistW != NULL)
7588 {
7589 GlobalFree(ArglistW);
7590 ArglistW = NULL;
7591 }
7592}
7593
7594/*
7595 * Remember "name" is an argument that was added to the argument list.
7596 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7597 * is called.
7598 */
7599 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007600used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007601{
7602 int i;
7603
7604 if (used_file_indexes == NULL)
7605 return;
7606 for (i = used_file_argc + 1; i < global_argc; ++i)
7607 if (STRCMP(global_argv[i], name) == 0)
7608 {
7609 used_file_argc = i;
7610 used_file_indexes[used_file_count++] = i;
7611 break;
7612 }
7613 used_file_literal = literal;
7614 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007615 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007616}
7617
7618/*
7619 * Remember the length of the argument list as it was. If it changes then we
7620 * leave it alone when 'encoding' is set.
7621 */
7622 void
7623set_alist_count(void)
7624{
7625 used_alist_count = GARGCOUNT;
7626}
7627
7628/*
7629 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02007630 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007631 * and convert them to 'encoding'.
7632 */
7633 void
7634fix_arg_enc(void)
7635{
7636 int i;
7637 int idx;
7638 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007639 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007640
Bram Moolenaar0f873732019-12-05 20:28:46 +01007641 // Safety checks:
7642 // - if argument count differs between the wide and non-wide argument
7643 // list, something must be wrong.
7644 // - the file name arguments must have been located.
7645 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007646 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007647 || ArglistW == NULL
7648 || used_file_indexes == NULL
7649 || used_file_count == 0
7650 || used_alist_count != GARGCOUNT)
7651 return;
7652
Bram Moolenaar0f873732019-12-05 20:28:46 +01007653 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007654 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007655 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007656 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00007657 for (i = 0; i < GARGCOUNT; ++i)
7658 fnum_list[i] = GARGLIST[i].ae_fnum;
7659
Bram Moolenaar0f873732019-12-05 20:28:46 +01007660 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007661 alist_clear(&global_alist);
7662 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007663 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007664
7665 for (i = 0; i < used_file_count; ++i)
7666 {
7667 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007668 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007669 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007670 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007671 int literal = used_file_literal;
7672
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007673#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01007674 // When using diff mode may need to concatenate file name to
7675 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007676 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7677 && !mch_isdir(alist_name(&GARGLIST[0])))
7678 {
7679 char_u *r;
7680
7681 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7682 if (r != NULL)
7683 {
7684 vim_free(str);
7685 str = r;
7686 }
7687 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007688#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01007689 // Re-use the old buffer by renaming it. When not using literal
7690 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00007691 if (used_file_literal)
7692 buf_set_name(fnum_list[i], str);
7693
Bram Moolenaar0f873732019-12-05 20:28:46 +01007694 // Check backtick literal. backtick literal is already expanded in
7695 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007696 if (literal == FALSE)
7697 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007698 size_t len = STRLEN(str);
7699
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007700 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7701 literal = TRUE;
7702 }
7703 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007704 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007705 }
7706
7707 if (!used_file_literal)
7708 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007709 // Now expand wildcards in the arguments.
7710 // Temporarily add '(' and ')' to 'isfname'. These are valid
7711 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00007712 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01007713 // Also, unset wildignore to not be influenced by this option.
7714 // The arguments specified in command-line should be kept even if
7715 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00007716 // Use :legacy so that it also works when in Vim9 script.
7717 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
7718 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007719 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00007720 do_cmdline_cmd(
7721 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
7722 do_cmdline_cmd(
7723 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007724 }
7725
Bram Moolenaar0f873732019-12-05 20:28:46 +01007726 // If wildcard expansion failed, we are editing the first file of the
7727 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007728 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7729 {
7730 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00007731 if (GARGCOUNT == 1 && used_file_full_path
7732 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
7733 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007734 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007735
7736 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007737}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007738
7739 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007740mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007741{
7742 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007743 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007744
Bram Moolenaar964b3742019-05-24 18:54:09 +02007745 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007746 if (envbuf == NULL)
7747 return -1;
7748
7749 sprintf((char *)envbuf, "%s=%s", var, value);
7750
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007751 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007752
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007753 vim_free(envbuf);
7754 if (p == NULL)
7755 return -1;
7756 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007757#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007758 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007759#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007760 // Unlike Un*x systems, we can free the string for _wputenv().
7761 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007762
7763 return 0;
7764}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007765
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007766/*
7767 * Support for 256 colors and 24-bit colors was added in Windows 10
7768 * version 1703 (Creators update).
7769 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007770#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7771
7772/*
7773 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02007774 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007775 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007776#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007777
7778/*
7779 * ConPTY differences between versions, need different logic.
7780 * version 1903 (May 2019 update).
7781 */
7782#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
7783
7784/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007785 * version 1909 (November 2019 update).
7786 */
7787#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
7788
7789/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007790 * Stay ahead of the next update, and when it's done, fix this.
7791 * version ? (2020 update, temporarily use the build number of insider preview)
7792 */
7793#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
7794
7795/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02007796 * Confirm until this version. Also the logic changes.
7797 * insider preview.
7798 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02007799#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007800
7801/*
7802 * Not stable now.
7803 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007804#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007805
7806 static void
7807vtp_flag_init(void)
7808{
7809 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007810#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007811 DWORD mode;
7812 HANDLE out;
7813
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007814# ifdef VIMDLL
7815 if (!gui.in_use)
7816# endif
7817 {
7818 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007819
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007820 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7821 GetConsoleMode(out, &mode);
7822 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7823 if (SetConsoleMode(out, mode) == 0)
7824 vtp_working = 0;
7825 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007826#endif
7827
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007828 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007829 conpty_working = 1;
7830 if (ver >= CONPTY_STABLE_BUILD)
7831 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007832
Bram Moolenaar57da6982019-09-13 22:30:11 +02007833 if (ver <= CONPTY_INSIDER_BUILD)
7834 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007835 if (ver <= CONPTY_1909_BUILD)
7836 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02007837 if (ver <= CONPTY_1903_BUILD)
7838 conpty_type = 2;
7839 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
7840 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007841
7842 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
7843 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007844}
7845
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007846#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007847
7848 static void
7849vtp_init(void)
7850{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007851 HMODULE hKerneldll;
7852 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007853# ifdef FEAT_TERMGUICOLORS
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01007854 COLORREF fg;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007855# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007856
Bram Moolenaar0f873732019-12-05 20:28:46 +01007857 // Use functions supported from Vista
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007858 hKerneldll = GetModuleHandle("kernel32.dll");
7859 if (hKerneldll != NULL)
7860 {
7861 pGetConsoleScreenBufferInfoEx =
7862 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7863 hKerneldll, "GetConsoleScreenBufferInfoEx");
7864 pSetConsoleScreenBufferInfoEx =
7865 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7866 hKerneldll, "SetConsoleScreenBufferInfoEx");
7867 if (pGetConsoleScreenBufferInfoEx != NULL
7868 && pSetConsoleScreenBufferInfoEx != NULL)
7869 has_csbiex = TRUE;
7870 }
7871
7872 csbi.cbSize = sizeof(csbi);
7873 if (has_csbiex)
7874 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007875 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7876 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
Bram Moolenaardf543822020-01-30 11:53:59 +01007877 store_console_bg_rgb = save_console_bg_rgb;
7878 store_console_fg_rgb = save_console_fg_rgb;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007879
7880# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007881 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007882 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007883 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007884# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007885
7886 set_console_color_rgb();
7887}
7888
7889 static void
7890vtp_exit(void)
7891{
Bram Moolenaardf543822020-01-30 11:53:59 +01007892 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007893}
7894
Bram Moolenaar06b7b582020-05-30 17:49:25 +02007895 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007896vtp_printf(
7897 char *format,
7898 ...)
7899{
7900 char_u buf[100];
7901 va_list list;
7902 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007903 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007904
7905 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007906 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007907 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007908 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007909 return (int)result;
7910}
7911
7912 static void
7913vtp_sgr_bulk(
7914 int arg)
7915{
7916 int args[1];
7917
7918 args[0] = arg;
7919 vtp_sgr_bulks(1, args);
7920}
7921
K.Takata6e1d31e2022-02-03 13:05:32 +00007922# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007923 if ((*p-- = "0123456789"[(n = x % 10)]) \
7924 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
7925 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
7926
K.Takata6e1d31e2022-02-03 13:05:32 +00007927# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007928 case x: \
7929 FAST256(newargs[x - 1]);
7930
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007931 static void
7932vtp_sgr_bulks(
7933 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007934 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007935{
K.Takata6e1d31e2022-02-03 13:05:32 +00007936# define MAXSGR 16
7937# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007938 char_u buf[SGRBUFSIZE];
7939 char_u *p;
7940 int in, out;
7941 int newargs[16];
7942 static int sgrfgr = -1, sgrfgg, sgrfgb;
7943 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007944
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007945 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007946 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007947 sgrfgr = sgrbgr = -1;
7948 vtp_printf("033[m");
7949 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007950 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007951
7952 in = out = 0;
7953 while (in < argc)
7954 {
7955 int s = args[in];
7956 int copylen = 1;
7957
7958 if (s == 38)
7959 {
7960 if (argc - in >= 5 && args[in + 1] == 2)
7961 {
7962 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
7963 && sgrfgb == args[in + 4])
7964 {
7965 in += 5;
7966 copylen = 0;
7967 }
7968 else
7969 {
7970 sgrfgr = args[in + 2];
7971 sgrfgg = args[in + 3];
7972 sgrfgb = args[in + 4];
7973 copylen = 5;
7974 }
7975 }
7976 else if (argc - in >= 3 && args[in + 1] == 5)
7977 {
7978 sgrfgr = -1;
7979 copylen = 3;
7980 }
7981 }
7982 else if (s == 48)
7983 {
7984 if (argc - in >= 5 && args[in + 1] == 2)
7985 {
7986 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
7987 && sgrbgb == args[in + 4])
7988 {
7989 in += 5;
7990 copylen = 0;
7991 }
7992 else
7993 {
7994 sgrbgr = args[in + 2];
7995 sgrbgg = args[in + 3];
7996 sgrbgb = args[in + 4];
7997 copylen = 5;
7998 }
7999 }
8000 else if (argc - in >= 3 && args[in + 1] == 5)
8001 {
8002 sgrbgr = -1;
8003 copylen = 3;
8004 }
8005 }
8006 else if (30 <= s && s <= 39)
8007 sgrfgr = -1;
8008 else if (90 <= s && s <= 97)
8009 sgrfgr = -1;
8010 else if (40 <= s && s <= 49)
8011 sgrbgr = -1;
8012 else if (100 <= s && s <= 107)
8013 sgrbgr = -1;
8014 else if (s == 0)
8015 sgrfgr = sgrbgr = -1;
8016
8017 while (copylen--)
8018 newargs[out++] = args[in++];
8019 }
8020
8021 p = &buf[sizeof(buf) - 1];
8022 *p-- = 'm';
8023
8024 switch (out)
8025 {
8026 int n, m;
8027 DWORD r;
8028
8029 FAST256CASE(16);
8030 *p-- = ';';
8031 FAST256CASE(15);
8032 *p-- = ';';
8033 FAST256CASE(14);
8034 *p-- = ';';
8035 FAST256CASE(13);
8036 *p-- = ';';
8037 FAST256CASE(12);
8038 *p-- = ';';
8039 FAST256CASE(11);
8040 *p-- = ';';
8041 FAST256CASE(10);
8042 *p-- = ';';
8043 FAST256CASE(9);
8044 *p-- = ';';
8045 FAST256CASE(8);
8046 *p-- = ';';
8047 FAST256CASE(7);
8048 *p-- = ';';
8049 FAST256CASE(6);
8050 *p-- = ';';
8051 FAST256CASE(5);
8052 *p-- = ';';
8053 FAST256CASE(4);
8054 *p-- = ';';
8055 FAST256CASE(3);
8056 *p-- = ';';
8057 FAST256CASE(2);
8058 *p-- = ';';
8059 FAST256CASE(1);
8060 *p-- = '[';
8061 *p = '\033';
8062 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8063 default:
8064 break;
8065 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008066}
8067
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008068 static void
8069wt_init(void)
8070{
8071 wt_working = (mch_getenv("WT_SESSION") != NULL);
8072}
8073
8074 int
8075use_wt(void)
8076{
8077 return USE_WT;
8078}
8079
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008080# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008081 static int
8082ctermtoxterm(
8083 int cterm)
8084{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008085 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008086
8087 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8088 return (((int)r << 16) | ((int)g << 8) | (int)b);
8089}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008090# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008091
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008092 static void
8093set_console_color_rgb(void)
8094{
8095# ifdef FEAT_TERMGUICOLORS
8096 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008097 guicolor_T fg, bg;
8098 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008099
8100 if (!USE_VTP)
8101 return;
8102
Bram Moolenaara050b942019-12-02 21:35:31 +01008103 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8104
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008105 if (USE_WT)
8106 {
8107 term_fg_rgb_color(fg);
8108 term_bg_rgb_color(bg);
8109 return;
8110 }
8111
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008112 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8113 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8114
8115 csbi.cbSize = sizeof(csbi);
8116 if (has_csbiex)
8117 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8118
8119 csbi.cbSize = sizeof(csbi);
8120 csbi.srWindow.Right += 1;
8121 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008122 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8123 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008124 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8125 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008126 if (has_csbiex)
8127 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8128# endif
8129}
8130
Bram Moolenaara050b942019-12-02 21:35:31 +01008131# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8132 void
8133get_default_console_color(
8134 int *cterm_fg,
8135 int *cterm_bg,
8136 guicolor_T *gui_fg,
8137 guicolor_T *gui_bg)
8138{
8139 int id;
8140 guicolor_T guifg = INVALCOLOR;
8141 guicolor_T guibg = INVALCOLOR;
8142 int ctermfg = 0;
8143 int ctermbg = 0;
8144
8145 id = syn_name2id((char_u *)"Normal");
8146 if (id > 0 && p_tgc)
8147 syn_id2colors(id, &guifg, &guibg);
8148 if (guifg == INVALCOLOR)
8149 {
8150 ctermfg = -1;
8151 if (id > 0)
8152 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8153 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
8154 : default_console_color_fg;
8155 cterm_normal_fg_gui_color = guifg;
8156 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8157 }
8158 if (guibg == INVALCOLOR)
8159 {
8160 ctermbg = -1;
8161 if (id > 0)
8162 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01008163 cterm_normal_bg_gui_color = guibg =
8164 ctermbg != -1 ? ctermtoxterm(ctermbg) : INVALCOLOR;
8165
8166 if (ctermbg < 0)
8167 ctermbg = 0;
Bram Moolenaara050b942019-12-02 21:35:31 +01008168 }
8169
8170 *cterm_fg = ctermfg;
8171 *cterm_bg = ctermbg;
8172 *gui_fg = guifg;
8173 *gui_bg = guibg;
8174}
8175# endif
8176
Bram Moolenaardf543822020-01-30 11:53:59 +01008177/*
8178 * Set the console colors to the original colors or the last set colors.
8179 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008180 static void
8181reset_console_color_rgb(void)
8182{
8183# ifdef FEAT_TERMGUICOLORS
8184 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8185
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008186 if (USE_WT)
8187 return;
8188
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008189 csbi.cbSize = sizeof(csbi);
8190 if (has_csbiex)
8191 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8192
8193 csbi.cbSize = sizeof(csbi);
8194 csbi.srWindow.Right += 1;
8195 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008196 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8197 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
8198 if (has_csbiex)
8199 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8200# endif
8201}
8202
8203/*
8204 * Set the console colors to the original colors.
8205 */
8206 static void
8207restore_console_color_rgb(void)
8208{
8209# ifdef FEAT_TERMGUICOLORS
8210 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8211
8212 csbi.cbSize = sizeof(csbi);
8213 if (has_csbiex)
8214 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8215
8216 csbi.cbSize = sizeof(csbi);
8217 csbi.srWindow.Right += 1;
8218 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008219 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8220 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008221 if (has_csbiex)
8222 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8223# endif
8224}
8225
8226 void
8227control_console_color_rgb(void)
8228{
8229 if (USE_VTP)
8230 set_console_color_rgb();
8231 else
8232 reset_console_color_rgb();
8233}
8234
8235 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008236use_vtp(void)
8237{
8238 return USE_VTP;
8239}
8240
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008241 int
8242is_term_win32(void)
8243{
8244 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8245}
8246
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008247 int
8248has_vtp_working(void)
8249{
8250 return vtp_working;
8251}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008252
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008253#endif
8254
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008255 int
8256has_conpty_working(void)
8257{
8258 return conpty_working;
8259}
8260
8261 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008262get_conpty_type(void)
8263{
8264 return conpty_type;
8265}
8266
8267 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008268is_conpty_stable(void)
8269{
8270 return conpty_stable;
8271}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008272
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008273 int
8274get_conpty_fix_type(void)
8275{
8276 return conpty_fix_type;
8277}
8278
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008279#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008280 void
8281resize_console_buf(void)
8282{
8283 CONSOLE_SCREEN_BUFFER_INFO csbi;
8284 COORD coord;
8285 SMALL_RECT newsize;
8286
8287 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8288 {
8289 coord.X = SRWIDTH(csbi.srWindow);
8290 coord.Y = SRHEIGHT(csbi.srWindow);
8291 SetConsoleScreenBufferSize(g_hConOut, coord);
8292
8293 newsize.Left = 0;
8294 newsize.Top = 0;
8295 newsize.Right = coord.X - 1;
8296 newsize.Bottom = coord.Y - 1;
8297 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8298
8299 SetConsoleScreenBufferSize(g_hConOut, coord);
8300 }
8301}
8302#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008303
8304 char *
8305GetWin32Error(void)
8306{
K.Takatad68b2fc2022-02-12 11:18:37 +00008307 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008308 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008309
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008310 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8311 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008312 if (oldmsg != NULL)
8313 LocalFree(oldmsg);
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008314 if (msg != NULL)
8315 {
8316 // remove trailing \r\n
8317 char *pcrlf = strstr(msg, "\r\n");
8318 if (pcrlf != NULL)
8319 *pcrlf = '\0';
K.Takatad68b2fc2022-02-12 11:18:37 +00008320 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008321 }
8322 return msg;
8323}
Paul Ollis65745772022-06-05 16:55:54 +01008324
8325#if defined(FEAT_RELTIME) || defined(PROTO)
8326static HANDLE timer_handle;
8327static int timer_active = FALSE;
8328
8329/*
8330 * Calls to start_timeout alternate the return value pointer between the two
8331 * entries in timeout_flags. If the previously active timeout is very close to
8332 * expiring when start_timeout() is called then a race condition means that the
8333 * set_flag() function may still be invoked after the previous timer is
8334 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8335 * timeouts.
8336 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008337static sig_atomic_t timeout_flags[2];
8338static int timeout_flag_idx = 0;
8339static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01008340
8341
8342 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01008343set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01008344{
8345 int *timeout_flag = (int *)param;
8346
8347 *timeout_flag = TRUE;
8348}
8349
8350/*
8351 * Stop any active timeout.
8352 */
8353 void
8354stop_timeout(void)
8355{
8356 if (timer_active)
8357 {
8358 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
8359 timer_active = FALSE;
8360 if (!ret && GetLastError() != ERROR_IO_PENDING)
8361 {
8362 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
8363 }
8364 }
8365 *timeout_flag = FALSE;
8366}
8367
8368/*
8369 * Start the timeout timer.
8370 *
8371 * The period is defined in milliseconds.
8372 *
8373 * The return value is a pointer to a flag that is initialised to 0. If the
8374 * timeout expires, the flag is set to 1. This will only return pointers to
8375 * static memory; i.e. any pointer returned by this function may always be
8376 * safely dereferenced.
8377 *
8378 * This function is not expected to fail, but if it does it still returns a
8379 * valid flag pointer; the flag will remain stuck at zero.
8380 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008381 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01008382start_timeout(long msec)
8383{
Paul Ollis65745772022-06-05 16:55:54 +01008384 BOOL ret;
8385
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008386 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01008387
8388 stop_timeout();
8389 ret = CreateTimerQueueTimer(
8390 &timer_handle, NULL, set_flag, timeout_flag,
8391 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
8392 if (!ret)
8393 {
8394 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
8395 }
8396 else
8397 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008398 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01008399 timer_active = TRUE;
8400 *timeout_flag = FALSE;
8401 }
8402 return timeout_flag;
8403}
8404#endif