blob: a01cee5b812ed36ddf492fe9b9e7f974e0e38180 [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
12 * Used for both the console version and the Win32 GUI. A lot of code is for
Bram Moolenaar4f974752019-02-17 17:44:42 +010013 * the console version only, so there is a lot of "#ifndef FEAT_GUI_MSWIN".
Bram Moolenaar071d4272004-06-13 20:20:40 +000014 *
15 * Win32 (Windows NT and Windows 95) system-dependent routines.
16 * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17 * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18 *
19 * George V. Reilly <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
Bram Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010032
Bram Moolenaar0f873732019-12-05 20:28:46 +010033// cproto fails on missing include files
Bram Moolenaar82881492012-11-20 16:53:39 +010034#ifndef PROTO
35# include <process.h>
Bram Moolenaare7bebc42021-02-01 20:50:37 +010036# include <winternl.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010037#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000038
39#undef chdir
40#ifdef __GNUC__
41# ifndef __MINGW32__
42# include <dirent.h>
43# endif
44#else
45# include <direct.h>
46#endif
47
Bram Moolenaar82881492012-11-20 16:53:39 +010048#ifndef PROTO
Bram Moolenaar651fca82021-11-29 20:39:38 +000049# if !defined(FEAT_GUI_MSWIN)
Bram Moolenaar82881492012-11-20 16:53:39 +010050# include <shellapi.h>
51# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000052#endif
53
Bram Moolenaarfb630902016-10-29 14:55:00 +020054#ifdef FEAT_JOB_CHANNEL
55# include <tlhelp32.h>
56#endif
57
Bram Moolenaar071d4272004-06-13 20:20:40 +000058#ifdef __MINGW32__
59# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
60# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
61# endif
62# ifndef RIGHTMOST_BUTTON_PRESSED
63# define RIGHTMOST_BUTTON_PRESSED 0x0002
64# endif
65# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
66# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
67# endif
68# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
69# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
70# endif
71# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
72# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
73# endif
74
75/*
76 * EventFlags
77 */
78# ifndef MOUSE_MOVED
79# define MOUSE_MOVED 0x0001
80# endif
81# ifndef DOUBLE_CLICK
82# define DOUBLE_CLICK 0x0002
83# endif
84#endif
85
Bram Moolenaar0f873732019-12-05 20:28:46 +010086// Record all output and all keyboard & mouse input
87// #define MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +000088
89#ifdef MCH_WRITE_DUMP
90FILE* fdDump = NULL;
91#endif
92
93/*
94 * When generating prototypes for Win32 on Unix, these lines make the syntax
95 * errors disappear. They do not need to be correct.
96 */
97#ifdef PROTO
Bram Moolenaar912bc4a2019-12-01 18:58:11 +010098# define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000099typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000100typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000101typedef int ACCESS_MASK;
102typedef int BOOL;
103typedef int COLORREF;
104typedef int CONSOLE_CURSOR_INFO;
105typedef int COORD;
106typedef int DWORD;
107typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100108typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000109typedef int HDC;
110typedef int HFONT;
111typedef int HICON;
112typedef int HINSTANCE;
113typedef int HWND;
114typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200115typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000116typedef int KEY_EVENT_RECORD;
117typedef int LOGFONT;
118typedef int LPBOOL;
119typedef int LPCTSTR;
120typedef int LPDWORD;
121typedef int LPSTR;
122typedef int LPTSTR;
123typedef int LPVOID;
124typedef int MOUSE_EVENT_RECORD;
125typedef int PACL;
126typedef int PDWORD;
127typedef int PHANDLE;
128typedef int PRINTDLG;
129typedef int PSECURITY_DESCRIPTOR;
130typedef int PSID;
131typedef int SECURITY_INFORMATION;
132typedef int SHORT;
133typedef int SMALL_RECT;
134typedef int TEXTMETRIC;
135typedef int TOKEN_INFORMATION_CLASS;
136typedef int TRUSTEE;
137typedef int WORD;
138typedef int WCHAR;
139typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100140typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200141typedef int SE_OBJECT_TYPE;
142typedef int PSNSECINFO;
143typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100144typedef int STARTUPINFO;
145typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200146typedef int LPSECURITY_ATTRIBUTES;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100147# define __stdcall // empty
Bram Moolenaar071d4272004-06-13 20:20:40 +0000148#endif
149
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200150#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100151// Win32 Console handles for input and output
Bram Moolenaar071d4272004-06-13 20:20:40 +0000152static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
153static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
154
Bram Moolenaar0f873732019-12-05 20:28:46 +0100155// Win32 Screen buffer,coordinate,console I/O information
Bram Moolenaar071d4272004-06-13 20:20:40 +0000156static SMALL_RECT g_srScrollRegion;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100157static COORD g_coord; // 0-based, but external coords are 1-based
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158
Bram Moolenaar0f873732019-12-05 20:28:46 +0100159// The attribute of the screen when the editor was started
160static WORD g_attrDefault = 7; // lightgray text on black background
Bram Moolenaar071d4272004-06-13 20:20:40 +0000161static WORD g_attrCurrent;
162
Bram Moolenaar0f873732019-12-05 20:28:46 +0100163static int g_fCBrkPressed = FALSE; // set by ctrl-break interrupt
164static int g_fCtrlCPressed = FALSE; // set when ctrl-C or ctrl-break detected
165static int g_fForceExit = FALSE; // set when forcefully exiting
Bram Moolenaar071d4272004-06-13 20:20:40 +0000166
Bram Moolenaar071d4272004-06-13 20:20:40 +0000167static void scroll(unsigned cLines);
168static void set_scroll_region(unsigned left, unsigned top,
169 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100170static void set_scroll_region_tb(unsigned top, unsigned bottom);
171static void set_scroll_region_lr(unsigned left, unsigned right);
172static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000173static void delete_lines(unsigned cLines);
174static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000175static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000176static int s_cursor_visible = TRUE;
177static int did_create_conin = FALSE;
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200178#endif
179#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000180static int s_dont_use_vimrun = TRUE;
181static int need_vimrun_warning = FALSE;
182static char *vimrun_path = "vimrun ";
183#endif
184
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200185static int win32_getattrs(char_u *name);
186static int win32_setattrs(char_u *name, int attrs);
187static int win32_set_archive(char_u *name);
188
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100189static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200190static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100191static int conpty_stable = 0;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +0200192static int conpty_fix_type = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100193static void vtp_flag_init();
194
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200195#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100196static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100197static void vtp_init();
198static void vtp_exit();
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100199static void vtp_sgr_bulk(int arg);
200static void vtp_sgr_bulks(int argc, int *argv);
201
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200202static int wt_working = 0;
203static void wt_init();
204
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100205static guicolor_T save_console_bg_rgb;
206static guicolor_T save_console_fg_rgb;
Bram Moolenaardf543822020-01-30 11:53:59 +0100207static guicolor_T store_console_bg_rgb;
208static guicolor_T store_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100209
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200210static int g_color_index_bg = 0;
211static int g_color_index_fg = 7;
212
213# ifdef FEAT_TERMGUICOLORS
214static int default_console_color_bg = 0x000000; // black
215static int default_console_color_fg = 0xc0c0c0; // white
216# endif
217
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100218# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200219# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200220# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100221# else
222# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200223# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100224# endif
225
226static void set_console_color_rgb(void);
227static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100228static void restore_console_color_rgb(void);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100229#endif
230
Bram Moolenaar0f873732019-12-05 20:28:46 +0100231// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100232#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
233# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
234#endif
235
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200236#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100237static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000238#endif
239
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200240static char_u *exe_path = NULL;
241
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100242static BOOL win8_or_later = FALSE;
243
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200244#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100245// Dynamic loading for portability
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100246typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
247{
248 ULONG cbSize;
249 COORD dwSize;
250 COORD dwCursorPosition;
251 WORD wAttributes;
252 SMALL_RECT srWindow;
253 COORD dwMaximumWindowSize;
254 WORD wPopupAttributes;
255 BOOL bFullscreenSupported;
256 COLORREF ColorTable[16];
257} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
258typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
259static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
260typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
261static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
262static BOOL has_csbiex = FALSE;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100263#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100264
265/*
266 * Get version number including build number
267 */
268typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100269#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100270 (((major) << 24) | ((minor) << 16) | (build))
271
272 static DWORD
273get_build_number(void)
274{
275 OSVERSIONINFOW osver = {sizeof(OSVERSIONINFOW)};
276 HMODULE hNtdll;
277 PfnRtlGetVersion pRtlGetVersion;
278 DWORD ver = MAKE_VER(0, 0, 0);
279
280 hNtdll = GetModuleHandle("ntdll.dll");
281 if (hNtdll != NULL)
282 {
283 pRtlGetVersion =
284 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
285 pRtlGetVersion(&osver);
286 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
287 min(osver.dwMinorVersion, 255),
288 min(osver.dwBuildNumber, 32767));
289 }
290 return ver;
291}
292
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200293#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200294 static BOOL
295is_ambiwidth_event(
296 INPUT_RECORD *ir)
297{
298 return ir->EventType == KEY_EVENT
299 && ir->Event.KeyEvent.bKeyDown
300 && ir->Event.KeyEvent.wRepeatCount == 1
301 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
302 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000303 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200304 && ir->Event.KeyEvent.dwControlKeyState == 2;
305}
306
307 static void
308make_ambiwidth_event(
309 INPUT_RECORD *down,
310 INPUT_RECORD *up)
311{
312 down->Event.KeyEvent.wVirtualKeyCode = 0;
313 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000314 down->Event.KeyEvent.uChar.UnicodeChar
315 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200316 down->Event.KeyEvent.dwControlKeyState = 0;
317}
318
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100319/*
320 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100321 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100322 */
323 static BOOL
324read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100325 HANDLE hInput,
326 INPUT_RECORD *lpBuffer,
327 DWORD nLength,
328 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100329{
330 enum
331 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100332 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100333 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100334 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100335 static DWORD s_dwIndex = 0;
336 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100337 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100338 int head;
339 int tail;
340 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200341 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100342
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200343 if (nLength == -2)
344 return (s_dwMax > 0) ? TRUE : FALSE;
345
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100346 if (!win8_or_later)
347 {
348 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200349 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
350 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100351 }
352
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100353 if (s_dwMax == 0)
354 {
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200355 if (!USE_WT && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200356 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200357 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
358 if (dwEvents == 0 && nLength == -1)
359 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
360 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100361 s_dwIndex = 0;
362 s_dwMax = dwEvents;
363 if (dwEvents == 0)
364 {
365 *lpEvents = 0;
366 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100367 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100368
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200369 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
370 if (is_ambiwidth_event(&s_irCache[i]))
371 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
372
Bram Moolenaardd415a62014-02-05 14:02:27 +0100373 if (s_dwMax > 1)
374 {
375 head = 0;
376 tail = s_dwMax - 1;
377 while (head != tail)
378 {
379 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
380 && s_irCache[head + 1].EventType
381 == WINDOW_BUFFER_SIZE_EVENT)
382 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100383 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100384 for (i = head; i < tail; ++i)
385 s_irCache[i] = s_irCache[i + 1];
386 --tail;
387 continue;
388 }
389 head++;
390 }
391 s_dwMax = tail + 1;
392 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100393 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100394
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200395 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
396 {
397 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
398 {
399 s_irPseudo = s_irCache[s_dwIndex];
400 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
401 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
402 *lpBuffer = s_irPseudo;
403 *lpEvents = 1;
404 return TRUE;
405 }
406 }
407
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100408 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200409 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100410 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100411 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100412 return TRUE;
413}
414
415/*
416 * Version of PeekConsoleInput() that works with IME.
417 */
418 static BOOL
419peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100420 HANDLE hInput,
421 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200422 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100423 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100424{
K.Takata135e1522022-01-29 15:27:58 +0000425 return read_console_input(hInput, lpBuffer, (DWORD)-1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100426}
427
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100428# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200429 static DWORD
430msg_wait_for_multiple_objects(
431 DWORD nCount,
432 LPHANDLE pHandles,
433 BOOL fWaitAll,
434 DWORD dwMilliseconds,
435 DWORD dwWakeMask)
436{
K.Takata135e1522022-01-29 15:27:58 +0000437 if (read_console_input(NULL, NULL, (DWORD)-2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200438 return WAIT_OBJECT_0;
439 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
440 dwMilliseconds, dwWakeMask);
441}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100442# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200443
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100444# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200445 static DWORD
446wait_for_single_object(
447 HANDLE hHandle,
448 DWORD dwMilliseconds)
449{
K.Takata54119102022-02-03 13:33:03 +0000450 if (read_console_input(NULL, NULL, (DWORD)-2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200451 return WAIT_OBJECT_0;
452 return WaitForSingleObject(hHandle, dwMilliseconds);
453}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100454# endif
455#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200456
Bram Moolenaar071d4272004-06-13 20:20:40 +0000457 static void
458get_exe_name(void)
459{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100460 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
461 // as the maximum length that works (plus a NUL byte).
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100462#define MAX_ENV_PATH_LEN 8192
463 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200464 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000465
466 if (exe_name == NULL)
467 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100468 // store the name of the executable, may be used for $VIM
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100469 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000470 if (*temp != NUL)
471 exe_name = FullName_save((char_u *)temp, FALSE);
472 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000473
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200474 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000475 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200476 exe_path = vim_strnsave(exe_name, gettail_sep(exe_name) - exe_name);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200477 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000478 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100479 // Append our starting directory to $PATH, so that when doing
480 // "!xxd" it's found in our starting directory. Needed because
481 // SearchPath() also looks there.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200482 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100483 if (p == NULL
484 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200485 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100486 if (p == NULL || *p == NUL)
487 temp[0] = NUL;
488 else
489 {
490 STRCPY(temp, p);
491 STRCAT(temp, ";");
492 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200493 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100494 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200495 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000496 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000497 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000498}
499
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200500/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100501 * Unescape characters in "p" that appear in "escaped".
502 */
503 static void
504unescape_shellxquote(char_u *p, char_u *escaped)
505{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100506 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100507 int n;
508
509 while (*p != NUL)
510 {
511 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
512 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100513 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100514 p += n;
515 l -= n;
516 }
517}
518
519/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200520 * Load library "name".
521 */
522 HINSTANCE
523vimLoadLib(char *name)
524{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200525 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200526
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200527 // No need to load any library when registering OLE.
528 if (found_register_arg)
529 return dll;
530
Bram Moolenaar0f873732019-12-05 20:28:46 +0100531 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
532 // vimLoadLib() recursively, which causes a stack overflow.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200533 if (exe_path == NULL)
534 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200535 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200536 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200537 WCHAR old_dirw[MAXPATHL];
538
539 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
540 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100541 // Change directory to where the executable is, both to make
542 // sure we find a .dll there and to avoid looking for a .dll
543 // in the current directory.
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100544 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200545 dll = LoadLibrary(name);
546 SetCurrentDirectoryW(old_dirw);
547 return dll;
548 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200549 }
550 return dll;
551}
552
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200553#if defined(VIMDLL) || defined(PROTO)
554/*
555 * Check if the current executable file is for the GUI subsystem.
556 */
557 int
558mch_is_gui_executable(void)
559{
560 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
561 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
562 PIMAGE_NT_HEADERS pPE;
563
564 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
565 return FALSE;
566 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
567 if (pPE->Signature != IMAGE_NT_SIGNATURE)
568 return FALSE;
569 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
570 return TRUE;
571 return FALSE;
572}
573#endif
574
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100575#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
576/*
577 * Get related information about 'funcname' which is imported by 'hInst'.
578 * If 'info' is 0, return the function address.
579 * If 'info' is 1, return the module name which the function is imported from.
580 */
581 static void *
582get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
583{
584 PBYTE pImage = (PBYTE)hInst;
585 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
586 PIMAGE_NT_HEADERS pPE;
587 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100588 PIMAGE_THUNK_DATA pIAT; // Import Address Table
589 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100590 PIMAGE_IMPORT_BY_NAME pImpName;
591
592 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
593 return NULL;
594 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
595 if (pPE->Signature != IMAGE_NT_SIGNATURE)
596 return NULL;
597 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
598 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
599 .VirtualAddress);
600 for (; pImpDesc->FirstThunk; ++pImpDesc)
601 {
602 if (!pImpDesc->OriginalFirstThunk)
603 continue;
604 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
605 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
606 for (; pIAT->u1.Function; ++pIAT, ++pINT)
607 {
608 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
609 continue;
610 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
611 + (UINT_PTR)(pINT->u1.AddressOfData));
612 if (strcmp((char *)pImpName->Name, funcname) == 0)
613 {
614 switch (info)
615 {
616 case 0:
617 return (void *)pIAT->u1.Function;
618 case 1:
619 return (void *)(pImage + pImpDesc->Name);
620 default:
621 return NULL;
622 }
623 }
624 }
625 }
626 return NULL;
627}
628
629/*
630 * Get the module handle which 'funcname' in 'hInst' is imported from.
631 */
632 HINSTANCE
633find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
634{
635 char *modulename;
636
637 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
638 if (modulename != NULL)
639 return GetModuleHandleA(modulename);
640 return NULL;
641}
642
643/*
644 * Get the address of 'funcname' which is imported by 'hInst' DLL.
645 */
646 void *
647get_dll_import_func(HINSTANCE hInst, const char *funcname)
648{
649 return get_imported_func_info(hInst, funcname, 0);
650}
651#endif
652
Bram Moolenaar071d4272004-06-13 20:20:40 +0000653#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
654# ifndef GETTEXT_DLL
655# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200656# define GETTEXT_DLL_ALT1 "libintl-8.dll"
657# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000658# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100659// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000660static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200661static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000662static char *null_libintl_textdomain(const char *);
663static char *null_libintl_bindtextdomain(const char *, const char *);
664static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100665static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000666
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200667static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000668char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200669char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
670 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000671char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
672char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000673 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000674char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
675 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100676int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000677
678 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100679dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000680{
681 int i;
682 static struct
683 {
684 char *name;
685 FARPROC *ptr;
686 } libintl_entry[] =
687 {
688 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200689 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000690 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
691 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
692 {NULL, NULL}
693 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100694 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000695
Bram Moolenaar7554c542018-10-06 15:03:15 +0200696 // No need to initialize twice.
697 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000698 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200699 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100700 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100701# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100702 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200703 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100704# endif
705# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200706 if (!hLibintlDLL)
707 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100708# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100709 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000710 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200711 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000712 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200713 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000714 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200715 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000716 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200717 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000718 }
719 for (i = 0; libintl_entry[i].name != NULL
720 && libintl_entry[i].ptr != NULL; ++i)
721 {
K.Takata54119102022-02-03 13:33:03 +0000722 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000723 libintl_entry[i].name)) == NULL)
724 {
725 dyn_libintl_end();
726 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000727 {
728 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000729 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000730 verbose_leave();
731 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000732 return 0;
733 }
734 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000735
Bram Moolenaar0f873732019-12-05 20:28:46 +0100736 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000737 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000738 "bind_textdomain_codeset");
739 if (dyn_libintl_bind_textdomain_codeset == NULL)
740 dyn_libintl_bind_textdomain_codeset =
741 null_libintl_bind_textdomain_codeset;
742
Bram Moolenaar0f873732019-12-05 20:28:46 +0100743 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100744 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
745 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100746 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100747 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
748 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100749
Bram Moolenaar071d4272004-06-13 20:20:40 +0000750 return 1;
751}
752
753 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100754dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000755{
756 if (hLibintlDLL)
757 FreeLibrary(hLibintlDLL);
758 hLibintlDLL = NULL;
759 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200760 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000761 dyn_libintl_textdomain = null_libintl_textdomain;
762 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000763 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100764 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000765}
766
767 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000768null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000769{
770 return (char*)msgid;
771}
772
773 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200774null_libintl_ngettext(
775 const char *msgid,
776 const char *msgid_plural,
777 unsigned long n)
778{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200779 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200780}
781
Bram Moolenaaree695f72016-08-03 22:08:45 +0200782 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100783null_libintl_bindtextdomain(
784 const char *domainname UNUSED,
785 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000786{
787 return NULL;
788}
789
790 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100791null_libintl_bind_textdomain_codeset(
792 const char *domainname UNUSED,
793 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000794{
795 return NULL;
796}
797
798 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100799null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000800{
801 return NULL;
802}
803
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200804 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100805null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100806{
807 return 0;
808}
809
Bram Moolenaar0f873732019-12-05 20:28:46 +0100810#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000811
Bram Moolenaar0f873732019-12-05 20:28:46 +0100812// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000813
814#ifndef VER_PLATFORM_WIN32_WINDOWS
815# define VER_PLATFORM_WIN32_WINDOWS 1
816#endif
817
Bram Moolenaar071d4272004-06-13 20:20:40 +0000818#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100819# ifndef PROTO
820# include <aclapi.h>
821# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200822# ifndef PROTECTED_DACL_SECURITY_INFORMATION
823# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
824# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000825#endif
826
Bram Moolenaar27515922013-06-29 15:36:26 +0200827#ifdef HAVE_ACL
828/*
829 * Enables or disables the specified privilege.
830 */
831 static BOOL
832win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
833{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100834 BOOL bResult;
835 LUID luid;
836 HANDLE hToken;
837 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200838
839 if (!OpenProcessToken(GetCurrentProcess(),
840 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
841 return FALSE;
842
843 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
844 {
845 CloseHandle(hToken);
846 return FALSE;
847 }
848
Bram Moolenaar45500912014-07-09 20:51:07 +0200849 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200850 tokenPrivileges.Privileges[0].Luid = luid;
851 tokenPrivileges.Privileges[0].Attributes = bEnable ?
852 SE_PRIVILEGE_ENABLED : 0;
853
854 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
855 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
856
857 CloseHandle(hToken);
858
859 return bResult && GetLastError() == ERROR_SUCCESS;
860}
861#endif
862
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100863#ifdef _MSC_VER
864// Suppress the deprecation warning for using GetVersionEx().
865// It is needed for implementing "windowsversion()".
866# pragma warning(push)
867# pragma warning(disable: 4996)
868#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000869/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200870 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000871 */
872 void
873PlatformId(void)
874{
875 static int done = FALSE;
876
877 if (!done)
878 {
879 OSVERSIONINFO ovi;
880
881 ovi.dwOSVersionInfoSize = sizeof(ovi);
882 GetVersionEx(&ovi);
883
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200884#ifdef FEAT_EVAL
Bram Moolenaar0c1e3742019-12-27 13:49:24 +0100885 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
886 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200887#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100888 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
889 || ovi.dwMajorVersion > 6)
890 win8_or_later = TRUE;
891
Bram Moolenaar071d4272004-06-13 20:20:40 +0000892#ifdef HAVE_ACL
Bram Moolenaar0f873732019-12-05 20:28:46 +0100893 // Enable privilege for getting or setting SACLs.
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200894 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000895#endif
896 done = TRUE;
897 }
898}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100899#ifdef _MSC_VER
900# pragma warning(pop)
901#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000902
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200903#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000904
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100905# define SHIFT (SHIFT_PRESSED)
906# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
907# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
908# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000909
910
Bram Moolenaar0f873732019-12-05 20:28:46 +0100911// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
912// We map function keys to their ANSI terminal equivalents, as produced
913// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
914// ANSI key with a value >= '\300' is nonstandard, but provided anyway
915// so that the user can have access to all SHIFT-, CTRL-, and ALT-
916// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000917
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000918static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000919{
920 WORD wVirtKey;
921 BOOL fAnsiKey;
922 int chAlone;
923 int chShift;
924 int chCtrl;
925 int chAlt;
926} VirtKeyMap[] =
927{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200928// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000929 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
930
931 { VK_F1, TRUE, ';', 'T', '^', 'h', },
932 { VK_F2, TRUE, '<', 'U', '_', 'i', },
933 { VK_F3, TRUE, '=', 'V', '`', 'j', },
934 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
935 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
936 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
937 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
938 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
939 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
940 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200941 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
942 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000943
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200944 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
945 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
946 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
947 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
948 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
949 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
950 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
951 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
952 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
953 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100954 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000955
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200956 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000957
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100958# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200959 // Most people don't have F13-F20, but what the hell...
960 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
961 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
962 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
963 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
964 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
965 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
966 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
967 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100968# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200969 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
970 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
971 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
972 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000973
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200974 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
975 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
976 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
977 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
978 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
979 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
980 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
981 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
982 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
983 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100984 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000985};
986
987
Bram Moolenaar0f873732019-12-05 20:28:46 +0100988/*
989 * The return code indicates key code size.
990 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000991 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +0000992win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000993 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000994{
995 UINT uMods = pker->dwControlKeyState;
996 static int s_iIsDead = 0;
997 static WORD awAnsiCode[2];
998 static BYTE abKeystate[256];
999
1000
1001 if (s_iIsDead == 2)
1002 {
K.Takata972db232022-02-04 10:45:38 +00001003 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001004 s_iIsDead = 0;
1005 return 1;
1006 }
1007
K.Takata972db232022-02-04 10:45:38 +00001008 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001009 return 1;
1010
Bram Moolenaara80faa82020-04-12 19:37:17 +02001011 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001012
Bram Moolenaar0f873732019-12-05 20:28:46 +01001013 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001014 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001015
1016 if (uMods & SHIFT_PRESSED)
1017 abKeystate[VK_SHIFT] = 0x80;
1018 if (uMods & CAPSLOCK_ON)
1019 abKeystate[VK_CAPITAL] = 1;
1020
1021 if ((uMods & ALT_GR) == ALT_GR)
1022 {
1023 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1024 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1025 }
1026
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001027 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1028 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001029
1030 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001031 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001032
1033 return s_iIsDead;
1034}
1035
Bram Moolenaar071d4272004-06-13 20:20:40 +00001036static BOOL g_fJustGotFocus = FALSE;
1037
1038/*
1039 * Decode a KEY_EVENT into one or two keystrokes
1040 */
1041 static BOOL
1042decode_key_event(
1043 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001044 WCHAR *pch,
1045 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001046 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001047 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001048{
1049 int i;
1050 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1051
1052 *pch = *pch2 = NUL;
1053 g_fJustGotFocus = FALSE;
1054
Bram Moolenaar0f873732019-12-05 20:28:46 +01001055 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001056 if (!pker->bKeyDown)
1057 return FALSE;
1058
Bram Moolenaar0f873732019-12-05 20:28:46 +01001059 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001060 switch (pker->wVirtualKeyCode)
1061 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001062 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001063 case VK_SHIFT:
1064 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001065 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001066 return FALSE;
1067
1068 default:
1069 break;
1070 }
1071
Bram Moolenaar0f873732019-12-05 20:28:46 +01001072 // special cases
K.Takata972db232022-02-04 10:45:38 +00001073 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0
1074 && pker->uChar.UnicodeChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001075 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001076 // Ctrl-6 is Ctrl-^
Bram Moolenaar071d4272004-06-13 20:20:40 +00001077 if (pker->wVirtualKeyCode == '6')
1078 {
1079 *pch = Ctrl_HAT;
1080 return TRUE;
1081 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001082 // Ctrl-2 is Ctrl-@
Bram Moolenaar071d4272004-06-13 20:20:40 +00001083 else if (pker->wVirtualKeyCode == '2')
1084 {
1085 *pch = NUL;
1086 return TRUE;
1087 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001088 // Ctrl-- is Ctrl-_
Bram Moolenaar071d4272004-06-13 20:20:40 +00001089 else if (pker->wVirtualKeyCode == 0xBD)
1090 {
1091 *pch = Ctrl__;
1092 return TRUE;
1093 }
1094 }
1095
Bram Moolenaar0f873732019-12-05 20:28:46 +01001096 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001097 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1098 {
1099 *pch = K_NUL;
1100 *pch2 = '\017';
1101 return TRUE;
1102 }
1103
K.Takataeeec2542021-06-02 13:28:16 +02001104 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001105 {
1106 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1107 {
1108 if (nModifs == 0)
1109 *pch = VirtKeyMap[i].chAlone;
1110 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1111 *pch = VirtKeyMap[i].chShift;
1112 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1113 *pch = VirtKeyMap[i].chCtrl;
1114 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1115 *pch = VirtKeyMap[i].chAlt;
1116
1117 if (*pch != 0)
1118 {
1119 if (VirtKeyMap[i].fAnsiKey)
1120 {
1121 *pch2 = *pch;
1122 *pch = K_NUL;
1123 }
1124
1125 return TRUE;
1126 }
1127 }
1128 }
1129
1130 i = win32_kbd_patch_key(pker);
1131
1132 if (i < 0)
1133 *pch = NUL;
1134 else
1135 {
K.Takata972db232022-02-04 10:45:38 +00001136 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001137
1138 if (pmodifiers != NULL)
1139 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001140 // Pass on the ALT key as a modifier, but only when not combined
1141 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001142 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1143 *pmodifiers |= MOD_MASK_ALT;
1144
Bram Moolenaar0f873732019-12-05 20:28:46 +01001145 // Pass on SHIFT only for special keys, because we don't know when
1146 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001147 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1148 *pmodifiers |= MOD_MASK_SHIFT;
1149
Bram Moolenaar0f873732019-12-05 20:28:46 +01001150 // Pass on CTRL only for non-special keys, because we don't know
1151 // when it's already included with the character. And not when
1152 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001153 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1154 && *pch >= 0x20 && *pch < 0x80)
1155 *pmodifiers |= MOD_MASK_CTRL;
1156 }
1157 }
1158
1159 return (*pch != NUL);
1160}
1161
Bram Moolenaar0f873732019-12-05 20:28:46 +01001162#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001163
1164
Bram Moolenaar071d4272004-06-13 20:20:40 +00001165/*
1166 * For the GUI the mouse handling is in gui_w32.c.
1167 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001168#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001169 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001170mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001171{
1172}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001173#else
Bram Moolenaar0f873732019-12-05 20:28:46 +01001174static int g_fMouseAvail = FALSE; // mouse present
1175static int g_fMouseActive = FALSE; // mouse enabled
1176static int g_nMouseClick = -1; // mouse status
1177static int g_xMouse; // mouse x coordinate
1178static int g_yMouse; // mouse y coordinate
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001179static DWORD g_cmodein = 0; // Original console input mode
1180static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001181
1182/*
1183 * Enable or disable mouse input
1184 */
1185 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001186mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001187{
1188 DWORD cmodein;
1189
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001190# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001191 if (gui.in_use)
1192 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001193# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001194 if (!g_fMouseAvail)
1195 return;
1196
1197 g_fMouseActive = on;
1198 GetConsoleMode(g_hConIn, &cmodein);
1199
1200 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001201 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001202 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001203 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1204 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001205 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001206 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001207 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001208 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1209 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001210
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001211 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001212}
1213
Bram Moolenaar157d8132018-03-06 17:09:20 +01001214
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001215# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001216/*
1217 * Called when 'balloonevalterm' changed.
1218 */
1219 void
1220mch_bevalterm_changed(void)
1221{
1222 mch_setmouse(g_fMouseActive);
1223}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001224# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001225
Bram Moolenaar071d4272004-06-13 20:20:40 +00001226/*
1227 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1228 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1229 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1230 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1231 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1232 * and we return the mouse position in g_xMouse and g_yMouse.
1233 *
1234 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1235 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1236 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1237 *
1238 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1239 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1240 *
1241 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1242 * moves, even if it stays within the same character cell. We ignore
1243 * all MOUSE_MOVED messages if the position hasn't really changed, and
1244 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1245 * we're only interested in MOUSE_DRAG).
1246 *
1247 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1248 * 2-button mouses by pressing the left & right buttons simultaneously.
1249 * In practice, it's almost impossible to click both at the same time,
1250 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1251 * in such cases, if the user is clicking quickly.
1252 */
1253 static BOOL
1254decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001255 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001256{
1257 static int s_nOldButton = -1;
1258 static int s_nOldMouseClick = -1;
1259 static int s_xOldMouse = -1;
1260 static int s_yOldMouse = -1;
1261 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001262# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001263 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001264# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001265 static int s_cClicks = 1;
1266 static BOOL s_fReleased = TRUE;
1267 static DWORD s_dwLastClickTime = 0;
1268 static BOOL s_fNextIsMiddle = FALSE;
1269
Bram Moolenaar0f873732019-12-05 20:28:46 +01001270 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001271
1272 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1273 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1274 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1275 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1276
1277 int nButton;
1278
1279 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1280 cButtons = 2;
1281
1282 if (!g_fMouseAvail || !g_fMouseActive)
1283 {
1284 g_nMouseClick = -1;
1285 return FALSE;
1286 }
1287
Bram Moolenaar0f873732019-12-05 20:28:46 +01001288 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001289 if (g_fJustGotFocus)
1290 {
1291 g_fJustGotFocus = FALSE;
1292 return FALSE;
1293 }
1294
Bram Moolenaar0f873732019-12-05 20:28:46 +01001295 // unprocessed mouse click?
Bram Moolenaar071d4272004-06-13 20:20:40 +00001296 if (g_nMouseClick != -1)
1297 return TRUE;
1298
1299 nButton = -1;
1300 g_xMouse = pmer->dwMousePosition.X;
1301 g_yMouse = pmer->dwMousePosition.Y;
1302
1303 if (pmer->dwEventFlags == MOUSE_MOVED)
1304 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001305 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1306 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001307 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1308 return FALSE;
1309 }
1310
Bram Moolenaar0f873732019-12-05 20:28:46 +01001311 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001312 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1313 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001314 nButton = MOUSE_RELEASE;
1315
Bram Moolenaar0f873732019-12-05 20:28:46 +01001316 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001317 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001318 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001319# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001320 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001321 if (p_bevalterm)
1322 nButton = MOUSE_DRAG;
1323 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001324# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001325 return FALSE;
1326 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001327
Bram Moolenaar071d4272004-06-13 20:20:40 +00001328 s_fReleased = TRUE;
1329 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001330 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001331 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001332 // on a 2-button mouse, hold down left and right buttons
1333 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001334
1335 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1336 {
1337 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1338
Bram Moolenaar0f873732019-12-05 20:28:46 +01001339 // if either left or right button only is pressed, see if the
1340 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001341 if (dwLR == LEFT || dwLR == RIGHT)
1342 {
1343 for (;;)
1344 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001345 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001346 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1347 != WAIT_OBJECT_0)
1348 break;
1349 else
1350 {
1351 DWORD cRecords = 0;
1352 INPUT_RECORD ir;
1353 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1354
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001355 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001356
1357 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1358 || !(pmer2->dwButtonState & LEFT_RIGHT))
1359 break;
1360 else
1361 {
1362 if (pmer2->dwEventFlags != MOUSE_MOVED)
1363 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001364 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001365
1366 return decode_mouse_event(pmer2);
1367 }
1368 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1369 s_yOldMouse == pmer2->dwMousePosition.Y)
1370 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001371 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001372 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001373
Bram Moolenaar0f873732019-12-05 20:28:46 +01001374 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001375 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001376
1377 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1378 break;
1379 }
1380 else
1381 break;
1382 }
1383 }
1384 }
1385 }
1386 }
1387
1388 if (s_fNextIsMiddle)
1389 {
1390 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1391 ? MOUSE_DRAG : MOUSE_MIDDLE;
1392 s_fNextIsMiddle = FALSE;
1393 }
1394 else if (cButtons == 2 &&
1395 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1396 {
1397 nButton = MOUSE_MIDDLE;
1398
1399 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1400 {
1401 s_fNextIsMiddle = TRUE;
1402 nButton = MOUSE_RELEASE;
1403 }
1404 }
1405 else if ((pmer->dwButtonState & LEFT) == LEFT)
1406 nButton = MOUSE_LEFT;
1407 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1408 nButton = MOUSE_MIDDLE;
1409 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1410 nButton = MOUSE_RIGHT;
1411
1412 if (! s_fReleased && ! s_fNextIsMiddle
1413 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1414 return FALSE;
1415
1416 s_fReleased = s_fNextIsMiddle;
1417 }
1418
1419 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1420 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001421 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001422 if (nButton != -1 && nButton != MOUSE_RELEASE)
1423 {
1424 DWORD dwCurrentTime = GetTickCount();
1425
1426 if (s_xOldMouse != g_xMouse
1427 || s_yOldMouse != g_yMouse
1428 || s_nOldButton != nButton
1429 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001430# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001431 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001432# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001433 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1434 {
1435 s_cClicks = 1;
1436 }
1437 else if (++s_cClicks > 4)
1438 {
1439 s_cClicks = 1;
1440 }
1441
1442 s_dwLastClickTime = dwCurrentTime;
1443 }
1444 }
1445 else if (pmer->dwEventFlags == MOUSE_MOVED)
1446 {
1447 if (nButton != -1 && nButton != MOUSE_RELEASE)
1448 nButton = MOUSE_DRAG;
1449
1450 s_cClicks = 1;
1451 }
1452
1453 if (nButton == -1)
1454 return FALSE;
1455
1456 if (nButton != MOUSE_RELEASE)
1457 s_nOldButton = nButton;
1458
1459 g_nMouseClick = nButton;
1460
1461 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1462 g_nMouseClick |= MOUSE_SHIFT;
1463 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1464 g_nMouseClick |= MOUSE_CTRL;
1465 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1466 g_nMouseClick |= MOUSE_ALT;
1467
1468 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1469 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1470
Bram Moolenaar0f873732019-12-05 20:28:46 +01001471 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001472 if (s_xOldMouse == g_xMouse
1473 && s_yOldMouse == g_yMouse
1474 && s_nOldMouseClick == g_nMouseClick)
1475 {
1476 g_nMouseClick = -1;
1477 return FALSE;
1478 }
1479
1480 s_xOldMouse = g_xMouse;
1481 s_yOldMouse = g_yMouse;
1482 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001483# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001484 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001485# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001486 s_nOldMouseClick = g_nMouseClick;
1487
1488 return TRUE;
1489}
1490
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001491#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001492
1493
1494#ifdef MCH_CURSOR_SHAPE
1495/*
1496 * Set the shape of the cursor.
1497 * 'thickness' can be from 1 (thin) to 99 (block)
1498 */
1499 static void
1500mch_set_cursor_shape(int thickness)
1501{
1502 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1503 ConsoleCursorInfo.dwSize = thickness;
1504 ConsoleCursorInfo.bVisible = s_cursor_visible;
1505
1506 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1507 if (s_cursor_visible)
1508 SetConsoleCursorPosition(g_hConOut, g_coord);
1509}
1510
1511 void
1512mch_update_cursor(void)
1513{
1514 int idx;
1515 int thickness;
1516
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001517# ifdef VIMDLL
1518 if (gui.in_use)
1519 return;
1520# endif
1521
Bram Moolenaar071d4272004-06-13 20:20:40 +00001522 /*
1523 * How the cursor is drawn depends on the current mode.
1524 */
1525 idx = get_shape_idx(FALSE);
1526
1527 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001528 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00001529 else
1530 thickness = shape_table[idx].percentage;
1531 mch_set_cursor_shape(thickness);
1532}
1533#endif
1534
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001535#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001536/*
1537 * Handle FOCUS_EVENT.
1538 */
1539 static void
1540handle_focus_event(INPUT_RECORD ir)
1541{
1542 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1543 ui_focus_change((int)g_fJustGotFocus);
1544}
1545
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001546static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1547
Bram Moolenaar071d4272004-06-13 20:20:40 +00001548/*
1549 * Wait until console input from keyboard or mouse is available,
1550 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001551 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001552 * Return TRUE if something is available FALSE if not.
1553 */
1554 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001555WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001556{
1557 DWORD dwNow = 0, dwEndTime = 0;
1558 INPUT_RECORD ir;
1559 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001560 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001561# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001562 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001563# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001564
1565 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001566 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001567 dwEndTime = GetTickCount() + msec;
1568 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001569 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001570 dwEndTime = INFINITE;
1571
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001572 // We need to loop until the end of the time period, because
1573 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001574 for (;;)
1575 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001576 // Only process messages when waiting.
1577 if (msec != 0)
1578 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001579# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001580 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001581# endif
1582# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001583 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001584# endif
1585# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001586 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001587# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001588 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001589
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001590 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001591# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001592 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001593# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001594 )
1595 return TRUE;
1596
1597 if (msec > 0)
1598 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001599 // If the specified wait time has passed, return. Beware that
1600 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001601 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001602 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001603 break;
1604 }
1605 if (msec != 0)
1606 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001607 DWORD dwWaitTime = dwEndTime - dwNow;
1608
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001609 // Don't wait for more than 11 msec to avoid dropping characters,
1610 // check channel while waiting for input and handle a callback from
1611 // 'balloonexpr'.
1612 if (dwWaitTime > 11)
1613 dwWaitTime = 11;
1614
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001615# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001616 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001617 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001618# endif
1619# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001620 // When waiting very briefly don't trigger timers.
1621 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001622 {
1623 long due_time;
1624
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001625 // Trigger timers and then get the time in msec until the next
1626 // one is due. Wait up to that time.
1627 due_time = check_due_timer();
1628 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001629 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001630 // timer may have used feedkeys().
1631 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001632 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001633 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1634 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001635 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001636# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001637 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001638# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001639 // Wait for either an event on the console input or a
1640 // message in the client-server window.
1641 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1642 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001643# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001644 wait_for_single_object(g_hConIn, dwWaitTime)
1645 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001646# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001647 )
1648 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001649 }
1650
1651 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001652 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001653
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001654# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02001655 // May have to redraw if the cursor ends up in the wrong place.
1656 // Only when not peeking.
1657 if (State & CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001658 {
1659 CONSOLE_SCREEN_BUFFER_INFO csbi;
1660
1661 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1662 {
1663 if (csbi.dwCursorPosition.Y != msg_row)
1664 {
matveyte08795e2021-05-07 15:00:17 +02001665 // The screen is now messed up, must redraw the command
1666 // line and later all the windows.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001667 redraw_all_later(CLEAR);
matveyte08795e2021-05-07 15:00:17 +02001668 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001669 redrawcmd();
1670 }
1671 }
1672 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001673# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001674
1675 if (cRecords > 0)
1676 {
1677 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1678 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001679# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01001680 // Windows IME sends two '\n's with only one 'ENTER'. First:
1681 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00001682 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001683 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1684 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001685 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001686 continue;
1687 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001688# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001689 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1690 NULL, FALSE))
1691 return TRUE;
1692 }
1693
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001694 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001695
1696 if (ir.EventType == FOCUS_EVENT)
1697 handle_focus_event(ir);
1698 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001699 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001700 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1701
Bram Moolenaar36698e32019-12-11 22:57:40 +01001702 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001703 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001704 if (dwSize.X != Columns || dwSize.Y != Rows)
1705 {
1706 CONSOLE_SCREEN_BUFFER_INFO csbi;
1707 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01001708 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001709 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01001710 if (dwSize.X != Columns || dwSize.Y != Rows)
1711 {
1712 ResizeConBuf(g_hConOut, dwSize);
1713 shell_resized();
1714 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001715 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001716 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717 else if (ir.EventType == MOUSE_EVENT
1718 && decode_mouse_event(&ir.Event.MouseEvent))
1719 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001720 }
1721 else if (msec == 0)
1722 break;
1723 }
1724
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001725# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01001726 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001727 if (input_available())
1728 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001729# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001730
Bram Moolenaar071d4272004-06-13 20:20:40 +00001731 return FALSE;
1732}
1733
Bram Moolenaar071d4272004-06-13 20:20:40 +00001734/*
1735 * return non-zero if a character is available
1736 */
1737 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001738mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001739{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001740# ifdef VIMDLL
1741 if (gui.in_use)
1742 return TRUE;
1743# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001744 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001745}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001746
1747# if defined(FEAT_TERMINAL) || defined(PROTO)
1748/*
1749 * Check for any pending input or messages.
1750 */
1751 int
1752mch_check_messages(void)
1753{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001754# ifdef VIMDLL
1755 if (gui.in_use)
1756 return TRUE;
1757# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001758 return WaitForChar(0L, TRUE);
1759}
1760# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001761
1762/*
1763 * Create the console input. Used when reading stdin doesn't work.
1764 */
1765 static void
1766create_conin(void)
1767{
1768 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1769 FILE_SHARE_READ|FILE_SHARE_WRITE,
1770 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001771 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001772 did_create_conin = TRUE;
1773}
1774
1775/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001776 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001777 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001778 static WCHAR
1779tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001780{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001781 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001782
1783 for (;;)
1784 {
1785 INPUT_RECORD ir;
1786 DWORD cRecords = 0;
1787
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001788# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001789 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001790 if (input_available())
1791 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001792 if (g_nMouseClick != -1)
1793 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001794# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001795 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001796 {
1797 if (did_create_conin)
1798 read_error_exit();
1799 create_conin();
1800 continue;
1801 }
1802
1803 if (ir.EventType == KEY_EVENT)
1804 {
1805 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1806 pmodifiers, TRUE))
1807 return ch;
1808 }
1809 else if (ir.EventType == FOCUS_EVENT)
1810 handle_focus_event(ir);
1811 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1812 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001813 else if (ir.EventType == MOUSE_EVENT)
1814 {
1815 if (decode_mouse_event(&ir.Event.MouseEvent))
1816 return 0;
1817 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001818 }
1819}
Bram Moolenaar0f873732019-12-05 20:28:46 +01001820#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001821
1822
1823/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001824 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001825 * Get one or more characters from the keyboard or the mouse.
1826 * If time == 0, do not wait for characters.
1827 * If time == n, wait a short time for characters.
1828 * If time == -1, wait forever for characters.
1829 * Returns the number of characters read into buf.
1830 */
1831 int
1832mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001833 char_u *buf UNUSED,
1834 int maxlen UNUSED,
1835 long time UNUSED,
1836 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001837{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001838#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001839
1840 int len;
1841 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001842# ifdef VIMDLL
1843// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
1844# define TYPEAHEADSPACE 6
1845# else
1846# define TYPEAHEADSPACE 0
1847# endif
1848# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001849 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001850 static int typeaheadlen = 0;
1851
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001852# ifdef VIMDLL
1853 if (gui.in_use)
1854 return 0;
1855# endif
1856
Bram Moolenaar0f873732019-12-05 20:28:46 +01001857 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001858 if (typeaheadlen > 0)
1859 goto theend;
1860
Bram Moolenaar071d4272004-06-13 20:20:40 +00001861 if (time >= 0)
1862 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001863 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00001864 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001865 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001866 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00001867 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001868 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00001869
Bram Moolenaar3918c952005-03-15 22:34:55 +00001870 /*
1871 * If there is no character available within 2 seconds (default)
1872 * write the autoscript file to disk. Or cause the CursorHold event
1873 * to be triggered.
1874 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001875 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001876 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001877 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001878 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001879 buf[0] = K_SPECIAL;
1880 buf[1] = KS_EXTRA;
1881 buf[2] = (int)KE_CURSORHOLD;
1882 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001883 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001884 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001885 }
1886 }
1887
1888 /*
1889 * Try to read as many characters as there are, until the buffer is full.
1890 */
1891
Bram Moolenaar0f873732019-12-05 20:28:46 +01001892 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001893 g_fCBrkPressed = FALSE;
1894
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001895# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001896 if (fdDump)
1897 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001898# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001899
Bram Moolenaar0f873732019-12-05 20:28:46 +01001900 // Keep looping until there is something in the typeahead buffer and more
1901 // to get and still room in the buffer (up to two bytes for a char and
1902 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001903 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001904 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001905 {
1906 if (typebuf_changed(tb_change_cnt))
1907 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001908 // "buf" may be invalid now if a client put something in the
1909 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001910 typeaheadlen = 0;
1911 break;
1912 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001913 if (g_nMouseClick != -1)
1914 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001915# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001916 if (fdDump)
1917 fprintf(fdDump, "{%02x @ %d, %d}",
1918 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001919# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001920 typeahead[typeaheadlen++] = ESC + 128;
1921 typeahead[typeaheadlen++] = 'M';
1922 typeahead[typeaheadlen++] = g_nMouseClick;
1923 typeahead[typeaheadlen++] = g_xMouse + '!';
1924 typeahead[typeaheadlen++] = g_yMouse + '!';
1925 g_nMouseClick = -1;
1926 }
1927 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001928 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001929 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001930 int modifiers = 0;
1931
1932 c = tgetch(&modifiers, &ch2);
1933
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 }
1941
1942 if (c == Ctrl_C && ctrl_c_interrupts)
1943 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001944# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001945 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001946# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001947 got_int = TRUE;
1948 }
1949
Bram Moolenaar071d4272004-06-13 20:20:40 +00001950 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001951 {
1952 int n = 1;
1953
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001954 if (ch2 == NUL)
1955 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001956 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001957 char_u *p;
1958 WCHAR ch[2];
1959
1960 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01001961 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001962 {
1963 ch[1] = tgetch(&modifiers, &ch2);
1964 n++;
1965 }
1966 p = utf16_to_enc(ch, &n);
1967 if (p != NULL)
1968 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001969 for (i = 0, j = 0; i < n; i++)
1970 {
1971 typeahead[typeaheadlen + j++] = p[i];
1972# ifdef VIMDLL
1973 if (p[i] == CSI)
1974 {
1975 typeahead[typeaheadlen + j++] = KS_EXTRA;
1976 typeahead[typeaheadlen + j++] = KE_CSI;
1977 }
1978# endif
1979 }
1980 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001981 vim_free(p);
1982 }
1983 }
1984 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001985 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001986 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001987# ifdef VIMDLL
1988 if (c == CSI)
1989 {
1990 typeahead[typeaheadlen + 1] = KS_EXTRA;
1991 typeahead[typeaheadlen + 2] = KE_CSI;
1992 n = 3;
1993 }
1994# endif
1995 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001996 if (ch2 != NUL)
1997 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001998 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001999 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002000 switch (ch2)
2001 {
2002 case (WCHAR)'\324': // SHIFT+Insert
2003 case (WCHAR)'\325': // CTRL+Insert
2004 case (WCHAR)'\327': // SHIFT+Delete
2005 case (WCHAR)'\330': // CTRL+Delete
2006 typeahead[typeaheadlen + n] = (char_u)ch2;
2007 n++;
2008 break;
2009
2010 default:
2011 typeahead[typeaheadlen + n] = 3;
2012 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2013 n += 2;
2014 break;
2015 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002016 }
2017 else
2018 {
2019 typeahead[typeaheadlen + n] = 3;
2020 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2021 n += 2;
2022 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002023 }
2024
Bram Moolenaar0f873732019-12-05 20:28:46 +01002025 // Use the ALT key to set the 8th bit of the character
2026 // when it's one byte, the 8th bit isn't set yet and not
2027 // using a double-byte encoding (would become a lead
2028 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002029 if ((modifiers & MOD_MASK_ALT)
2030 && n == 1
2031 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002032 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002033 )
2034 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002035 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2036 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002037 modifiers &= ~MOD_MASK_ALT;
2038 }
2039
2040 if (modifiers != 0)
2041 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002042 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002043 mch_memmove(typeahead + typeaheadlen + 3,
2044 typeahead + typeaheadlen, n);
2045 typeahead[typeaheadlen++] = K_SPECIAL;
2046 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2047 typeahead[typeaheadlen++] = modifiers;
2048 }
2049
2050 typeaheadlen += n;
2051
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002052# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002053 if (fdDump)
2054 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002055# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002056 }
2057 }
2058 }
2059
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002060# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002061 if (fdDump)
2062 {
2063 fputs("]\n", fdDump);
2064 fflush(fdDump);
2065 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002066# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002067
Bram Moolenaar071d4272004-06-13 20:20:40 +00002068theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002069 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002070 len = 0;
2071 while (len < maxlen && typeaheadlen > 0)
2072 {
2073 buf[len++] = typeahead[0];
2074 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2075 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002076# ifdef FEAT_JOB_CHANNEL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002077 if (len > 0)
2078 {
2079 buf[len] = NUL;
2080 ch_log(NULL, "raw key input: \"%s\"", buf);
2081 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002082# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002083 return len;
2084
Bram Moolenaar0f873732019-12-05 20:28:46 +01002085#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002086 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002087#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002088}
2089
Bram Moolenaar82881492012-11-20 16:53:39 +01002090#ifndef PROTO
2091# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002092# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002093# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002094#endif
2095
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002096/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002097 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002098 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2099 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002100 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002101 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002102 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002103executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002104{
Bram Moolenaar95da1362020-05-30 18:37:55 +02002105 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01002106 {
Bram Moolenaar95da1362020-05-30 18:37:55 +02002107 if (path != NULL)
2108 *path = FullName_save((char_u *)name, FALSE);
2109 return TRUE;
2110 }
2111 return FALSE;
2112}
2113
2114/*
2115 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2116 * If "use_path" is FALSE: Return TRUE if "name" exists.
2117 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2118 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2119 * the allocated memory.
2120 */
2121 static int
2122executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2123{
2124 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2125 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2126 // UTF-8.
2127 char_u buf[_MAX_PATH * 3];
2128 size_t len = STRLEN(name);
2129 size_t tmplen;
2130 char_u *p, *e, *e2;
2131 char_u *pathbuf = NULL;
2132 char_u *pathext = NULL;
2133 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002134 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002135 int noext = FALSE;
2136 int retval = FALSE;
2137
2138 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002139 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002140
2141 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002142 shname = gettail(p_sh);
2143 if (strstr((char *)shname, "sh") != NULL &&
2144 !(strstr((char *)shname, "powershell") != NULL
2145 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002146 noext = TRUE;
2147
2148 if (use_pathext)
2149 {
2150 pathext = mch_getenv("PATHEXT");
2151 if (pathext == NULL)
2152 pathext = (char_u *)".com;.exe;.bat;.cmd";
2153
2154 if (noext == FALSE)
2155 {
2156 /*
2157 * Loop over all extensions in $PATHEXT.
2158 * Check "name" ends with extension.
2159 */
2160 p = pathext;
2161 while (*p)
2162 {
2163 if (p[0] == ';'
2164 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2165 {
2166 // Skip empty or single ".".
2167 ++p;
2168 continue;
2169 }
2170 e = vim_strchr(p, ';');
2171 if (e == NULL)
2172 e = p + STRLEN(p);
2173 tmplen = e - p;
2174
2175 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2176 {
2177 noext = TRUE;
2178 break;
2179 }
2180
2181 p = e;
2182 }
2183 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002184 }
2185
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002186 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002187 if (pathext == NULL)
2188 pathext = (char_u *)".";
2189 else if (noext == TRUE)
2190 {
2191 if (pathextbuf == NULL)
2192 pathextbuf = alloc(STRLEN(pathext) + 3);
2193 if (pathextbuf == NULL)
2194 {
2195 retval = FALSE;
2196 goto theend;
2197 }
2198 STRCPY(pathextbuf, ".;");
2199 STRCAT(pathextbuf, pathext);
2200 pathext = pathextbuf;
2201 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002202
Bram Moolenaar95da1362020-05-30 18:37:55 +02002203 // Use $PATH when "use_path" is TRUE and "name" is basename.
2204 if (use_path && gettail((char_u *)name) == (char_u *)name)
2205 {
2206 p = mch_getenv("PATH");
2207 if (p != NULL)
2208 {
2209 pathbuf = alloc(STRLEN(p) + 3);
2210 if (pathbuf == NULL)
2211 {
2212 retval = FALSE;
2213 goto theend;
2214 }
2215 STRCPY(pathbuf, ".;");
2216 STRCAT(pathbuf, p);
2217 }
2218 }
2219
2220 /*
2221 * Walk through all entries in $PATH to check if "name" exists there and
2222 * is an executable file.
2223 */
2224 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2225 while (*p)
2226 {
2227 if (*p == ';') // Skip empty entry
2228 {
2229 ++p;
2230 continue;
2231 }
2232 e = vim_strchr(p, ';');
2233 if (e == NULL)
2234 e = p + STRLEN(p);
2235
2236 if (e - p + len + 2 > sizeof(buf))
2237 {
2238 retval = FALSE;
2239 goto theend;
2240 }
2241 // A single "." that means current dir.
2242 if (e - p == 1 && *p == '.')
2243 STRCPY(buf, name);
2244 else
2245 {
2246 vim_strncpy(buf, p, e - p);
2247 add_pathsep(buf);
2248 STRCAT(buf, name);
2249 }
2250 tmplen = STRLEN(buf);
2251
2252 /*
2253 * Loop over all extensions in $PATHEXT.
2254 * Check "name" with extension added.
2255 */
2256 p = pathext;
2257 while (*p)
2258 {
2259 if (*p == ';')
2260 {
2261 // Skip empty entry
2262 ++p;
2263 continue;
2264 }
2265 e2 = vim_strchr(p, (int)';');
2266 if (e2 == NULL)
2267 e2 = p + STRLEN(p);
2268
2269 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2270 {
2271 // Not a single "." that means no extension is added.
2272 if (e2 - p + tmplen + 1 > sizeof(buf))
2273 {
2274 retval = FALSE;
2275 goto theend;
2276 }
2277 vim_strncpy(buf + tmplen, p, e2 - p);
2278 }
2279 if (executable_file((char *)buf, path))
2280 {
2281 retval = TRUE;
2282 goto theend;
2283 }
2284
2285 p = e2;
2286 }
2287
2288 p = e;
2289 }
2290
2291theend:
2292 free(pathextbuf);
2293 free(pathbuf);
2294 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002295}
2296
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002297#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2298 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002299/*
2300 * Bad parameter handler.
2301 *
2302 * Certain MS CRT functions will intentionally crash when passed invalid
2303 * parameters to highlight possible security holes. Setting this function as
2304 * the bad parameter handler will prevent the crash.
2305 *
2306 * In debug builds the parameters contain CRT information that might help track
2307 * down the source of a problem, but in non-debug builds the arguments are all
2308 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2309 * worth allowing these to make debugging of issues easier.
2310 */
2311 static void
2312bad_param_handler(const wchar_t *expression,
2313 const wchar_t *function,
2314 const wchar_t *file,
2315 unsigned int line,
2316 uintptr_t pReserved)
2317{
2318}
2319
2320# define SET_INVALID_PARAM_HANDLER \
2321 ((void)_set_invalid_parameter_handler(bad_param_handler))
2322#else
2323# define SET_INVALID_PARAM_HANDLER
2324#endif
2325
Bram Moolenaar4f974752019-02-17 17:44:42 +01002326#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002327
2328/*
2329 * GUI version of mch_init().
2330 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002331 static void
2332mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002333{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002334# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002335 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002336# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002337
Bram Moolenaar0f873732019-12-05 20:28:46 +01002338 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002339 SET_INVALID_PARAM_HANDLER;
2340
Bram Moolenaar0f873732019-12-05 20:28:46 +01002341 // Let critical errors result in a failure, not in a dialog box. Required
2342 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002343 SetErrorMode(SEM_FAILCRITICALERRORS);
2344
Bram Moolenaar0f873732019-12-05 20:28:46 +01002345 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002346
Bram Moolenaar0f873732019-12-05 20:28:46 +01002347 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002348 Rows = 25;
2349 Columns = 80;
2350
Bram Moolenaar0f873732019-12-05 20:28:46 +01002351 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002352 {
2353 char_u vimrun_location[_MAX_PATH + 4];
2354
Bram Moolenaar0f873732019-12-05 20:28:46 +01002355 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002356 STRCPY(vimrun_location, exe_name);
2357 STRCPY(gettail(vimrun_location), "vimrun.exe");
2358 if (mch_getperm(vimrun_location) >= 0)
2359 {
2360 if (*skiptowhite(vimrun_location) != NUL)
2361 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002362 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002363 mch_memmove(vimrun_location + 1, vimrun_location,
2364 STRLEN(vimrun_location) + 1);
2365 *vimrun_location = '"';
2366 STRCPY(gettail(vimrun_location), "vimrun\" ");
2367 }
2368 else
2369 STRCPY(gettail(vimrun_location), "vimrun ");
2370
2371 vimrun_path = (char *)vim_strsave(vimrun_location);
2372 s_dont_use_vimrun = FALSE;
2373 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002374 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002375 s_dont_use_vimrun = FALSE;
2376
Bram Moolenaar0f873732019-12-05 20:28:46 +01002377 // Don't give the warning for a missing vimrun.exe right now, but only
2378 // when vimrun was supposed to be used. Don't bother people that do
2379 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002380 if (s_dont_use_vimrun)
2381 need_vimrun_warning = TRUE;
2382 }
2383
2384 /*
2385 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2386 * Otherwise the default "findstr /n" is used.
2387 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002388 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002389 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2390
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002391# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002392 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002393# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002394
2395 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002396}
2397
2398
Bram Moolenaar0f873732019-12-05 20:28:46 +01002399#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002400
2401#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002402
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002403# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2404# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002405
2406/*
2407 * ClearConsoleBuffer()
2408 * Description:
2409 * Clears the entire contents of the console screen buffer, using the
2410 * specified attribute.
2411 * Returns:
2412 * TRUE on success
2413 */
2414 static BOOL
2415ClearConsoleBuffer(WORD wAttribute)
2416{
2417 CONSOLE_SCREEN_BUFFER_INFO csbi;
2418 COORD coord;
2419 DWORD NumCells, dummy;
2420
2421 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2422 return FALSE;
2423
2424 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2425 coord.X = 0;
2426 coord.Y = 0;
2427 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2428 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002429 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002430 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2431 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002432 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002433
2434 return TRUE;
2435}
2436
2437/*
2438 * FitConsoleWindow()
2439 * Description:
2440 * Checks if the console window will fit within given buffer dimensions.
2441 * Also, if requested, will shrink the window to fit.
2442 * Returns:
2443 * TRUE on success
2444 */
2445 static BOOL
2446FitConsoleWindow(
2447 COORD dwBufferSize,
2448 BOOL WantAdjust)
2449{
2450 CONSOLE_SCREEN_BUFFER_INFO csbi;
2451 COORD dwWindowSize;
2452 BOOL NeedAdjust = FALSE;
2453
2454 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2455 {
2456 /*
2457 * A buffer resize will fail if the current console window does
2458 * not lie completely within that buffer. To avoid this, we might
2459 * have to move and possibly shrink the window.
2460 */
2461 if (csbi.srWindow.Right >= dwBufferSize.X)
2462 {
2463 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2464 if (dwWindowSize.X > dwBufferSize.X)
2465 dwWindowSize.X = dwBufferSize.X;
2466 csbi.srWindow.Right = dwBufferSize.X - 1;
2467 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2468 NeedAdjust = TRUE;
2469 }
2470 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2471 {
2472 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2473 if (dwWindowSize.Y > dwBufferSize.Y)
2474 dwWindowSize.Y = dwBufferSize.Y;
2475 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2476 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2477 NeedAdjust = TRUE;
2478 }
2479 if (NeedAdjust && WantAdjust)
2480 {
2481 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2482 return FALSE;
2483 }
2484 return TRUE;
2485 }
2486
2487 return FALSE;
2488}
2489
2490typedef struct ConsoleBufferStruct
2491{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002492 BOOL IsValid;
2493 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002494 PCHAR_INFO Buffer;
2495 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002496 PSMALL_RECT Regions;
2497 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002498} ConsoleBuffer;
2499
2500/*
2501 * SaveConsoleBuffer()
2502 * Description:
2503 * Saves important information about the console buffer, including the
2504 * actual buffer contents. The saved information is suitable for later
2505 * restoration by RestoreConsoleBuffer().
2506 * Returns:
2507 * TRUE if all information was saved; FALSE otherwise
2508 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2509 */
2510 static BOOL
2511SaveConsoleBuffer(
2512 ConsoleBuffer *cb)
2513{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002514 DWORD NumCells;
2515 COORD BufferCoord;
2516 SMALL_RECT ReadRegion;
2517 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002518 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002519
Bram Moolenaar071d4272004-06-13 20:20:40 +00002520 if (cb == NULL)
2521 return FALSE;
2522
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002523 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002524 {
2525 cb->IsValid = FALSE;
2526 return FALSE;
2527 }
2528 cb->IsValid = TRUE;
2529
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002530 /*
2531 * Allocate a buffer large enough to hold the entire console screen
2532 * buffer. If this ConsoleBuffer structure has already been initialized
2533 * with a buffer of the correct size, then just use that one.
2534 */
2535 if (!cb->IsValid || cb->Buffer == NULL ||
2536 cb->BufferSize.X != cb->Info.dwSize.X ||
2537 cb->BufferSize.Y != cb->Info.dwSize.Y)
2538 {
2539 cb->BufferSize.X = cb->Info.dwSize.X;
2540 cb->BufferSize.Y = cb->Info.dwSize.Y;
2541 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2542 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002543 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002544 if (cb->Buffer == NULL)
2545 return FALSE;
2546 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002547
2548 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002549 * We will now copy the console screen buffer into our buffer.
2550 * ReadConsoleOutput() seems to be limited as far as how much you
2551 * can read at a time. Empirically, this number seems to be about
2552 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2553 * in chunks until it is all copied. The chunks will all have the
2554 * same horizontal characteristics, so initialize them now. The
2555 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002556 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002557 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002558 ReadRegion.Left = 0;
2559 ReadRegion.Right = cb->Info.dwSize.X - 1;
2560 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002561
2562 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2563 if (cb->Regions == NULL || numregions != cb->NumRegions)
2564 {
2565 cb->NumRegions = numregions;
2566 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002567 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002568 if (cb->Regions == NULL)
2569 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002570 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002571 return FALSE;
2572 }
2573 }
2574
2575 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002576 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002577 /*
2578 * Read into position (0, Y) in our buffer.
2579 */
2580 BufferCoord.Y = Y;
2581 /*
2582 * Read the region whose top left corner is (0, Y) and whose bottom
2583 * right corner is (width - 1, Y + Y_incr - 1). This should define
2584 * a region of size width by Y_incr. Don't worry if this region is
2585 * too large for the remaining buffer; it will be cropped.
2586 */
2587 ReadRegion.Top = Y;
2588 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002589 if (!ReadConsoleOutputW(g_hConOut, // output handle
2590 cb->Buffer, // our buffer
2591 cb->BufferSize, // dimensions of our buffer
2592 BufferCoord, // offset in our buffer
2593 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002594 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002595 VIM_CLEAR(cb->Buffer);
2596 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002597 return FALSE;
2598 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002599 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002600 }
2601
2602 return TRUE;
2603}
2604
2605/*
2606 * RestoreConsoleBuffer()
2607 * Description:
2608 * Restores important information about the console buffer, including the
2609 * actual buffer contents, if desired. The information to restore is in
2610 * the same format used by SaveConsoleBuffer().
2611 * Returns:
2612 * TRUE on success
2613 */
2614 static BOOL
2615RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002616 ConsoleBuffer *cb,
2617 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002618{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002619 COORD BufferCoord;
2620 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002621 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002622
2623 if (cb == NULL || !cb->IsValid)
2624 return FALSE;
2625
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002626 /*
2627 * Before restoring the buffer contents, clear the current buffer, and
2628 * restore the cursor position and window information. Doing this now
2629 * prevents old buffer contents from "flashing" onto the screen.
2630 */
2631 if (RestoreScreen)
2632 ClearConsoleBuffer(cb->Info.wAttributes);
2633
2634 FitConsoleWindow(cb->Info.dwSize, TRUE);
2635 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2636 return FALSE;
2637 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2638 return FALSE;
2639
2640 if (!RestoreScreen)
2641 {
2642 /*
2643 * No need to restore the screen buffer contents, so we're done.
2644 */
2645 return TRUE;
2646 }
2647
2648 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2649 return FALSE;
2650 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2651 return FALSE;
2652
2653 /*
2654 * Restore the screen buffer contents.
2655 */
2656 if (cb->Buffer != NULL)
2657 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002658 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002659 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002660 BufferCoord.X = cb->Regions[i].Left;
2661 BufferCoord.Y = cb->Regions[i].Top;
2662 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01002663 if (!WriteConsoleOutputW(g_hConOut, // output handle
2664 cb->Buffer, // our buffer
2665 cb->BufferSize, // dimensions of our buffer
2666 BufferCoord, // offset in our buffer
2667 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02002668 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002669 }
2670 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002671
2672 return TRUE;
2673}
2674
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002675# define FEAT_RESTORE_ORIG_SCREEN
2676# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002677static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002678# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002679static ConsoleBuffer g_cbNonTermcap = { 0 };
2680static ConsoleBuffer g_cbTermcap = { 0 };
2681
Bram Moolenaar071d4272004-06-13 20:20:40 +00002682char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01002683HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00002684static HICON g_hOrigIconSmall = NULL;
2685static HICON g_hOrigIcon = NULL;
2686static HICON g_hVimIcon = NULL;
2687static BOOL g_fCanChangeIcon = FALSE;
2688
Bram Moolenaar071d4272004-06-13 20:20:40 +00002689/*
2690 * GetConsoleIcon()
2691 * Description:
2692 * Attempts to retrieve the small icon and/or the big icon currently in
2693 * use by a given window.
2694 * Returns:
2695 * TRUE on success
2696 */
2697 static BOOL
2698GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002699 HWND hWnd,
2700 HICON *phIconSmall,
2701 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002702{
2703 if (hWnd == NULL)
2704 return FALSE;
2705
2706 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002707 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2708 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002709 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002710 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2711 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002712 return TRUE;
2713}
2714
2715/*
2716 * SetConsoleIcon()
2717 * Description:
2718 * Attempts to change the small icon and/or the big icon currently in
2719 * use by a given window.
2720 * Returns:
2721 * TRUE on success
2722 */
2723 static BOOL
2724SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002725 HWND hWnd,
2726 HICON hIconSmall,
2727 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002728{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002729 if (hWnd == NULL)
2730 return FALSE;
2731
2732 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002733 SendMessage(hWnd, WM_SETICON,
2734 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002735 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002736 SendMessage(hWnd, WM_SETICON,
2737 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002738 return TRUE;
2739}
2740
2741/*
2742 * SaveConsoleTitleAndIcon()
2743 * Description:
2744 * Saves the current console window title in g_szOrigTitle, for later
2745 * restoration. Also, attempts to obtain a handle to the console window,
2746 * and use it to save the small and big icons currently in use by the
2747 * console window. This is not always possible on some versions of Windows;
2748 * nor is it possible when running Vim remotely using Telnet (since the
2749 * console window the user sees is owned by a remote process).
2750 */
2751 static void
2752SaveConsoleTitleAndIcon(void)
2753{
Bram Moolenaar0f873732019-12-05 20:28:46 +01002754 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002755 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2756 return;
2757
2758 /*
2759 * Obtain a handle to the console window using GetConsoleWindow() from
2760 * KERNEL32.DLL; we need to handle in order to change the window icon.
2761 * This function only exists on NT-based Windows, starting with Windows
2762 * 2000. On older operating systems, we can't change the window icon
2763 * anyway.
2764 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002765 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002766 if (g_hWnd == NULL)
2767 return;
2768
Bram Moolenaar0f873732019-12-05 20:28:46 +01002769 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002770 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2771 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2772 return;
2773
Bram Moolenaar0f873732019-12-05 20:28:46 +01002774 // Extract the first icon contained in the Vim executable.
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002775 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002776 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002777 if (g_hVimIcon != NULL)
2778 g_fCanChangeIcon = TRUE;
2779}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002780
2781static int g_fWindInitCalled = FALSE;
2782static int g_fTermcapMode = FALSE;
2783static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002784
2785/*
2786 * non-GUI version of mch_init().
2787 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002788 static void
2789mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002790{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002791# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002792 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002793# endif
2794# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002795 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002796# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002797
Bram Moolenaar0f873732019-12-05 20:28:46 +01002798 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002799 SET_INVALID_PARAM_HANDLER;
2800
Bram Moolenaar0f873732019-12-05 20:28:46 +01002801 // Let critical errors result in a failure, not in a dialog box. Required
2802 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002803 SetErrorMode(SEM_FAILCRITICALERRORS);
2804
Bram Moolenaar0f873732019-12-05 20:28:46 +01002805 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002806 out_flush();
2807
Bram Moolenaar0f873732019-12-05 20:28:46 +01002808 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00002809 if (read_cmd_fd == 0)
2810 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2811 else
2812 create_conin();
2813 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2814
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002815# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01002816 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002817 SaveConsoleBuffer(&g_cbOrig);
2818 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002819# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01002820 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002821 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2822 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002823# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002824 if (cterm_normal_fg_color == 0)
2825 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2826 if (cterm_normal_bg_color == 0)
2827 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2828
Bram Moolenaarbdace832019-03-02 10:13:42 +01002829 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002830 g_color_index_fg = g_attrDefault & 0xf;
2831 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2832
Bram Moolenaar0f873732019-12-05 20:28:46 +01002833 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00002834 update_tcap(g_attrCurrent);
2835
2836 GetConsoleCursorInfo(g_hConOut, &g_cci);
2837 GetConsoleMode(g_hConIn, &g_cmodein);
2838 GetConsoleMode(g_hConOut, &g_cmodeout);
2839
Bram Moolenaar071d4272004-06-13 20:20:40 +00002840 SaveConsoleTitleAndIcon();
2841 /*
2842 * Set both the small and big icons of the console window to Vim's icon.
2843 * Note that Vim presently only has one size of icon (32x32), but it
2844 * automatically gets scaled down to 16x16 when setting the small icon.
2845 */
2846 if (g_fCanChangeIcon)
2847 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002848
2849 ui_get_shellsize();
2850
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002851# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002852 fdDump = fopen("dump", "wt");
2853
2854 if (fdDump)
2855 {
2856 time_t t;
2857
2858 time(&t);
2859 fputs(ctime(&t), fdDump);
2860 fflush(fdDump);
2861 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002862# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002863
2864 g_fWindInitCalled = TRUE;
2865
Bram Moolenaar071d4272004-06-13 20:20:40 +00002866 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002867
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002868# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002869 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002870# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002871
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02002872 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002873 vtp_init();
Bram Moolenaar06b7b582020-05-30 17:49:25 +02002874 wt_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002875}
2876
2877/*
2878 * non-GUI version of mch_exit().
2879 * Shut down and exit with status `r'
2880 * Careful: mch_exit() may be called before mch_init()!
2881 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002882 static void
2883mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002884{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002885 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002886
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002887 vtp_exit();
2888
Bram Moolenaar955f1982017-02-05 15:10:51 +01002889 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002890 if (g_fWindInitCalled)
2891 settmode(TMODE_COOK);
2892
Bram Moolenaar0f873732019-12-05 20:28:46 +01002893 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00002894
2895 if (g_fWindInitCalled)
2896 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02002897 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002898 /*
2899 * Restore both the small and big icons of the console window to
2900 * what they were at startup. Don't do this when the window is
2901 * closed, Vim would hang here.
2902 */
2903 if (g_fCanChangeIcon && !g_fForceExit)
2904 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002905
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002906# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002907 if (fdDump)
2908 {
2909 time_t t;
2910
2911 time(&t);
2912 fputs(ctime(&t), fdDump);
2913 fclose(fdDump);
2914 }
2915 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002916# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002917 }
2918
2919 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02002920 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002921 SetConsoleMode(g_hConOut, g_cmodeout);
2922
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002923# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00002924 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002925# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002926
2927 exit(r);
2928}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002929#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002930
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002931 void
2932mch_init(void)
2933{
2934#ifdef VIMDLL
2935 if (gui.starting)
2936 mch_init_g();
2937 else
2938 mch_init_c();
2939#elif defined(FEAT_GUI_MSWIN)
2940 mch_init_g();
2941#else
2942 mch_init_c();
2943#endif
2944}
2945
2946 void
2947mch_exit(int r)
2948{
Bram Moolenaar173d8412020-04-19 14:02:26 +02002949#ifdef FEAT_NETBEANS_INTG
2950 netbeans_send_disconnect();
2951#endif
2952
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002953#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02002954 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002955 mch_exit_g(r);
2956 else
2957 mch_exit_c(r);
2958#elif defined(FEAT_GUI_MSWIN)
2959 mch_exit_g(r);
2960#else
2961 mch_exit_c(r);
2962#endif
2963}
2964
Bram Moolenaar071d4272004-06-13 20:20:40 +00002965/*
2966 * Do we have an interactive window?
2967 */
2968 int
2969mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002970 int argc UNUSED,
2971 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002972{
2973 get_exe_name();
2974
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002975#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002976 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00002977#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002978# ifdef VIMDLL
2979 if (gui.in_use)
2980 return OK;
2981# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002982 if (isatty(1))
2983 return OK;
2984 return FAIL;
2985#endif
2986}
2987
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002988/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002989 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002990 * When "len" is > 0, also expand short to long filenames.
2991 */
2992 void
2993fname_case(
2994 char_u *name,
2995 int len)
2996{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002997 int flen;
2998 WCHAR *p;
2999 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003000
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003001 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003002 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003003 return;
3004
3005 slash_adjust(name);
3006
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003007 p = enc_to_utf16(name, NULL);
3008 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003009 return;
3010
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003011 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003012 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003013 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003014
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003015 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003016 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003017 if (len > 0 || flen >= (int)STRLEN(q))
3018 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3019 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003020 }
3021 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003022 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003023}
3024
3025
3026/*
3027 * Insert user name in s[len].
3028 */
3029 int
3030mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003031 char_u *s,
3032 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003033{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003034 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003035 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003036
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003037 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003038 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003039 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003040
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003041 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003042 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003043 vim_strncpy(s, p, len - 1);
3044 vim_free(p);
3045 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003046 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003047 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048 s[0] = NUL;
3049 return FAIL;
3050}
3051
3052
3053/*
3054 * Insert host name in s[len].
3055 */
3056 void
3057mch_get_host_name(
3058 char_u *s,
3059 int len)
3060{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003061 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003062 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003063
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003064 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003065 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003066 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003067
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003068 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003069 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003070 vim_strncpy(s, p, len - 1);
3071 vim_free(p);
3072 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003073 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003074 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003075}
3076
3077
3078/*
3079 * return process ID
3080 */
3081 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003082mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003083{
3084 return (long)GetCurrentProcessId();
3085}
3086
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003087/*
3088 * return TRUE if process "pid" is still running
3089 */
3090 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003091mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003092{
3093 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3094 DWORD status = 0;
3095 int ret = FALSE;
3096
3097 if (hProcess == NULL)
3098 return FALSE; // might not have access
3099 if (GetExitCodeProcess(hProcess, &status) )
3100 ret = status == STILL_ACTIVE;
3101 CloseHandle(hProcess);
3102 return ret;
3103}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003104
3105/*
3106 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3107 * Return OK for success, FAIL for failure.
3108 */
3109 int
3110mch_dirname(
3111 char_u *buf,
3112 int len)
3113{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003114 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003115
Bram Moolenaar071d4272004-06-13 20:20:40 +00003116 /*
3117 * Originally this was:
3118 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3119 * But the Win32s known bug list says that getcwd() doesn't work
3120 * so use the Win32 system call instead. <Negri>
3121 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003122 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003123 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003124 WCHAR wcbuf[_MAX_PATH + 1];
3125 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003126
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003127 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003128 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003129 p = utf16_to_enc(wcbuf, NULL);
3130 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003131 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003132 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003133 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003134 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003135 }
3136 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003137 if (p == NULL)
3138 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003139
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003140 if (p != NULL)
3141 {
3142 vim_strncpy(buf, p, len - 1);
3143 vim_free(p);
3144 return OK;
3145 }
3146 }
3147 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003148}
3149
3150/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003151 * Get file permissions for "name".
3152 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003153 */
3154 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003155mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003156{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003157 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003158 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003159
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003160 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003161 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003162}
3163
3164
3165/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003166 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003167 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003168 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003169 */
3170 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003171mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003172{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003173 long n;
3174 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003175
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003176 p = enc_to_utf16(name, NULL);
3177 if (p == NULL)
3178 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003179
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003180 n = _wchmod(p, perm);
3181 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003182 if (n == -1)
3183 return FAIL;
3184
3185 win32_set_archive(name);
3186
3187 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003188}
3189
3190/*
3191 * Set hidden flag for "name".
3192 */
3193 void
3194mch_hide(char_u *name)
3195{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003196 int attrs = win32_getattrs(name);
3197 if (attrs == -1)
3198 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003199
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003200 attrs |= FILE_ATTRIBUTE_HIDDEN;
3201 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003202}
3203
3204/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003205 * Return TRUE if file "name" exists and is hidden.
3206 */
3207 int
3208mch_ishidden(char_u *name)
3209{
3210 int f = win32_getattrs(name);
3211
3212 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003213 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003214
3215 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3216}
3217
3218/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003219 * return TRUE if "name" is a directory
3220 * return FALSE if "name" is not a directory or upon error
3221 */
3222 int
3223mch_isdir(char_u *name)
3224{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003225 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003226
3227 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003228 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003229
3230 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3231}
3232
3233/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003234 * return TRUE if "name" is a directory, NOT a symlink to a directory
3235 * return FALSE if "name" is not a directory
3236 * return FALSE for error
3237 */
3238 int
3239mch_isrealdir(char_u *name)
3240{
3241 return mch_isdir(name) && !mch_is_symbolic_link(name);
3242}
3243
3244/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003245 * Create directory "name".
3246 * Return 0 on success, -1 on error.
3247 */
3248 int
3249mch_mkdir(char_u *name)
3250{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003251 WCHAR *p;
3252 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003253
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003254 p = enc_to_utf16(name, NULL);
3255 if (p == NULL)
3256 return -1;
3257 retval = _wmkdir(p);
3258 vim_free(p);
3259 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003260}
3261
3262/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003263 * Delete directory "name".
3264 * Return 0 on success, -1 on error.
3265 */
3266 int
3267mch_rmdir(char_u *name)
3268{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003269 WCHAR *p;
3270 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003271
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003272 p = enc_to_utf16(name, NULL);
3273 if (p == NULL)
3274 return -1;
3275 retval = _wrmdir(p);
3276 vim_free(p);
3277 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003278}
3279
3280/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003281 * Return TRUE if file "fname" has more than one link.
3282 */
3283 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003284mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003285{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003286 BY_HANDLE_FILE_INFORMATION info;
3287
3288 return win32_fileinfo(fname, &info) == FILEINFO_OK
3289 && info.nNumberOfLinks > 1;
3290}
3291
3292/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003293 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003294 */
3295 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003296mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003297{
3298 HANDLE hFind;
3299 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003300 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003301 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003302 WIN32_FIND_DATAW findDataW;
3303
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003304 wn = enc_to_utf16(name, NULL);
3305 if (wn == NULL)
3306 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003307
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003308 hFind = FindFirstFileW(wn, &findDataW);
3309 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003310 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003311 {
3312 fileFlags = findDataW.dwFileAttributes;
3313 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003314 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003315 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003316
3317 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003318 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3319 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003320 res = TRUE;
3321
3322 return res;
3323}
3324
3325/*
3326 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3327 * link.
3328 */
3329 int
3330mch_is_linked(char_u *fname)
3331{
3332 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3333 return TRUE;
3334 return FALSE;
3335}
3336
3337/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003338 * Get the by-handle-file-information for "fname".
3339 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003340 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003341 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3342 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3343 */
3344 int
3345win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3346{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003347 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003348 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003349 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003350
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003351 wn = enc_to_utf16(fname, NULL);
3352 if (wn == NULL)
3353 return FILEINFO_ENC_FAIL;
3354
3355 hFile = CreateFileW(wn, // file name
3356 GENERIC_READ, // access mode
3357 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3358 NULL, // security descriptor
3359 OPEN_EXISTING, // creation disposition
3360 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3361 NULL); // handle to template file
3362 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003363
3364 if (hFile != INVALID_HANDLE_VALUE)
3365 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003366 if (GetFileInformationByHandle(hFile, info) != 0)
3367 res = FILEINFO_OK;
3368 else
3369 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003370 CloseHandle(hFile);
3371 }
3372
Bram Moolenaar03f48552006-02-28 23:52:23 +00003373 return res;
3374}
3375
3376/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003377 * get file attributes for `name'
3378 * -1 : error
3379 * else FILE_ATTRIBUTE_* defined in winnt.h
3380 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003381 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003382win32_getattrs(char_u *name)
3383{
3384 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003385 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003386
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003387 p = enc_to_utf16(name, NULL);
3388 if (p == NULL)
3389 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003390
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003391 attr = GetFileAttributesW(p);
3392 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003393
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003394 return attr;
3395}
3396
3397/*
3398 * set file attributes for `name' to `attrs'
3399 *
3400 * return -1 for failure, 0 otherwise
3401 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003402 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003403win32_setattrs(char_u *name, int attrs)
3404{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003405 int res;
3406 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003407
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003408 p = enc_to_utf16(name, NULL);
3409 if (p == NULL)
3410 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003411
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003412 res = SetFileAttributesW(p, attrs);
3413 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003414
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003415 return res ? 0 : -1;
3416}
3417
3418/*
3419 * Set archive flag for "name".
3420 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003421 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003422win32_set_archive(char_u *name)
3423{
3424 int attrs = win32_getattrs(name);
3425 if (attrs == -1)
3426 return -1;
3427
3428 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3429 return win32_setattrs(name, attrs);
3430}
3431
3432/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003433 * Return TRUE if file or directory "name" is writable (not readonly).
3434 * Strange semantics of Win32: a readonly directory is writable, but you can't
3435 * delete a file. Let's say this means it is writable.
3436 */
3437 int
3438mch_writable(char_u *name)
3439{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003440 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003441
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003442 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3443 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003444}
3445
Bram Moolenaar071d4272004-06-13 20:20:40 +00003446/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003447 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003448 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003449 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3450 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003451 */
3452 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003453mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003454{
Bram Moolenaar95da1362020-05-30 18:37:55 +02003455 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003456}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003457
3458/*
3459 * Check what "name" is:
3460 * NODE_NORMAL: file or directory (or doesn't exist)
3461 * NODE_WRITABLE: writable device, socket, fifo, etc.
3462 * NODE_OTHER: non-writable things
3463 */
3464 int
3465mch_nodetype(char_u *name)
3466{
3467 HANDLE hFile;
3468 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003469 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003470
Bram Moolenaar0f873732019-12-05 20:28:46 +01003471 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3472 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3473 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00003474 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3475 return NODE_WRITABLE;
3476
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003477 wn = enc_to_utf16(name, NULL);
3478 if (wn == NULL)
3479 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003480
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003481 hFile = CreateFileW(wn, // file name
3482 GENERIC_WRITE, // access mode
3483 0, // share mode
3484 NULL, // security descriptor
3485 OPEN_EXISTING, // creation disposition
3486 0, // file attributes
3487 NULL); // handle to template file
3488 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003489 if (hFile == INVALID_HANDLE_VALUE)
3490 return NODE_NORMAL;
3491
3492 type = GetFileType(hFile);
3493 CloseHandle(hFile);
3494 if (type == FILE_TYPE_CHAR)
3495 return NODE_WRITABLE;
3496 if (type == FILE_TYPE_DISK)
3497 return NODE_NORMAL;
3498 return NODE_OTHER;
3499}
3500
3501#ifdef HAVE_ACL
3502struct my_acl
3503{
3504 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3505 PSID pSidOwner;
3506 PSID pSidGroup;
3507 PACL pDacl;
3508 PACL pSacl;
3509};
3510#endif
3511
3512/*
3513 * Return a pointer to the ACL of file "fname" in allocated memory.
3514 * Return NULL if the ACL is not available for whatever reason.
3515 */
3516 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003517mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003518{
3519#ifndef HAVE_ACL
3520 return (vim_acl_T)NULL;
3521#else
3522 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003523 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003524
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003525 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003526 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003527 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003528 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003529
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003530 wn = enc_to_utf16(fname, NULL);
3531 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003532 {
3533 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003534 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003535 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003536
3537 // Try to retrieve the entire security descriptor.
3538 err = GetNamedSecurityInfoW(
3539 wn, // Abstract filename
3540 SE_FILE_OBJECT, // File Object
3541 OWNER_SECURITY_INFORMATION |
3542 GROUP_SECURITY_INFORMATION |
3543 DACL_SECURITY_INFORMATION |
3544 SACL_SECURITY_INFORMATION,
3545 &p->pSidOwner, // Ownership information.
3546 &p->pSidGroup, // Group membership.
3547 &p->pDacl, // Discretionary information.
3548 &p->pSacl, // For auditing purposes.
3549 &p->pSecurityDescriptor);
3550 if (err == ERROR_ACCESS_DENIED ||
3551 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003552 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003553 // Retrieve only DACL.
3554 (void)GetNamedSecurityInfoW(
3555 wn,
3556 SE_FILE_OBJECT,
3557 DACL_SECURITY_INFORMATION,
3558 NULL,
3559 NULL,
3560 &p->pDacl,
3561 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003562 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003563 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003564 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003565 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003566 mch_free_acl((vim_acl_T)p);
3567 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003568 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003569 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003570 }
3571
3572 return (vim_acl_T)p;
3573#endif
3574}
3575
Bram Moolenaar27515922013-06-29 15:36:26 +02003576#ifdef HAVE_ACL
3577/*
3578 * Check if "acl" contains inherited ACE.
3579 */
3580 static BOOL
3581is_acl_inherited(PACL acl)
3582{
3583 DWORD i;
3584 ACL_SIZE_INFORMATION acl_info;
3585 PACCESS_ALLOWED_ACE ace;
3586
3587 acl_info.AceCount = 0;
3588 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3589 for (i = 0; i < acl_info.AceCount; i++)
3590 {
3591 GetAce(acl, i, (LPVOID *)&ace);
3592 if (ace->Header.AceFlags & INHERITED_ACE)
3593 return TRUE;
3594 }
3595 return FALSE;
3596}
3597#endif
3598
Bram Moolenaar071d4272004-06-13 20:20:40 +00003599/*
3600 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3601 * Errors are ignored.
3602 * This must only be called with "acl" equal to what mch_get_acl() returned.
3603 */
3604 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003605mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003606{
3607#ifdef HAVE_ACL
3608 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003609 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003610 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003611
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003612 if (p == NULL)
3613 return;
3614
3615 wn = enc_to_utf16(fname, NULL);
3616 if (wn == NULL)
3617 return;
3618
3619 // Set security flags
3620 if (p->pSidOwner)
3621 sec_info |= OWNER_SECURITY_INFORMATION;
3622 if (p->pSidGroup)
3623 sec_info |= GROUP_SECURITY_INFORMATION;
3624 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003625 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003626 sec_info |= DACL_SECURITY_INFORMATION;
3627 // Do not inherit its parent's DACL.
3628 // If the DACL is inherited, Cygwin permissions would be changed.
3629 if (!is_acl_inherited(p->pDacl))
3630 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003631 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003632 if (p->pSacl)
3633 sec_info |= SACL_SECURITY_INFORMATION;
3634
3635 (void)SetNamedSecurityInfoW(
3636 wn, // Abstract filename
3637 SE_FILE_OBJECT, // File Object
3638 sec_info,
3639 p->pSidOwner, // Ownership information.
3640 p->pSidGroup, // Group membership.
3641 p->pDacl, // Discretionary information.
3642 p->pSacl // For auditing purposes.
3643 );
3644 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003645#endif
3646}
3647
3648 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003649mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003650{
3651#ifdef HAVE_ACL
3652 struct my_acl *p = (struct my_acl *)acl;
3653
3654 if (p != NULL)
3655 {
3656 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3657 vim_free(p);
3658 }
3659#endif
3660}
3661
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003662#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003663
3664/*
3665 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3666 */
3667 static BOOL WINAPI
3668handler_routine(
3669 DWORD dwCtrlType)
3670{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003671 INPUT_RECORD ir;
3672 DWORD out;
3673
Bram Moolenaar071d4272004-06-13 20:20:40 +00003674 switch (dwCtrlType)
3675 {
3676 case CTRL_C_EVENT:
3677 if (ctrl_c_interrupts)
3678 g_fCtrlCPressed = TRUE;
3679 return TRUE;
3680
3681 case CTRL_BREAK_EVENT:
3682 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003683 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003684 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02003685 ir.EventType = KEY_EVENT;
3686 ir.Event.KeyEvent.bKeyDown = TRUE;
3687 ir.Event.KeyEvent.wRepeatCount = 1;
3688 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3689 ir.Event.KeyEvent.wVirtualScanCode = 0;
3690 ir.Event.KeyEvent.dwControlKeyState = 0;
3691 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3692 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003693 return TRUE;
3694
Bram Moolenaar0f873732019-12-05 20:28:46 +01003695 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00003696 case CTRL_CLOSE_EVENT:
3697 case CTRL_LOGOFF_EVENT:
3698 case CTRL_SHUTDOWN_EVENT:
3699 windgoto((int)Rows - 1, 0);
3700 g_fForceExit = TRUE;
3701
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003702 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003703 (dwCtrlType == CTRL_CLOSE_EVENT
3704 ? _("close")
3705 : dwCtrlType == CTRL_LOGOFF_EVENT
3706 ? _("logoff")
3707 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003708# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00003709 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003710# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003711
Bram Moolenaar0f873732019-12-05 20:28:46 +01003712 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00003713
Bram Moolenaar0f873732019-12-05 20:28:46 +01003714 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00003715
3716 default:
3717 return FALSE;
3718 }
3719}
3720
3721
3722/*
3723 * set the tty in (raw) ? "raw" : "cooked" mode
3724 */
3725 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02003726mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003727{
3728 DWORD cmodein;
3729 DWORD cmodeout;
3730 BOOL bEnableHandler;
3731
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003732# ifdef VIMDLL
3733 if (gui.in_use)
3734 return;
3735# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003736 GetConsoleMode(g_hConIn, &cmodein);
3737 GetConsoleMode(g_hConOut, &cmodeout);
3738 if (tmode == TMODE_RAW)
3739 {
3740 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3741 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003742 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003743 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003744 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003745 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
3746 }
3747 else
3748 {
3749 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
3750 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003751 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003752# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01003753 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
3754 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003755 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003756# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003757 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003758# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003759 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003760 bEnableHandler = TRUE;
3761 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01003762 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00003763 {
3764 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3765 ENABLE_ECHO_INPUT);
3766 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3767 bEnableHandler = FALSE;
3768 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003769 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003770 SetConsoleMode(g_hConOut, cmodeout);
3771 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3772
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003773# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003774 if (fdDump)
3775 {
3776 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3777 tmode == TMODE_RAW ? "raw" :
3778 tmode == TMODE_COOK ? "cooked" : "normal",
3779 cmodein, cmodeout);
3780 fflush(fdDump);
3781 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003782# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003783}
3784
3785
3786/*
3787 * Get the size of the current window in `Rows' and `Columns'
3788 * Return OK when size could be determined, FAIL otherwise.
3789 */
3790 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003791mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003792{
3793 CONSOLE_SCREEN_BUFFER_INFO csbi;
3794
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003795# ifdef VIMDLL
3796 if (gui.in_use)
3797 return OK;
3798# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003799 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3800 {
3801 /*
3802 * For some reason, we are trying to get the screen dimensions
3803 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3804 * variables are really intended to mean the size of Vim screen
3805 * while in termcap mode.
3806 */
3807 Rows = g_cbTermcap.Info.dwSize.Y;
3808 Columns = g_cbTermcap.Info.dwSize.X;
3809 }
3810 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3811 {
3812 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3813 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3814 }
3815 else
3816 {
3817 Rows = 25;
3818 Columns = 80;
3819 }
3820 return OK;
3821}
3822
3823/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003824 * Resize console buffer to 'COORD'
3825 */
3826 static void
3827ResizeConBuf(
3828 HANDLE hConsole,
3829 COORD coordScreen)
3830{
3831 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3832 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003833# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003834 if (fdDump)
3835 {
3836 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3837 GetLastError());
3838 fflush(fdDump);
3839 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003840# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003841 }
3842}
3843
3844/*
3845 * Resize console window size to 'srWindowRect'
3846 */
3847 static void
3848ResizeWindow(
3849 HANDLE hConsole,
3850 SMALL_RECT srWindowRect)
3851{
3852 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
3853 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003854# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003855 if (fdDump)
3856 {
3857 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3858 GetLastError());
3859 fflush(fdDump);
3860 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003861# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003862 }
3863}
3864
3865/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003866 * Set a console window to `xSize' * `ySize'
3867 */
3868 static void
3869ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003870 HANDLE hConsole,
3871 int xSize,
3872 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003873{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003874 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
3875 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003876 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003877 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02003878 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003879
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003880# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003881 if (fdDump)
3882 {
3883 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3884 fflush(fdDump);
3885 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003886# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003887
Bram Moolenaar0f873732019-12-05 20:28:46 +01003888 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00003889 coordScreen = GetLargestConsoleWindowSize(hConsole);
3890
Bram Moolenaar0f873732019-12-05 20:28:46 +01003891 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00003892 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3893 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3894 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3895
3896 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3897 {
3898 int sx, sy;
3899
3900 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3901 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3902 if (sy < ySize || sx < xSize)
3903 {
3904 /*
3905 * Increasing number of lines/columns, do buffer first.
3906 * Use the maximal size in x and y direction.
3907 */
3908 if (sy < ySize)
3909 coordScreen.Y = ySize;
3910 else
3911 coordScreen.Y = sy;
3912 if (sx < xSize)
3913 coordScreen.X = xSize;
3914 else
3915 coordScreen.X = sx;
3916 SetConsoleScreenBufferSize(hConsole, coordScreen);
3917 }
3918 }
3919
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003920 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003921 coordScreen.X = xSize;
3922 coordScreen.Y = ySize;
3923
Bram Moolenaar2551c032018-08-23 22:38:31 +02003924 // In the new console call API, only the first time in reverse order
3925 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003926 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003927 ResizeWindow(hConsole, srWindowRect);
3928 ResizeConBuf(hConsole, coordScreen);
3929 }
3930 else
3931 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003932 // Workaround for a Windows 10 bug
3933 cursor.X = srWindowRect.Left;
3934 cursor.Y = srWindowRect.Top;
3935 SetConsoleCursorPosition(hConsole, cursor);
3936
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003937 ResizeConBuf(hConsole, coordScreen);
3938 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02003939 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003940 }
3941}
3942
3943
3944/*
3945 * Set the console window to `Rows' * `Columns'
3946 */
3947 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003948mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003949{
3950 COORD coordScreen;
3951
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003952# ifdef VIMDLL
3953 if (gui.in_use)
3954 return;
3955# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01003956 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00003957 if (suppress_winsize != 0)
3958 {
3959 suppress_winsize = 2;
3960 return;
3961 }
3962
3963 if (term_console)
3964 {
3965 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3966
Bram Moolenaar0f873732019-12-05 20:28:46 +01003967 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00003968 if (Rows > coordScreen.Y)
3969 Rows = coordScreen.Y;
3970 if (Columns > coordScreen.X)
3971 Columns = coordScreen.X;
3972
3973 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3974 }
3975}
3976
3977/*
3978 * Rows and/or Columns has changed.
3979 */
3980 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003981mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003982{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003983# ifdef VIMDLL
3984 if (gui.in_use)
3985 return;
3986# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003987 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3988}
3989
3990
3991/*
3992 * Called when started up, to set the winsize that was delayed.
3993 */
3994 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003995mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003996{
3997 if (suppress_winsize == 2)
3998 {
3999 suppress_winsize = 0;
4000 mch_set_shellsize();
4001 shell_resized();
4002 }
4003 suppress_winsize = 0;
4004}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004005#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004006
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004007 static BOOL
4008vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004009 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004010 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004011 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004012 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004013 PROCESS_INFORMATION *pi,
4014 LPVOID *env,
4015 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004016{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004017 BOOL ret = FALSE;
4018 WCHAR *wcmd, *wcwd = NULL;
4019
4020 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4021 if (wcmd == NULL)
4022 return FALSE;
4023 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004024 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004025 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4026 if (wcwd == NULL)
4027 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004028 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004029
4030 ret = CreateProcessW(
4031 NULL, // Executable name
4032 wcmd, // Command to execute
4033 NULL, // Process security attributes
4034 NULL, // Thread security attributes
4035 inherit_handles, // Inherit handles
4036 flags, // Creation flags
4037 env, // Environment
4038 wcwd, // Current directory
4039 (LPSTARTUPINFOW)si, // Startup information
4040 pi); // Process information
4041theend:
4042 vim_free(wcmd);
4043 vim_free(wcwd);
4044 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004045}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004046
4047
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004048 static HINSTANCE
4049vim_shell_execute(
4050 char *cmd,
4051 INT n_show_cmd)
4052{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004053 HINSTANCE ret;
4054 WCHAR *wcmd;
4055
4056 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4057 if (wcmd == NULL)
4058 return (HINSTANCE) 0;
4059
4060 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4061 vim_free(wcmd);
4062 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004063}
4064
4065
Bram Moolenaar4f974752019-02-17 17:44:42 +01004066#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004067
4068/*
4069 * Specialised version of system() for Win32 GUI mode.
4070 * This version proceeds as follows:
4071 * 1. Create a console window for use by the subprocess
4072 * 2. Run the subprocess (it gets the allocated console by default)
4073 * 3. Wait for the subprocess to terminate and get its exit code
4074 * 4. Prompt the user to press a key to close the console window
4075 */
4076 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004077mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004078{
4079 STARTUPINFO si;
4080 PROCESS_INFORMATION pi;
4081 DWORD ret = 0;
4082 HWND hwnd = GetFocus();
4083
4084 si.cb = sizeof(si);
4085 si.lpReserved = NULL;
4086 si.lpDesktop = NULL;
4087 si.lpTitle = NULL;
4088 si.dwFlags = STARTF_USESHOWWINDOW;
4089 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004090 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004091 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004092 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004093 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004094 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004095 else
4096 si.wShowWindow = SW_SHOWNORMAL;
4097 si.cbReserved2 = 0;
4098 si.lpReserved2 = NULL;
4099
Bram Moolenaar0f873732019-12-05 20:28:46 +01004100 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004101 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004102 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4103 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004104
Bram Moolenaar0f873732019-12-05 20:28:46 +01004105 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004106 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004107# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004108 int delay = 1;
4109
Bram Moolenaar0f873732019-12-05 20:28:46 +01004110 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004111 for (;;)
4112 {
4113 MSG msg;
4114
K.Takatab7057bd2022-01-21 11:37:07 +00004115 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004116 {
4117 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004118 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004119 delay = 1;
4120 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004121 }
4122 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4123 break;
4124
Bram Moolenaar0f873732019-12-05 20:28:46 +01004125 // We start waiting for a very short time and then increase it, so
4126 // that we respond quickly when the process is quick, and don't
4127 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004128 if (delay < 50)
4129 delay += 10;
4130 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004131# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004132 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004133# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004134
Bram Moolenaar0f873732019-12-05 20:28:46 +01004135 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004136 GetExitCodeProcess(pi.hProcess, &ret);
4137 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004138
Bram Moolenaar0f873732019-12-05 20:28:46 +01004139 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004140 CloseHandle(pi.hThread);
4141 CloseHandle(pi.hProcess);
4142
Bram Moolenaar0f873732019-12-05 20:28:46 +01004143 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004144 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4145
4146 return ret;
4147}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004148
4149/*
4150 * Thread launched by the gui to send the current buffer data to the
4151 * process. This way avoid to hang up vim totally if the children
4152 * process take a long time to process the lines.
4153 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004154 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004155sub_process_writer(LPVOID param)
4156{
4157 HANDLE g_hChildStd_IN_Wr = param;
4158 linenr_T lnum = curbuf->b_op_start.lnum;
4159 DWORD len = 0;
4160 DWORD l;
4161 char_u *lp = ml_get(lnum);
4162 char_u *s;
4163 int written = 0;
4164
4165 for (;;)
4166 {
4167 l = (DWORD)STRLEN(lp + written);
4168 if (l == 0)
4169 len = 0;
4170 else if (lp[written] == NL)
4171 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004172 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004173 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4174 }
4175 else
4176 {
4177 s = vim_strchr(lp + written, NL);
4178 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4179 s == NULL ? l : (DWORD)(s - (lp + written)),
4180 &len, NULL);
4181 }
4182 if (len == (int)l)
4183 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004184 // Finished a line, add a NL, unless this line should not have
4185 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004186 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004187 || (!curbuf->b_p_bin
4188 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004189 || (lnum != curbuf->b_no_eol_lnum
4190 && (lnum != curbuf->b_ml.ml_line_count
4191 || curbuf->b_p_eol)))
4192 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004193 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4194 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004195 }
4196
4197 ++lnum;
4198 if (lnum > curbuf->b_op_end.lnum)
4199 break;
4200
4201 lp = ml_get(lnum);
4202 written = 0;
4203 }
4204 else if (len > 0)
4205 written += len;
4206 }
4207
Bram Moolenaar0f873732019-12-05 20:28:46 +01004208 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004209 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004210 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004211}
4212
4213
Bram Moolenaar0f873732019-12-05 20:28:46 +01004214# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004215
4216/*
4217 * This function read from the children's stdout and write the
4218 * data on screen or in the buffer accordingly.
4219 */
4220 static void
4221dump_pipe(int options,
4222 HANDLE g_hChildStd_OUT_Rd,
4223 garray_T *ga,
4224 char_u buffer[],
4225 DWORD *buffer_off)
4226{
4227 DWORD availableBytes = 0;
4228 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004229 int ret;
4230 DWORD len;
4231 DWORD toRead;
4232 int repeatCount;
4233
Bram Moolenaar0f873732019-12-05 20:28:46 +01004234 // we query the pipe to see if there is any data to read
4235 // to avoid to perform a blocking read
4236 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4237 NULL, // optional buffer
4238 0, // buffer size
4239 NULL, // number of read bytes
4240 &availableBytes, // available bytes total
4241 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004242
4243 repeatCount = 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004244 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004245 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004246 {
4247 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004248 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004249 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004250 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004251
Bram Moolenaar0f873732019-12-05 20:28:46 +01004252 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004253 if (len == 0)
4254 break;
4255
4256 availableBytes -= len;
4257
4258 if (options & SHELL_READ)
4259 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004260 // Do NUL -> NL translation, append NL separated
4261 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004262 for (i = 0; i < len; ++i)
4263 {
4264 if (buffer[i] == NL)
4265 append_ga_line(ga);
4266 else if (buffer[i] == NUL)
4267 ga_append(ga, NL);
4268 else
4269 ga_append(ga, buffer[i]);
4270 }
4271 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004272 else if (has_mbyte)
4273 {
4274 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004275 int c;
4276 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004277
4278 len += *buffer_off;
4279 buffer[len] = NUL;
4280
Bram Moolenaar0f873732019-12-05 20:28:46 +01004281 // Check if the last character in buffer[] is
4282 // incomplete, keep these bytes for the next
4283 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004284 for (p = buffer; p < buffer + len; p += l)
4285 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004286 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004287 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004288 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004289 else if (MB_BYTE2LEN(*p) != l)
4290 break;
4291 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004292 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004293 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004294 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004295 if (len >= 12)
4296 ++p;
4297 else
4298 {
4299 *buffer_off = len;
4300 return;
4301 }
4302 }
4303 c = *p;
4304 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004305 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004306 if (p < buffer + len)
4307 {
4308 *p = c;
4309 *buffer_off = (DWORD)((buffer + len) - p);
4310 mch_memmove(buffer, p, *buffer_off);
4311 return;
4312 }
4313 *buffer_off = 0;
4314 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004315 else
4316 {
4317 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004318 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004319 }
4320
4321 windgoto(msg_row, msg_col);
4322 cursor_on();
4323 out_flush();
4324 }
4325}
4326
4327/*
4328 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4329 * for communication and doesn't open any new window.
4330 */
4331 static int
4332mch_system_piped(char *cmd, int options)
4333{
4334 STARTUPINFO si;
4335 PROCESS_INFORMATION pi;
4336 DWORD ret = 0;
4337
4338 HANDLE g_hChildStd_IN_Rd = NULL;
4339 HANDLE g_hChildStd_IN_Wr = NULL;
4340 HANDLE g_hChildStd_OUT_Rd = NULL;
4341 HANDLE g_hChildStd_OUT_Wr = NULL;
4342
Bram Moolenaar0f873732019-12-05 20:28:46 +01004343 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004344 DWORD len;
4345
Bram Moolenaar0f873732019-12-05 20:28:46 +01004346 // buffer used to receive keys
4347 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4348 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004349
4350 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004351 int noread_cnt = 0;
4352 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004353 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004354 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004355 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004356
4357 SECURITY_ATTRIBUTES saAttr;
4358
Bram Moolenaar0f873732019-12-05 20:28:46 +01004359 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004360 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4361 saAttr.bInheritHandle = TRUE;
4362 saAttr.lpSecurityDescriptor = NULL;
4363
4364 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004365 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004366 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004367 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004368 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004369 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004370 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004371 {
4372 CloseHandle(g_hChildStd_IN_Rd);
4373 CloseHandle(g_hChildStd_IN_Wr);
4374 CloseHandle(g_hChildStd_OUT_Rd);
4375 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004376 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004377 }
4378
4379 si.cb = sizeof(si);
4380 si.lpReserved = NULL;
4381 si.lpDesktop = NULL;
4382 si.lpTitle = NULL;
4383 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4384
Bram Moolenaar0f873732019-12-05 20:28:46 +01004385 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004386 si.hStdError = g_hChildStd_OUT_Wr;
4387 si.hStdOutput = g_hChildStd_OUT_Wr;
4388 si.hStdInput = g_hChildStd_IN_Rd;
4389 si.wShowWindow = SW_HIDE;
4390 si.cbReserved2 = 0;
4391 si.lpReserved2 = NULL;
4392
4393 if (options & SHELL_READ)
4394 ga_init2(&ga, 1, BUFLEN);
4395
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004396 if (cmd != NULL)
4397 {
4398 p = (char *)vim_strsave((char_u *)cmd);
4399 if (p != NULL)
4400 unescape_shellxquote((char_u *)p, p_sxe);
4401 else
4402 p = cmd;
4403 }
4404
Bram Moolenaar0f873732019-12-05 20:28:46 +01004405 // Now, run the command.
4406 // About "Inherit handles" being TRUE: this command can be litigious,
4407 // handle inheritance was deactivated for pending temp file, but, if we
4408 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004409 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4410 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004411
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004412 if (p != cmd)
4413 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004414
Bram Moolenaar0f873732019-12-05 20:28:46 +01004415 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004416 CloseHandle(g_hChildStd_IN_Rd);
4417 CloseHandle(g_hChildStd_OUT_Wr);
4418
4419 if (options & SHELL_WRITE)
4420 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004421 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004422 _beginthreadex(NULL, // security attributes
4423 0, // default stack size
4424 sub_process_writer, // function to be executed
4425 g_hChildStd_IN_Wr, // parameter
4426 0, // creation flag, start immediately
4427 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004428 CloseHandle(thread);
4429 g_hChildStd_IN_Wr = NULL;
4430 }
4431
Bram Moolenaar0f873732019-12-05 20:28:46 +01004432 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004433 for (;;)
4434 {
4435 MSG msg;
4436
K.Takatab7057bd2022-01-21 11:37:07 +00004437 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004438 {
4439 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004440 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004441 }
4442
Bram Moolenaar0f873732019-12-05 20:28:46 +01004443 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004444 if ((options & (SHELL_READ|SHELL_WRITE))
4445# ifdef FEAT_GUI
4446 || gui.in_use
4447# endif
4448 )
4449 {
4450 len = 0;
4451 if (!(options & SHELL_EXPAND)
4452 && ((options &
4453 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4454 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4455# ifdef FEAT_GUI
4456 || gui.in_use
4457# endif
4458 )
4459 && (ta_len > 0 || noread_cnt > 4))
4460 {
4461 if (ta_len == 0)
4462 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004463 // Get extra characters when we don't have any. Reset the
4464 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004465 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004466 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4467 }
4468 if (ta_len > 0 || len > 0)
4469 {
4470 /*
4471 * For pipes: Check for CTRL-C: send interrupt signal to
4472 * child. Check for CTRL-D: EOF, close pipe to child.
4473 */
4474 if (len == 1 && cmd != NULL)
4475 {
4476 if (ta_buf[ta_len] == Ctrl_C)
4477 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004478 // Learn what exit code is expected, for
4479 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004480 TerminateProcess(pi.hProcess, 9);
4481 }
4482 if (ta_buf[ta_len] == Ctrl_D)
4483 {
4484 CloseHandle(g_hChildStd_IN_Wr);
4485 g_hChildStd_IN_Wr = NULL;
4486 }
4487 }
4488
Bram Moolenaarf4140482020-02-15 23:06:45 +01004489 term_replace_bs_del_keycode(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004490
4491 /*
4492 * For pipes: echo the typed characters. For a pty this
4493 * does not seem to work.
4494 */
4495 for (i = ta_len; i < ta_len + len; ++i)
4496 {
4497 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4498 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004499 else if (has_mbyte)
4500 {
4501 int l = (*mb_ptr2len)(ta_buf + i);
4502
4503 msg_outtrans_len(ta_buf + i, l);
4504 i += l - 1;
4505 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004506 else
4507 msg_outtrans_len(ta_buf + i, 1);
4508 }
4509 windgoto(msg_row, msg_col);
4510 out_flush();
4511
4512 ta_len += len;
4513
4514 /*
4515 * Write the characters to the child, unless EOF has been
4516 * typed for pipes. Write one character at a time, to
4517 * avoid losing too much typeahead. When writing buffer
4518 * lines, drop the typed characters (only check for
4519 * CTRL-C).
4520 */
4521 if (options & SHELL_WRITE)
4522 ta_len = 0;
4523 else if (g_hChildStd_IN_Wr != NULL)
4524 {
4525 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4526 1, &len, NULL);
4527 // if we are typing in, we want to keep things reactive
4528 delay = 1;
4529 if (len > 0)
4530 {
4531 ta_len -= len;
4532 mch_memmove(ta_buf, ta_buf + len, ta_len);
4533 }
4534 }
4535 }
4536 }
4537 }
4538
4539 if (ta_len)
4540 ui_inchar_undo(ta_buf, ta_len);
4541
4542 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4543 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004544 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004545 break;
4546 }
4547
4548 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004549 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004550
Bram Moolenaar0f873732019-12-05 20:28:46 +01004551 // We start waiting for a very short time and then increase it, so
4552 // that we respond quickly when the process is quick, and don't
4553 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004554 if (delay < 50)
4555 delay += 10;
4556 }
4557
Bram Moolenaar0f873732019-12-05 20:28:46 +01004558 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004559 CloseHandle(g_hChildStd_OUT_Rd);
4560 if (g_hChildStd_IN_Wr != NULL)
4561 CloseHandle(g_hChildStd_IN_Wr);
4562
4563 WaitForSingleObject(pi.hProcess, INFINITE);
4564
Bram Moolenaar0f873732019-12-05 20:28:46 +01004565 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004566 GetExitCodeProcess(pi.hProcess, &ret);
4567
4568 if (options & SHELL_READ)
4569 {
4570 if (ga.ga_len > 0)
4571 {
4572 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01004573 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004574 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4575 }
4576 else
4577 curbuf->b_no_eol_lnum = 0;
4578 ga_clear(&ga);
4579 }
4580
Bram Moolenaar0f873732019-12-05 20:28:46 +01004581 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004582 CloseHandle(pi.hThread);
4583 CloseHandle(pi.hProcess);
4584
4585 return ret;
4586}
4587
4588 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004589mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004590{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004591 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004592 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004593 return mch_system_piped(cmd, options);
4594 else
4595 return mch_system_classic(cmd, options);
4596}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004597#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004598
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004599#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004600 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02004601mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004602{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004603 int ret;
4604 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004605 char_u *buf;
4606 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004607
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004608 // If the command starts and ends with double quotes, enclose the command
4609 // in parentheses.
4610 len = STRLEN(cmd);
4611 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
4612 {
4613 len += 3;
4614 buf = alloc(len);
4615 if (buf == NULL)
4616 return -1;
4617 vim_snprintf((char *)buf, len, "(%s)", cmd);
4618 wcmd = enc_to_utf16(buf, NULL);
4619 free(buf);
4620 }
4621 else
4622 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4623
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004624 if (wcmd == NULL)
4625 return -1;
4626
4627 ret = _wsystem(wcmd);
4628 vim_free(wcmd);
4629 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004630}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004631
4632#endif
4633
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004634 static int
4635mch_system(char *cmd, int options)
4636{
4637#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004638 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004639 return mch_system_g(cmd, options);
4640 else
4641 return mch_system_c(cmd, options);
4642#elif defined(FEAT_GUI_MSWIN)
4643 return mch_system_g(cmd, options);
4644#else
4645 return mch_system_c(cmd, options);
4646#endif
4647}
4648
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004649#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4650/*
4651 * Use a terminal window to run a shell command in.
4652 */
4653 static int
4654mch_call_shell_terminal(
4655 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004656 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004657{
4658 jobopt_T opt;
4659 char_u *newcmd = NULL;
4660 typval_T argvar[2];
4661 long_u cmdlen;
4662 int retval = -1;
4663 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004664 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004665 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004666 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004667
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004668 if (cmd == NULL)
4669 cmdlen = STRLEN(p_sh) + 1;
4670 else
4671 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004672 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004673 if (newcmd == NULL)
4674 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004675 if (cmd == NULL)
4676 {
4677 STRCPY(newcmd, p_sh);
4678 ch_log(NULL, "starting terminal to run a shell");
4679 }
4680 else
4681 {
4682 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4683 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4684 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004685
4686 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004687
4688 argvar[0].v_type = VAR_STRING;
4689 argvar[0].vval.v_string = newcmd;
4690 argvar[1].v_type = VAR_UNKNOWN;
4691 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004692 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004693 {
4694 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004695 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004696 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004697
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004698 job = term_getjob(buf->b_term);
4699 ++job->jv_refcount;
4700
Bram Moolenaar0f873732019-12-05 20:28:46 +01004701 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004702 aucmd_prepbuf(&aco, buf);
4703
4704 clear_oparg(&oa);
4705 while (term_use_loop())
4706 {
4707 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4708 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004709 // If terminal_loop() returns OK we got a key that is handled
4710 // in Normal model. We don't do redrawing anyway.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004711 if (terminal_loop(TRUE) == OK)
4712 normal_cmd(&oa, TRUE);
4713 }
4714 else
4715 normal_cmd(&oa, TRUE);
4716 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004717 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004718 ch_log(NULL, "system command finished");
4719
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004720 job_unref(job);
4721
Bram Moolenaar0f873732019-12-05 20:28:46 +01004722 // restore curwin/curbuf and a few other things
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004723 aucmd_restbuf(&aco);
4724
4725 wait_return(TRUE);
4726 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4727
4728 vim_free(newcmd);
4729 return retval;
4730}
4731#endif
4732
Bram Moolenaar071d4272004-06-13 20:20:40 +00004733/*
4734 * Either execute a command by calling the shell or start a new shell
4735 */
4736 int
4737mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004738 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004739 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00004740{
4741 int x = 0;
4742 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004743 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004744
Bram Moolenaar0f873732019-12-05 20:28:46 +01004745 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02004746 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004747 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004748 if (cmd == NULL)
4749 wcscat(szShellTitle, L" :sh");
4750 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004751 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004752 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004753
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004754 if (wn != NULL)
4755 {
4756 wcscat(szShellTitle, L" - !");
4757 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02004758 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004759 wcscat(szShellTitle, wn);
4760 SetConsoleTitleW(szShellTitle);
4761 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004762 }
4763 }
4764 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004765
4766 out_flush();
4767
4768#ifdef MCH_WRITE_DUMP
4769 if (fdDump)
4770 {
4771 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4772 fflush(fdDump);
4773 }
4774#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004775#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004776 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004777 if (
4778# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004779 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004780# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004781 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004782 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4783 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004784 char_u *cmdbase = cmd;
4785
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004786 if (cmdbase != NULL)
4787 // Skip a leading quote and (.
4788 while (*cmdbase == '"' || *cmdbase == '(')
4789 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004790
4791 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01004792 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
4793 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004794 {
4795 // Use a terminal window to run the command in.
4796 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004797 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004798 return x;
4799 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004800 }
4801#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004802
4803 /*
4804 * Catch all deadly signals while running the external command, because a
4805 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4806 */
4807 signal(SIGINT, SIG_IGN);
4808#if defined(__GNUC__) && !defined(__MINGW32__)
4809 signal(SIGKILL, SIG_IGN);
4810#else
4811 signal(SIGBREAK, SIG_IGN);
4812#endif
4813 signal(SIGILL, SIG_IGN);
4814 signal(SIGFPE, SIG_IGN);
4815 signal(SIGSEGV, SIG_IGN);
4816 signal(SIGTERM, SIG_IGN);
4817 signal(SIGABRT, SIG_IGN);
4818
4819 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004820 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00004821
4822 if (cmd == NULL)
4823 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004824 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004825 }
4826 else
4827 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004828 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004829 char_u *newcmd = NULL;
4830 char_u *cmdbase = cmd;
4831 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004832
Bram Moolenaar0f873732019-12-05 20:28:46 +01004833 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004834 if (*cmdbase == '"' )
4835 ++cmdbase;
4836 if (*cmdbase == '(')
4837 ++cmdbase;
4838
Bram Moolenaar1c465442017-03-12 20:10:05 +01004839 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004840 {
4841 STARTUPINFO si;
4842 PROCESS_INFORMATION pi;
4843 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004844 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004845 char_u *p;
4846
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004847 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004848 si.cb = sizeof(si);
4849 si.lpReserved = NULL;
4850 si.lpDesktop = NULL;
4851 si.lpTitle = NULL;
4852 si.dwFlags = 0;
4853 si.cbReserved2 = 0;
4854 si.lpReserved2 = NULL;
4855
4856 cmdbase = skipwhite(cmdbase + 5);
4857 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004858 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004859 {
4860 cmdbase = skipwhite(cmdbase + 4);
4861 si.dwFlags = STARTF_USESHOWWINDOW;
4862 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004863 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004864 }
4865 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004866 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004867 {
4868 cmdbase = skipwhite(cmdbase + 2);
4869 flags = CREATE_NO_WINDOW;
4870 si.dwFlags = STARTF_USESTDHANDLES;
4871 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004872 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004873 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004874 NULL, // Security att.
4875 OPEN_EXISTING, // Open flags
4876 FILE_ATTRIBUTE_NORMAL, // File att.
4877 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004878 si.hStdOutput = si.hStdInput;
4879 si.hStdError = si.hStdInput;
4880 }
4881
Bram Moolenaar0f873732019-12-05 20:28:46 +01004882 // Remove a trailing ", ) and )" if they have a match
4883 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004884 if (cmdbase > cmd)
4885 {
4886 p = cmdbase + STRLEN(cmdbase);
4887 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4888 *--p = NUL;
4889 if (p > cmdbase && p[-1] == ')'
4890 && (*cmd =='(' || cmd[1] == '('))
4891 *--p = NUL;
4892 }
4893
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004894 newcmd = cmdbase;
4895 unescape_shellxquote(cmdbase, p_sxe);
4896
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004897 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004898 * If creating new console, arguments are passed to the
4899 * 'cmd.exe' as-is. If it's not, arguments are not treated
4900 * correctly for current 'cmd.exe'. So unescape characters in
4901 * shellxescape except '|' for avoiding to be treated as
4902 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004903 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004904 if (flags != CREATE_NEW_CONSOLE)
4905 {
4906 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004907 char_u *cmd_shell = mch_getenv("COMSPEC");
4908
4909 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004910 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004911
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004912 subcmd = vim_strsave_escaped_ext(cmdbase,
4913 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004914 if (subcmd != NULL)
4915 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004916 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004917 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004918 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004919 if (newcmd != NULL)
4920 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004921 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004922 else
4923 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004924 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004925 }
4926 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004927
4928 /*
4929 * Now, start the command as a process, so that it doesn't
4930 * inherit our handles which causes unpleasant dangling swap
4931 * files if we exit before the spawned process
4932 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004933 if (vim_create_process((char *)newcmd, FALSE, flags,
4934 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004935 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004936 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4937 > (HINSTANCE)32)
4938 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004939 else
4940 {
4941 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01004942#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004943# ifdef VIMDLL
4944 if (gui.in_use)
4945# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00004946 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004947#endif
4948 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004949
4950 if (newcmd != cmdbase)
4951 vim_free(newcmd);
4952
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004953 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004954 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004955 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004956 CloseHandle(si.hStdInput);
4957 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004958 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004959 CloseHandle(pi.hThread);
4960 CloseHandle(pi.hProcess);
4961 }
4962 else
4963 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004964 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01004965#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004966 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004967 (!s_dont_use_vimrun && p_stmp ?
4968 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
4969 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004970#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004971 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004972
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004973 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004974 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004975 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01004976#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004977 if (
4978# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004979 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004980# endif
4981 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004982 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01004983 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
4984 "External commands will not pause after completion.\n"
4985 "See :help win32-vimrun for more information.");
4986 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004987 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
4988 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01004989
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004990 if (wmsg != NULL && wtitle != NULL)
4991 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
4992 vim_free(wmsg);
4993 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004994 need_vimrun_warning = FALSE;
4995 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004996 if (
4997# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004998 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004999# endif
5000 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005001 // Use vimrun to execute the command. It opens a console
5002 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005003 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005004 vimrun_path,
5005 (msg_silent != 0 || (options & SHELL_DOOUT))
5006 ? "-s " : "",
5007 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005008 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005009# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005010 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005011# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005012 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005013 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005014 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5015 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005016 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005017#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005018 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005019 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005020 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005021 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005022 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005023 }
5024 }
5025
5026 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005027 {
5028 // The shell may have messed with the mode, always set it.
5029 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005030 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005031 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005032
Bram Moolenaar0f873732019-12-05 20:28:46 +01005033 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005034 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005035#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005036 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005037 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005038#endif
5039 )
5040 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005041 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005042 msg_putchar('\n');
5043 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005044 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005045
5046 signal(SIGINT, SIG_DFL);
5047#if defined(__GNUC__) && !defined(__MINGW32__)
5048 signal(SIGKILL, SIG_DFL);
5049#else
5050 signal(SIGBREAK, SIG_DFL);
5051#endif
5052 signal(SIGILL, SIG_DFL);
5053 signal(SIGFPE, SIG_DFL);
5054 signal(SIGSEGV, SIG_DFL);
5055 signal(SIGTERM, SIG_DFL);
5056 signal(SIGABRT, SIG_DFL);
5057
5058 return x;
5059}
5060
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005061#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005062 static HANDLE
5063job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005064 char_u *fname,
5065 DWORD dwDesiredAccess,
5066 DWORD dwShareMode,
5067 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5068 DWORD dwCreationDisposition,
5069 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005070{
5071 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005072 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005073
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005074 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005075 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005076 return INVALID_HANDLE_VALUE;
5077
5078 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5079 lpSecurityAttributes, dwCreationDisposition,
5080 dwFlagsAndAttributes, NULL);
5081 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005082 return h;
5083}
5084
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005085/*
5086 * Turn the dictionary "env" into a NUL separated list that can be used as the
5087 * environment argument of vim_create_process().
5088 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005089 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005090win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005091{
5092 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005093 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005094 LPVOID base = GetEnvironmentStringsW();
5095
Bram Moolenaar0f873732019-12-05 20:28:46 +01005096 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005097 if (ga_grow(gap, 1) == FAIL)
5098 return;
5099
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005100 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005101 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005102 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005103 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005104 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005105 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005106 typval_T *item = &dict_lookup(hi)->di_tv;
5107 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005108 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005109 --todo;
5110 if (wkey != NULL && wval != NULL)
5111 {
5112 size_t n;
5113 size_t lkey = wcslen(wkey);
5114 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005115
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005116 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5117 continue;
5118 for (n = 0; n < lkey; n++)
5119 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5120 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5121 for (n = 0; n < lval; n++)
5122 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5123 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5124 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005125 vim_free(wkey);
5126 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005127 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005128 }
5129 }
5130
Bram Moolenaar355757a2020-02-10 22:06:32 +01005131 if (base)
5132 {
5133 WCHAR *p = (WCHAR*) base;
5134
5135 // for last \0
5136 if (ga_grow(gap, 1) == FAIL)
5137 return;
5138
5139 while (*p != 0 || *(p + 1) != 0)
5140 {
5141 if (ga_grow(gap, 1) == OK)
5142 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5143 p++;
5144 }
5145 FreeEnvironmentStrings(base);
5146 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5147 }
5148
Bram Moolenaar493359e2018-06-12 20:25:52 +02005149# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005150 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005151# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005152 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005153 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005154# endif
5155# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005156 char_u *version = get_vim_var_str(VV_VERSION);
5157 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005158# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005159 // size of "VIM_SERVERNAME=" and value,
5160 // plus "VIM_TERMINAL=" and value,
5161 // plus two terminating NULs
5162 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005163# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005164 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005165# endif
5166# ifdef FEAT_TERMINAL
5167 + 13 + version_len + 2
5168# endif
5169 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005170
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005171 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005172 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005173# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005174 for (n = 0; n < 15; n++)
5175 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5176 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005177 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005178 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5179 (WCHAR)servername[n];
5180 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005181# endif
5182# ifdef FEAT_TERMINAL
5183 if (is_terminal)
5184 {
5185 for (n = 0; n < 13; n++)
5186 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5187 (WCHAR)"VIM_TERMINAL="[n];
5188 for (n = 0; n < version_len; n++)
5189 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5190 (WCHAR)version[n];
5191 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5192 }
5193# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005194 }
5195 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005196# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005197}
5198
Bram Moolenaarb091f302019-01-19 14:37:00 +01005199/*
5200 * Create a pair of pipes.
5201 * Return TRUE for success, FALSE for failure.
5202 */
5203 static BOOL
5204create_pipe_pair(HANDLE handles[2])
5205{
5206 static LONG s;
5207 char name[64];
5208 SECURITY_ATTRIBUTES sa;
5209
5210 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5211 GetCurrentProcessId(),
5212 InterlockedIncrement(&s));
5213
5214 // Create named pipe. Max size of named pipe is 65535.
5215 handles[1] = CreateNamedPipe(
5216 name,
5217 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5218 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005219 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005220
5221 if (handles[1] == INVALID_HANDLE_VALUE)
5222 return FALSE;
5223
5224 sa.nLength = sizeof(sa);
5225 sa.bInheritHandle = TRUE;
5226 sa.lpSecurityDescriptor = NULL;
5227
5228 handles[0] = CreateFile(name,
5229 FILE_GENERIC_READ,
5230 FILE_SHARE_READ, &sa,
5231 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5232
5233 if (handles[0] == INVALID_HANDLE_VALUE)
5234 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005235 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005236 return FALSE;
5237 }
5238
5239 return TRUE;
5240}
5241
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005242 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005243mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005244{
5245 STARTUPINFO si;
5246 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005247 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005248 SECURITY_ATTRIBUTES saAttr;
5249 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005250 HANDLE ifd[2];
5251 HANDLE ofd[2];
5252 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005253 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005254
5255 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5256 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5257 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5258 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5259 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5260 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5261 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5262
5263 if (use_out_for_err && use_null_for_out)
5264 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005265
5266 ifd[0] = INVALID_HANDLE_VALUE;
5267 ifd[1] = INVALID_HANDLE_VALUE;
5268 ofd[0] = INVALID_HANDLE_VALUE;
5269 ofd[1] = INVALID_HANDLE_VALUE;
5270 efd[0] = INVALID_HANDLE_VALUE;
5271 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005272 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005273
Bram Moolenaar14207f42016-10-27 21:13:10 +02005274 jo = CreateJobObject(NULL, NULL);
5275 if (jo == NULL)
5276 {
5277 job->jv_status = JOB_FAILED;
5278 goto failed;
5279 }
5280
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005281 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005282 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005283
Bram Moolenaar76467df2016-02-12 19:30:26 +01005284 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005285 ZeroMemory(&si, sizeof(si));
5286 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005287 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005288 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005289
Bram Moolenaard8070362016-02-15 21:56:54 +01005290 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5291 saAttr.bInheritHandle = TRUE;
5292 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005293
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005294 if (use_file_for_in)
5295 {
5296 char_u *fname = options->jo_io_name[PART_IN];
5297
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005298 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5299 FILE_SHARE_READ | FILE_SHARE_WRITE,
5300 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5301 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005302 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005303 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005304 goto failed;
5305 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005306 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005307 else if (!use_null_for_in
5308 && (!create_pipe_pair(ifd)
5309 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005310 goto failed;
5311
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005312 if (use_file_for_out)
5313 {
5314 char_u *fname = options->jo_io_name[PART_OUT];
5315
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005316 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5317 FILE_SHARE_READ | FILE_SHARE_WRITE,
5318 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5319 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005320 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005321 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005322 goto failed;
5323 }
5324 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005325 else if (!use_null_for_out &&
5326 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005327 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005328 goto failed;
5329
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005330 if (use_file_for_err)
5331 {
5332 char_u *fname = options->jo_io_name[PART_ERR];
5333
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005334 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5335 FILE_SHARE_READ | FILE_SHARE_WRITE,
5336 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5337 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005338 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005339 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005340 goto failed;
5341 }
5342 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005343 else if (!use_out_for_err && !use_null_for_err &&
5344 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005345 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005346 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005347
Bram Moolenaard8070362016-02-15 21:56:54 +01005348 si.dwFlags |= STARTF_USESTDHANDLES;
5349 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005350 si.hStdOutput = ofd[1];
5351 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5352
5353 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5354 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005355 if (options->jo_set & JO_CHANNEL)
5356 {
5357 channel = options->jo_channel;
5358 if (channel != NULL)
5359 ++channel->ch_refcount;
5360 }
5361 else
5362 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005363 if (channel == NULL)
5364 goto failed;
5365 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005366
5367 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005368 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005369 CREATE_DEFAULT_ERROR_MODE |
5370 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005371 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005372 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005373 &si, &pi,
5374 ga.ga_data,
5375 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005376 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005377 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005378 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005379 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005380 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005381
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005382 ga_clear(&ga);
5383
Bram Moolenaar14207f42016-10-27 21:13:10 +02005384 if (!AssignProcessToJobObject(jo, pi.hProcess))
5385 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005386 // if failing, switch the way to terminate
5387 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005388 CloseHandle(jo);
5389 jo = NULL;
5390 }
5391 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005392 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005393 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005394 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005395 job->jv_status = JOB_STARTED;
5396
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005397 CloseHandle(ifd[0]);
5398 CloseHandle(ofd[1]);
5399 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005400 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005401
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005402 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005403 if (channel != NULL)
5404 {
5405 channel_set_pipes(channel,
5406 use_file_for_in || use_null_for_in
5407 ? INVALID_FD : (sock_T)ifd[1],
5408 use_file_for_out || use_null_for_out
5409 ? INVALID_FD : (sock_T)ofd[0],
5410 use_out_for_err || use_file_for_err || use_null_for_err
5411 ? INVALID_FD : (sock_T)efd[0]);
5412 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005413 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005414 return;
5415
5416failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005417 CloseHandle(ifd[0]);
5418 CloseHandle(ofd[0]);
5419 CloseHandle(efd[0]);
5420 CloseHandle(ifd[1]);
5421 CloseHandle(ofd[1]);
5422 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005423 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005424 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005425}
5426
5427 char *
5428mch_job_status(job_T *job)
5429{
5430 DWORD dwExitCode = 0;
5431
Bram Moolenaar76467df2016-02-12 19:30:26 +01005432 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5433 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005434 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005435 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005436 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005437 {
5438 ch_log(job->jv_channel, "Job ended");
5439 job->jv_status = JOB_ENDED;
5440 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005441 return "dead";
5442 }
5443 return "run";
5444}
5445
Bram Moolenaar97792de2016-10-15 18:36:49 +02005446 job_T *
5447mch_detect_ended_job(job_T *job_list)
5448{
5449 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5450 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5451 job_T *job = job_list;
5452
5453 while (job != NULL)
5454 {
5455 DWORD n;
5456 DWORD result;
5457
5458 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5459 && job != NULL; job = job->jv_next)
5460 {
5461 if (job->jv_status == JOB_STARTED)
5462 {
5463 jobHandles[n] = job->jv_proc_info.hProcess;
5464 jobArray[n] = job;
5465 ++n;
5466 }
5467 }
5468 if (n == 0)
5469 continue;
5470 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5471 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5472 {
5473 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5474
5475 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5476 return wait_job;
5477 }
5478 }
5479 return NULL;
5480}
5481
Bram Moolenaarfb630902016-10-29 14:55:00 +02005482 static BOOL
5483terminate_all(HANDLE process, int code)
5484{
5485 PROCESSENTRY32 pe;
5486 HANDLE h = INVALID_HANDLE_VALUE;
5487 DWORD pid = GetProcessId(process);
5488
5489 if (pid != 0)
5490 {
5491 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5492 if (h != INVALID_HANDLE_VALUE)
5493 {
5494 pe.dwSize = sizeof(PROCESSENTRY32);
5495 if (!Process32First(h, &pe))
5496 goto theend;
5497
5498 do
5499 {
5500 if (pe.th32ParentProcessID == pid)
5501 {
5502 HANDLE ph = OpenProcess(
5503 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5504 if (ph != NULL)
5505 {
5506 terminate_all(ph, code);
5507 CloseHandle(ph);
5508 }
5509 }
5510 } while (Process32Next(h, &pe));
5511
5512 CloseHandle(h);
5513 }
5514 }
5515
5516theend:
5517 return TerminateProcess(process, code);
5518}
5519
5520/*
5521 * Send a (deadly) signal to "job".
5522 * Return FAIL if it didn't work.
5523 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005524 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005525mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005526{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005527 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005528
Bram Moolenaar923d9262016-02-25 20:56:01 +01005529 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005530 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005531 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02005532 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005533 {
5534 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5535 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00005536 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005537 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01005538 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005539 }
5540
5541 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5542 return FAIL;
5543 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005544 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5545 job->jv_proc_info.dwProcessId)
5546 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005547 FreeConsole();
5548 return ret;
5549}
5550
5551/*
5552 * Clear the data related to "job".
5553 */
5554 void
5555mch_clear_job(job_T *job)
5556{
5557 if (job->jv_status != JOB_FAILED)
5558 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005559 if (job->jv_job_object != NULL)
5560 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005561 CloseHandle(job->jv_proc_info.hProcess);
5562 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005563}
5564#endif
5565
Bram Moolenaar071d4272004-06-13 20:20:40 +00005566
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005567#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005568
5569/*
5570 * Start termcap mode
5571 */
5572 static void
5573termcap_mode_start(void)
5574{
5575 DWORD cmodein;
5576
5577 if (g_fTermcapMode)
5578 return;
5579
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005580 if (!p_rs && USE_VTP)
5581 vtp_printf("\033[?1049h");
5582
Bram Moolenaar071d4272004-06-13 20:20:40 +00005583 SaveConsoleBuffer(&g_cbNonTermcap);
5584
5585 if (g_cbTermcap.IsValid)
5586 {
5587 /*
5588 * We've been in termcap mode before. Restore certain screen
5589 * characteristics, including the buffer size and the window
5590 * size. Since we will be redrawing the screen, we don't need
5591 * to restore the actual contents of the buffer.
5592 */
5593 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005594 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005595 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5596 Rows = g_cbTermcap.Info.dwSize.Y;
5597 Columns = g_cbTermcap.Info.dwSize.X;
5598 }
5599 else
5600 {
5601 /*
5602 * This is our first time entering termcap mode. Clear the console
5603 * screen buffer, and resize the buffer to match the current window
5604 * size. We will use this as the size of our editing environment.
5605 */
5606 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005607 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005608 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5609 }
5610
Bram Moolenaar071d4272004-06-13 20:20:40 +00005611 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005612
5613 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005614 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005615 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005616 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005617 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
5618 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005619 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005620 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005621 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005622 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5623 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005624 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005625 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005626
5627 redraw_later_clear();
5628 g_fTermcapMode = TRUE;
5629}
5630
5631
5632/*
5633 * End termcap mode
5634 */
5635 static void
5636termcap_mode_end(void)
5637{
5638 DWORD cmodein;
5639 ConsoleBuffer *cb;
5640 COORD coord;
5641 DWORD dwDummy;
5642
5643 if (!g_fTermcapMode)
5644 return;
5645
5646 SaveConsoleBuffer(&g_cbTermcap);
5647
5648 GetConsoleMode(g_hConIn, &cmodein);
5649 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005650 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5651 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005652
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005653# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005654 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005655# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005656 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005657# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005658 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01005659 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005660 SetConsoleCursorInfo(g_hConOut, &g_cci);
5661
5662 if (p_rs || exiting)
5663 {
5664 /*
5665 * Clear anything that happens to be on the current line.
5666 */
5667 coord.X = 0;
5668 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5669 FillConsoleOutputCharacter(g_hConOut, ' ',
5670 cb->Info.dwSize.X, coord, &dwDummy);
5671 /*
5672 * The following is just for aesthetics. If we are exiting without
5673 * restoring the screen, then we want to have a prompt string
5674 * appear at the bottom line. However, the command interpreter
5675 * seems to always advance the cursor one line before displaying
5676 * the prompt string, which causes the screen to scroll. To
5677 * counter this, move the cursor up one line before exiting.
5678 */
5679 if (exiting && !p_rs)
5680 coord.Y--;
5681 /*
5682 * Position the cursor at the leftmost column of the desired row.
5683 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005684 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005685 }
5686
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005687 if (!p_rs && USE_VTP)
Bram Moolenaar0afdcf82020-04-01 18:29:10 +02005688 vtp_printf("\033[?1049l");
5689
Bram Moolenaar071d4272004-06-13 20:20:40 +00005690 g_fTermcapMode = FALSE;
5691}
Bram Moolenaar0f873732019-12-05 20:28:46 +01005692#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005693
5694
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005695#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005696 void
5697mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005698 char_u *s UNUSED,
5699 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005700{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005701 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00005702}
5703
5704#else
5705
5706/*
5707 * clear `n' chars, starting from `coord'
5708 */
5709 static void
5710clear_chars(
5711 COORD coord,
5712 DWORD n)
5713{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005714 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02005715 {
5716 DWORD dwDummy;
5717
5718 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5719 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
5720 &dwDummy);
5721 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005722 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005723 {
5724 set_console_color_rgb();
5725 gotoxy(coord.X + 1, coord.Y + 1);
5726 vtp_printf("\033[%dX", n);
5727 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005728}
5729
5730
5731/*
5732 * Clear the screen
5733 */
5734 static void
5735clear_screen(void)
5736{
5737 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005738
5739 if (!USE_VTP)
5740 clear_chars(g_coord, Rows * Columns);
5741 else
5742 {
5743 set_console_color_rgb();
5744 gotoxy(1, 1);
5745 vtp_printf("\033[2J");
5746 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005747}
5748
5749
5750/*
5751 * Clear to end of display
5752 */
5753 static void
5754clear_to_end_of_display(void)
5755{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005756 COORD save = g_coord;
5757
5758 if (!USE_VTP)
5759 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005760 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005761 else
5762 {
5763 set_console_color_rgb();
5764 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5765 vtp_printf("\033[0J");
5766
5767 gotoxy(save.X + 1, save.Y + 1);
5768 g_coord = save;
5769 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005770}
5771
5772
5773/*
5774 * Clear to end of line
5775 */
5776 static void
5777clear_to_end_of_line(void)
5778{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005779 COORD save = g_coord;
5780
5781 if (!USE_VTP)
5782 clear_chars(g_coord, Columns - g_coord.X);
5783 else
5784 {
5785 set_console_color_rgb();
5786 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5787 vtp_printf("\033[0K");
5788
5789 gotoxy(save.X + 1, save.Y + 1);
5790 g_coord = save;
5791 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005792}
5793
5794
5795/*
5796 * Scroll the scroll region up by `cLines' lines
5797 */
5798 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005799scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005800{
5801 COORD oldcoord = g_coord;
5802
5803 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5804 delete_lines(cLines);
5805
5806 g_coord = oldcoord;
5807}
5808
5809
5810/*
5811 * Set the scroll region
5812 */
5813 static void
5814set_scroll_region(
5815 unsigned left,
5816 unsigned top,
5817 unsigned right,
5818 unsigned bottom)
5819{
5820 if (left >= right
5821 || top >= bottom
5822 || right > (unsigned) Columns - 1
5823 || bottom > (unsigned) Rows - 1)
5824 return;
5825
5826 g_srScrollRegion.Left = left;
5827 g_srScrollRegion.Top = top;
5828 g_srScrollRegion.Right = right;
5829 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005830}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005831
Bram Moolenaar6982f422019-02-16 16:48:01 +01005832 static void
5833set_scroll_region_tb(
5834 unsigned top,
5835 unsigned bottom)
5836{
5837 if (top >= bottom || bottom > (unsigned)Rows - 1)
5838 return;
5839
5840 g_srScrollRegion.Top = top;
5841 g_srScrollRegion.Bottom = bottom;
5842}
5843
5844 static void
5845set_scroll_region_lr(
5846 unsigned left,
5847 unsigned right)
5848{
5849 if (left >= right || right > (unsigned)Columns - 1)
5850 return;
5851
5852 g_srScrollRegion.Left = left;
5853 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005854}
5855
5856
5857/*
5858 * Insert `cLines' lines at the current cursor position
5859 */
5860 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005861insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005862{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005863 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005864 COORD dest;
5865 CHAR_INFO fill;
5866
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005867 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5868
Bram Moolenaar6982f422019-02-16 16:48:01 +01005869 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005870 dest.Y = g_coord.Y + cLines;
5871
Bram Moolenaar6982f422019-02-16 16:48:01 +01005872 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005873 source.Top = g_coord.Y;
5874 source.Right = g_srScrollRegion.Right;
5875 source.Bottom = g_srScrollRegion.Bottom - cLines;
5876
Bram Moolenaar6982f422019-02-16 16:48:01 +01005877 clip.Left = g_srScrollRegion.Left;
5878 clip.Top = g_coord.Y;
5879 clip.Right = g_srScrollRegion.Right;
5880 clip.Bottom = g_srScrollRegion.Bottom;
5881
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005882 fill.Char.AsciiChar = ' ';
5883 if (!USE_VTP)
5884 fill.Attributes = g_attrCurrent;
5885 else
5886 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005887
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005888 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005889
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005890 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5891
Bram Moolenaar6982f422019-02-16 16:48:01 +01005892 // Here we have to deal with a win32 console flake: If the scroll
5893 // region looks like abc and we scroll c to a and fill with d we get
5894 // cbd... if we scroll block c one line at a time to a, we get cdd...
5895 // vim expects cdd consistently... So we have to deal with that
5896 // here... (this also occurs scrolling the same way in the other
5897 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005898
5899 if (source.Bottom < dest.Y)
5900 {
5901 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005902 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005903
Bram Moolenaar6982f422019-02-16 16:48:01 +01005904 coord.X = source.Left;
5905 for (i = clip.Top; i < dest.Y; ++i)
5906 {
5907 coord.Y = i;
5908 clear_chars(coord, source.Right - source.Left + 1);
5909 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005910 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02005911
5912 if (USE_WT)
5913 {
5914 COORD coord;
5915 int i;
5916
5917 coord.X = source.Left;
5918 for (i = source.Top; i < dest.Y; ++i)
5919 {
5920 coord.Y = i;
5921 clear_chars(coord, source.Right - source.Left + 1);
5922 }
5923 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005924}
5925
5926
5927/*
5928 * Delete `cLines' lines at the current cursor position
5929 */
5930 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005931delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005932{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005933 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005934 COORD dest;
5935 CHAR_INFO fill;
5936 int nb;
5937
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005938 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5939
Bram Moolenaar6982f422019-02-16 16:48:01 +01005940 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005941 dest.Y = g_coord.Y;
5942
Bram Moolenaar6982f422019-02-16 16:48:01 +01005943 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005944 source.Top = g_coord.Y + cLines;
5945 source.Right = g_srScrollRegion.Right;
5946 source.Bottom = g_srScrollRegion.Bottom;
5947
Bram Moolenaar6982f422019-02-16 16:48:01 +01005948 clip.Left = g_srScrollRegion.Left;
5949 clip.Top = g_coord.Y;
5950 clip.Right = g_srScrollRegion.Right;
5951 clip.Bottom = g_srScrollRegion.Bottom;
5952
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005953 fill.Char.AsciiChar = ' ';
5954 if (!USE_VTP)
5955 fill.Attributes = g_attrCurrent;
5956 else
5957 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005958
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005959 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005960
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005961 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5962
Bram Moolenaar6982f422019-02-16 16:48:01 +01005963 // Here we have to deal with a win32 console flake; See insert_lines()
5964 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005965
5966 nb = dest.Y + (source.Bottom - source.Top) + 1;
5967
5968 if (nb < source.Top)
5969 {
5970 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005971 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005972
Bram Moolenaar6982f422019-02-16 16:48:01 +01005973 coord.X = source.Left;
5974 for (i = nb; i < clip.Bottom; ++i)
5975 {
5976 coord.Y = i;
5977 clear_chars(coord, source.Right - source.Left + 1);
5978 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005979 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02005980
5981 if (USE_WT)
5982 {
5983 COORD coord;
5984 int i;
5985
5986 coord.X = source.Left;
5987 for (i = nb; i <= source.Bottom; ++i)
5988 {
5989 coord.Y = i;
5990 clear_chars(coord, source.Right - source.Left + 1);
5991 }
5992 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005993}
5994
5995
5996/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02005997 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005998 */
5999 static void
6000gotoxy(
6001 unsigned x,
6002 unsigned y)
6003{
6004 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6005 return;
6006
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006007 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006008 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006009 // There are reports of double-width characters not displayed
6010 // correctly. This workaround should fix it, similar to how it's done
6011 // for VTP.
6012 g_coord.X = 0;
6013 SetConsoleCursorPosition(g_hConOut, g_coord);
6014
Bram Moolenaar2313b612019-09-27 14:14:32 +02006015 // external cursor coords are 1-based; internal are 0-based
6016 g_coord.X = x - 1;
6017 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006018 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006019 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006020 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006021 {
6022 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006023 // destruction. Insider build bug. Always enabled because it's cheap
6024 // and avoids mistakes with recognizing the build.
6025 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006026
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006027 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006028
6029 g_coord.X = x - 1;
6030 g_coord.Y = y - 1;
6031 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006032}
6033
6034
6035/*
6036 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006037 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006038 */
6039 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006040textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006041{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006042 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006043
6044 SetConsoleTextAttribute(g_hConOut, wAttr);
6045}
6046
6047
6048 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006049textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006050{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006051 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006052
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006053 if (!USE_VTP)
6054 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6055 else
6056 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006057}
6058
6059
6060 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006061textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006062{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006063 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006064
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006065 if (!USE_VTP)
6066 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6067 else
6068 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006069}
6070
6071
6072/*
6073 * restore the default text attribute (whatever we started with)
6074 */
6075 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006076normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006077{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006078 if (!USE_VTP)
6079 textattr(g_attrDefault);
6080 else
6081 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006082}
6083
6084
6085static WORD g_attrPreStandout = 0;
6086
6087/*
6088 * Make the text standout, by brightening it
6089 */
6090 static void
6091standout(void)
6092{
6093 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006094
Bram Moolenaar071d4272004-06-13 20:20:40 +00006095 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6096}
6097
6098
6099/*
6100 * Turn off standout mode
6101 */
6102 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006103standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006104{
6105 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006106 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006107
6108 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006109}
6110
6111
6112/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006113 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006114 */
6115 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006116mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006117{
6118 char_u *p;
6119 int n;
6120
6121 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6122 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006123 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006124# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006125 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006126# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006127 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006128 {
6129 p = T_ME + 2;
6130 n = getdigits(&p);
6131 if (*p == 'm' && n > 0)
6132 {
6133 cterm_normal_fg_color = (n & 0xf) + 1;
6134 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6135 }
6136 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006137# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006138 cterm_normal_fg_gui_color = INVALCOLOR;
6139 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006140# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006141}
6142
6143
6144/*
6145 * visual bell: flash the screen
6146 */
6147 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006148visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006149{
6150 COORD coordOrigin = {0, 0};
6151 WORD attrFlash = ~g_attrCurrent & 0xff;
6152
6153 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006154 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006155
6156 if (oldattrs == NULL)
6157 return;
6158 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6159 coordOrigin, &dwDummy);
6160 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6161 coordOrigin, &dwDummy);
6162
Bram Moolenaar0f873732019-12-05 20:28:46 +01006163 Sleep(15); // wait for 15 msec
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006164 if (!USE_VTP)
6165 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006166 coordOrigin, &dwDummy);
6167 vim_free(oldattrs);
6168}
6169
6170
6171/*
6172 * Make the cursor visible or invisible
6173 */
6174 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006175cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006176{
6177 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006178
6179 if (USE_VTP)
6180 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6181
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006182# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006183 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006184# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006185}
6186
6187
6188/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006189 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006190 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006191 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006192 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006193write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006194 char_u *pchBuf,
6195 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006196{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006197 COORD coord = g_coord;
6198 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006199 DWORD n, cchwritten;
6200 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006201 static WCHAR *unicodebuf = NULL;
6202 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006203 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006204 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006205 static WCHAR *utf8spbuf = NULL;
6206 static int utf8splength;
6207 static DWORD utf8spcells;
6208 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006209
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006210 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006211 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006212 utf8usingbuf = &unicodebuf;
6213 do
6214 {
6215 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6216 unicodebuf, unibuflen);
6217 if (length && length <= unibuflen)
6218 break;
6219 vim_free(unicodebuf);
6220 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6221 unibuflen = unibuflen ? 0 : length;
6222 } while(1);
6223 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006224 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006225 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6226 {
6227 if (utf8usingbuf != &utf8spbuf)
6228 {
6229 if (utf8spbuf == NULL)
6230 {
6231 cells = mb_string2cells((char_u *)" ", 1);
6232 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6233 utf8spbuf = LALLOC_MULT(WCHAR, length);
6234 if (utf8spbuf != NULL)
6235 {
6236 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6237 utf8usingbuf = &utf8spbuf;
6238 utf8splength = length;
6239 utf8spcells = cells;
6240 }
6241 }
6242 else
6243 {
6244 utf8usingbuf = &utf8spbuf;
6245 length = utf8splength;
6246 cells = utf8spcells;
6247 }
6248 }
6249 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006250
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006251 if (!USE_VTP)
6252 {
6253 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6254 coord, &written);
6255 // When writing fails or didn't write a single character, pretend one
6256 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006257 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006258 coord, &cchwritten) == 0
6259 || cchwritten == 0 || cchwritten == (DWORD)-1)
6260 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006261 }
6262 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006263 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006264 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006265 NULL) == 0 || cchwritten == 0)
6266 cchwritten = 1;
6267 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006268
K.Takata135e1522022-01-29 15:27:58 +00006269 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006270 {
6271 written = cbToWrite;
6272 g_coord.X += (SHORT)cells;
6273 }
6274 else
6275 {
6276 char_u *p = pchBuf;
6277 for (n = 0; n < cchwritten; n++)
6278 MB_CPTR_ADV(p);
6279 written = p - pchBuf;
6280 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006281 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006282
6283 while (g_coord.X > g_srScrollRegion.Right)
6284 {
6285 g_coord.X -= (SHORT) Columns;
6286 if (g_coord.Y < g_srScrollRegion.Bottom)
6287 g_coord.Y++;
6288 }
6289
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006290 // Cursor under VTP is always in the correct position, no need to reset.
6291 if (!USE_VTP)
6292 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006293
6294 return written;
6295}
6296
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006297 static char_u *
6298get_seq(
6299 int *args,
6300 int *count,
6301 char_u *head)
6302{
6303 int argc;
6304 char_u *p;
6305
6306 if (head == NULL || *head != '\033')
6307 return NULL;
6308
6309 argc = 0;
6310 p = head;
6311 ++p;
6312 do
6313 {
6314 ++p;
6315 args[argc] = getdigits(&p);
6316 argc += (argc < 15) ? 1 : 0;
6317 } while (*p == ';');
6318 *count = argc;
6319
6320 return p;
6321}
6322
6323 static char_u *
6324get_sgr(
6325 int *args,
6326 int *count,
6327 char_u *head)
6328{
6329 char_u *p = get_seq(args, count, head);
6330
6331 return (p && *p == 'm') ? ++p : NULL;
6332}
6333
6334/*
6335 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6336 */
6337 static char_u *
6338sgrn2(
6339 char_u *head,
6340 int n)
6341{
6342 int argc;
6343 int args[16];
6344 char_u *p = get_sgr(args, &argc, head);
6345
6346 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6347}
6348
6349/*
6350 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6351 */
6352 static char_u *
6353sgrnc(
6354 char_u *head,
6355 int n)
6356{
6357 int argc;
6358 int args[16];
6359 char_u *p = get_sgr(args, &argc, head);
6360
6361 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6362 ? p : NULL;
6363}
6364
6365 static char_u *
6366skipblank(char_u *q)
6367{
6368 char_u *p = q;
6369
6370 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6371 ++p;
6372 return p;
6373}
6374
6375/*
6376 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6377 * NULL.
6378 */
6379 static char_u *
6380sgrn2c(
6381 char_u *head,
6382 int n)
6383{
6384 char_u *p = sgrn2(head, n);
6385
6386 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6387}
6388
6389/*
6390 * If there is only a newline between the sequence immediately following it,
6391 * a pointer to the character following the newline is returned.
6392 * Otherwise NULL.
6393 */
6394 static char_u *
6395sgrn2cn(
6396 char_u *head,
6397 int n)
6398{
6399 char_u *p = sgrn2(head, n);
6400
6401 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6402}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006403
6404/*
6405 * mch_write(): write the output buffer to the screen, translating ESC
6406 * sequences into calls to console output routines.
6407 */
6408 void
6409mch_write(
6410 char_u *s,
6411 int len)
6412{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006413 char_u *end = s + len;
6414
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006415# ifdef VIMDLL
6416 if (gui.in_use)
6417 return;
6418# endif
6419
Bram Moolenaar071d4272004-06-13 20:20:40 +00006420 if (!term_console)
6421 {
6422 write(1, s, (unsigned)len);
6423 return;
6424 }
6425
Bram Moolenaar0f873732019-12-05 20:28:46 +01006426 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00006427 while (len--)
6428 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006429 int prefix = -1;
6430 char_u ch;
6431
6432 // While processing a sequence, on rare occasions it seems that another
6433 // sequence may be inserted asynchronously.
6434 if (len < 0)
6435 {
6436 redraw_all_later(CLEAR);
6437 return;
6438 }
6439
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006440 while (s + ++prefix < end)
6441 {
6442 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006443 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6444 && ch != '\a' && ch != '\033'))
6445 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006446 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006447
6448 if (p_wd)
6449 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006450 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006451 if (prefix != 0)
6452 prefix = 1;
6453 }
6454
6455 if (prefix != 0)
6456 {
6457 DWORD nWritten;
6458
6459 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006460# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006461 if (fdDump)
6462 {
6463 fputc('>', fdDump);
6464 fwrite(s, sizeof(char_u), nWritten, fdDump);
6465 fputs("<\n", fdDump);
6466 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006467# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006468 len -= (nWritten - 1);
6469 s += nWritten;
6470 }
6471 else if (s[0] == '\n')
6472 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006473 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00006474 if (g_coord.Y == g_srScrollRegion.Bottom)
6475 {
6476 scroll(1);
6477 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6478 }
6479 else
6480 {
6481 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6482 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006483# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006484 if (fdDump)
6485 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006486# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006487 s++;
6488 }
6489 else if (s[0] == '\r')
6490 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006491 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00006492 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006493# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006494 if (fdDump)
6495 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006496# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006497 s++;
6498 }
6499 else if (s[0] == '\b')
6500 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006501 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00006502 if (g_coord.X > g_srScrollRegion.Left)
6503 g_coord.X--;
6504 else if (g_coord.Y > g_srScrollRegion.Top)
6505 {
6506 g_coord.X = g_srScrollRegion.Right;
6507 g_coord.Y--;
6508 }
6509 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006510# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006511 if (fdDump)
6512 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006513# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006514 s++;
6515 }
6516 else if (s[0] == '\a')
6517 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006518 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00006519 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006520# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006521 if (fdDump)
6522 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006523# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006524 s++;
6525 }
6526 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6527 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006528# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006529 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006530# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006531 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006532 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006533 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006534
6535 switch (s[2])
6536 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006537 case '0': case '1': case '2': case '3': case '4':
6538 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006539 if (*(p = get_seq(args, &argc, s)) != 'm')
6540 goto notsgr;
6541
6542 p = s;
6543
6544 // Handling frequent optional sequences. Output to the screen
6545 // takes too long, so do not output as much as possible.
6546
6547 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
6548 // resetFG,FG,BG are omitted.
6549 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006550 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006551 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
6552 len = len + 1 - (int)(p - s);
6553 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006554 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006555 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006556
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006557 // If FG,BG,BG,FG of SGR are connected, the first FG can be
6558 // omitted.
6559 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
6560 p = sp;
6561
6562 // If FG,BG,FG,BG of SGR are connected, the first FG can be
6563 // omitted.
6564 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
6565 p = sp;
6566
6567 // If BG,BG of SGR are connected, the first BG can be omitted.
6568 if (sgrn2((sp = sgrn2(p, 48)), 48))
6569 p = sp;
6570
6571 // If restoreFG and FG are connected, the restoreFG can be
6572 // omitted.
6573 if (sgrn2((sp = sgrnc(p, 39)), 38))
6574 p = sp;
6575
6576 p = get_seq(args, &argc, p);
6577
6578notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006579 arg1 = args[0];
6580 arg2 = args[1];
6581 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006582 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006583 if (argc == 1 && args[0] == 0)
6584 normvideo();
6585 else if (argc == 1)
6586 {
6587 if (USE_VTP)
6588 textcolor((WORD) arg1);
6589 else
6590 textattr((WORD) arg1);
6591 }
6592 else if (USE_VTP)
6593 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006594 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006595 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006596 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006597 gotoxy(arg2, arg1);
6598 }
6599 else if (argc == 2 && *p == 'r')
6600 {
6601 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6602 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006603 else if (argc == 2 && *p == 'R')
6604 {
6605 set_scroll_region_tb(arg1, arg2);
6606 }
6607 else if (argc == 2 && *p == 'V')
6608 {
6609 set_scroll_region_lr(arg1, arg2);
6610 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006611 else if (argc == 1 && *p == 'A')
6612 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006613 gotoxy(g_coord.X + 1,
6614 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6615 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006616 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006617 {
6618 textbackground((WORD) arg1);
6619 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006620 else if (argc == 1 && *p == 'C')
6621 {
6622 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6623 g_coord.Y + 1);
6624 }
6625 else if (argc == 1 && *p == 'f')
6626 {
6627 textcolor((WORD) arg1);
6628 }
6629 else if (argc == 1 && *p == 'H')
6630 {
6631 gotoxy(1, arg1);
6632 }
6633 else if (argc == 1 && *p == 'L')
6634 {
6635 insert_lines(arg1);
6636 }
6637 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006638 {
6639 delete_lines(arg1);
6640 }
6641
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006642 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006643 s = p + 1;
6644 break;
6645
Bram Moolenaar071d4272004-06-13 20:20:40 +00006646 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006647 gotoxy(g_coord.X + 1,
6648 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6649 goto got3;
6650
6651 case 'B':
6652 visual_bell();
6653 goto got3;
6654
6655 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006656 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6657 g_coord.Y + 1);
6658 goto got3;
6659
6660 case 'E':
6661 termcap_mode_end();
6662 goto got3;
6663
6664 case 'F':
6665 standout();
6666 goto got3;
6667
6668 case 'f':
6669 standend();
6670 goto got3;
6671
6672 case 'H':
6673 gotoxy(1, 1);
6674 goto got3;
6675
6676 case 'j':
6677 clear_to_end_of_display();
6678 goto got3;
6679
6680 case 'J':
6681 clear_screen();
6682 goto got3;
6683
6684 case 'K':
6685 clear_to_end_of_line();
6686 goto got3;
6687
6688 case 'L':
6689 insert_lines(1);
6690 goto got3;
6691
6692 case 'M':
6693 delete_lines(1);
6694 goto got3;
6695
6696 case 'S':
6697 termcap_mode_start();
6698 goto got3;
6699
6700 case 'V':
6701 cursor_visible(TRUE);
6702 goto got3;
6703
6704 case 'v':
6705 cursor_visible(FALSE);
6706 goto got3;
6707
6708 got3:
6709 s += 3;
6710 len -= 2;
6711 }
6712
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006713# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006714 if (fdDump)
6715 {
6716 fputs("ESC | ", fdDump);
6717 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6718 fputc('\n', fdDump);
6719 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006720# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006721 }
6722 else
6723 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006724 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00006725 DWORD nWritten;
6726
6727 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006728# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006729 if (fdDump)
6730 {
6731 fputc('>', fdDump);
6732 fwrite(s, sizeof(char_u), nWritten, fdDump);
6733 fputs("<\n", fdDump);
6734 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006735# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006736
6737 len -= (nWritten - 1);
6738 s += nWritten;
6739 }
6740 }
6741
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006742# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006743 if (fdDump)
6744 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006745# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006746}
6747
Bram Moolenaar0f873732019-12-05 20:28:46 +01006748#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006749
6750
6751/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006752 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006753 */
6754 void
6755mch_delay(
6756 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02006757 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006758{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006759#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006760 Sleep((int)msec); // never wait for input
6761#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006762# ifdef VIMDLL
6763 if (gui.in_use)
6764 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006765 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006766 return;
6767 }
6768# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02006769 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006770# ifdef FEAT_MZSCHEME
6771 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6772 {
6773 int towait = p_mzq;
6774
Bram Moolenaar0f873732019-12-05 20:28:46 +01006775 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006776 while (msec > 0)
6777 {
6778 mzvim_check_threads();
6779 if (msec < towait)
6780 towait = msec;
6781 Sleep(towait);
6782 msec -= towait;
6783 }
6784 }
6785 else
6786# endif
6787 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006788 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006789 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006790#endif
6791}
6792
6793
6794/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006795 * This version of remove is not scared by a readonly (backup) file.
6796 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006797 * Return 0 for success, -1 for failure.
6798 */
6799 int
6800mch_remove(char_u *name)
6801{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006802 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006803 int n;
6804
Bram Moolenaar203258c2016-01-17 22:15:16 +01006805 /*
6806 * On Windows, deleting a directory's symbolic link is done by
6807 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6808 */
6809 if (mch_isdir(name) && mch_is_symbolic_link(name))
6810 return mch_rmdir(name);
6811
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006812 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6813
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006814 wn = enc_to_utf16(name, NULL);
6815 if (wn == NULL)
6816 return -1;
6817
6818 n = DeleteFileW(wn) ? 0 : -1;
6819 vim_free(wn);
6820 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006821}
6822
6823
6824/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006825 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006826 */
6827 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006828mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006829{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006830#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
6831# ifdef VIMDLL
6832 if (!gui.in_use)
6833# endif
6834 if (g_fCtrlCPressed || g_fCBrkPressed)
6835 {
6836 ctrl_break_was_pressed = g_fCBrkPressed;
6837 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6838 got_int = TRUE;
6839 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006840#endif
6841}
6842
Bram Moolenaar0f873732019-12-05 20:28:46 +01006843// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01006844#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006845
6846/*
6847 * How much main memory in KiB that can be used by VIM.
6848 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006849 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006850mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006851{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006852 MEMORYSTATUSEX ms;
6853
Bram Moolenaar0f873732019-12-05 20:28:46 +01006854 // Need to use GlobalMemoryStatusEx() when there is more memory than
6855 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006856 ms.dwLength = sizeof(MEMORYSTATUSEX);
6857 GlobalMemoryStatusEx(&ms);
6858 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006859 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006860 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006861 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006862 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006863 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006864 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006865 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006866 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006867 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01006868 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006869 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006870}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006871
Bram Moolenaar071d4272004-06-13 20:20:40 +00006872/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006873 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00006874 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6875 * file whose short file name is "FOO.BAR" (its long file name will
6876 * be correct: "foo.bar~"). Because a file can be accessed by
6877 * either its SFN or its LFN, "foo.bar" has effectively been
6878 * renamed to "foo.bar", which is not at all what was wanted. This
6879 * seems to happen only when renaming files with three-character
6880 * extensions by appending a suffix that does not include ".".
6881 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6882 *
6883 * There is another problem, which isn't really a bug but isn't right either:
6884 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6885 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6886 * service pack 6. Doesn't seem to happen on Windows 98.
6887 *
6888 * Like rename(), returns 0 upon success, non-zero upon failure.
6889 * Should probably set errno appropriately when errors occur.
6890 */
6891 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006892mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006893{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006894 WCHAR *p;
6895 int i;
6896 WCHAR szTempFile[_MAX_PATH + 1];
6897 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006898 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006899
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006900 // No need to play tricks unless the file name contains a "~" as the
6901 // seventh character.
6902 p = wold;
6903 for (i = 0; wold[i] != NUL; ++i)
6904 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6905 && wold[i + 1] != 0)
6906 p = wold + i + 1;
6907 if ((int)(wold + i - p) < 8 || p[6] != '~')
6908 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006909
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006910 // Get base path of new file name. Undocumented feature: If pszNewFile is
6911 // a directory, no error is returned and pszFilePart will be NULL.
6912 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006913 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006914 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006915
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006916 // Get (and create) a unique temporary file name in directory of new file
6917 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006918 return -2;
6919
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006920 // blow the temp file away
6921 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006922 return -3;
6923
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006924 // rename old file to the temp file
6925 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006926 return -4;
6927
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006928 // now create an empty file called pszOldFile; this prevents the operating
6929 // system using pszOldFile as an alias (SFN) if we're renaming within the
6930 // same directory. For example, we're editing a file called
6931 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6932 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
6933 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
6934 // cause all sorts of problems later in buf_write(). So, we create an
6935 // empty file called filena~1.txt and the system will have to find some
6936 // other SFN for filena~1.txt~, such as filena~2.txt
6937 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006938 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6939 return -5;
6940 if (!CloseHandle(hf))
6941 return -6;
6942
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006943 // rename the temp file to the new file
6944 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006945 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006946 // Renaming failed. Rename the file back to its old name, so that it
6947 // looks like nothing happened.
6948 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006949 return -7;
6950 }
6951
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006952 // Seems to be left around on Novell filesystems
6953 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006954
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006955 // finally, remove the empty old file
6956 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006957 return -8;
6958
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006959 return 0;
6960}
6961
6962
6963/*
6964 * Converts the filenames to UTF-16, then call mch_wrename().
6965 * Like rename(), returns 0 upon success, non-zero upon failure.
6966 */
6967 int
6968mch_rename(
6969 const char *pszOldFile,
6970 const char *pszNewFile)
6971{
6972 WCHAR *wold = NULL;
6973 WCHAR *wnew = NULL;
6974 int retval = -1;
6975
6976 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6977 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
6978 if (wold != NULL && wnew != NULL)
6979 retval = mch_wrename(wold, wnew);
6980 vim_free(wold);
6981 vim_free(wnew);
6982 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006983}
6984
6985/*
6986 * Get the default shell for the current hardware platform
6987 */
6988 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006989default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006990{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006991 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006992}
6993
6994/*
6995 * mch_access() extends access() to do more detailed check on network drives.
6996 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6997 */
6998 int
6999mch_access(char *n, int p)
7000{
7001 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007002 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007003 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007004
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007005 wn = enc_to_utf16((char_u *)n, NULL);
7006 if (wn == NULL)
7007 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007008
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007009 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007010 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007011 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007012
7013 if (p & R_OK)
7014 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007015 // Read check is performed by seeing if we can do a find file on
7016 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007017 int i;
7018 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007019
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007020 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7021 TempNameW[i] = wn[i];
7022 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7023 TempNameW[i++] = '\\';
7024 TempNameW[i++] = '*';
7025 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007026
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007027 hFile = FindFirstFileW(TempNameW, &d);
7028 if (hFile == INVALID_HANDLE_VALUE)
7029 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007030 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007031 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007032 }
7033
7034 if (p & W_OK)
7035 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007036 // Trying to create a temporary file in the directory should catch
7037 // directories on read-only network shares. However, in
7038 // directories whose ACL allows writes but denies deletes will end
7039 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007040 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7041 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007042 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007043 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007044 }
7045 }
7046 else
7047 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007048 // Don't consider a file read-only if another process has opened it.
7049 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7050
Bram Moolenaar0f873732019-12-05 20:28:46 +01007051 // Trying to open the file for the required access does ACL, read-only
7052 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007053 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7054 | ((p & R_OK) ? GENERIC_READ : 0);
7055
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007056 hFile = CreateFileW(wn, access_mode, share_mode,
7057 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007058 if (hFile == INVALID_HANDLE_VALUE)
7059 goto getout;
7060 CloseHandle(hFile);
7061 }
7062
Bram Moolenaar0f873732019-12-05 20:28:46 +01007063 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007064getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007065 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007066 return retval;
7067}
7068
Bram Moolenaar071d4272004-06-13 20:20:40 +00007069/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007070 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007071 */
7072 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007073mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007074{
7075 WCHAR *wn;
7076 int f;
7077
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007078 wn = enc_to_utf16((char_u *)name, NULL);
7079 if (wn == NULL)
7080 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007081
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007082 f = _wopen(wn, flags, mode);
7083 vim_free(wn);
7084 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007085}
7086
7087/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007088 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007089 */
7090 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007091mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007092{
7093 WCHAR *wn, *wm;
7094 FILE *f = NULL;
7095
Bram Moolenaara12a1612019-01-24 16:39:02 +01007096#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007097 // Work around an annoying assertion in the Microsoft debug CRT
7098 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007099 char newMode = mode[strlen(mode) - 1];
7100 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007101
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007102 _get_fmode(&oldMode);
7103 if (newMode == 't')
7104 _set_fmode(_O_TEXT);
7105 else if (newMode == 'b')
7106 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007107#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007108 wn = enc_to_utf16((char_u *)name, NULL);
7109 wm = enc_to_utf16((char_u *)mode, NULL);
7110 if (wn != NULL && wm != NULL)
7111 f = _wfopen(wn, wm);
7112 vim_free(wn);
7113 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007114
Bram Moolenaara12a1612019-01-24 16:39:02 +01007115#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007116 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007117#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007118 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007119}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007120
Bram Moolenaar071d4272004-06-13 20:20:40 +00007121/*
7122 * SUB STREAM (aka info stream) handling:
7123 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007124 * NTFS can have sub streams for each file. The normal contents of a file is
7125 * stored in the main stream, and extra contents (author information, title and
7126 * so on) can be stored in a sub stream. After Windows 2000, the user can
7127 * access and store this information in sub streams via an explorer's property
7128 * menu item in the right click menu. This information in sub streams was lost
7129 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007130 *
7131 * Incomplete explanation:
7132 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7133 * More useful info and an example:
7134 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7135 */
7136
7137/*
7138 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7139 * and write to stream "substream" of file "to".
7140 * Errors are ignored.
7141 */
7142 static void
7143copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7144{
7145 HANDLE hTo;
7146 WCHAR *to_name;
7147
7148 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7149 wcscpy(to_name, to);
7150 wcscat(to_name, substream);
7151
7152 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7153 FILE_ATTRIBUTE_NORMAL, NULL);
7154 if (hTo != INVALID_HANDLE_VALUE)
7155 {
7156 long done;
7157 DWORD todo;
7158 DWORD readcnt, written;
7159 char buf[4096];
7160
Bram Moolenaar0f873732019-12-05 20:28:46 +01007161 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007162 for (done = 0; done < len; done += written)
7163 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007164 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007165 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7166 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007167 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7168 FALSE, FALSE, context)
7169 || readcnt != todo
7170 || !WriteFile(hTo, buf, todo, &written, NULL)
7171 || written != todo)
7172 break;
7173 }
7174 CloseHandle(hTo);
7175 }
7176
7177 free(to_name);
7178}
7179
7180/*
7181 * Copy info streams from file "from" to file "to".
7182 */
7183 static void
7184copy_infostreams(char_u *from, char_u *to)
7185{
7186 WCHAR *fromw;
7187 WCHAR *tow;
7188 HANDLE sh;
7189 WIN32_STREAM_ID sid;
7190 int headersize;
7191 WCHAR streamname[_MAX_PATH];
7192 DWORD readcount;
7193 void *context = NULL;
7194 DWORD lo, hi;
7195 int len;
7196
Bram Moolenaar0f873732019-12-05 20:28:46 +01007197 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007198 fromw = enc_to_utf16(from, NULL);
7199 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007200 if (fromw != NULL && tow != NULL)
7201 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007202 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007203 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7204 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7205 if (sh != INVALID_HANDLE_VALUE)
7206 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007207 // Use BackupRead() to find the info streams. Repeat until we
7208 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007209 for (;;)
7210 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007211 // Get the header to find the length of the stream name. If
7212 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007213 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007214 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007215 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7216 &readcount, FALSE, FALSE, &context)
7217 || readcount == 0)
7218 break;
7219
Bram Moolenaar0f873732019-12-05 20:28:46 +01007220 // We only deal with streams that have a name. The normal
7221 // file data appears to be without a name, even though docs
7222 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007223 if (sid.dwStreamNameSize > 0)
7224 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007225 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007226 if (!BackupRead(sh, (LPBYTE)streamname,
7227 sid.dwStreamNameSize,
7228 &readcount, FALSE, FALSE, &context))
7229 break;
7230
Bram Moolenaar0f873732019-12-05 20:28:46 +01007231 // Copy an info stream with a name ":anything:$DATA".
7232 // Skip "::$DATA", it has no stream name (examples suggest
7233 // it might be used for the normal file contents).
7234 // Note that BackupRead() counts bytes, but the name is in
7235 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007236 len = readcount / sizeof(WCHAR);
7237 streamname[len] = 0;
7238 if (len > 7 && wcsicmp(streamname + len - 6,
7239 L":$DATA") == 0)
7240 {
7241 streamname[len - 6] = 0;
7242 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007243 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007244 }
7245 }
7246
Bram Moolenaar0f873732019-12-05 20:28:46 +01007247 // Advance to the next stream. We might try seeking too far,
7248 // but BackupSeek() doesn't skip over stream borders, thus
7249 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007250 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007251 &lo, &hi, &context);
7252 }
7253
Bram Moolenaar0f873732019-12-05 20:28:46 +01007254 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007255 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7256
7257 CloseHandle(sh);
7258 }
7259 }
7260 vim_free(fromw);
7261 vim_free(tow);
7262}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007263
7264/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007265 * ntdll.dll definitions
7266 */
7267#define FileEaInformation 7
7268#ifndef STATUS_SUCCESS
7269# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7270#endif
7271
7272typedef struct _FILE_FULL_EA_INFORMATION_ {
7273 ULONG NextEntryOffset;
7274 UCHAR Flags;
7275 UCHAR EaNameLength;
7276 USHORT EaValueLength;
7277 CHAR EaName[1];
7278} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7279
7280typedef struct _FILE_EA_INFORMATION_ {
7281 ULONG EaSize;
7282} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7283
7284typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7285 PHANDLE FileHandle,
7286 ACCESS_MASK DesiredAccess,
7287 POBJECT_ATTRIBUTES ObjectAttributes,
7288 PIO_STATUS_BLOCK IoStatusBlock,
7289 ULONG ShareAccess,
7290 ULONG OpenOptions);
7291typedef NTSTATUS (NTAPI *PfnNtClose)(
7292 HANDLE Handle);
7293typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
7294 HANDLE FileHandle,
7295 PIO_STATUS_BLOCK IoStatusBlock,
7296 PVOID Buffer,
7297 ULONG Length);
7298typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7299 HANDLE FileHandle,
7300 PIO_STATUS_BLOCK IoStatusBlock,
7301 PVOID Buffer,
7302 ULONG Length,
7303 BOOLEAN ReturnSingleEntry,
7304 PVOID EaList,
7305 ULONG EaListLength,
7306 PULONG EaIndex,
7307 BOOLEAN RestartScan);
7308typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
7309 HANDLE FileHandle,
7310 PIO_STATUS_BLOCK IoStatusBlock,
7311 PVOID FileInformation,
7312 ULONG Length,
7313 FILE_INFORMATION_CLASS FileInformationClass);
7314typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7315 PUNICODE_STRING DestinationString,
7316 PCWSTR SourceString);
7317
7318PfnNtOpenFile pNtOpenFile = NULL;
7319PfnNtClose pNtClose = NULL;
7320PfnNtSetEaFile pNtSetEaFile = NULL;
7321PfnNtQueryEaFile pNtQueryEaFile = NULL;
7322PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7323PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
7324
7325/*
7326 * Load ntdll.dll functions.
7327 */
7328 static BOOL
7329load_ntdll(void)
7330{
7331 static int loaded = -1;
7332
7333 if (loaded == -1)
7334 {
7335 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7336 if (hNtdll != NULL)
7337 {
7338 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7339 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7340 pNtSetEaFile = (PfnNtSetEaFile)
7341 GetProcAddress(hNtdll, "NtSetEaFile");
7342 pNtQueryEaFile = (PfnNtQueryEaFile)
7343 GetProcAddress(hNtdll, "NtQueryEaFile");
7344 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7345 GetProcAddress(hNtdll, "NtQueryInformationFile");
7346 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7347 GetProcAddress(hNtdll, "RtlInitUnicodeString");
7348 }
7349 if (pNtOpenFile == NULL
7350 || pNtClose == NULL
7351 || pNtSetEaFile == NULL
7352 || pNtQueryEaFile == NULL
7353 || pNtQueryInformationFile == NULL
7354 || pRtlInitUnicodeString == NULL)
7355 loaded = FALSE;
7356 else
7357 loaded = TRUE;
7358 }
7359 return (BOOL) loaded;
7360}
7361
7362/*
7363 * Copy extended attributes (EA) from file "from" to file "to".
7364 */
7365 static void
7366copy_extattr(char_u *from, char_u *to)
7367{
7368 char_u *fromf = NULL;
7369 char_u *tof = NULL;
7370 WCHAR *fromw = NULL;
7371 WCHAR *tow = NULL;
7372 UNICODE_STRING u;
7373 HANDLE h;
7374 OBJECT_ATTRIBUTES oa;
7375 IO_STATUS_BLOCK iosb;
7376 FILE_EA_INFORMATION_ eainfo = {0};
7377 void *ea = NULL;
7378
7379 if (!load_ntdll())
7380 return;
7381
7382 // Convert the file names to the fully qualified object names.
7383 fromf = alloc(STRLEN(from) + 5);
7384 tof = alloc(STRLEN(to) + 5);
7385 if (fromf == NULL || tof == NULL)
7386 goto theend;
7387 STRCPY(fromf, "\\??\\");
7388 STRCAT(fromf, from);
7389 STRCPY(tof, "\\??\\");
7390 STRCAT(tof, to);
7391
7392 // Convert the names to wide characters.
7393 fromw = enc_to_utf16(fromf, NULL);
7394 tow = enc_to_utf16(tof, NULL);
7395 if (fromw == NULL || tow == NULL)
7396 goto theend;
7397
7398 // Get the EA.
7399 pRtlInitUnicodeString(&u, fromw);
7400 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7401 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7402 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7403 goto theend;
7404 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7405 FileEaInformation);
7406 if (eainfo.EaSize != 0)
7407 {
7408 ea = alloc(eainfo.EaSize);
7409 if (ea != NULL)
7410 {
7411 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7412 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7413 {
7414 vim_free(ea);
7415 ea = NULL;
7416 }
7417 }
7418 }
7419 pNtClose(h);
7420
7421 // Set the EA.
7422 if (ea != NULL)
7423 {
7424 pRtlInitUnicodeString(&u, tow);
7425 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7426 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7427 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7428 goto theend;
7429
7430 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
7431 pNtClose(h);
7432 }
7433
7434theend:
7435 vim_free(fromf);
7436 vim_free(tof);
7437 vim_free(fromw);
7438 vim_free(tow);
7439 vim_free(ea);
7440}
7441
7442/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007443 * Copy file attributes from file "from" to file "to".
7444 * For Windows NT and later we copy info streams.
7445 * Always returns zero, errors are ignored.
7446 */
7447 int
7448mch_copy_file_attribute(char_u *from, char_u *to)
7449{
Bram Moolenaar0f873732019-12-05 20:28:46 +01007450 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007451 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007452 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007453 return 0;
7454}
7455
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007456
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007457/*
K.Takatadc73b4b2021-06-08 18:32:36 +02007458 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007459 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007460static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007461static LPWSTR *ArglistW = NULL;
7462static int global_argc = 0;
7463static char **global_argv;
7464
Bram Moolenaar0f873732019-12-05 20:28:46 +01007465static int used_file_argc = 0; // last argument in global_argv[] used
7466 // for the argument list.
7467static int *used_file_indexes = NULL; // indexes in global_argv[] for
7468 // command line arguments added to
7469 // the argument list
7470static int used_file_count = 0; // nr of entries in used_file_indexes
7471static int used_file_literal = FALSE; // take file names literally
7472static int used_file_full_path = FALSE; // file name was full path
7473static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007474static int used_alist_count = 0;
7475
7476
7477/*
7478 * Get the command line arguments. Unicode version.
7479 * Returns argc. Zero when something fails.
7480 */
7481 int
7482get_cmd_argsW(char ***argvp)
7483{
7484 char **argv = NULL;
7485 int argc = 0;
7486 int i;
7487
Bram Moolenaar14993322014-09-09 12:25:33 +02007488 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007489 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7490 if (ArglistW != NULL)
7491 {
7492 argv = malloc((nArgsW + 1) * sizeof(char *));
7493 if (argv != NULL)
7494 {
7495 argc = nArgsW;
7496 argv[argc] = NULL;
7497 for (i = 0; i < argc; ++i)
7498 {
7499 int len;
7500
K.Takatadc73b4b2021-06-08 18:32:36 +02007501 // Convert each Unicode argument to UTF-8.
7502 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007503 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007504 (LPSTR *)&argv[i], &len, 0, 0);
7505 if (argv[i] == NULL)
7506 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007507 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007508 while (i > 0)
7509 free(argv[--i]);
7510 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007511 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007512 argc = 0;
7513 }
7514 }
7515 }
7516 }
7517
7518 global_argc = argc;
7519 global_argv = argv;
7520 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007521 {
7522 if (used_file_indexes != NULL)
7523 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007524 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007525 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007526
7527 if (argvp != NULL)
7528 *argvp = argv;
7529 return argc;
7530}
7531
7532 void
7533free_cmd_argsW(void)
7534{
7535 if (ArglistW != NULL)
7536 {
7537 GlobalFree(ArglistW);
7538 ArglistW = NULL;
7539 }
7540}
7541
7542/*
7543 * Remember "name" is an argument that was added to the argument list.
7544 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7545 * is called.
7546 */
7547 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007548used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007549{
7550 int i;
7551
7552 if (used_file_indexes == NULL)
7553 return;
7554 for (i = used_file_argc + 1; i < global_argc; ++i)
7555 if (STRCMP(global_argv[i], name) == 0)
7556 {
7557 used_file_argc = i;
7558 used_file_indexes[used_file_count++] = i;
7559 break;
7560 }
7561 used_file_literal = literal;
7562 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007563 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007564}
7565
7566/*
7567 * Remember the length of the argument list as it was. If it changes then we
7568 * leave it alone when 'encoding' is set.
7569 */
7570 void
7571set_alist_count(void)
7572{
7573 used_alist_count = GARGCOUNT;
7574}
7575
7576/*
7577 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02007578 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007579 * and convert them to 'encoding'.
7580 */
7581 void
7582fix_arg_enc(void)
7583{
7584 int i;
7585 int idx;
7586 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007587 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007588
Bram Moolenaar0f873732019-12-05 20:28:46 +01007589 // Safety checks:
7590 // - if argument count differs between the wide and non-wide argument
7591 // list, something must be wrong.
7592 // - the file name arguments must have been located.
7593 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007594 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007595 || ArglistW == NULL
7596 || used_file_indexes == NULL
7597 || used_file_count == 0
7598 || used_alist_count != GARGCOUNT)
7599 return;
7600
Bram Moolenaar0f873732019-12-05 20:28:46 +01007601 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007602 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007603 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007604 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00007605 for (i = 0; i < GARGCOUNT; ++i)
7606 fnum_list[i] = GARGLIST[i].ae_fnum;
7607
Bram Moolenaar0f873732019-12-05 20:28:46 +01007608 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007609 alist_clear(&global_alist);
7610 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007611 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007612
7613 for (i = 0; i < used_file_count; ++i)
7614 {
7615 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007616 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007617 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007618 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007619 int literal = used_file_literal;
7620
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007621#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01007622 // When using diff mode may need to concatenate file name to
7623 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007624 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7625 && !mch_isdir(alist_name(&GARGLIST[0])))
7626 {
7627 char_u *r;
7628
7629 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7630 if (r != NULL)
7631 {
7632 vim_free(str);
7633 str = r;
7634 }
7635 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007636#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01007637 // Re-use the old buffer by renaming it. When not using literal
7638 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00007639 if (used_file_literal)
7640 buf_set_name(fnum_list[i], str);
7641
Bram Moolenaar0f873732019-12-05 20:28:46 +01007642 // Check backtick literal. backtick literal is already expanded in
7643 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007644 if (literal == FALSE)
7645 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007646 size_t len = STRLEN(str);
7647
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007648 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7649 literal = TRUE;
7650 }
7651 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007652 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007653 }
7654
7655 if (!used_file_literal)
7656 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007657 // Now expand wildcards in the arguments.
7658 // Temporarily add '(' and ')' to 'isfname'. These are valid
7659 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00007660 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01007661 // Also, unset wildignore to not be influenced by this option.
7662 // The arguments specified in command-line should be kept even if
7663 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00007664 // Use :legacy so that it also works when in Vim9 script.
7665 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
7666 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007667 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00007668 do_cmdline_cmd(
7669 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
7670 do_cmdline_cmd(
7671 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007672 }
7673
Bram Moolenaar0f873732019-12-05 20:28:46 +01007674 // If wildcard expansion failed, we are editing the first file of the
7675 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007676 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7677 {
7678 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00007679 if (GARGCOUNT == 1 && used_file_full_path
7680 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
7681 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007682 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007683
7684 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007685}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007686
7687 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007688mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007689{
7690 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007691 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007692
Bram Moolenaar964b3742019-05-24 18:54:09 +02007693 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007694 if (envbuf == NULL)
7695 return -1;
7696
7697 sprintf((char *)envbuf, "%s=%s", var, value);
7698
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007699 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007700
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007701 vim_free(envbuf);
7702 if (p == NULL)
7703 return -1;
7704 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007705#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007706 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007707#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007708 // Unlike Un*x systems, we can free the string for _wputenv().
7709 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007710
7711 return 0;
7712}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007713
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007714/*
7715 * Support for 256 colors and 24-bit colors was added in Windows 10
7716 * version 1703 (Creators update).
7717 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007718#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7719
7720/*
7721 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02007722 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007723 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007724#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007725
7726/*
7727 * ConPTY differences between versions, need different logic.
7728 * version 1903 (May 2019 update).
7729 */
7730#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
7731
7732/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007733 * version 1909 (November 2019 update).
7734 */
7735#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
7736
7737/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007738 * Stay ahead of the next update, and when it's done, fix this.
7739 * version ? (2020 update, temporarily use the build number of insider preview)
7740 */
7741#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
7742
7743/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02007744 * Confirm until this version. Also the logic changes.
7745 * insider preview.
7746 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02007747#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007748
7749/*
7750 * Not stable now.
7751 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007752#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007753
7754 static void
7755vtp_flag_init(void)
7756{
7757 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007758#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007759 DWORD mode;
7760 HANDLE out;
7761
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007762# ifdef VIMDLL
7763 if (!gui.in_use)
7764# endif
7765 {
7766 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007767
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007768 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7769 GetConsoleMode(out, &mode);
7770 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7771 if (SetConsoleMode(out, mode) == 0)
7772 vtp_working = 0;
7773 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007774#endif
7775
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007776 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007777 conpty_working = 1;
7778 if (ver >= CONPTY_STABLE_BUILD)
7779 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007780
Bram Moolenaar57da6982019-09-13 22:30:11 +02007781 if (ver <= CONPTY_INSIDER_BUILD)
7782 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007783 if (ver <= CONPTY_1909_BUILD)
7784 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02007785 if (ver <= CONPTY_1903_BUILD)
7786 conpty_type = 2;
7787 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
7788 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007789
7790 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
7791 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007792}
7793
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007794#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007795
7796 static void
7797vtp_init(void)
7798{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007799 HMODULE hKerneldll;
7800 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007801# ifdef FEAT_TERMGUICOLORS
7802 COLORREF fg, bg;
7803# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007804
Bram Moolenaar0f873732019-12-05 20:28:46 +01007805 // Use functions supported from Vista
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007806 hKerneldll = GetModuleHandle("kernel32.dll");
7807 if (hKerneldll != NULL)
7808 {
7809 pGetConsoleScreenBufferInfoEx =
7810 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7811 hKerneldll, "GetConsoleScreenBufferInfoEx");
7812 pSetConsoleScreenBufferInfoEx =
7813 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7814 hKerneldll, "SetConsoleScreenBufferInfoEx");
7815 if (pGetConsoleScreenBufferInfoEx != NULL
7816 && pSetConsoleScreenBufferInfoEx != NULL)
7817 has_csbiex = TRUE;
7818 }
7819
7820 csbi.cbSize = sizeof(csbi);
7821 if (has_csbiex)
7822 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007823 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7824 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
Bram Moolenaardf543822020-01-30 11:53:59 +01007825 store_console_bg_rgb = save_console_bg_rgb;
7826 store_console_fg_rgb = save_console_fg_rgb;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007827
7828# ifdef FEAT_TERMGUICOLORS
7829 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7830 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7831 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7832 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7833 default_console_color_bg = bg;
7834 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007835# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007836
7837 set_console_color_rgb();
7838}
7839
7840 static void
7841vtp_exit(void)
7842{
Bram Moolenaardf543822020-01-30 11:53:59 +01007843 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007844}
7845
Bram Moolenaar06b7b582020-05-30 17:49:25 +02007846 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007847vtp_printf(
7848 char *format,
7849 ...)
7850{
7851 char_u buf[100];
7852 va_list list;
7853 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007854 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007855
7856 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007857 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007858 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007859 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007860 return (int)result;
7861}
7862
7863 static void
7864vtp_sgr_bulk(
7865 int arg)
7866{
7867 int args[1];
7868
7869 args[0] = arg;
7870 vtp_sgr_bulks(1, args);
7871}
7872
K.Takata6e1d31e2022-02-03 13:05:32 +00007873# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007874 if ((*p-- = "0123456789"[(n = x % 10)]) \
7875 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
7876 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
7877
K.Takata6e1d31e2022-02-03 13:05:32 +00007878# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007879 case x: \
7880 FAST256(newargs[x - 1]);
7881
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007882 static void
7883vtp_sgr_bulks(
7884 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007885 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007886{
K.Takata6e1d31e2022-02-03 13:05:32 +00007887# define MAXSGR 16
7888# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007889 char_u buf[SGRBUFSIZE];
7890 char_u *p;
7891 int in, out;
7892 int newargs[16];
7893 static int sgrfgr = -1, sgrfgg, sgrfgb;
7894 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007895
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007896 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007897 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007898 sgrfgr = sgrbgr = -1;
7899 vtp_printf("033[m");
7900 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007901 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007902
7903 in = out = 0;
7904 while (in < argc)
7905 {
7906 int s = args[in];
7907 int copylen = 1;
7908
7909 if (s == 38)
7910 {
7911 if (argc - in >= 5 && args[in + 1] == 2)
7912 {
7913 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
7914 && sgrfgb == args[in + 4])
7915 {
7916 in += 5;
7917 copylen = 0;
7918 }
7919 else
7920 {
7921 sgrfgr = args[in + 2];
7922 sgrfgg = args[in + 3];
7923 sgrfgb = args[in + 4];
7924 copylen = 5;
7925 }
7926 }
7927 else if (argc - in >= 3 && args[in + 1] == 5)
7928 {
7929 sgrfgr = -1;
7930 copylen = 3;
7931 }
7932 }
7933 else if (s == 48)
7934 {
7935 if (argc - in >= 5 && args[in + 1] == 2)
7936 {
7937 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
7938 && sgrbgb == args[in + 4])
7939 {
7940 in += 5;
7941 copylen = 0;
7942 }
7943 else
7944 {
7945 sgrbgr = args[in + 2];
7946 sgrbgg = args[in + 3];
7947 sgrbgb = args[in + 4];
7948 copylen = 5;
7949 }
7950 }
7951 else if (argc - in >= 3 && args[in + 1] == 5)
7952 {
7953 sgrbgr = -1;
7954 copylen = 3;
7955 }
7956 }
7957 else if (30 <= s && s <= 39)
7958 sgrfgr = -1;
7959 else if (90 <= s && s <= 97)
7960 sgrfgr = -1;
7961 else if (40 <= s && s <= 49)
7962 sgrbgr = -1;
7963 else if (100 <= s && s <= 107)
7964 sgrbgr = -1;
7965 else if (s == 0)
7966 sgrfgr = sgrbgr = -1;
7967
7968 while (copylen--)
7969 newargs[out++] = args[in++];
7970 }
7971
7972 p = &buf[sizeof(buf) - 1];
7973 *p-- = 'm';
7974
7975 switch (out)
7976 {
7977 int n, m;
7978 DWORD r;
7979
7980 FAST256CASE(16);
7981 *p-- = ';';
7982 FAST256CASE(15);
7983 *p-- = ';';
7984 FAST256CASE(14);
7985 *p-- = ';';
7986 FAST256CASE(13);
7987 *p-- = ';';
7988 FAST256CASE(12);
7989 *p-- = ';';
7990 FAST256CASE(11);
7991 *p-- = ';';
7992 FAST256CASE(10);
7993 *p-- = ';';
7994 FAST256CASE(9);
7995 *p-- = ';';
7996 FAST256CASE(8);
7997 *p-- = ';';
7998 FAST256CASE(7);
7999 *p-- = ';';
8000 FAST256CASE(6);
8001 *p-- = ';';
8002 FAST256CASE(5);
8003 *p-- = ';';
8004 FAST256CASE(4);
8005 *p-- = ';';
8006 FAST256CASE(3);
8007 *p-- = ';';
8008 FAST256CASE(2);
8009 *p-- = ';';
8010 FAST256CASE(1);
8011 *p-- = '[';
8012 *p = '\033';
8013 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8014 default:
8015 break;
8016 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008017}
8018
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008019 static void
8020wt_init(void)
8021{
8022 wt_working = (mch_getenv("WT_SESSION") != NULL);
8023}
8024
8025 int
8026use_wt(void)
8027{
8028 return USE_WT;
8029}
8030
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008031# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008032 static int
8033ctermtoxterm(
8034 int cterm)
8035{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008036 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008037
8038 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8039 return (((int)r << 16) | ((int)g << 8) | (int)b);
8040}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008041# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008042
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008043 static void
8044set_console_color_rgb(void)
8045{
8046# ifdef FEAT_TERMGUICOLORS
8047 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008048 guicolor_T fg, bg;
8049 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008050
8051 if (!USE_VTP)
8052 return;
8053
Bram Moolenaara050b942019-12-02 21:35:31 +01008054 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8055
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008056 if (USE_WT)
8057 {
8058 term_fg_rgb_color(fg);
8059 term_bg_rgb_color(bg);
8060 return;
8061 }
8062
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008063 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8064 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8065
8066 csbi.cbSize = sizeof(csbi);
8067 if (has_csbiex)
8068 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8069
8070 csbi.cbSize = sizeof(csbi);
8071 csbi.srWindow.Right += 1;
8072 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008073 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8074 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008075 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8076 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008077 if (has_csbiex)
8078 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8079# endif
8080}
8081
Bram Moolenaara050b942019-12-02 21:35:31 +01008082# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8083 void
8084get_default_console_color(
8085 int *cterm_fg,
8086 int *cterm_bg,
8087 guicolor_T *gui_fg,
8088 guicolor_T *gui_bg)
8089{
8090 int id;
8091 guicolor_T guifg = INVALCOLOR;
8092 guicolor_T guibg = INVALCOLOR;
8093 int ctermfg = 0;
8094 int ctermbg = 0;
8095
8096 id = syn_name2id((char_u *)"Normal");
8097 if (id > 0 && p_tgc)
8098 syn_id2colors(id, &guifg, &guibg);
8099 if (guifg == INVALCOLOR)
8100 {
8101 ctermfg = -1;
8102 if (id > 0)
8103 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8104 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
8105 : default_console_color_fg;
8106 cterm_normal_fg_gui_color = guifg;
8107 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8108 }
8109 if (guibg == INVALCOLOR)
8110 {
8111 ctermbg = -1;
8112 if (id > 0)
8113 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8114 guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8115 : default_console_color_bg;
8116 cterm_normal_bg_gui_color = guibg;
8117 ctermbg = ctermbg < 0 ? 0 : ctermbg;
8118 }
8119
8120 *cterm_fg = ctermfg;
8121 *cterm_bg = ctermbg;
8122 *gui_fg = guifg;
8123 *gui_bg = guibg;
8124}
8125# endif
8126
Bram Moolenaardf543822020-01-30 11:53:59 +01008127/*
8128 * Set the console colors to the original colors or the last set colors.
8129 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008130 static void
8131reset_console_color_rgb(void)
8132{
8133# ifdef FEAT_TERMGUICOLORS
8134 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8135
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008136 if (USE_WT)
8137 return;
8138
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008139 csbi.cbSize = sizeof(csbi);
8140 if (has_csbiex)
8141 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8142
8143 csbi.cbSize = sizeof(csbi);
8144 csbi.srWindow.Right += 1;
8145 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008146 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8147 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
8148 if (has_csbiex)
8149 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8150# endif
8151}
8152
8153/*
8154 * Set the console colors to the original colors.
8155 */
8156 static void
8157restore_console_color_rgb(void)
8158{
8159# ifdef FEAT_TERMGUICOLORS
8160 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8161
8162 csbi.cbSize = sizeof(csbi);
8163 if (has_csbiex)
8164 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8165
8166 csbi.cbSize = sizeof(csbi);
8167 csbi.srWindow.Right += 1;
8168 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008169 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8170 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008171 if (has_csbiex)
8172 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8173# endif
8174}
8175
8176 void
8177control_console_color_rgb(void)
8178{
8179 if (USE_VTP)
8180 set_console_color_rgb();
8181 else
8182 reset_console_color_rgb();
8183}
8184
8185 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008186use_vtp(void)
8187{
8188 return USE_VTP;
8189}
8190
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008191 int
8192is_term_win32(void)
8193{
8194 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8195}
8196
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008197 int
8198has_vtp_working(void)
8199{
8200 return vtp_working;
8201}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008202
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008203#endif
8204
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008205 int
8206has_conpty_working(void)
8207{
8208 return conpty_working;
8209}
8210
8211 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008212get_conpty_type(void)
8213{
8214 return conpty_type;
8215}
8216
8217 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008218is_conpty_stable(void)
8219{
8220 return conpty_stable;
8221}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008222
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008223 int
8224get_conpty_fix_type(void)
8225{
8226 return conpty_fix_type;
8227}
8228
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008229#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008230 void
8231resize_console_buf(void)
8232{
8233 CONSOLE_SCREEN_BUFFER_INFO csbi;
8234 COORD coord;
8235 SMALL_RECT newsize;
8236
8237 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8238 {
8239 coord.X = SRWIDTH(csbi.srWindow);
8240 coord.Y = SRHEIGHT(csbi.srWindow);
8241 SetConsoleScreenBufferSize(g_hConOut, coord);
8242
8243 newsize.Left = 0;
8244 newsize.Top = 0;
8245 newsize.Right = coord.X - 1;
8246 newsize.Bottom = coord.Y - 1;
8247 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8248
8249 SetConsoleScreenBufferSize(g_hConOut, coord);
8250 }
8251}
8252#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008253
8254 char *
8255GetWin32Error(void)
8256{
8257 char *msg = NULL;
8258 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8259 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
8260 if (msg != NULL)
8261 {
8262 // remove trailing \r\n
8263 char *pcrlf = strstr(msg, "\r\n");
8264 if (pcrlf != NULL)
8265 *pcrlf = '\0';
8266 }
8267 return msg;
8268}