blob: 53107d5301fbb048e17ac89152d075f2bec400f4 [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
K.Takatad68b2fc2022-02-12 11:18:37 +0000523vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200524{
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 Moolenaar63ff72a2022-02-07 13:54:01 +0000575#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
576 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100577/*
578 * Get related information about 'funcname' which is imported by 'hInst'.
579 * If 'info' is 0, return the function address.
580 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000581 * If 'info' is 2, hook the function with 'ptr', and return the original
582 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100583 */
584 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000585get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
586 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100587{
588 PBYTE pImage = (PBYTE)hInst;
589 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
590 PIMAGE_NT_HEADERS pPE;
591 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100592 PIMAGE_THUNK_DATA pIAT; // Import Address Table
593 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100594 PIMAGE_IMPORT_BY_NAME pImpName;
595
596 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
597 return NULL;
598 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
599 if (pPE->Signature != IMAGE_NT_SIGNATURE)
600 return NULL;
601 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
602 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
603 .VirtualAddress);
604 for (; pImpDesc->FirstThunk; ++pImpDesc)
605 {
606 if (!pImpDesc->OriginalFirstThunk)
607 continue;
608 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
609 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
610 for (; pIAT->u1.Function; ++pIAT, ++pINT)
611 {
612 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
613 continue;
614 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
615 + (UINT_PTR)(pINT->u1.AddressOfData));
616 if (strcmp((char *)pImpName->Name, funcname) == 0)
617 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000618 void *original;
619 DWORD old, new = PAGE_READWRITE;
620
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100621 switch (info)
622 {
623 case 0:
624 return (void *)pIAT->u1.Function;
625 case 1:
626 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000627 case 2:
628 original = (void *)pIAT->u1.Function;
629 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
630 new, &old);
631 pIAT->u1.Function = (UINT_PTR)ptr;
632 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
633 old, &new);
634 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100635 default:
636 return NULL;
637 }
638 }
639 }
640 }
641 return NULL;
642}
643
644/*
645 * Get the module handle which 'funcname' in 'hInst' is imported from.
646 */
647 HINSTANCE
648find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
649{
650 char *modulename;
651
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000652 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100653 if (modulename != NULL)
654 return GetModuleHandleA(modulename);
655 return NULL;
656}
657
658/*
659 * Get the address of 'funcname' which is imported by 'hInst' DLL.
660 */
661 void *
662get_dll_import_func(HINSTANCE hInst, const char *funcname)
663{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000664 return get_imported_func_info(hInst, funcname, 0, NULL);
665}
666
667/*
668 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
669 * and return the original function address.
670 */
671 void *
672hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
673{
674 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100675}
676#endif
677
Bram Moolenaar071d4272004-06-13 20:20:40 +0000678#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
679# ifndef GETTEXT_DLL
680# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200681# define GETTEXT_DLL_ALT1 "libintl-8.dll"
682# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000683# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100684// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000685static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200686static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000687static char *null_libintl_textdomain(const char *);
688static char *null_libintl_bindtextdomain(const char *, const char *);
689static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100690static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000691
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200692static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000693char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200694char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
695 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000696char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
697char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000698 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000699char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
700 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100701int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000702
703 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100704dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000705{
706 int i;
707 static struct
708 {
709 char *name;
710 FARPROC *ptr;
711 } libintl_entry[] =
712 {
713 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200714 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000715 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
716 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
717 {NULL, NULL}
718 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100719 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000720
Bram Moolenaar7554c542018-10-06 15:03:15 +0200721 // No need to initialize twice.
722 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000723 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200724 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100725 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100726# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100727 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200728 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100729# endif
730# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200731 if (!hLibintlDLL)
732 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100733# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100734 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000735 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200736 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000737 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200738 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000739 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200740 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000741 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200742 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000743 }
744 for (i = 0; libintl_entry[i].name != NULL
745 && libintl_entry[i].ptr != NULL; ++i)
746 {
K.Takata54119102022-02-03 13:33:03 +0000747 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000748 libintl_entry[i].name)) == NULL)
749 {
750 dyn_libintl_end();
751 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000752 {
753 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000754 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000755 verbose_leave();
756 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000757 return 0;
758 }
759 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000760
Bram Moolenaar0f873732019-12-05 20:28:46 +0100761 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000762 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000763 "bind_textdomain_codeset");
764 if (dyn_libintl_bind_textdomain_codeset == NULL)
765 dyn_libintl_bind_textdomain_codeset =
766 null_libintl_bind_textdomain_codeset;
767
Bram Moolenaar0f873732019-12-05 20:28:46 +0100768 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100769 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
770 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100771 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100772 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
773 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100774
Bram Moolenaar071d4272004-06-13 20:20:40 +0000775 return 1;
776}
777
778 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100779dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000780{
781 if (hLibintlDLL)
782 FreeLibrary(hLibintlDLL);
783 hLibintlDLL = NULL;
784 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200785 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000786 dyn_libintl_textdomain = null_libintl_textdomain;
787 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000788 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100789 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000790}
791
792 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000793null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000794{
795 return (char*)msgid;
796}
797
798 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200799null_libintl_ngettext(
800 const char *msgid,
801 const char *msgid_plural,
802 unsigned long n)
803{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200804 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200805}
806
Bram Moolenaaree695f72016-08-03 22:08:45 +0200807 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100808null_libintl_bindtextdomain(
809 const char *domainname UNUSED,
810 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000811{
812 return NULL;
813}
814
815 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100816null_libintl_bind_textdomain_codeset(
817 const char *domainname UNUSED,
818 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000819{
820 return NULL;
821}
822
823 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100824null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000825{
826 return NULL;
827}
828
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200829 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100830null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100831{
832 return 0;
833}
834
Bram Moolenaar0f873732019-12-05 20:28:46 +0100835#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000836
Bram Moolenaar0f873732019-12-05 20:28:46 +0100837// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000838
839#ifndef VER_PLATFORM_WIN32_WINDOWS
840# define VER_PLATFORM_WIN32_WINDOWS 1
841#endif
842
Bram Moolenaar071d4272004-06-13 20:20:40 +0000843#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100844# ifndef PROTO
845# include <aclapi.h>
846# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200847# ifndef PROTECTED_DACL_SECURITY_INFORMATION
848# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
849# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000850#endif
851
Bram Moolenaar27515922013-06-29 15:36:26 +0200852#ifdef HAVE_ACL
853/*
854 * Enables or disables the specified privilege.
855 */
856 static BOOL
857win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
858{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100859 BOOL bResult;
860 LUID luid;
861 HANDLE hToken;
862 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200863
864 if (!OpenProcessToken(GetCurrentProcess(),
865 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
866 return FALSE;
867
868 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
869 {
870 CloseHandle(hToken);
871 return FALSE;
872 }
873
Bram Moolenaar45500912014-07-09 20:51:07 +0200874 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200875 tokenPrivileges.Privileges[0].Luid = luid;
876 tokenPrivileges.Privileges[0].Attributes = bEnable ?
877 SE_PRIVILEGE_ENABLED : 0;
878
879 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
880 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
881
882 CloseHandle(hToken);
883
884 return bResult && GetLastError() == ERROR_SUCCESS;
885}
886#endif
887
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100888#ifdef _MSC_VER
889// Suppress the deprecation warning for using GetVersionEx().
890// It is needed for implementing "windowsversion()".
891# pragma warning(push)
892# pragma warning(disable: 4996)
893#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000894/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200895 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000896 */
897 void
898PlatformId(void)
899{
900 static int done = FALSE;
901
902 if (!done)
903 {
904 OSVERSIONINFO ovi;
905
906 ovi.dwOSVersionInfoSize = sizeof(ovi);
907 GetVersionEx(&ovi);
908
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200909#ifdef FEAT_EVAL
Bram Moolenaar0c1e3742019-12-27 13:49:24 +0100910 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
911 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200912#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100913 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
914 || ovi.dwMajorVersion > 6)
915 win8_or_later = TRUE;
916
Bram Moolenaar071d4272004-06-13 20:20:40 +0000917#ifdef HAVE_ACL
Bram Moolenaar0f873732019-12-05 20:28:46 +0100918 // Enable privilege for getting or setting SACLs.
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200919 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000920#endif
921 done = TRUE;
922 }
923}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100924#ifdef _MSC_VER
925# pragma warning(pop)
926#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000927
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200928#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000929
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100930# define SHIFT (SHIFT_PRESSED)
931# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
932# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
933# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000934
935
Bram Moolenaar0f873732019-12-05 20:28:46 +0100936// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
937// We map function keys to their ANSI terminal equivalents, as produced
938// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
939// ANSI key with a value >= '\300' is nonstandard, but provided anyway
940// so that the user can have access to all SHIFT-, CTRL-, and ALT-
941// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000942
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000943static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000944{
945 WORD wVirtKey;
946 BOOL fAnsiKey;
947 int chAlone;
948 int chShift;
949 int chCtrl;
950 int chAlt;
951} VirtKeyMap[] =
952{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200953// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000954 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
955
956 { VK_F1, TRUE, ';', 'T', '^', 'h', },
957 { VK_F2, TRUE, '<', 'U', '_', 'i', },
958 { VK_F3, TRUE, '=', 'V', '`', 'j', },
959 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
960 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
961 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
962 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
963 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
964 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
965 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200966 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
967 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000968
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200969 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
970 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
971 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
972 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
973 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
974 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
975 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
976 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
977 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
978 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100979 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000980
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200981 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000982
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100983# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200984 // Most people don't have F13-F20, but what the hell...
985 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
986 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
987 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
988 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
989 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
990 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
991 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
992 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100993# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200994 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
995 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
996 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
997 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000998
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200999 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
1000 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
1001 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
1002 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
1003 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
1004 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
1005 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
1006 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
1007 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
1008 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001009 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001010};
1011
1012
Bram Moolenaar0f873732019-12-05 20:28:46 +01001013/*
1014 * The return code indicates key code size.
1015 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001016 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001017win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001018 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001019{
1020 UINT uMods = pker->dwControlKeyState;
1021 static int s_iIsDead = 0;
1022 static WORD awAnsiCode[2];
1023 static BYTE abKeystate[256];
1024
1025
1026 if (s_iIsDead == 2)
1027 {
K.Takata972db232022-02-04 10:45:38 +00001028 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001029 s_iIsDead = 0;
1030 return 1;
1031 }
1032
K.Takata972db232022-02-04 10:45:38 +00001033 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001034 return 1;
1035
Bram Moolenaara80faa82020-04-12 19:37:17 +02001036 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001037
Bram Moolenaar0f873732019-12-05 20:28:46 +01001038 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001039 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001040
1041 if (uMods & SHIFT_PRESSED)
1042 abKeystate[VK_SHIFT] = 0x80;
1043 if (uMods & CAPSLOCK_ON)
1044 abKeystate[VK_CAPITAL] = 1;
1045
1046 if ((uMods & ALT_GR) == ALT_GR)
1047 {
1048 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1049 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1050 }
1051
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001052 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1053 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001054
1055 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001056 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001057
1058 return s_iIsDead;
1059}
1060
Bram Moolenaar071d4272004-06-13 20:20:40 +00001061static BOOL g_fJustGotFocus = FALSE;
1062
1063/*
1064 * Decode a KEY_EVENT into one or two keystrokes
1065 */
1066 static BOOL
1067decode_key_event(
1068 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001069 WCHAR *pch,
1070 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001071 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001072 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001073{
1074 int i;
1075 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1076
1077 *pch = *pch2 = NUL;
1078 g_fJustGotFocus = FALSE;
1079
Bram Moolenaar0f873732019-12-05 20:28:46 +01001080 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001081 if (!pker->bKeyDown)
1082 return FALSE;
1083
Bram Moolenaar0f873732019-12-05 20:28:46 +01001084 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001085 switch (pker->wVirtualKeyCode)
1086 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001087 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001088 case VK_SHIFT:
1089 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001090 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001091 return FALSE;
1092
1093 default:
1094 break;
1095 }
1096
Bram Moolenaar0f873732019-12-05 20:28:46 +01001097 // special cases
K.Takata972db232022-02-04 10:45:38 +00001098 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0
1099 && pker->uChar.UnicodeChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001100 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001101 // Ctrl-6 is Ctrl-^
Bram Moolenaar071d4272004-06-13 20:20:40 +00001102 if (pker->wVirtualKeyCode == '6')
1103 {
1104 *pch = Ctrl_HAT;
1105 return TRUE;
1106 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001107 // Ctrl-2 is Ctrl-@
Bram Moolenaar071d4272004-06-13 20:20:40 +00001108 else if (pker->wVirtualKeyCode == '2')
1109 {
1110 *pch = NUL;
1111 return TRUE;
1112 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001113 // Ctrl-- is Ctrl-_
Bram Moolenaar071d4272004-06-13 20:20:40 +00001114 else if (pker->wVirtualKeyCode == 0xBD)
1115 {
1116 *pch = Ctrl__;
1117 return TRUE;
1118 }
1119 }
1120
Bram Moolenaar0f873732019-12-05 20:28:46 +01001121 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001122 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1123 {
1124 *pch = K_NUL;
1125 *pch2 = '\017';
1126 return TRUE;
1127 }
1128
K.Takataeeec2542021-06-02 13:28:16 +02001129 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001130 {
1131 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1132 {
1133 if (nModifs == 0)
1134 *pch = VirtKeyMap[i].chAlone;
1135 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1136 *pch = VirtKeyMap[i].chShift;
1137 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1138 *pch = VirtKeyMap[i].chCtrl;
1139 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1140 *pch = VirtKeyMap[i].chAlt;
1141
1142 if (*pch != 0)
1143 {
1144 if (VirtKeyMap[i].fAnsiKey)
1145 {
1146 *pch2 = *pch;
1147 *pch = K_NUL;
1148 }
1149
1150 return TRUE;
1151 }
1152 }
1153 }
1154
1155 i = win32_kbd_patch_key(pker);
1156
1157 if (i < 0)
1158 *pch = NUL;
1159 else
1160 {
K.Takata972db232022-02-04 10:45:38 +00001161 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001162
1163 if (pmodifiers != NULL)
1164 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001165 // Pass on the ALT key as a modifier, but only when not combined
1166 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001167 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1168 *pmodifiers |= MOD_MASK_ALT;
1169
Bram Moolenaar0f873732019-12-05 20:28:46 +01001170 // Pass on SHIFT only for special keys, because we don't know when
1171 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001172 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1173 *pmodifiers |= MOD_MASK_SHIFT;
1174
Bram Moolenaar0f873732019-12-05 20:28:46 +01001175 // Pass on CTRL only for non-special keys, because we don't know
1176 // when it's already included with the character. And not when
1177 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001178 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1179 && *pch >= 0x20 && *pch < 0x80)
1180 *pmodifiers |= MOD_MASK_CTRL;
1181 }
1182 }
1183
1184 return (*pch != NUL);
1185}
1186
Bram Moolenaar0f873732019-12-05 20:28:46 +01001187#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001188
1189
Bram Moolenaar071d4272004-06-13 20:20:40 +00001190/*
1191 * For the GUI the mouse handling is in gui_w32.c.
1192 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001193#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001194 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001195mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001196{
1197}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001198#else
Bram Moolenaar0f873732019-12-05 20:28:46 +01001199static int g_fMouseAvail = FALSE; // mouse present
1200static int g_fMouseActive = FALSE; // mouse enabled
1201static int g_nMouseClick = -1; // mouse status
1202static int g_xMouse; // mouse x coordinate
1203static int g_yMouse; // mouse y coordinate
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001204static DWORD g_cmodein = 0; // Original console input mode
1205static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001206
1207/*
1208 * Enable or disable mouse input
1209 */
1210 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001211mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001212{
1213 DWORD cmodein;
1214
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001215# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001216 if (gui.in_use)
1217 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001218# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001219 if (!g_fMouseAvail)
1220 return;
1221
1222 g_fMouseActive = on;
1223 GetConsoleMode(g_hConIn, &cmodein);
1224
1225 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001226 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001227 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001228 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1229 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001230 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001231 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001232 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001233 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1234 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001235
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001236 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001237}
1238
Bram Moolenaar157d8132018-03-06 17:09:20 +01001239
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001240# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001241/*
1242 * Called when 'balloonevalterm' changed.
1243 */
1244 void
1245mch_bevalterm_changed(void)
1246{
1247 mch_setmouse(g_fMouseActive);
1248}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001249# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001250
Bram Moolenaar071d4272004-06-13 20:20:40 +00001251/*
1252 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1253 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1254 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1255 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1256 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1257 * and we return the mouse position in g_xMouse and g_yMouse.
1258 *
1259 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1260 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1261 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1262 *
1263 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1264 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1265 *
1266 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1267 * moves, even if it stays within the same character cell. We ignore
1268 * all MOUSE_MOVED messages if the position hasn't really changed, and
1269 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1270 * we're only interested in MOUSE_DRAG).
1271 *
1272 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1273 * 2-button mouses by pressing the left & right buttons simultaneously.
1274 * In practice, it's almost impossible to click both at the same time,
1275 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1276 * in such cases, if the user is clicking quickly.
1277 */
1278 static BOOL
1279decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001280 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001281{
1282 static int s_nOldButton = -1;
1283 static int s_nOldMouseClick = -1;
1284 static int s_xOldMouse = -1;
1285 static int s_yOldMouse = -1;
1286 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001287# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001288 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001289# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001290 static int s_cClicks = 1;
1291 static BOOL s_fReleased = TRUE;
1292 static DWORD s_dwLastClickTime = 0;
1293 static BOOL s_fNextIsMiddle = FALSE;
1294
Bram Moolenaar0f873732019-12-05 20:28:46 +01001295 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001296
1297 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1298 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1299 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1300 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1301
1302 int nButton;
1303
1304 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1305 cButtons = 2;
1306
1307 if (!g_fMouseAvail || !g_fMouseActive)
1308 {
1309 g_nMouseClick = -1;
1310 return FALSE;
1311 }
1312
Bram Moolenaar0f873732019-12-05 20:28:46 +01001313 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001314 if (g_fJustGotFocus)
1315 {
1316 g_fJustGotFocus = FALSE;
1317 return FALSE;
1318 }
1319
Bram Moolenaar0f873732019-12-05 20:28:46 +01001320 // unprocessed mouse click?
Bram Moolenaar071d4272004-06-13 20:20:40 +00001321 if (g_nMouseClick != -1)
1322 return TRUE;
1323
1324 nButton = -1;
1325 g_xMouse = pmer->dwMousePosition.X;
1326 g_yMouse = pmer->dwMousePosition.Y;
1327
1328 if (pmer->dwEventFlags == MOUSE_MOVED)
1329 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001330 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1331 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001332 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1333 return FALSE;
1334 }
1335
Bram Moolenaar0f873732019-12-05 20:28:46 +01001336 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001337 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1338 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001339 nButton = MOUSE_RELEASE;
1340
Bram Moolenaar0f873732019-12-05 20:28:46 +01001341 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001342 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001343 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001344# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001345 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001346 if (p_bevalterm)
1347 nButton = MOUSE_DRAG;
1348 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001349# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001350 return FALSE;
1351 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001352
Bram Moolenaar071d4272004-06-13 20:20:40 +00001353 s_fReleased = TRUE;
1354 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001355 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001356 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001357 // on a 2-button mouse, hold down left and right buttons
1358 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001359
1360 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1361 {
1362 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1363
Bram Moolenaar0f873732019-12-05 20:28:46 +01001364 // if either left or right button only is pressed, see if the
1365 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001366 if (dwLR == LEFT || dwLR == RIGHT)
1367 {
1368 for (;;)
1369 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001370 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001371 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1372 != WAIT_OBJECT_0)
1373 break;
1374 else
1375 {
1376 DWORD cRecords = 0;
1377 INPUT_RECORD ir;
1378 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1379
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001380 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001381
1382 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1383 || !(pmer2->dwButtonState & LEFT_RIGHT))
1384 break;
1385 else
1386 {
1387 if (pmer2->dwEventFlags != MOUSE_MOVED)
1388 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001389 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001390
1391 return decode_mouse_event(pmer2);
1392 }
1393 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1394 s_yOldMouse == pmer2->dwMousePosition.Y)
1395 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001396 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001397 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001398
Bram Moolenaar0f873732019-12-05 20:28:46 +01001399 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001400 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001401
1402 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1403 break;
1404 }
1405 else
1406 break;
1407 }
1408 }
1409 }
1410 }
1411 }
1412
1413 if (s_fNextIsMiddle)
1414 {
1415 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1416 ? MOUSE_DRAG : MOUSE_MIDDLE;
1417 s_fNextIsMiddle = FALSE;
1418 }
1419 else if (cButtons == 2 &&
1420 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1421 {
1422 nButton = MOUSE_MIDDLE;
1423
1424 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1425 {
1426 s_fNextIsMiddle = TRUE;
1427 nButton = MOUSE_RELEASE;
1428 }
1429 }
1430 else if ((pmer->dwButtonState & LEFT) == LEFT)
1431 nButton = MOUSE_LEFT;
1432 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1433 nButton = MOUSE_MIDDLE;
1434 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1435 nButton = MOUSE_RIGHT;
1436
1437 if (! s_fReleased && ! s_fNextIsMiddle
1438 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1439 return FALSE;
1440
1441 s_fReleased = s_fNextIsMiddle;
1442 }
1443
1444 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1445 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001446 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001447 if (nButton != -1 && nButton != MOUSE_RELEASE)
1448 {
1449 DWORD dwCurrentTime = GetTickCount();
1450
1451 if (s_xOldMouse != g_xMouse
1452 || s_yOldMouse != g_yMouse
1453 || s_nOldButton != nButton
1454 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001455# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001456 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001457# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001458 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1459 {
1460 s_cClicks = 1;
1461 }
1462 else if (++s_cClicks > 4)
1463 {
1464 s_cClicks = 1;
1465 }
1466
1467 s_dwLastClickTime = dwCurrentTime;
1468 }
1469 }
1470 else if (pmer->dwEventFlags == MOUSE_MOVED)
1471 {
1472 if (nButton != -1 && nButton != MOUSE_RELEASE)
1473 nButton = MOUSE_DRAG;
1474
1475 s_cClicks = 1;
1476 }
1477
1478 if (nButton == -1)
1479 return FALSE;
1480
1481 if (nButton != MOUSE_RELEASE)
1482 s_nOldButton = nButton;
1483
1484 g_nMouseClick = nButton;
1485
1486 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1487 g_nMouseClick |= MOUSE_SHIFT;
1488 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1489 g_nMouseClick |= MOUSE_CTRL;
1490 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1491 g_nMouseClick |= MOUSE_ALT;
1492
1493 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1494 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1495
Bram Moolenaar0f873732019-12-05 20:28:46 +01001496 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001497 if (s_xOldMouse == g_xMouse
1498 && s_yOldMouse == g_yMouse
1499 && s_nOldMouseClick == g_nMouseClick)
1500 {
1501 g_nMouseClick = -1;
1502 return FALSE;
1503 }
1504
1505 s_xOldMouse = g_xMouse;
1506 s_yOldMouse = g_yMouse;
1507 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001508# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001509 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001510# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001511 s_nOldMouseClick = g_nMouseClick;
1512
1513 return TRUE;
1514}
1515
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001516#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001517
1518
1519#ifdef MCH_CURSOR_SHAPE
1520/*
1521 * Set the shape of the cursor.
1522 * 'thickness' can be from 1 (thin) to 99 (block)
1523 */
1524 static void
1525mch_set_cursor_shape(int thickness)
1526{
1527 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1528 ConsoleCursorInfo.dwSize = thickness;
1529 ConsoleCursorInfo.bVisible = s_cursor_visible;
1530
1531 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1532 if (s_cursor_visible)
1533 SetConsoleCursorPosition(g_hConOut, g_coord);
1534}
1535
1536 void
1537mch_update_cursor(void)
1538{
1539 int idx;
1540 int thickness;
1541
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001542# ifdef VIMDLL
1543 if (gui.in_use)
1544 return;
1545# endif
1546
Bram Moolenaar071d4272004-06-13 20:20:40 +00001547 /*
1548 * How the cursor is drawn depends on the current mode.
1549 */
1550 idx = get_shape_idx(FALSE);
1551
1552 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001553 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00001554 else
1555 thickness = shape_table[idx].percentage;
1556 mch_set_cursor_shape(thickness);
1557}
1558#endif
1559
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001560#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001561/*
1562 * Handle FOCUS_EVENT.
1563 */
1564 static void
1565handle_focus_event(INPUT_RECORD ir)
1566{
1567 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1568 ui_focus_change((int)g_fJustGotFocus);
1569}
1570
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001571static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1572
Bram Moolenaar071d4272004-06-13 20:20:40 +00001573/*
1574 * Wait until console input from keyboard or mouse is available,
1575 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001576 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001577 * Return TRUE if something is available FALSE if not.
1578 */
1579 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001580WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001581{
1582 DWORD dwNow = 0, dwEndTime = 0;
1583 INPUT_RECORD ir;
1584 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001585 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001586# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001587 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001588# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001589
1590 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001591 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001592 dwEndTime = GetTickCount() + msec;
1593 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001594 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001595 dwEndTime = INFINITE;
1596
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001597 // We need to loop until the end of the time period, because
1598 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001599 for (;;)
1600 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001601 // Only process messages when waiting.
1602 if (msec != 0)
1603 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001604# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001605 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001606# endif
1607# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001608 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001609# endif
1610# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001611 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001612# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001613 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001614
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001615 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001616# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001617 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001618# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001619 )
1620 return TRUE;
1621
1622 if (msec > 0)
1623 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001624 // If the specified wait time has passed, return. Beware that
1625 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001626 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001627 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001628 break;
1629 }
1630 if (msec != 0)
1631 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001632 DWORD dwWaitTime = dwEndTime - dwNow;
1633
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001634 // Don't wait for more than 11 msec to avoid dropping characters,
1635 // check channel while waiting for input and handle a callback from
1636 // 'balloonexpr'.
1637 if (dwWaitTime > 11)
1638 dwWaitTime = 11;
1639
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001640# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001641 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001642 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001643# endif
1644# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001645 // When waiting very briefly don't trigger timers.
1646 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001647 {
1648 long due_time;
1649
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001650 // Trigger timers and then get the time in msec until the next
1651 // one is due. Wait up to that time.
1652 due_time = check_due_timer();
1653 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001654 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001655 // timer may have used feedkeys().
1656 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001657 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001658 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1659 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001660 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001661# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001662 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001663# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001664 // Wait for either an event on the console input or a
1665 // message in the client-server window.
1666 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1667 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001668# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001669 wait_for_single_object(g_hConIn, dwWaitTime)
1670 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001671# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001672 )
1673 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001674 }
1675
1676 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001677 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001678
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001679# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02001680 // May have to redraw if the cursor ends up in the wrong place.
1681 // Only when not peeking.
1682 if (State & CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001683 {
1684 CONSOLE_SCREEN_BUFFER_INFO csbi;
1685
1686 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1687 {
1688 if (csbi.dwCursorPosition.Y != msg_row)
1689 {
matveyte08795e2021-05-07 15:00:17 +02001690 // The screen is now messed up, must redraw the command
1691 // line and later all the windows.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001692 redraw_all_later(CLEAR);
matveyte08795e2021-05-07 15:00:17 +02001693 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001694 redrawcmd();
1695 }
1696 }
1697 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001698# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001699
1700 if (cRecords > 0)
1701 {
1702 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1703 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001704# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01001705 // Windows IME sends two '\n's with only one 'ENTER'. First:
1706 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00001707 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001708 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1709 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001710 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001711 continue;
1712 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001713# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001714 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1715 NULL, FALSE))
1716 return TRUE;
1717 }
1718
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001719 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001720
1721 if (ir.EventType == FOCUS_EVENT)
1722 handle_focus_event(ir);
1723 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001724 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001725 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1726
Bram Moolenaar36698e32019-12-11 22:57:40 +01001727 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001728 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001729 if (dwSize.X != Columns || dwSize.Y != Rows)
1730 {
1731 CONSOLE_SCREEN_BUFFER_INFO csbi;
1732 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01001733 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001734 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01001735 if (dwSize.X != Columns || dwSize.Y != Rows)
1736 {
1737 ResizeConBuf(g_hConOut, dwSize);
1738 shell_resized();
1739 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001740 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001741 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001742 else if (ir.EventType == MOUSE_EVENT
1743 && decode_mouse_event(&ir.Event.MouseEvent))
1744 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001745 }
1746 else if (msec == 0)
1747 break;
1748 }
1749
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001750# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01001751 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001752 if (input_available())
1753 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001754# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001755
Bram Moolenaar071d4272004-06-13 20:20:40 +00001756 return FALSE;
1757}
1758
Bram Moolenaar071d4272004-06-13 20:20:40 +00001759/*
1760 * return non-zero if a character is available
1761 */
1762 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001763mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001764{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001765# ifdef VIMDLL
1766 if (gui.in_use)
1767 return TRUE;
1768# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001769 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001770}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001771
1772# if defined(FEAT_TERMINAL) || defined(PROTO)
1773/*
1774 * Check for any pending input or messages.
1775 */
1776 int
1777mch_check_messages(void)
1778{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001779# ifdef VIMDLL
1780 if (gui.in_use)
1781 return TRUE;
1782# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001783 return WaitForChar(0L, TRUE);
1784}
1785# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001786
1787/*
1788 * Create the console input. Used when reading stdin doesn't work.
1789 */
1790 static void
1791create_conin(void)
1792{
1793 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1794 FILE_SHARE_READ|FILE_SHARE_WRITE,
1795 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001796 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001797 did_create_conin = TRUE;
1798}
1799
1800/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001801 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001802 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001803 static WCHAR
1804tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001805{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001806 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001807
1808 for (;;)
1809 {
1810 INPUT_RECORD ir;
1811 DWORD cRecords = 0;
1812
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001813# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001814 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001815 if (input_available())
1816 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001817 if (g_nMouseClick != -1)
1818 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001819# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001820 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001821 {
1822 if (did_create_conin)
1823 read_error_exit();
1824 create_conin();
1825 continue;
1826 }
1827
1828 if (ir.EventType == KEY_EVENT)
1829 {
1830 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1831 pmodifiers, TRUE))
1832 return ch;
1833 }
1834 else if (ir.EventType == FOCUS_EVENT)
1835 handle_focus_event(ir);
1836 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1837 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001838 else if (ir.EventType == MOUSE_EVENT)
1839 {
1840 if (decode_mouse_event(&ir.Event.MouseEvent))
1841 return 0;
1842 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001843 }
1844}
Bram Moolenaar0f873732019-12-05 20:28:46 +01001845#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001846
1847
1848/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001849 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001850 * Get one or more characters from the keyboard or the mouse.
1851 * If time == 0, do not wait for characters.
1852 * If time == n, wait a short time for characters.
1853 * If time == -1, wait forever for characters.
1854 * Returns the number of characters read into buf.
1855 */
1856 int
1857mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001858 char_u *buf UNUSED,
1859 int maxlen UNUSED,
1860 long time UNUSED,
1861 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001862{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001863#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001864
1865 int len;
1866 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001867# ifdef VIMDLL
1868// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
1869# define TYPEAHEADSPACE 6
1870# else
1871# define TYPEAHEADSPACE 0
1872# endif
1873# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001874 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001875 static int typeaheadlen = 0;
1876
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001877# ifdef VIMDLL
1878 if (gui.in_use)
1879 return 0;
1880# endif
1881
Bram Moolenaar0f873732019-12-05 20:28:46 +01001882 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001883 if (typeaheadlen > 0)
1884 goto theend;
1885
Bram Moolenaar071d4272004-06-13 20:20:40 +00001886 if (time >= 0)
1887 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001888 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00001889 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001890 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001891 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00001892 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001893 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00001894
Bram Moolenaar3918c952005-03-15 22:34:55 +00001895 /*
1896 * If there is no character available within 2 seconds (default)
1897 * write the autoscript file to disk. Or cause the CursorHold event
1898 * to be triggered.
1899 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001900 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001901 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001902 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001903 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001904 buf[0] = K_SPECIAL;
1905 buf[1] = KS_EXTRA;
1906 buf[2] = (int)KE_CURSORHOLD;
1907 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001908 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001909 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001910 }
1911 }
1912
1913 /*
1914 * Try to read as many characters as there are, until the buffer is full.
1915 */
1916
Bram Moolenaar0f873732019-12-05 20:28:46 +01001917 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001918 g_fCBrkPressed = FALSE;
1919
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001920# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001921 if (fdDump)
1922 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001923# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001924
Bram Moolenaar0f873732019-12-05 20:28:46 +01001925 // Keep looping until there is something in the typeahead buffer and more
1926 // to get and still room in the buffer (up to two bytes for a char and
1927 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001928 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001929 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001930 {
1931 if (typebuf_changed(tb_change_cnt))
1932 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001933 // "buf" may be invalid now if a client put something in the
1934 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001935 typeaheadlen = 0;
1936 break;
1937 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001938 if (g_nMouseClick != -1)
1939 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001940# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001941 if (fdDump)
1942 fprintf(fdDump, "{%02x @ %d, %d}",
1943 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001944# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001945 typeahead[typeaheadlen++] = ESC + 128;
1946 typeahead[typeaheadlen++] = 'M';
1947 typeahead[typeaheadlen++] = g_nMouseClick;
1948 typeahead[typeaheadlen++] = g_xMouse + '!';
1949 typeahead[typeaheadlen++] = g_yMouse + '!';
1950 g_nMouseClick = -1;
1951 }
1952 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001953 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001954 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001955 int modifiers = 0;
1956
1957 c = tgetch(&modifiers, &ch2);
1958
1959 if (typebuf_changed(tb_change_cnt))
1960 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001961 // "buf" may be invalid now if a client put something in the
1962 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001963 typeaheadlen = 0;
1964 break;
1965 }
1966
1967 if (c == Ctrl_C && ctrl_c_interrupts)
1968 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001969# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001970 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001971# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001972 got_int = TRUE;
1973 }
1974
Bram Moolenaar071d4272004-06-13 20:20:40 +00001975 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001976 {
1977 int n = 1;
1978
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001979 if (ch2 == NUL)
1980 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001981 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001982 char_u *p;
1983 WCHAR ch[2];
1984
1985 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01001986 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001987 {
1988 ch[1] = tgetch(&modifiers, &ch2);
1989 n++;
1990 }
1991 p = utf16_to_enc(ch, &n);
1992 if (p != NULL)
1993 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001994 for (i = 0, j = 0; i < n; i++)
1995 {
1996 typeahead[typeaheadlen + j++] = p[i];
1997# ifdef VIMDLL
1998 if (p[i] == CSI)
1999 {
2000 typeahead[typeaheadlen + j++] = KS_EXTRA;
2001 typeahead[typeaheadlen + j++] = KE_CSI;
2002 }
2003# endif
2004 }
2005 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002006 vim_free(p);
2007 }
2008 }
2009 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002010 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002011 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002012# ifdef VIMDLL
2013 if (c == CSI)
2014 {
2015 typeahead[typeaheadlen + 1] = KS_EXTRA;
2016 typeahead[typeaheadlen + 2] = KE_CSI;
2017 n = 3;
2018 }
2019# endif
2020 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002021 if (ch2 != NUL)
2022 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002023 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002024 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002025 switch (ch2)
2026 {
2027 case (WCHAR)'\324': // SHIFT+Insert
2028 case (WCHAR)'\325': // CTRL+Insert
2029 case (WCHAR)'\327': // SHIFT+Delete
2030 case (WCHAR)'\330': // CTRL+Delete
2031 typeahead[typeaheadlen + n] = (char_u)ch2;
2032 n++;
2033 break;
2034
2035 default:
2036 typeahead[typeaheadlen + n] = 3;
2037 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2038 n += 2;
2039 break;
2040 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002041 }
2042 else
2043 {
2044 typeahead[typeaheadlen + n] = 3;
2045 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2046 n += 2;
2047 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002048 }
2049
Bram Moolenaar0f873732019-12-05 20:28:46 +01002050 // Use the ALT key to set the 8th bit of the character
2051 // when it's one byte, the 8th bit isn't set yet and not
2052 // using a double-byte encoding (would become a lead
2053 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002054 if ((modifiers & MOD_MASK_ALT)
2055 && n == 1
2056 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002058 )
2059 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002060 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2061 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002062 modifiers &= ~MOD_MASK_ALT;
2063 }
2064
2065 if (modifiers != 0)
2066 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002067 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002068 mch_memmove(typeahead + typeaheadlen + 3,
2069 typeahead + typeaheadlen, n);
2070 typeahead[typeaheadlen++] = K_SPECIAL;
2071 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2072 typeahead[typeaheadlen++] = modifiers;
2073 }
2074
2075 typeaheadlen += n;
2076
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002077# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002078 if (fdDump)
2079 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002080# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002081 }
2082 }
2083 }
2084
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002085# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002086 if (fdDump)
2087 {
2088 fputs("]\n", fdDump);
2089 fflush(fdDump);
2090 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002091# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002092
Bram Moolenaar071d4272004-06-13 20:20:40 +00002093theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002094 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002095 len = 0;
2096 while (len < maxlen && typeaheadlen > 0)
2097 {
2098 buf[len++] = typeahead[0];
2099 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2100 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002101# ifdef FEAT_JOB_CHANNEL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002102 if (len > 0)
2103 {
2104 buf[len] = NUL;
2105 ch_log(NULL, "raw key input: \"%s\"", buf);
2106 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002107# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002108 return len;
2109
Bram Moolenaar0f873732019-12-05 20:28:46 +01002110#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002111 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002112#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002113}
2114
Bram Moolenaar82881492012-11-20 16:53:39 +01002115#ifndef PROTO
2116# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002117# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002118# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002119#endif
2120
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002121/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002122 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002123 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2124 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002125 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002126 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002127 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002128executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002129{
Bram Moolenaar95da1362020-05-30 18:37:55 +02002130 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01002131 {
Bram Moolenaar95da1362020-05-30 18:37:55 +02002132 if (path != NULL)
2133 *path = FullName_save((char_u *)name, FALSE);
2134 return TRUE;
2135 }
2136 return FALSE;
2137}
2138
2139/*
2140 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2141 * If "use_path" is FALSE: Return TRUE if "name" exists.
2142 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2143 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2144 * the allocated memory.
2145 */
2146 static int
2147executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2148{
2149 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2150 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2151 // UTF-8.
2152 char_u buf[_MAX_PATH * 3];
2153 size_t len = STRLEN(name);
2154 size_t tmplen;
2155 char_u *p, *e, *e2;
2156 char_u *pathbuf = NULL;
2157 char_u *pathext = NULL;
2158 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002159 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002160 int noext = FALSE;
2161 int retval = FALSE;
2162
2163 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002164 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002165
2166 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002167 shname = gettail(p_sh);
2168 if (strstr((char *)shname, "sh") != NULL &&
2169 !(strstr((char *)shname, "powershell") != NULL
2170 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002171 noext = TRUE;
2172
2173 if (use_pathext)
2174 {
2175 pathext = mch_getenv("PATHEXT");
2176 if (pathext == NULL)
2177 pathext = (char_u *)".com;.exe;.bat;.cmd";
2178
2179 if (noext == FALSE)
2180 {
2181 /*
2182 * Loop over all extensions in $PATHEXT.
2183 * Check "name" ends with extension.
2184 */
2185 p = pathext;
2186 while (*p)
2187 {
2188 if (p[0] == ';'
2189 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2190 {
2191 // Skip empty or single ".".
2192 ++p;
2193 continue;
2194 }
2195 e = vim_strchr(p, ';');
2196 if (e == NULL)
2197 e = p + STRLEN(p);
2198 tmplen = e - p;
2199
2200 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2201 {
2202 noext = TRUE;
2203 break;
2204 }
2205
2206 p = e;
2207 }
2208 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002209 }
2210
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002211 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002212 if (pathext == NULL)
2213 pathext = (char_u *)".";
2214 else if (noext == TRUE)
2215 {
2216 if (pathextbuf == NULL)
2217 pathextbuf = alloc(STRLEN(pathext) + 3);
2218 if (pathextbuf == NULL)
2219 {
2220 retval = FALSE;
2221 goto theend;
2222 }
2223 STRCPY(pathextbuf, ".;");
2224 STRCAT(pathextbuf, pathext);
2225 pathext = pathextbuf;
2226 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002227
Bram Moolenaar95da1362020-05-30 18:37:55 +02002228 // Use $PATH when "use_path" is TRUE and "name" is basename.
2229 if (use_path && gettail((char_u *)name) == (char_u *)name)
2230 {
2231 p = mch_getenv("PATH");
2232 if (p != NULL)
2233 {
2234 pathbuf = alloc(STRLEN(p) + 3);
2235 if (pathbuf == NULL)
2236 {
2237 retval = FALSE;
2238 goto theend;
2239 }
2240 STRCPY(pathbuf, ".;");
2241 STRCAT(pathbuf, p);
2242 }
2243 }
2244
2245 /*
2246 * Walk through all entries in $PATH to check if "name" exists there and
2247 * is an executable file.
2248 */
2249 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2250 while (*p)
2251 {
2252 if (*p == ';') // Skip empty entry
2253 {
2254 ++p;
2255 continue;
2256 }
2257 e = vim_strchr(p, ';');
2258 if (e == NULL)
2259 e = p + STRLEN(p);
2260
2261 if (e - p + len + 2 > sizeof(buf))
2262 {
2263 retval = FALSE;
2264 goto theend;
2265 }
2266 // A single "." that means current dir.
2267 if (e - p == 1 && *p == '.')
2268 STRCPY(buf, name);
2269 else
2270 {
2271 vim_strncpy(buf, p, e - p);
2272 add_pathsep(buf);
2273 STRCAT(buf, name);
2274 }
2275 tmplen = STRLEN(buf);
2276
2277 /*
2278 * Loop over all extensions in $PATHEXT.
2279 * Check "name" with extension added.
2280 */
2281 p = pathext;
2282 while (*p)
2283 {
2284 if (*p == ';')
2285 {
2286 // Skip empty entry
2287 ++p;
2288 continue;
2289 }
2290 e2 = vim_strchr(p, (int)';');
2291 if (e2 == NULL)
2292 e2 = p + STRLEN(p);
2293
2294 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2295 {
2296 // Not a single "." that means no extension is added.
2297 if (e2 - p + tmplen + 1 > sizeof(buf))
2298 {
2299 retval = FALSE;
2300 goto theend;
2301 }
2302 vim_strncpy(buf + tmplen, p, e2 - p);
2303 }
2304 if (executable_file((char *)buf, path))
2305 {
2306 retval = TRUE;
2307 goto theend;
2308 }
2309
2310 p = e2;
2311 }
2312
2313 p = e;
2314 }
2315
2316theend:
2317 free(pathextbuf);
2318 free(pathbuf);
2319 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002320}
2321
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002322#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2323 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002324/*
2325 * Bad parameter handler.
2326 *
2327 * Certain MS CRT functions will intentionally crash when passed invalid
2328 * parameters to highlight possible security holes. Setting this function as
2329 * the bad parameter handler will prevent the crash.
2330 *
2331 * In debug builds the parameters contain CRT information that might help track
2332 * down the source of a problem, but in non-debug builds the arguments are all
2333 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2334 * worth allowing these to make debugging of issues easier.
2335 */
2336 static void
2337bad_param_handler(const wchar_t *expression,
2338 const wchar_t *function,
2339 const wchar_t *file,
2340 unsigned int line,
2341 uintptr_t pReserved)
2342{
2343}
2344
2345# define SET_INVALID_PARAM_HANDLER \
2346 ((void)_set_invalid_parameter_handler(bad_param_handler))
2347#else
2348# define SET_INVALID_PARAM_HANDLER
2349#endif
2350
Bram Moolenaar4f974752019-02-17 17:44:42 +01002351#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002352
2353/*
2354 * GUI version of mch_init().
2355 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002356 static void
2357mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002358{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002359# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002360 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002361# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002362
Bram Moolenaar0f873732019-12-05 20:28:46 +01002363 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002364 SET_INVALID_PARAM_HANDLER;
2365
Bram Moolenaar0f873732019-12-05 20:28:46 +01002366 // Let critical errors result in a failure, not in a dialog box. Required
2367 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002368 SetErrorMode(SEM_FAILCRITICALERRORS);
2369
Bram Moolenaar0f873732019-12-05 20:28:46 +01002370 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002371
Bram Moolenaar0f873732019-12-05 20:28:46 +01002372 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002373 Rows = 25;
2374 Columns = 80;
2375
Bram Moolenaar0f873732019-12-05 20:28:46 +01002376 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002377 {
2378 char_u vimrun_location[_MAX_PATH + 4];
2379
Bram Moolenaar0f873732019-12-05 20:28:46 +01002380 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002381 STRCPY(vimrun_location, exe_name);
2382 STRCPY(gettail(vimrun_location), "vimrun.exe");
2383 if (mch_getperm(vimrun_location) >= 0)
2384 {
2385 if (*skiptowhite(vimrun_location) != NUL)
2386 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002387 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002388 mch_memmove(vimrun_location + 1, vimrun_location,
2389 STRLEN(vimrun_location) + 1);
2390 *vimrun_location = '"';
2391 STRCPY(gettail(vimrun_location), "vimrun\" ");
2392 }
2393 else
2394 STRCPY(gettail(vimrun_location), "vimrun ");
2395
2396 vimrun_path = (char *)vim_strsave(vimrun_location);
2397 s_dont_use_vimrun = FALSE;
2398 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002399 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002400 s_dont_use_vimrun = FALSE;
2401
Bram Moolenaar0f873732019-12-05 20:28:46 +01002402 // Don't give the warning for a missing vimrun.exe right now, but only
2403 // when vimrun was supposed to be used. Don't bother people that do
2404 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002405 if (s_dont_use_vimrun)
2406 need_vimrun_warning = TRUE;
2407 }
2408
2409 /*
2410 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2411 * Otherwise the default "findstr /n" is used.
2412 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002413 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01002414 set_option_value_give_err((char_u *)"grepprg",
2415 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002416
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002417# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002418 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002419# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002420
2421 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002422}
2423
2424
Bram Moolenaar0f873732019-12-05 20:28:46 +01002425#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002426
2427#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002428
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002429# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2430# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002431
2432/*
2433 * ClearConsoleBuffer()
2434 * Description:
2435 * Clears the entire contents of the console screen buffer, using the
2436 * specified attribute.
2437 * Returns:
2438 * TRUE on success
2439 */
2440 static BOOL
2441ClearConsoleBuffer(WORD wAttribute)
2442{
2443 CONSOLE_SCREEN_BUFFER_INFO csbi;
2444 COORD coord;
2445 DWORD NumCells, dummy;
2446
2447 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2448 return FALSE;
2449
2450 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2451 coord.X = 0;
2452 coord.Y = 0;
2453 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2454 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002455 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002456 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2457 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002458 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002459
2460 return TRUE;
2461}
2462
2463/*
2464 * FitConsoleWindow()
2465 * Description:
2466 * Checks if the console window will fit within given buffer dimensions.
2467 * Also, if requested, will shrink the window to fit.
2468 * Returns:
2469 * TRUE on success
2470 */
2471 static BOOL
2472FitConsoleWindow(
2473 COORD dwBufferSize,
2474 BOOL WantAdjust)
2475{
2476 CONSOLE_SCREEN_BUFFER_INFO csbi;
2477 COORD dwWindowSize;
2478 BOOL NeedAdjust = FALSE;
2479
2480 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2481 {
2482 /*
2483 * A buffer resize will fail if the current console window does
2484 * not lie completely within that buffer. To avoid this, we might
2485 * have to move and possibly shrink the window.
2486 */
2487 if (csbi.srWindow.Right >= dwBufferSize.X)
2488 {
2489 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2490 if (dwWindowSize.X > dwBufferSize.X)
2491 dwWindowSize.X = dwBufferSize.X;
2492 csbi.srWindow.Right = dwBufferSize.X - 1;
2493 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2494 NeedAdjust = TRUE;
2495 }
2496 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2497 {
2498 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2499 if (dwWindowSize.Y > dwBufferSize.Y)
2500 dwWindowSize.Y = dwBufferSize.Y;
2501 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2502 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2503 NeedAdjust = TRUE;
2504 }
2505 if (NeedAdjust && WantAdjust)
2506 {
2507 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2508 return FALSE;
2509 }
2510 return TRUE;
2511 }
2512
2513 return FALSE;
2514}
2515
2516typedef struct ConsoleBufferStruct
2517{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002518 BOOL IsValid;
2519 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002520 PCHAR_INFO Buffer;
2521 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002522 PSMALL_RECT Regions;
2523 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002524} ConsoleBuffer;
2525
2526/*
2527 * SaveConsoleBuffer()
2528 * Description:
2529 * Saves important information about the console buffer, including the
2530 * actual buffer contents. The saved information is suitable for later
2531 * restoration by RestoreConsoleBuffer().
2532 * Returns:
2533 * TRUE if all information was saved; FALSE otherwise
2534 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2535 */
2536 static BOOL
2537SaveConsoleBuffer(
2538 ConsoleBuffer *cb)
2539{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002540 DWORD NumCells;
2541 COORD BufferCoord;
2542 SMALL_RECT ReadRegion;
2543 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002544 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002545
Bram Moolenaar071d4272004-06-13 20:20:40 +00002546 if (cb == NULL)
2547 return FALSE;
2548
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002549 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002550 {
2551 cb->IsValid = FALSE;
2552 return FALSE;
2553 }
2554 cb->IsValid = TRUE;
2555
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002556 /*
2557 * Allocate a buffer large enough to hold the entire console screen
2558 * buffer. If this ConsoleBuffer structure has already been initialized
2559 * with a buffer of the correct size, then just use that one.
2560 */
2561 if (!cb->IsValid || cb->Buffer == NULL ||
2562 cb->BufferSize.X != cb->Info.dwSize.X ||
2563 cb->BufferSize.Y != cb->Info.dwSize.Y)
2564 {
2565 cb->BufferSize.X = cb->Info.dwSize.X;
2566 cb->BufferSize.Y = cb->Info.dwSize.Y;
2567 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2568 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002569 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002570 if (cb->Buffer == NULL)
2571 return FALSE;
2572 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002573
2574 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002575 * We will now copy the console screen buffer into our buffer.
2576 * ReadConsoleOutput() seems to be limited as far as how much you
2577 * can read at a time. Empirically, this number seems to be about
2578 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2579 * in chunks until it is all copied. The chunks will all have the
2580 * same horizontal characteristics, so initialize them now. The
2581 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002582 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002583 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002584 ReadRegion.Left = 0;
2585 ReadRegion.Right = cb->Info.dwSize.X - 1;
2586 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002587
2588 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2589 if (cb->Regions == NULL || numregions != cb->NumRegions)
2590 {
2591 cb->NumRegions = numregions;
2592 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002593 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002594 if (cb->Regions == NULL)
2595 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002596 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002597 return FALSE;
2598 }
2599 }
2600
2601 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002602 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002603 /*
2604 * Read into position (0, Y) in our buffer.
2605 */
2606 BufferCoord.Y = Y;
2607 /*
2608 * Read the region whose top left corner is (0, Y) and whose bottom
2609 * right corner is (width - 1, Y + Y_incr - 1). This should define
2610 * a region of size width by Y_incr. Don't worry if this region is
2611 * too large for the remaining buffer; it will be cropped.
2612 */
2613 ReadRegion.Top = Y;
2614 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002615 if (!ReadConsoleOutputW(g_hConOut, // output handle
2616 cb->Buffer, // our buffer
2617 cb->BufferSize, // dimensions of our buffer
2618 BufferCoord, // offset in our buffer
2619 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002620 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002621 VIM_CLEAR(cb->Buffer);
2622 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002623 return FALSE;
2624 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002625 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002626 }
2627
2628 return TRUE;
2629}
2630
2631/*
2632 * RestoreConsoleBuffer()
2633 * Description:
2634 * Restores important information about the console buffer, including the
2635 * actual buffer contents, if desired. The information to restore is in
2636 * the same format used by SaveConsoleBuffer().
2637 * Returns:
2638 * TRUE on success
2639 */
2640 static BOOL
2641RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002642 ConsoleBuffer *cb,
2643 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002644{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002645 COORD BufferCoord;
2646 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002647 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002648
2649 if (cb == NULL || !cb->IsValid)
2650 return FALSE;
2651
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002652 /*
2653 * Before restoring the buffer contents, clear the current buffer, and
2654 * restore the cursor position and window information. Doing this now
2655 * prevents old buffer contents from "flashing" onto the screen.
2656 */
2657 if (RestoreScreen)
2658 ClearConsoleBuffer(cb->Info.wAttributes);
2659
2660 FitConsoleWindow(cb->Info.dwSize, TRUE);
2661 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2662 return FALSE;
2663 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2664 return FALSE;
2665
2666 if (!RestoreScreen)
2667 {
2668 /*
2669 * No need to restore the screen buffer contents, so we're done.
2670 */
2671 return TRUE;
2672 }
2673
2674 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2675 return FALSE;
2676 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2677 return FALSE;
2678
2679 /*
2680 * Restore the screen buffer contents.
2681 */
2682 if (cb->Buffer != NULL)
2683 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002684 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002685 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002686 BufferCoord.X = cb->Regions[i].Left;
2687 BufferCoord.Y = cb->Regions[i].Top;
2688 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01002689 if (!WriteConsoleOutputW(g_hConOut, // output handle
2690 cb->Buffer, // our buffer
2691 cb->BufferSize, // dimensions of our buffer
2692 BufferCoord, // offset in our buffer
2693 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02002694 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002695 }
2696 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002697
2698 return TRUE;
2699}
2700
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002701# define FEAT_RESTORE_ORIG_SCREEN
2702# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002703static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002704# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002705static ConsoleBuffer g_cbNonTermcap = { 0 };
2706static ConsoleBuffer g_cbTermcap = { 0 };
2707
Bram Moolenaar071d4272004-06-13 20:20:40 +00002708char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01002709HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00002710static HICON g_hOrigIconSmall = NULL;
2711static HICON g_hOrigIcon = NULL;
2712static HICON g_hVimIcon = NULL;
2713static BOOL g_fCanChangeIcon = FALSE;
2714
Bram Moolenaar071d4272004-06-13 20:20:40 +00002715/*
2716 * GetConsoleIcon()
2717 * Description:
2718 * Attempts to retrieve 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
2724GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002725 HWND hWnd,
2726 HICON *phIconSmall,
2727 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002728{
2729 if (hWnd == NULL)
2730 return FALSE;
2731
2732 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002733 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2734 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002735 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002736 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2737 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002738 return TRUE;
2739}
2740
2741/*
2742 * SetConsoleIcon()
2743 * Description:
2744 * Attempts to change the small icon and/or the big icon currently in
2745 * use by a given window.
2746 * Returns:
2747 * TRUE on success
2748 */
2749 static BOOL
2750SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002751 HWND hWnd,
2752 HICON hIconSmall,
2753 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002754{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002755 if (hWnd == NULL)
2756 return FALSE;
2757
2758 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002759 SendMessage(hWnd, WM_SETICON,
2760 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002761 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002762 SendMessage(hWnd, WM_SETICON,
2763 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002764 return TRUE;
2765}
2766
2767/*
2768 * SaveConsoleTitleAndIcon()
2769 * Description:
2770 * Saves the current console window title in g_szOrigTitle, for later
2771 * restoration. Also, attempts to obtain a handle to the console window,
2772 * and use it to save the small and big icons currently in use by the
2773 * console window. This is not always possible on some versions of Windows;
2774 * nor is it possible when running Vim remotely using Telnet (since the
2775 * console window the user sees is owned by a remote process).
2776 */
2777 static void
2778SaveConsoleTitleAndIcon(void)
2779{
Bram Moolenaar0f873732019-12-05 20:28:46 +01002780 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002781 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2782 return;
2783
2784 /*
2785 * Obtain a handle to the console window using GetConsoleWindow() from
2786 * KERNEL32.DLL; we need to handle in order to change the window icon.
2787 * This function only exists on NT-based Windows, starting with Windows
2788 * 2000. On older operating systems, we can't change the window icon
2789 * anyway.
2790 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002791 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002792 if (g_hWnd == NULL)
2793 return;
2794
Bram Moolenaar0f873732019-12-05 20:28:46 +01002795 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002796 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2797 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2798 return;
2799
Bram Moolenaar0f873732019-12-05 20:28:46 +01002800 // Extract the first icon contained in the Vim executable.
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002801 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002802 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002803 if (g_hVimIcon != NULL)
2804 g_fCanChangeIcon = TRUE;
2805}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002806
2807static int g_fWindInitCalled = FALSE;
2808static int g_fTermcapMode = FALSE;
2809static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002810
2811/*
2812 * non-GUI version of mch_init().
2813 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002814 static void
2815mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002816{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002817# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002818 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002819# endif
2820# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002821 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002822# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002823
Bram Moolenaar0f873732019-12-05 20:28:46 +01002824 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002825 SET_INVALID_PARAM_HANDLER;
2826
Bram Moolenaar0f873732019-12-05 20:28:46 +01002827 // Let critical errors result in a failure, not in a dialog box. Required
2828 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002829 SetErrorMode(SEM_FAILCRITICALERRORS);
2830
Bram Moolenaar0f873732019-12-05 20:28:46 +01002831 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002832 out_flush();
2833
Bram Moolenaar0f873732019-12-05 20:28:46 +01002834 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00002835 if (read_cmd_fd == 0)
2836 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2837 else
2838 create_conin();
2839 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2840
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002841# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01002842 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002843 SaveConsoleBuffer(&g_cbOrig);
2844 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002845# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01002846 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002847 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2848 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002849# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002850 if (cterm_normal_fg_color == 0)
2851 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2852 if (cterm_normal_bg_color == 0)
2853 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2854
Bram Moolenaarbdace832019-03-02 10:13:42 +01002855 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002856 g_color_index_fg = g_attrDefault & 0xf;
2857 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2858
Bram Moolenaar0f873732019-12-05 20:28:46 +01002859 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00002860 update_tcap(g_attrCurrent);
2861
2862 GetConsoleCursorInfo(g_hConOut, &g_cci);
2863 GetConsoleMode(g_hConIn, &g_cmodein);
2864 GetConsoleMode(g_hConOut, &g_cmodeout);
2865
Bram Moolenaar071d4272004-06-13 20:20:40 +00002866 SaveConsoleTitleAndIcon();
2867 /*
2868 * Set both the small and big icons of the console window to Vim's icon.
2869 * Note that Vim presently only has one size of icon (32x32), but it
2870 * automatically gets scaled down to 16x16 when setting the small icon.
2871 */
2872 if (g_fCanChangeIcon)
2873 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002874
2875 ui_get_shellsize();
2876
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002877# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002878 fdDump = fopen("dump", "wt");
2879
2880 if (fdDump)
2881 {
2882 time_t t;
2883
2884 time(&t);
2885 fputs(ctime(&t), fdDump);
2886 fflush(fdDump);
2887 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002888# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002889
2890 g_fWindInitCalled = TRUE;
2891
Bram Moolenaar071d4272004-06-13 20:20:40 +00002892 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002893
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002894# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002895 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002896# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002897
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02002898 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002899 vtp_init();
Bram Moolenaar06b7b582020-05-30 17:49:25 +02002900 wt_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002901}
2902
2903/*
2904 * non-GUI version of mch_exit().
2905 * Shut down and exit with status `r'
2906 * Careful: mch_exit() may be called before mch_init()!
2907 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002908 static void
2909mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002910{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002911 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002912
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002913 vtp_exit();
2914
Bram Moolenaar955f1982017-02-05 15:10:51 +01002915 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002916 if (g_fWindInitCalled)
2917 settmode(TMODE_COOK);
2918
Bram Moolenaar0f873732019-12-05 20:28:46 +01002919 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00002920
2921 if (g_fWindInitCalled)
2922 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02002923 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002924 /*
2925 * Restore both the small and big icons of the console window to
2926 * what they were at startup. Don't do this when the window is
2927 * closed, Vim would hang here.
2928 */
2929 if (g_fCanChangeIcon && !g_fForceExit)
2930 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002931
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002932# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002933 if (fdDump)
2934 {
2935 time_t t;
2936
2937 time(&t);
2938 fputs(ctime(&t), fdDump);
2939 fclose(fdDump);
2940 }
2941 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002942# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002943 }
2944
2945 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02002946 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002947 SetConsoleMode(g_hConOut, g_cmodeout);
2948
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002949# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00002950 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002951# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002952
2953 exit(r);
2954}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002955#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002956
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002957 void
2958mch_init(void)
2959{
2960#ifdef VIMDLL
2961 if (gui.starting)
2962 mch_init_g();
2963 else
2964 mch_init_c();
2965#elif defined(FEAT_GUI_MSWIN)
2966 mch_init_g();
2967#else
2968 mch_init_c();
2969#endif
2970}
2971
2972 void
2973mch_exit(int r)
2974{
Bram Moolenaar173d8412020-04-19 14:02:26 +02002975#ifdef FEAT_NETBEANS_INTG
2976 netbeans_send_disconnect();
2977#endif
2978
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002979#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02002980 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002981 mch_exit_g(r);
2982 else
2983 mch_exit_c(r);
2984#elif defined(FEAT_GUI_MSWIN)
2985 mch_exit_g(r);
2986#else
2987 mch_exit_c(r);
2988#endif
2989}
2990
Bram Moolenaar071d4272004-06-13 20:20:40 +00002991/*
2992 * Do we have an interactive window?
2993 */
2994 int
2995mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002996 int argc UNUSED,
2997 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002998{
2999 get_exe_name();
3000
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003001#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003002 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003003#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003004# ifdef VIMDLL
3005 if (gui.in_use)
3006 return OK;
3007# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003008 if (isatty(1))
3009 return OK;
3010 return FAIL;
3011#endif
3012}
3013
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003014/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003015 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003016 * When "len" is > 0, also expand short to long filenames.
3017 */
3018 void
3019fname_case(
3020 char_u *name,
3021 int len)
3022{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003023 int flen;
3024 WCHAR *p;
3025 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003026
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003027 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003028 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003029 return;
3030
3031 slash_adjust(name);
3032
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003033 p = enc_to_utf16(name, NULL);
3034 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003035 return;
3036
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003037 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003038 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003039 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003040
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003041 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003042 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003043 if (len > 0 || flen >= (int)STRLEN(q))
3044 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3045 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003046 }
3047 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003048 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003049}
3050
3051
3052/*
3053 * Insert user name in s[len].
3054 */
3055 int
3056mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003057 char_u *s,
3058 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003059{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003060 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003061 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003062
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003063 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003064 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003065 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003066
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003067 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003068 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003069 vim_strncpy(s, p, len - 1);
3070 vim_free(p);
3071 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003072 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003073 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003074 s[0] = NUL;
3075 return FAIL;
3076}
3077
3078
3079/*
3080 * Insert host name in s[len].
3081 */
3082 void
3083mch_get_host_name(
3084 char_u *s,
3085 int len)
3086{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003087 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003088 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003089
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003090 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003091 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003092 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003093
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003094 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003095 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003096 vim_strncpy(s, p, len - 1);
3097 vim_free(p);
3098 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003099 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003100 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003101}
3102
3103
3104/*
3105 * return process ID
3106 */
3107 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003108mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003109{
3110 return (long)GetCurrentProcessId();
3111}
3112
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003113/*
3114 * return TRUE if process "pid" is still running
3115 */
3116 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003117mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003118{
3119 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3120 DWORD status = 0;
3121 int ret = FALSE;
3122
3123 if (hProcess == NULL)
3124 return FALSE; // might not have access
3125 if (GetExitCodeProcess(hProcess, &status) )
3126 ret = status == STILL_ACTIVE;
3127 CloseHandle(hProcess);
3128 return ret;
3129}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003130
3131/*
3132 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3133 * Return OK for success, FAIL for failure.
3134 */
3135 int
3136mch_dirname(
3137 char_u *buf,
3138 int len)
3139{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003140 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003141
Bram Moolenaar071d4272004-06-13 20:20:40 +00003142 /*
3143 * Originally this was:
3144 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3145 * But the Win32s known bug list says that getcwd() doesn't work
3146 * so use the Win32 system call instead. <Negri>
3147 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003148 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003149 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003150 WCHAR wcbuf[_MAX_PATH + 1];
3151 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003152
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003153 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003154 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003155 p = utf16_to_enc(wcbuf, NULL);
3156 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003157 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003158 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003159 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003160 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003161 }
3162 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003163 if (p == NULL)
3164 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003165
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003166 if (p != NULL)
3167 {
3168 vim_strncpy(buf, p, len - 1);
3169 vim_free(p);
3170 return OK;
3171 }
3172 }
3173 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003174}
3175
3176/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003177 * Get file permissions for "name".
3178 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003179 */
3180 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003181mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003182{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003183 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003184 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003185
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003186 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003187 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003188}
3189
3190
3191/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003192 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003193 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003194 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003195 */
3196 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003197mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003198{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003199 long n;
3200 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003201
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003202 p = enc_to_utf16(name, NULL);
3203 if (p == NULL)
3204 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003205
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003206 n = _wchmod(p, perm);
3207 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003208 if (n == -1)
3209 return FAIL;
3210
3211 win32_set_archive(name);
3212
3213 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003214}
3215
3216/*
3217 * Set hidden flag for "name".
3218 */
3219 void
3220mch_hide(char_u *name)
3221{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003222 int attrs = win32_getattrs(name);
3223 if (attrs == -1)
3224 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003225
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003226 attrs |= FILE_ATTRIBUTE_HIDDEN;
3227 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003228}
3229
3230/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003231 * Return TRUE if file "name" exists and is hidden.
3232 */
3233 int
3234mch_ishidden(char_u *name)
3235{
3236 int f = win32_getattrs(name);
3237
3238 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003239 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003240
3241 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3242}
3243
3244/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003245 * return TRUE if "name" is a directory
3246 * return FALSE if "name" is not a directory or upon error
3247 */
3248 int
3249mch_isdir(char_u *name)
3250{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003251 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003252
3253 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003254 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003255
3256 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3257}
3258
3259/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003260 * return TRUE if "name" is a directory, NOT a symlink to a directory
3261 * return FALSE if "name" is not a directory
3262 * return FALSE for error
3263 */
3264 int
3265mch_isrealdir(char_u *name)
3266{
3267 return mch_isdir(name) && !mch_is_symbolic_link(name);
3268}
3269
3270/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003271 * Create directory "name".
3272 * Return 0 on success, -1 on error.
3273 */
3274 int
3275mch_mkdir(char_u *name)
3276{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003277 WCHAR *p;
3278 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003279
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003280 p = enc_to_utf16(name, NULL);
3281 if (p == NULL)
3282 return -1;
3283 retval = _wmkdir(p);
3284 vim_free(p);
3285 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003286}
3287
3288/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003289 * Delete directory "name".
3290 * Return 0 on success, -1 on error.
3291 */
3292 int
3293mch_rmdir(char_u *name)
3294{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003295 WCHAR *p;
3296 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003297
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003298 p = enc_to_utf16(name, NULL);
3299 if (p == NULL)
3300 return -1;
3301 retval = _wrmdir(p);
3302 vim_free(p);
3303 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003304}
3305
3306/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003307 * Return TRUE if file "fname" has more than one link.
3308 */
3309 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003310mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003311{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003312 BY_HANDLE_FILE_INFORMATION info;
3313
3314 return win32_fileinfo(fname, &info) == FILEINFO_OK
3315 && info.nNumberOfLinks > 1;
3316}
3317
3318/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003319 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003320 */
3321 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003322mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003323{
3324 HANDLE hFind;
3325 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003326 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003327 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003328 WIN32_FIND_DATAW findDataW;
3329
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003330 wn = enc_to_utf16(name, NULL);
3331 if (wn == NULL)
3332 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003333
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003334 hFind = FindFirstFileW(wn, &findDataW);
3335 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003336 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003337 {
3338 fileFlags = findDataW.dwFileAttributes;
3339 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003340 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003341 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003342
3343 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003344 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3345 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003346 res = TRUE;
3347
3348 return res;
3349}
3350
3351/*
3352 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3353 * link.
3354 */
3355 int
3356mch_is_linked(char_u *fname)
3357{
3358 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3359 return TRUE;
3360 return FALSE;
3361}
3362
3363/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003364 * Get the by-handle-file-information for "fname".
3365 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003366 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003367 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3368 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3369 */
3370 int
3371win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3372{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003373 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003374 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003375 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003376
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003377 wn = enc_to_utf16(fname, NULL);
3378 if (wn == NULL)
3379 return FILEINFO_ENC_FAIL;
3380
3381 hFile = CreateFileW(wn, // file name
3382 GENERIC_READ, // access mode
3383 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3384 NULL, // security descriptor
3385 OPEN_EXISTING, // creation disposition
3386 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3387 NULL); // handle to template file
3388 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003389
3390 if (hFile != INVALID_HANDLE_VALUE)
3391 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003392 if (GetFileInformationByHandle(hFile, info) != 0)
3393 res = FILEINFO_OK;
3394 else
3395 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003396 CloseHandle(hFile);
3397 }
3398
Bram Moolenaar03f48552006-02-28 23:52:23 +00003399 return res;
3400}
3401
3402/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003403 * get file attributes for `name'
3404 * -1 : error
3405 * else FILE_ATTRIBUTE_* defined in winnt.h
3406 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003407 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003408win32_getattrs(char_u *name)
3409{
3410 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003411 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003412
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003413 p = enc_to_utf16(name, NULL);
3414 if (p == NULL)
3415 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003416
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003417 attr = GetFileAttributesW(p);
3418 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003419
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003420 return attr;
3421}
3422
3423/*
3424 * set file attributes for `name' to `attrs'
3425 *
3426 * return -1 for failure, 0 otherwise
3427 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003428 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003429win32_setattrs(char_u *name, int attrs)
3430{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003431 int res;
3432 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003433
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003434 p = enc_to_utf16(name, NULL);
3435 if (p == NULL)
3436 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003437
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003438 res = SetFileAttributesW(p, attrs);
3439 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003440
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003441 return res ? 0 : -1;
3442}
3443
3444/*
3445 * Set archive flag for "name".
3446 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003447 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003448win32_set_archive(char_u *name)
3449{
3450 int attrs = win32_getattrs(name);
3451 if (attrs == -1)
3452 return -1;
3453
3454 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3455 return win32_setattrs(name, attrs);
3456}
3457
3458/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003459 * Return TRUE if file or directory "name" is writable (not readonly).
3460 * Strange semantics of Win32: a readonly directory is writable, but you can't
3461 * delete a file. Let's say this means it is writable.
3462 */
3463 int
3464mch_writable(char_u *name)
3465{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003466 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003467
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003468 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3469 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003470}
3471
Bram Moolenaar071d4272004-06-13 20:20:40 +00003472/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003473 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003474 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003475 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3476 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003477 */
3478 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003479mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003480{
Bram Moolenaar95da1362020-05-30 18:37:55 +02003481 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003482}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003483
3484/*
3485 * Check what "name" is:
3486 * NODE_NORMAL: file or directory (or doesn't exist)
3487 * NODE_WRITABLE: writable device, socket, fifo, etc.
3488 * NODE_OTHER: non-writable things
3489 */
3490 int
3491mch_nodetype(char_u *name)
3492{
3493 HANDLE hFile;
3494 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003495 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003496
Bram Moolenaar0f873732019-12-05 20:28:46 +01003497 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3498 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3499 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00003500 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3501 return NODE_WRITABLE;
3502
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003503 wn = enc_to_utf16(name, NULL);
3504 if (wn == NULL)
3505 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003506
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003507 hFile = CreateFileW(wn, // file name
3508 GENERIC_WRITE, // access mode
3509 0, // share mode
3510 NULL, // security descriptor
3511 OPEN_EXISTING, // creation disposition
3512 0, // file attributes
3513 NULL); // handle to template file
3514 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003515 if (hFile == INVALID_HANDLE_VALUE)
3516 return NODE_NORMAL;
3517
3518 type = GetFileType(hFile);
3519 CloseHandle(hFile);
3520 if (type == FILE_TYPE_CHAR)
3521 return NODE_WRITABLE;
3522 if (type == FILE_TYPE_DISK)
3523 return NODE_NORMAL;
3524 return NODE_OTHER;
3525}
3526
3527#ifdef HAVE_ACL
3528struct my_acl
3529{
3530 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3531 PSID pSidOwner;
3532 PSID pSidGroup;
3533 PACL pDacl;
3534 PACL pSacl;
3535};
3536#endif
3537
3538/*
3539 * Return a pointer to the ACL of file "fname" in allocated memory.
3540 * Return NULL if the ACL is not available for whatever reason.
3541 */
3542 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003543mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003544{
3545#ifndef HAVE_ACL
3546 return (vim_acl_T)NULL;
3547#else
3548 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003549 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003550
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003551 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003552 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003553 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003554 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003555
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003556 wn = enc_to_utf16(fname, NULL);
3557 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003558 {
3559 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003560 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003561 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003562
3563 // Try to retrieve the entire security descriptor.
3564 err = GetNamedSecurityInfoW(
3565 wn, // Abstract filename
3566 SE_FILE_OBJECT, // File Object
3567 OWNER_SECURITY_INFORMATION |
3568 GROUP_SECURITY_INFORMATION |
3569 DACL_SECURITY_INFORMATION |
3570 SACL_SECURITY_INFORMATION,
3571 &p->pSidOwner, // Ownership information.
3572 &p->pSidGroup, // Group membership.
3573 &p->pDacl, // Discretionary information.
3574 &p->pSacl, // For auditing purposes.
3575 &p->pSecurityDescriptor);
3576 if (err == ERROR_ACCESS_DENIED ||
3577 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003578 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003579 // Retrieve only DACL.
3580 (void)GetNamedSecurityInfoW(
3581 wn,
3582 SE_FILE_OBJECT,
3583 DACL_SECURITY_INFORMATION,
3584 NULL,
3585 NULL,
3586 &p->pDacl,
3587 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003588 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003589 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003590 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003591 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003592 mch_free_acl((vim_acl_T)p);
3593 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003594 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003595 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003596 }
3597
3598 return (vim_acl_T)p;
3599#endif
3600}
3601
Bram Moolenaar27515922013-06-29 15:36:26 +02003602#ifdef HAVE_ACL
3603/*
3604 * Check if "acl" contains inherited ACE.
3605 */
3606 static BOOL
3607is_acl_inherited(PACL acl)
3608{
3609 DWORD i;
3610 ACL_SIZE_INFORMATION acl_info;
3611 PACCESS_ALLOWED_ACE ace;
3612
3613 acl_info.AceCount = 0;
3614 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3615 for (i = 0; i < acl_info.AceCount; i++)
3616 {
3617 GetAce(acl, i, (LPVOID *)&ace);
3618 if (ace->Header.AceFlags & INHERITED_ACE)
3619 return TRUE;
3620 }
3621 return FALSE;
3622}
3623#endif
3624
Bram Moolenaar071d4272004-06-13 20:20:40 +00003625/*
3626 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3627 * Errors are ignored.
3628 * This must only be called with "acl" equal to what mch_get_acl() returned.
3629 */
3630 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003631mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003632{
3633#ifdef HAVE_ACL
3634 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003635 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003636 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003637
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003638 if (p == NULL)
3639 return;
3640
3641 wn = enc_to_utf16(fname, NULL);
3642 if (wn == NULL)
3643 return;
3644
3645 // Set security flags
3646 if (p->pSidOwner)
3647 sec_info |= OWNER_SECURITY_INFORMATION;
3648 if (p->pSidGroup)
3649 sec_info |= GROUP_SECURITY_INFORMATION;
3650 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003651 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003652 sec_info |= DACL_SECURITY_INFORMATION;
3653 // Do not inherit its parent's DACL.
3654 // If the DACL is inherited, Cygwin permissions would be changed.
3655 if (!is_acl_inherited(p->pDacl))
3656 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003657 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003658 if (p->pSacl)
3659 sec_info |= SACL_SECURITY_INFORMATION;
3660
3661 (void)SetNamedSecurityInfoW(
3662 wn, // Abstract filename
3663 SE_FILE_OBJECT, // File Object
3664 sec_info,
3665 p->pSidOwner, // Ownership information.
3666 p->pSidGroup, // Group membership.
3667 p->pDacl, // Discretionary information.
3668 p->pSacl // For auditing purposes.
3669 );
3670 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003671#endif
3672}
3673
3674 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003675mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003676{
3677#ifdef HAVE_ACL
3678 struct my_acl *p = (struct my_acl *)acl;
3679
3680 if (p != NULL)
3681 {
3682 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3683 vim_free(p);
3684 }
3685#endif
3686}
3687
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003688#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003689
3690/*
3691 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3692 */
3693 static BOOL WINAPI
3694handler_routine(
3695 DWORD dwCtrlType)
3696{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003697 INPUT_RECORD ir;
3698 DWORD out;
3699
Bram Moolenaar071d4272004-06-13 20:20:40 +00003700 switch (dwCtrlType)
3701 {
3702 case CTRL_C_EVENT:
3703 if (ctrl_c_interrupts)
3704 g_fCtrlCPressed = TRUE;
3705 return TRUE;
3706
3707 case CTRL_BREAK_EVENT:
3708 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003709 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003710 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02003711 ir.EventType = KEY_EVENT;
3712 ir.Event.KeyEvent.bKeyDown = TRUE;
3713 ir.Event.KeyEvent.wRepeatCount = 1;
3714 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3715 ir.Event.KeyEvent.wVirtualScanCode = 0;
3716 ir.Event.KeyEvent.dwControlKeyState = 0;
3717 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3718 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003719 return TRUE;
3720
Bram Moolenaar0f873732019-12-05 20:28:46 +01003721 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00003722 case CTRL_CLOSE_EVENT:
3723 case CTRL_LOGOFF_EVENT:
3724 case CTRL_SHUTDOWN_EVENT:
3725 windgoto((int)Rows - 1, 0);
3726 g_fForceExit = TRUE;
3727
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003728 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003729 (dwCtrlType == CTRL_CLOSE_EVENT
3730 ? _("close")
3731 : dwCtrlType == CTRL_LOGOFF_EVENT
3732 ? _("logoff")
3733 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003734# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00003735 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003736# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003737
Bram Moolenaar0f873732019-12-05 20:28:46 +01003738 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00003739
Bram Moolenaar0f873732019-12-05 20:28:46 +01003740 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00003741
3742 default:
3743 return FALSE;
3744 }
3745}
3746
3747
3748/*
3749 * set the tty in (raw) ? "raw" : "cooked" mode
3750 */
3751 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02003752mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003753{
3754 DWORD cmodein;
3755 DWORD cmodeout;
3756 BOOL bEnableHandler;
3757
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003758# ifdef VIMDLL
3759 if (gui.in_use)
3760 return;
3761# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003762 GetConsoleMode(g_hConIn, &cmodein);
3763 GetConsoleMode(g_hConOut, &cmodeout);
3764 if (tmode == TMODE_RAW)
3765 {
3766 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3767 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003768 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003769 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003770 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003771 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
3772 }
3773 else
3774 {
3775 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
3776 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003777 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003778# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01003779 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
3780 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003781 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003782# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003783 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003784# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003785 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003786 bEnableHandler = TRUE;
3787 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01003788 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00003789 {
3790 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3791 ENABLE_ECHO_INPUT);
3792 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3793 bEnableHandler = FALSE;
3794 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003795 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003796 SetConsoleMode(g_hConOut, cmodeout);
3797 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3798
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003799# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003800 if (fdDump)
3801 {
3802 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3803 tmode == TMODE_RAW ? "raw" :
3804 tmode == TMODE_COOK ? "cooked" : "normal",
3805 cmodein, cmodeout);
3806 fflush(fdDump);
3807 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003808# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003809}
3810
3811
3812/*
3813 * Get the size of the current window in `Rows' and `Columns'
3814 * Return OK when size could be determined, FAIL otherwise.
3815 */
3816 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003817mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003818{
3819 CONSOLE_SCREEN_BUFFER_INFO csbi;
3820
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003821# ifdef VIMDLL
3822 if (gui.in_use)
3823 return OK;
3824# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003825 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3826 {
3827 /*
3828 * For some reason, we are trying to get the screen dimensions
3829 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3830 * variables are really intended to mean the size of Vim screen
3831 * while in termcap mode.
3832 */
3833 Rows = g_cbTermcap.Info.dwSize.Y;
3834 Columns = g_cbTermcap.Info.dwSize.X;
3835 }
3836 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3837 {
3838 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3839 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3840 }
3841 else
3842 {
3843 Rows = 25;
3844 Columns = 80;
3845 }
3846 return OK;
3847}
3848
3849/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003850 * Resize console buffer to 'COORD'
3851 */
3852 static void
3853ResizeConBuf(
3854 HANDLE hConsole,
3855 COORD coordScreen)
3856{
3857 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3858 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003859# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003860 if (fdDump)
3861 {
3862 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3863 GetLastError());
3864 fflush(fdDump);
3865 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003866# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003867 }
3868}
3869
3870/*
3871 * Resize console window size to 'srWindowRect'
3872 */
3873 static void
3874ResizeWindow(
3875 HANDLE hConsole,
3876 SMALL_RECT srWindowRect)
3877{
3878 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
3879 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003880# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003881 if (fdDump)
3882 {
3883 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3884 GetLastError());
3885 fflush(fdDump);
3886 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003887# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003888 }
3889}
3890
3891/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003892 * Set a console window to `xSize' * `ySize'
3893 */
3894 static void
3895ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003896 HANDLE hConsole,
3897 int xSize,
3898 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003899{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003900 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
3901 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003902 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003903 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02003904 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003905
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003906# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003907 if (fdDump)
3908 {
3909 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3910 fflush(fdDump);
3911 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003912# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003913
Bram Moolenaar0f873732019-12-05 20:28:46 +01003914 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00003915 coordScreen = GetLargestConsoleWindowSize(hConsole);
3916
Bram Moolenaar0f873732019-12-05 20:28:46 +01003917 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00003918 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3919 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3920 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3921
3922 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3923 {
3924 int sx, sy;
3925
3926 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3927 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3928 if (sy < ySize || sx < xSize)
3929 {
3930 /*
3931 * Increasing number of lines/columns, do buffer first.
3932 * Use the maximal size in x and y direction.
3933 */
3934 if (sy < ySize)
3935 coordScreen.Y = ySize;
3936 else
3937 coordScreen.Y = sy;
3938 if (sx < xSize)
3939 coordScreen.X = xSize;
3940 else
3941 coordScreen.X = sx;
3942 SetConsoleScreenBufferSize(hConsole, coordScreen);
3943 }
3944 }
3945
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003946 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003947 coordScreen.X = xSize;
3948 coordScreen.Y = ySize;
3949
Bram Moolenaar2551c032018-08-23 22:38:31 +02003950 // In the new console call API, only the first time in reverse order
3951 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003952 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003953 ResizeWindow(hConsole, srWindowRect);
3954 ResizeConBuf(hConsole, coordScreen);
3955 }
3956 else
3957 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003958 // Workaround for a Windows 10 bug
3959 cursor.X = srWindowRect.Left;
3960 cursor.Y = srWindowRect.Top;
3961 SetConsoleCursorPosition(hConsole, cursor);
3962
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003963 ResizeConBuf(hConsole, coordScreen);
3964 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02003965 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003966 }
3967}
3968
3969
3970/*
3971 * Set the console window to `Rows' * `Columns'
3972 */
3973 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003974mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003975{
3976 COORD coordScreen;
3977
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003978# ifdef VIMDLL
3979 if (gui.in_use)
3980 return;
3981# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01003982 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00003983 if (suppress_winsize != 0)
3984 {
3985 suppress_winsize = 2;
3986 return;
3987 }
3988
3989 if (term_console)
3990 {
3991 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3992
Bram Moolenaar0f873732019-12-05 20:28:46 +01003993 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00003994 if (Rows > coordScreen.Y)
3995 Rows = coordScreen.Y;
3996 if (Columns > coordScreen.X)
3997 Columns = coordScreen.X;
3998
3999 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4000 }
4001}
4002
4003/*
4004 * Rows and/or Columns has changed.
4005 */
4006 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004007mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004008{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004009# ifdef VIMDLL
4010 if (gui.in_use)
4011 return;
4012# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004013 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4014}
4015
4016
4017/*
4018 * Called when started up, to set the winsize that was delayed.
4019 */
4020 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004021mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004022{
4023 if (suppress_winsize == 2)
4024 {
4025 suppress_winsize = 0;
4026 mch_set_shellsize();
4027 shell_resized();
4028 }
4029 suppress_winsize = 0;
4030}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004031#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004032
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004033 static BOOL
4034vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004035 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004036 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004037 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004038 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004039 PROCESS_INFORMATION *pi,
4040 LPVOID *env,
4041 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004042{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004043 BOOL ret = FALSE;
4044 WCHAR *wcmd, *wcwd = NULL;
4045
4046 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4047 if (wcmd == NULL)
4048 return FALSE;
4049 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004050 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004051 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4052 if (wcwd == NULL)
4053 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004054 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004055
4056 ret = CreateProcessW(
4057 NULL, // Executable name
4058 wcmd, // Command to execute
4059 NULL, // Process security attributes
4060 NULL, // Thread security attributes
4061 inherit_handles, // Inherit handles
4062 flags, // Creation flags
4063 env, // Environment
4064 wcwd, // Current directory
4065 (LPSTARTUPINFOW)si, // Startup information
4066 pi); // Process information
4067theend:
4068 vim_free(wcmd);
4069 vim_free(wcwd);
4070 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004071}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004072
4073
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004074 static HINSTANCE
4075vim_shell_execute(
4076 char *cmd,
4077 INT n_show_cmd)
4078{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004079 HINSTANCE ret;
4080 WCHAR *wcmd;
4081
4082 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4083 if (wcmd == NULL)
4084 return (HINSTANCE) 0;
4085
4086 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4087 vim_free(wcmd);
4088 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004089}
4090
4091
Bram Moolenaar4f974752019-02-17 17:44:42 +01004092#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004093
4094/*
4095 * Specialised version of system() for Win32 GUI mode.
4096 * This version proceeds as follows:
4097 * 1. Create a console window for use by the subprocess
4098 * 2. Run the subprocess (it gets the allocated console by default)
4099 * 3. Wait for the subprocess to terminate and get its exit code
4100 * 4. Prompt the user to press a key to close the console window
4101 */
4102 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004103mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004104{
4105 STARTUPINFO si;
4106 PROCESS_INFORMATION pi;
4107 DWORD ret = 0;
4108 HWND hwnd = GetFocus();
4109
4110 si.cb = sizeof(si);
4111 si.lpReserved = NULL;
4112 si.lpDesktop = NULL;
4113 si.lpTitle = NULL;
4114 si.dwFlags = STARTF_USESHOWWINDOW;
4115 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004116 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004117 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004118 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004119 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004120 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004121 else
4122 si.wShowWindow = SW_SHOWNORMAL;
4123 si.cbReserved2 = 0;
4124 si.lpReserved2 = NULL;
4125
Bram Moolenaar0f873732019-12-05 20:28:46 +01004126 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004127 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004128 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4129 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004130
Bram Moolenaar0f873732019-12-05 20:28:46 +01004131 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004132 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004133# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004134 int delay = 1;
4135
Bram Moolenaar0f873732019-12-05 20:28:46 +01004136 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004137 for (;;)
4138 {
4139 MSG msg;
4140
K.Takatab7057bd2022-01-21 11:37:07 +00004141 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004142 {
4143 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004144 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004145 delay = 1;
4146 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004147 }
4148 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4149 break;
4150
Bram Moolenaar0f873732019-12-05 20:28:46 +01004151 // We start waiting for a very short time and then increase it, so
4152 // that we respond quickly when the process is quick, and don't
4153 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004154 if (delay < 50)
4155 delay += 10;
4156 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004157# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004158 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004159# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004160
Bram Moolenaar0f873732019-12-05 20:28:46 +01004161 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004162 GetExitCodeProcess(pi.hProcess, &ret);
4163 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004164
Bram Moolenaar0f873732019-12-05 20:28:46 +01004165 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004166 CloseHandle(pi.hThread);
4167 CloseHandle(pi.hProcess);
4168
Bram Moolenaar0f873732019-12-05 20:28:46 +01004169 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004170 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4171
4172 return ret;
4173}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004174
4175/*
4176 * Thread launched by the gui to send the current buffer data to the
4177 * process. This way avoid to hang up vim totally if the children
4178 * process take a long time to process the lines.
4179 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004180 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004181sub_process_writer(LPVOID param)
4182{
4183 HANDLE g_hChildStd_IN_Wr = param;
4184 linenr_T lnum = curbuf->b_op_start.lnum;
4185 DWORD len = 0;
4186 DWORD l;
4187 char_u *lp = ml_get(lnum);
4188 char_u *s;
4189 int written = 0;
4190
4191 for (;;)
4192 {
4193 l = (DWORD)STRLEN(lp + written);
4194 if (l == 0)
4195 len = 0;
4196 else if (lp[written] == NL)
4197 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004198 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004199 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4200 }
4201 else
4202 {
4203 s = vim_strchr(lp + written, NL);
4204 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4205 s == NULL ? l : (DWORD)(s - (lp + written)),
4206 &len, NULL);
4207 }
4208 if (len == (int)l)
4209 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004210 // Finished a line, add a NL, unless this line should not have
4211 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004212 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004213 || (!curbuf->b_p_bin
4214 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004215 || (lnum != curbuf->b_no_eol_lnum
4216 && (lnum != curbuf->b_ml.ml_line_count
4217 || curbuf->b_p_eol)))
4218 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004219 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4220 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004221 }
4222
4223 ++lnum;
4224 if (lnum > curbuf->b_op_end.lnum)
4225 break;
4226
4227 lp = ml_get(lnum);
4228 written = 0;
4229 }
4230 else if (len > 0)
4231 written += len;
4232 }
4233
Bram Moolenaar0f873732019-12-05 20:28:46 +01004234 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004235 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004236 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004237}
4238
4239
Bram Moolenaar0f873732019-12-05 20:28:46 +01004240# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004241
4242/*
4243 * This function read from the children's stdout and write the
4244 * data on screen or in the buffer accordingly.
4245 */
4246 static void
4247dump_pipe(int options,
4248 HANDLE g_hChildStd_OUT_Rd,
4249 garray_T *ga,
4250 char_u buffer[],
4251 DWORD *buffer_off)
4252{
4253 DWORD availableBytes = 0;
4254 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004255 int ret;
4256 DWORD len;
4257 DWORD toRead;
4258 int repeatCount;
4259
Bram Moolenaar0f873732019-12-05 20:28:46 +01004260 // we query the pipe to see if there is any data to read
4261 // to avoid to perform a blocking read
4262 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4263 NULL, // optional buffer
4264 0, // buffer size
4265 NULL, // number of read bytes
4266 &availableBytes, // available bytes total
4267 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004268
4269 repeatCount = 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004270 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004271 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004272 {
4273 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004274 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004275 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004276 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004277
Bram Moolenaar0f873732019-12-05 20:28:46 +01004278 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004279 if (len == 0)
4280 break;
4281
4282 availableBytes -= len;
4283
4284 if (options & SHELL_READ)
4285 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004286 // Do NUL -> NL translation, append NL separated
4287 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004288 for (i = 0; i < len; ++i)
4289 {
4290 if (buffer[i] == NL)
4291 append_ga_line(ga);
4292 else if (buffer[i] == NUL)
4293 ga_append(ga, NL);
4294 else
4295 ga_append(ga, buffer[i]);
4296 }
4297 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004298 else if (has_mbyte)
4299 {
4300 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004301 int c;
4302 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004303
4304 len += *buffer_off;
4305 buffer[len] = NUL;
4306
Bram Moolenaar0f873732019-12-05 20:28:46 +01004307 // Check if the last character in buffer[] is
4308 // incomplete, keep these bytes for the next
4309 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004310 for (p = buffer; p < buffer + len; p += l)
4311 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004312 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004313 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004314 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004315 else if (MB_BYTE2LEN(*p) != l)
4316 break;
4317 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004318 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004319 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004320 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004321 if (len >= 12)
4322 ++p;
4323 else
4324 {
4325 *buffer_off = len;
4326 return;
4327 }
4328 }
4329 c = *p;
4330 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004331 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004332 if (p < buffer + len)
4333 {
4334 *p = c;
4335 *buffer_off = (DWORD)((buffer + len) - p);
4336 mch_memmove(buffer, p, *buffer_off);
4337 return;
4338 }
4339 *buffer_off = 0;
4340 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004341 else
4342 {
4343 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004344 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004345 }
4346
4347 windgoto(msg_row, msg_col);
4348 cursor_on();
4349 out_flush();
4350 }
4351}
4352
4353/*
4354 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4355 * for communication and doesn't open any new window.
4356 */
4357 static int
4358mch_system_piped(char *cmd, int options)
4359{
4360 STARTUPINFO si;
4361 PROCESS_INFORMATION pi;
4362 DWORD ret = 0;
4363
4364 HANDLE g_hChildStd_IN_Rd = NULL;
4365 HANDLE g_hChildStd_IN_Wr = NULL;
4366 HANDLE g_hChildStd_OUT_Rd = NULL;
4367 HANDLE g_hChildStd_OUT_Wr = NULL;
4368
Bram Moolenaar0f873732019-12-05 20:28:46 +01004369 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004370 DWORD len;
4371
Bram Moolenaar0f873732019-12-05 20:28:46 +01004372 // buffer used to receive keys
4373 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4374 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004375
4376 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004377 int noread_cnt = 0;
4378 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004379 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004380 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004381 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004382
4383 SECURITY_ATTRIBUTES saAttr;
4384
Bram Moolenaar0f873732019-12-05 20:28:46 +01004385 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004386 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4387 saAttr.bInheritHandle = TRUE;
4388 saAttr.lpSecurityDescriptor = NULL;
4389
4390 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004391 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004392 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004393 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004394 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004395 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004396 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004397 {
4398 CloseHandle(g_hChildStd_IN_Rd);
4399 CloseHandle(g_hChildStd_IN_Wr);
4400 CloseHandle(g_hChildStd_OUT_Rd);
4401 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004402 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004403 }
4404
4405 si.cb = sizeof(si);
4406 si.lpReserved = NULL;
4407 si.lpDesktop = NULL;
4408 si.lpTitle = NULL;
4409 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4410
Bram Moolenaar0f873732019-12-05 20:28:46 +01004411 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004412 si.hStdError = g_hChildStd_OUT_Wr;
4413 si.hStdOutput = g_hChildStd_OUT_Wr;
4414 si.hStdInput = g_hChildStd_IN_Rd;
4415 si.wShowWindow = SW_HIDE;
4416 si.cbReserved2 = 0;
4417 si.lpReserved2 = NULL;
4418
4419 if (options & SHELL_READ)
4420 ga_init2(&ga, 1, BUFLEN);
4421
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004422 if (cmd != NULL)
4423 {
4424 p = (char *)vim_strsave((char_u *)cmd);
4425 if (p != NULL)
4426 unescape_shellxquote((char_u *)p, p_sxe);
4427 else
4428 p = cmd;
4429 }
4430
Bram Moolenaar0f873732019-12-05 20:28:46 +01004431 // Now, run the command.
4432 // About "Inherit handles" being TRUE: this command can be litigious,
4433 // handle inheritance was deactivated for pending temp file, but, if we
4434 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004435 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4436 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004437
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004438 if (p != cmd)
4439 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004440
Bram Moolenaar0f873732019-12-05 20:28:46 +01004441 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004442 CloseHandle(g_hChildStd_IN_Rd);
4443 CloseHandle(g_hChildStd_OUT_Wr);
4444
4445 if (options & SHELL_WRITE)
4446 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004447 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004448 _beginthreadex(NULL, // security attributes
4449 0, // default stack size
4450 sub_process_writer, // function to be executed
4451 g_hChildStd_IN_Wr, // parameter
4452 0, // creation flag, start immediately
4453 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004454 CloseHandle(thread);
4455 g_hChildStd_IN_Wr = NULL;
4456 }
4457
Bram Moolenaar0f873732019-12-05 20:28:46 +01004458 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004459 for (;;)
4460 {
4461 MSG msg;
4462
K.Takatab7057bd2022-01-21 11:37:07 +00004463 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004464 {
4465 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004466 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004467 }
4468
Bram Moolenaar0f873732019-12-05 20:28:46 +01004469 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004470 if ((options & (SHELL_READ|SHELL_WRITE))
4471# ifdef FEAT_GUI
4472 || gui.in_use
4473# endif
4474 )
4475 {
4476 len = 0;
4477 if (!(options & SHELL_EXPAND)
4478 && ((options &
4479 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4480 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4481# ifdef FEAT_GUI
4482 || gui.in_use
4483# endif
4484 )
4485 && (ta_len > 0 || noread_cnt > 4))
4486 {
4487 if (ta_len == 0)
4488 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004489 // Get extra characters when we don't have any. Reset the
4490 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004491 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004492 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4493 }
4494 if (ta_len > 0 || len > 0)
4495 {
4496 /*
4497 * For pipes: Check for CTRL-C: send interrupt signal to
4498 * child. Check for CTRL-D: EOF, close pipe to child.
4499 */
4500 if (len == 1 && cmd != NULL)
4501 {
4502 if (ta_buf[ta_len] == Ctrl_C)
4503 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004504 // Learn what exit code is expected, for
4505 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004506 TerminateProcess(pi.hProcess, 9);
4507 }
4508 if (ta_buf[ta_len] == Ctrl_D)
4509 {
4510 CloseHandle(g_hChildStd_IN_Wr);
4511 g_hChildStd_IN_Wr = NULL;
4512 }
4513 }
4514
Bram Moolenaarf4140482020-02-15 23:06:45 +01004515 term_replace_bs_del_keycode(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004516
4517 /*
4518 * For pipes: echo the typed characters. For a pty this
4519 * does not seem to work.
4520 */
4521 for (i = ta_len; i < ta_len + len; ++i)
4522 {
4523 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4524 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004525 else if (has_mbyte)
4526 {
4527 int l = (*mb_ptr2len)(ta_buf + i);
4528
4529 msg_outtrans_len(ta_buf + i, l);
4530 i += l - 1;
4531 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004532 else
4533 msg_outtrans_len(ta_buf + i, 1);
4534 }
4535 windgoto(msg_row, msg_col);
4536 out_flush();
4537
4538 ta_len += len;
4539
4540 /*
4541 * Write the characters to the child, unless EOF has been
4542 * typed for pipes. Write one character at a time, to
4543 * avoid losing too much typeahead. When writing buffer
4544 * lines, drop the typed characters (only check for
4545 * CTRL-C).
4546 */
4547 if (options & SHELL_WRITE)
4548 ta_len = 0;
4549 else if (g_hChildStd_IN_Wr != NULL)
4550 {
4551 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4552 1, &len, NULL);
4553 // if we are typing in, we want to keep things reactive
4554 delay = 1;
4555 if (len > 0)
4556 {
4557 ta_len -= len;
4558 mch_memmove(ta_buf, ta_buf + len, ta_len);
4559 }
4560 }
4561 }
4562 }
4563 }
4564
4565 if (ta_len)
4566 ui_inchar_undo(ta_buf, ta_len);
4567
4568 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4569 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004570 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004571 break;
4572 }
4573
4574 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004575 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004576
Bram Moolenaar0f873732019-12-05 20:28:46 +01004577 // We start waiting for a very short time and then increase it, so
4578 // that we respond quickly when the process is quick, and don't
4579 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004580 if (delay < 50)
4581 delay += 10;
4582 }
4583
Bram Moolenaar0f873732019-12-05 20:28:46 +01004584 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004585 CloseHandle(g_hChildStd_OUT_Rd);
4586 if (g_hChildStd_IN_Wr != NULL)
4587 CloseHandle(g_hChildStd_IN_Wr);
4588
4589 WaitForSingleObject(pi.hProcess, INFINITE);
4590
Bram Moolenaar0f873732019-12-05 20:28:46 +01004591 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004592 GetExitCodeProcess(pi.hProcess, &ret);
4593
4594 if (options & SHELL_READ)
4595 {
4596 if (ga.ga_len > 0)
4597 {
4598 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01004599 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004600 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4601 }
4602 else
4603 curbuf->b_no_eol_lnum = 0;
4604 ga_clear(&ga);
4605 }
4606
Bram Moolenaar0f873732019-12-05 20:28:46 +01004607 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004608 CloseHandle(pi.hThread);
4609 CloseHandle(pi.hProcess);
4610
4611 return ret;
4612}
4613
4614 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004615mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004616{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004617 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004618 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004619 return mch_system_piped(cmd, options);
4620 else
4621 return mch_system_classic(cmd, options);
4622}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004623#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004624
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004625#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004626 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02004627mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004628{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004629 int ret;
4630 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004631 char_u *buf;
4632 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004633
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004634 // If the command starts and ends with double quotes, enclose the command
4635 // in parentheses.
4636 len = STRLEN(cmd);
4637 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
4638 {
4639 len += 3;
4640 buf = alloc(len);
4641 if (buf == NULL)
4642 return -1;
4643 vim_snprintf((char *)buf, len, "(%s)", cmd);
4644 wcmd = enc_to_utf16(buf, NULL);
4645 free(buf);
4646 }
4647 else
4648 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4649
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004650 if (wcmd == NULL)
4651 return -1;
4652
4653 ret = _wsystem(wcmd);
4654 vim_free(wcmd);
4655 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004656}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004657
4658#endif
4659
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004660 static int
4661mch_system(char *cmd, int options)
4662{
4663#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004664 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004665 return mch_system_g(cmd, options);
4666 else
4667 return mch_system_c(cmd, options);
4668#elif defined(FEAT_GUI_MSWIN)
4669 return mch_system_g(cmd, options);
4670#else
4671 return mch_system_c(cmd, options);
4672#endif
4673}
4674
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004675#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4676/*
4677 * Use a terminal window to run a shell command in.
4678 */
4679 static int
4680mch_call_shell_terminal(
4681 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004682 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004683{
4684 jobopt_T opt;
4685 char_u *newcmd = NULL;
4686 typval_T argvar[2];
4687 long_u cmdlen;
4688 int retval = -1;
4689 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004690 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004691 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004692 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004693
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004694 if (cmd == NULL)
4695 cmdlen = STRLEN(p_sh) + 1;
4696 else
4697 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004698 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004699 if (newcmd == NULL)
4700 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004701 if (cmd == NULL)
4702 {
4703 STRCPY(newcmd, p_sh);
4704 ch_log(NULL, "starting terminal to run a shell");
4705 }
4706 else
4707 {
4708 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4709 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4710 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004711
4712 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004713
4714 argvar[0].v_type = VAR_STRING;
4715 argvar[0].vval.v_string = newcmd;
4716 argvar[1].v_type = VAR_UNKNOWN;
4717 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004718 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004719 {
4720 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004721 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004722 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004723
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004724 job = term_getjob(buf->b_term);
4725 ++job->jv_refcount;
4726
Bram Moolenaar0f873732019-12-05 20:28:46 +01004727 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004728 aucmd_prepbuf(&aco, buf);
4729
4730 clear_oparg(&oa);
4731 while (term_use_loop())
4732 {
4733 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4734 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004735 // If terminal_loop() returns OK we got a key that is handled
4736 // in Normal model. We don't do redrawing anyway.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004737 if (terminal_loop(TRUE) == OK)
4738 normal_cmd(&oa, TRUE);
4739 }
4740 else
4741 normal_cmd(&oa, TRUE);
4742 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004743 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004744 ch_log(NULL, "system command finished");
4745
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004746 job_unref(job);
4747
Bram Moolenaar0f873732019-12-05 20:28:46 +01004748 // restore curwin/curbuf and a few other things
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004749 aucmd_restbuf(&aco);
4750
4751 wait_return(TRUE);
4752 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4753
4754 vim_free(newcmd);
4755 return retval;
4756}
4757#endif
4758
Bram Moolenaar071d4272004-06-13 20:20:40 +00004759/*
4760 * Either execute a command by calling the shell or start a new shell
4761 */
4762 int
4763mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004764 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004765 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00004766{
4767 int x = 0;
4768 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004769 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004770
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01004771#ifdef FEAT_JOB_CHANNEL
4772 ch_log(NULL, "executing shell command: %s", cmd);
4773#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004774 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02004775 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004776 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004777 if (cmd == NULL)
4778 wcscat(szShellTitle, L" :sh");
4779 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004780 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004781 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004782
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004783 if (wn != NULL)
4784 {
4785 wcscat(szShellTitle, L" - !");
4786 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02004787 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004788 wcscat(szShellTitle, wn);
4789 SetConsoleTitleW(szShellTitle);
4790 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004791 }
4792 }
4793 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004794
4795 out_flush();
4796
4797#ifdef MCH_WRITE_DUMP
4798 if (fdDump)
4799 {
4800 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4801 fflush(fdDump);
4802 }
4803#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004804#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004805 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004806 if (
4807# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004808 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004809# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004810 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004811 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4812 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004813 char_u *cmdbase = cmd;
4814
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004815 if (cmdbase != NULL)
4816 // Skip a leading quote and (.
4817 while (*cmdbase == '"' || *cmdbase == '(')
4818 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004819
4820 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01004821 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
4822 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004823 {
4824 // Use a terminal window to run the command in.
4825 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004826 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004827 return x;
4828 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004829 }
4830#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004831
4832 /*
4833 * Catch all deadly signals while running the external command, because a
4834 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4835 */
4836 signal(SIGINT, SIG_IGN);
4837#if defined(__GNUC__) && !defined(__MINGW32__)
4838 signal(SIGKILL, SIG_IGN);
4839#else
4840 signal(SIGBREAK, SIG_IGN);
4841#endif
4842 signal(SIGILL, SIG_IGN);
4843 signal(SIGFPE, SIG_IGN);
4844 signal(SIGSEGV, SIG_IGN);
4845 signal(SIGTERM, SIG_IGN);
4846 signal(SIGABRT, SIG_IGN);
4847
4848 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004849 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00004850
4851 if (cmd == NULL)
4852 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004853 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004854 }
4855 else
4856 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004857 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004858 char_u *newcmd = NULL;
4859 char_u *cmdbase = cmd;
4860 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004861
Bram Moolenaar0f873732019-12-05 20:28:46 +01004862 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004863 if (*cmdbase == '"' )
4864 ++cmdbase;
4865 if (*cmdbase == '(')
4866 ++cmdbase;
4867
Bram Moolenaar1c465442017-03-12 20:10:05 +01004868 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004869 {
4870 STARTUPINFO si;
4871 PROCESS_INFORMATION pi;
4872 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004873 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004874 char_u *p;
4875
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004876 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004877 si.cb = sizeof(si);
4878 si.lpReserved = NULL;
4879 si.lpDesktop = NULL;
4880 si.lpTitle = NULL;
4881 si.dwFlags = 0;
4882 si.cbReserved2 = 0;
4883 si.lpReserved2 = NULL;
4884
4885 cmdbase = skipwhite(cmdbase + 5);
4886 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004887 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004888 {
4889 cmdbase = skipwhite(cmdbase + 4);
4890 si.dwFlags = STARTF_USESHOWWINDOW;
4891 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004892 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004893 }
4894 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004895 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004896 {
4897 cmdbase = skipwhite(cmdbase + 2);
4898 flags = CREATE_NO_WINDOW;
4899 si.dwFlags = STARTF_USESTDHANDLES;
4900 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004901 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004902 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004903 NULL, // Security att.
4904 OPEN_EXISTING, // Open flags
4905 FILE_ATTRIBUTE_NORMAL, // File att.
4906 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004907 si.hStdOutput = si.hStdInput;
4908 si.hStdError = si.hStdInput;
4909 }
4910
Bram Moolenaar0f873732019-12-05 20:28:46 +01004911 // Remove a trailing ", ) and )" if they have a match
4912 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004913 if (cmdbase > cmd)
4914 {
4915 p = cmdbase + STRLEN(cmdbase);
4916 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4917 *--p = NUL;
4918 if (p > cmdbase && p[-1] == ')'
4919 && (*cmd =='(' || cmd[1] == '('))
4920 *--p = NUL;
4921 }
4922
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004923 newcmd = cmdbase;
4924 unescape_shellxquote(cmdbase, p_sxe);
4925
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004926 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004927 * If creating new console, arguments are passed to the
4928 * 'cmd.exe' as-is. If it's not, arguments are not treated
4929 * correctly for current 'cmd.exe'. So unescape characters in
4930 * shellxescape except '|' for avoiding to be treated as
4931 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004932 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004933 if (flags != CREATE_NEW_CONSOLE)
4934 {
4935 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004936 char_u *cmd_shell = mch_getenv("COMSPEC");
4937
4938 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004939 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004940
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004941 subcmd = vim_strsave_escaped_ext(cmdbase,
4942 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004943 if (subcmd != NULL)
4944 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004945 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004946 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004947 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004948 if (newcmd != NULL)
4949 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004950 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004951 else
4952 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004953 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004954 }
4955 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004956
4957 /*
4958 * Now, start the command as a process, so that it doesn't
4959 * inherit our handles which causes unpleasant dangling swap
4960 * files if we exit before the spawned process
4961 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004962 if (vim_create_process((char *)newcmd, FALSE, flags,
4963 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004964 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004965 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4966 > (HINSTANCE)32)
4967 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004968 else
4969 {
4970 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01004971#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004972# ifdef VIMDLL
4973 if (gui.in_use)
4974# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00004975 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004976#endif
4977 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004978
4979 if (newcmd != cmdbase)
4980 vim_free(newcmd);
4981
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004982 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004983 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004984 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004985 CloseHandle(si.hStdInput);
4986 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004987 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004988 CloseHandle(pi.hThread);
4989 CloseHandle(pi.hProcess);
4990 }
4991 else
4992 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004993 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01004994#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004995 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004996 (!s_dont_use_vimrun && p_stmp ?
4997 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
4998 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004999#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005000 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005001
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005002 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005003 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005004 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005005#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005006 if (
5007# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005008 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005009# endif
5010 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005011 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005012 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5013 "External commands will not pause after completion.\n"
5014 "See :help win32-vimrun for more information.");
5015 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005016 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5017 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005018
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005019 if (wmsg != NULL && wtitle != NULL)
5020 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5021 vim_free(wmsg);
5022 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005023 need_vimrun_warning = FALSE;
5024 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005025 if (
5026# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005027 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005028# endif
5029 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005030 // Use vimrun to execute the command. It opens a console
5031 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005032 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005033 vimrun_path,
5034 (msg_silent != 0 || (options & SHELL_DOOUT))
5035 ? "-s " : "",
5036 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005037 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005038# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005039 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005040# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005041 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005042 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005043 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5044 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005045 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005046#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005047 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005048 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005049 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005050 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005051 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005052 }
5053 }
5054
5055 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005056 {
5057 // The shell may have messed with the mode, always set it.
5058 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005059 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005060 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005061
Bram Moolenaar0f873732019-12-05 20:28:46 +01005062 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005063 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005064#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005065 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005066 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005067#endif
5068 )
5069 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005070 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005071 msg_putchar('\n');
5072 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005073 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005074
5075 signal(SIGINT, SIG_DFL);
5076#if defined(__GNUC__) && !defined(__MINGW32__)
5077 signal(SIGKILL, SIG_DFL);
5078#else
5079 signal(SIGBREAK, SIG_DFL);
5080#endif
5081 signal(SIGILL, SIG_DFL);
5082 signal(SIGFPE, SIG_DFL);
5083 signal(SIGSEGV, SIG_DFL);
5084 signal(SIGTERM, SIG_DFL);
5085 signal(SIGABRT, SIG_DFL);
5086
5087 return x;
5088}
5089
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005090#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005091 static HANDLE
5092job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005093 char_u *fname,
5094 DWORD dwDesiredAccess,
5095 DWORD dwShareMode,
5096 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5097 DWORD dwCreationDisposition,
5098 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005099{
5100 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005101 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005102
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005103 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005104 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005105 return INVALID_HANDLE_VALUE;
5106
5107 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5108 lpSecurityAttributes, dwCreationDisposition,
5109 dwFlagsAndAttributes, NULL);
5110 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005111 return h;
5112}
5113
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005114/*
5115 * Turn the dictionary "env" into a NUL separated list that can be used as the
5116 * environment argument of vim_create_process().
5117 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005118 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005119win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005120{
5121 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005122 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005123 LPVOID base = GetEnvironmentStringsW();
5124
Bram Moolenaar0f873732019-12-05 20:28:46 +01005125 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005126 if (ga_grow(gap, 1) == FAIL)
5127 return;
5128
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005129 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005130 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005131 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005132 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005133 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005134 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005135 typval_T *item = &dict_lookup(hi)->di_tv;
5136 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005137 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005138 --todo;
5139 if (wkey != NULL && wval != NULL)
5140 {
5141 size_t n;
5142 size_t lkey = wcslen(wkey);
5143 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005144
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005145 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5146 continue;
5147 for (n = 0; n < lkey; n++)
5148 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5149 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5150 for (n = 0; n < lval; n++)
5151 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5152 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5153 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005154 vim_free(wkey);
5155 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005156 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005157 }
5158 }
5159
Bram Moolenaar355757a2020-02-10 22:06:32 +01005160 if (base)
5161 {
5162 WCHAR *p = (WCHAR*) base;
5163
5164 // for last \0
5165 if (ga_grow(gap, 1) == FAIL)
5166 return;
5167
5168 while (*p != 0 || *(p + 1) != 0)
5169 {
5170 if (ga_grow(gap, 1) == OK)
5171 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5172 p++;
5173 }
5174 FreeEnvironmentStrings(base);
5175 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5176 }
5177
Bram Moolenaar493359e2018-06-12 20:25:52 +02005178# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005179 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005180# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005181 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005182 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005183# endif
5184# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005185 char_u *version = get_vim_var_str(VV_VERSION);
5186 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005187# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005188 // size of "VIM_SERVERNAME=" and value,
5189 // plus "VIM_TERMINAL=" and value,
5190 // plus two terminating NULs
5191 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005192# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005193 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005194# endif
5195# ifdef FEAT_TERMINAL
5196 + 13 + version_len + 2
5197# endif
5198 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005199
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005200 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005201 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005202# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005203 for (n = 0; n < 15; n++)
5204 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5205 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005206 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005207 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5208 (WCHAR)servername[n];
5209 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005210# endif
5211# ifdef FEAT_TERMINAL
5212 if (is_terminal)
5213 {
5214 for (n = 0; n < 13; n++)
5215 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5216 (WCHAR)"VIM_TERMINAL="[n];
5217 for (n = 0; n < version_len; n++)
5218 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5219 (WCHAR)version[n];
5220 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5221 }
5222# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005223 }
5224 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005225# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005226}
5227
Bram Moolenaarb091f302019-01-19 14:37:00 +01005228/*
5229 * Create a pair of pipes.
5230 * Return TRUE for success, FALSE for failure.
5231 */
5232 static BOOL
5233create_pipe_pair(HANDLE handles[2])
5234{
5235 static LONG s;
5236 char name[64];
5237 SECURITY_ATTRIBUTES sa;
5238
5239 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5240 GetCurrentProcessId(),
5241 InterlockedIncrement(&s));
5242
5243 // Create named pipe. Max size of named pipe is 65535.
5244 handles[1] = CreateNamedPipe(
5245 name,
5246 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5247 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005248 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005249
5250 if (handles[1] == INVALID_HANDLE_VALUE)
5251 return FALSE;
5252
5253 sa.nLength = sizeof(sa);
5254 sa.bInheritHandle = TRUE;
5255 sa.lpSecurityDescriptor = NULL;
5256
5257 handles[0] = CreateFile(name,
5258 FILE_GENERIC_READ,
5259 FILE_SHARE_READ, &sa,
5260 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5261
5262 if (handles[0] == INVALID_HANDLE_VALUE)
5263 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005264 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005265 return FALSE;
5266 }
5267
5268 return TRUE;
5269}
5270
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005271 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005272mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005273{
5274 STARTUPINFO si;
5275 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005276 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005277 SECURITY_ATTRIBUTES saAttr;
5278 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005279 HANDLE ifd[2];
5280 HANDLE ofd[2];
5281 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005282 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005283
5284 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5285 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5286 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5287 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5288 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5289 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5290 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5291
5292 if (use_out_for_err && use_null_for_out)
5293 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005294
5295 ifd[0] = INVALID_HANDLE_VALUE;
5296 ifd[1] = INVALID_HANDLE_VALUE;
5297 ofd[0] = INVALID_HANDLE_VALUE;
5298 ofd[1] = INVALID_HANDLE_VALUE;
5299 efd[0] = INVALID_HANDLE_VALUE;
5300 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005301 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005302
Bram Moolenaar14207f42016-10-27 21:13:10 +02005303 jo = CreateJobObject(NULL, NULL);
5304 if (jo == NULL)
5305 {
5306 job->jv_status = JOB_FAILED;
5307 goto failed;
5308 }
5309
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005310 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005311 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005312
Bram Moolenaar76467df2016-02-12 19:30:26 +01005313 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005314 ZeroMemory(&si, sizeof(si));
5315 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005316 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005317 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005318
Bram Moolenaard8070362016-02-15 21:56:54 +01005319 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5320 saAttr.bInheritHandle = TRUE;
5321 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005322
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005323 if (use_file_for_in)
5324 {
5325 char_u *fname = options->jo_io_name[PART_IN];
5326
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005327 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5328 FILE_SHARE_READ | FILE_SHARE_WRITE,
5329 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5330 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005331 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005332 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005333 goto failed;
5334 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005335 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005336 else if (!use_null_for_in
5337 && (!create_pipe_pair(ifd)
5338 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005339 goto failed;
5340
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005341 if (use_file_for_out)
5342 {
5343 char_u *fname = options->jo_io_name[PART_OUT];
5344
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005345 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5346 FILE_SHARE_READ | FILE_SHARE_WRITE,
5347 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5348 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005349 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005350 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005351 goto failed;
5352 }
5353 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005354 else if (!use_null_for_out &&
5355 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005356 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005357 goto failed;
5358
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005359 if (use_file_for_err)
5360 {
5361 char_u *fname = options->jo_io_name[PART_ERR];
5362
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005363 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5364 FILE_SHARE_READ | FILE_SHARE_WRITE,
5365 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5366 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005367 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005368 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005369 goto failed;
5370 }
5371 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005372 else if (!use_out_for_err && !use_null_for_err &&
5373 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005374 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005375 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005376
Bram Moolenaard8070362016-02-15 21:56:54 +01005377 si.dwFlags |= STARTF_USESTDHANDLES;
5378 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005379 si.hStdOutput = ofd[1];
5380 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5381
5382 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5383 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005384 if (options->jo_set & JO_CHANNEL)
5385 {
5386 channel = options->jo_channel;
5387 if (channel != NULL)
5388 ++channel->ch_refcount;
5389 }
5390 else
5391 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005392 if (channel == NULL)
5393 goto failed;
5394 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005395
5396 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005397 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005398 CREATE_DEFAULT_ERROR_MODE |
5399 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005400 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005401 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005402 &si, &pi,
5403 ga.ga_data,
5404 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005405 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005406 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005407 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005408 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005409 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005410
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005411 ga_clear(&ga);
5412
Bram Moolenaar14207f42016-10-27 21:13:10 +02005413 if (!AssignProcessToJobObject(jo, pi.hProcess))
5414 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005415 // if failing, switch the way to terminate
5416 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005417 CloseHandle(jo);
5418 jo = NULL;
5419 }
5420 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005421 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005422 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005423 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005424 job->jv_status = JOB_STARTED;
5425
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005426 CloseHandle(ifd[0]);
5427 CloseHandle(ofd[1]);
5428 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005429 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005430
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005431 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005432 if (channel != NULL)
5433 {
5434 channel_set_pipes(channel,
5435 use_file_for_in || use_null_for_in
5436 ? INVALID_FD : (sock_T)ifd[1],
5437 use_file_for_out || use_null_for_out
5438 ? INVALID_FD : (sock_T)ofd[0],
5439 use_out_for_err || use_file_for_err || use_null_for_err
5440 ? INVALID_FD : (sock_T)efd[0]);
5441 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005442 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005443 return;
5444
5445failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005446 CloseHandle(ifd[0]);
5447 CloseHandle(ofd[0]);
5448 CloseHandle(efd[0]);
5449 CloseHandle(ifd[1]);
5450 CloseHandle(ofd[1]);
5451 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005452 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005453 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005454}
5455
5456 char *
5457mch_job_status(job_T *job)
5458{
5459 DWORD dwExitCode = 0;
5460
Bram Moolenaar76467df2016-02-12 19:30:26 +01005461 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5462 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005463 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005464 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005465 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005466 {
5467 ch_log(job->jv_channel, "Job ended");
5468 job->jv_status = JOB_ENDED;
5469 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005470 return "dead";
5471 }
5472 return "run";
5473}
5474
Bram Moolenaar97792de2016-10-15 18:36:49 +02005475 job_T *
5476mch_detect_ended_job(job_T *job_list)
5477{
5478 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5479 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5480 job_T *job = job_list;
5481
5482 while (job != NULL)
5483 {
5484 DWORD n;
5485 DWORD result;
5486
5487 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5488 && job != NULL; job = job->jv_next)
5489 {
5490 if (job->jv_status == JOB_STARTED)
5491 {
5492 jobHandles[n] = job->jv_proc_info.hProcess;
5493 jobArray[n] = job;
5494 ++n;
5495 }
5496 }
5497 if (n == 0)
5498 continue;
5499 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5500 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5501 {
5502 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5503
5504 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5505 return wait_job;
5506 }
5507 }
5508 return NULL;
5509}
5510
Bram Moolenaarfb630902016-10-29 14:55:00 +02005511 static BOOL
5512terminate_all(HANDLE process, int code)
5513{
5514 PROCESSENTRY32 pe;
5515 HANDLE h = INVALID_HANDLE_VALUE;
5516 DWORD pid = GetProcessId(process);
5517
5518 if (pid != 0)
5519 {
5520 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5521 if (h != INVALID_HANDLE_VALUE)
5522 {
5523 pe.dwSize = sizeof(PROCESSENTRY32);
5524 if (!Process32First(h, &pe))
5525 goto theend;
5526
5527 do
5528 {
5529 if (pe.th32ParentProcessID == pid)
5530 {
5531 HANDLE ph = OpenProcess(
5532 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5533 if (ph != NULL)
5534 {
5535 terminate_all(ph, code);
5536 CloseHandle(ph);
5537 }
5538 }
5539 } while (Process32Next(h, &pe));
5540
5541 CloseHandle(h);
5542 }
5543 }
5544
5545theend:
5546 return TerminateProcess(process, code);
5547}
5548
5549/*
5550 * Send a (deadly) signal to "job".
5551 * Return FAIL if it didn't work.
5552 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005553 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005554mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005555{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005556 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005557
Bram Moolenaar923d9262016-02-25 20:56:01 +01005558 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005559 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005560 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02005561 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005562 {
5563 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5564 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00005565 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005566 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01005567 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005568 }
5569
5570 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5571 return FAIL;
5572 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005573 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5574 job->jv_proc_info.dwProcessId)
5575 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005576 FreeConsole();
5577 return ret;
5578}
5579
5580/*
5581 * Clear the data related to "job".
5582 */
5583 void
5584mch_clear_job(job_T *job)
5585{
5586 if (job->jv_status != JOB_FAILED)
5587 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005588 if (job->jv_job_object != NULL)
5589 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005590 CloseHandle(job->jv_proc_info.hProcess);
5591 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005592}
5593#endif
5594
Bram Moolenaar071d4272004-06-13 20:20:40 +00005595
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005596#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005597
5598/*
5599 * Start termcap mode
5600 */
5601 static void
5602termcap_mode_start(void)
5603{
5604 DWORD cmodein;
5605
5606 if (g_fTermcapMode)
5607 return;
5608
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005609 if (!p_rs && USE_VTP)
5610 vtp_printf("\033[?1049h");
5611
Bram Moolenaar071d4272004-06-13 20:20:40 +00005612 SaveConsoleBuffer(&g_cbNonTermcap);
5613
5614 if (g_cbTermcap.IsValid)
5615 {
5616 /*
5617 * We've been in termcap mode before. Restore certain screen
5618 * characteristics, including the buffer size and the window
5619 * size. Since we will be redrawing the screen, we don't need
5620 * to restore the actual contents of the buffer.
5621 */
5622 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005623 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005624 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5625 Rows = g_cbTermcap.Info.dwSize.Y;
5626 Columns = g_cbTermcap.Info.dwSize.X;
5627 }
5628 else
5629 {
5630 /*
5631 * This is our first time entering termcap mode. Clear the console
5632 * screen buffer, and resize the buffer to match the current window
5633 * size. We will use this as the size of our editing environment.
5634 */
5635 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005636 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005637 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5638 }
5639
Bram Moolenaar071d4272004-06-13 20:20:40 +00005640 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005641
5642 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005643 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005644 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005645 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005646 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
5647 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005648 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005649 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005650 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005651 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5652 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005653 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005654 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005655
5656 redraw_later_clear();
5657 g_fTermcapMode = TRUE;
5658}
5659
5660
5661/*
5662 * End termcap mode
5663 */
5664 static void
5665termcap_mode_end(void)
5666{
5667 DWORD cmodein;
5668 ConsoleBuffer *cb;
5669 COORD coord;
5670 DWORD dwDummy;
5671
5672 if (!g_fTermcapMode)
5673 return;
5674
5675 SaveConsoleBuffer(&g_cbTermcap);
5676
5677 GetConsoleMode(g_hConIn, &cmodein);
5678 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005679 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5680 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005681
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005682# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005683 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005684# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005685 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005686# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005687 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01005688 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005689 SetConsoleCursorInfo(g_hConOut, &g_cci);
5690
5691 if (p_rs || exiting)
5692 {
5693 /*
5694 * Clear anything that happens to be on the current line.
5695 */
5696 coord.X = 0;
5697 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5698 FillConsoleOutputCharacter(g_hConOut, ' ',
5699 cb->Info.dwSize.X, coord, &dwDummy);
5700 /*
5701 * The following is just for aesthetics. If we are exiting without
5702 * restoring the screen, then we want to have a prompt string
5703 * appear at the bottom line. However, the command interpreter
5704 * seems to always advance the cursor one line before displaying
5705 * the prompt string, which causes the screen to scroll. To
5706 * counter this, move the cursor up one line before exiting.
5707 */
5708 if (exiting && !p_rs)
5709 coord.Y--;
5710 /*
5711 * Position the cursor at the leftmost column of the desired row.
5712 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005713 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005714 }
5715
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005716 if (!p_rs && USE_VTP)
Bram Moolenaar0afdcf82020-04-01 18:29:10 +02005717 vtp_printf("\033[?1049l");
5718
Bram Moolenaar071d4272004-06-13 20:20:40 +00005719 g_fTermcapMode = FALSE;
5720}
Bram Moolenaar0f873732019-12-05 20:28:46 +01005721#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005722
5723
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005724#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005725 void
5726mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005727 char_u *s UNUSED,
5728 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005729{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005730 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00005731}
5732
5733#else
5734
5735/*
5736 * clear `n' chars, starting from `coord'
5737 */
5738 static void
5739clear_chars(
5740 COORD coord,
5741 DWORD n)
5742{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005743 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02005744 {
5745 DWORD dwDummy;
5746
5747 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5748 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
5749 &dwDummy);
5750 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005751 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005752 {
5753 set_console_color_rgb();
5754 gotoxy(coord.X + 1, coord.Y + 1);
5755 vtp_printf("\033[%dX", n);
5756 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005757}
5758
5759
5760/*
5761 * Clear the screen
5762 */
5763 static void
5764clear_screen(void)
5765{
5766 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005767
5768 if (!USE_VTP)
5769 clear_chars(g_coord, Rows * Columns);
5770 else
5771 {
5772 set_console_color_rgb();
5773 gotoxy(1, 1);
5774 vtp_printf("\033[2J");
5775 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005776}
5777
5778
5779/*
5780 * Clear to end of display
5781 */
5782 static void
5783clear_to_end_of_display(void)
5784{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005785 COORD save = g_coord;
5786
5787 if (!USE_VTP)
5788 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005789 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005790 else
5791 {
5792 set_console_color_rgb();
5793 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5794 vtp_printf("\033[0J");
5795
5796 gotoxy(save.X + 1, save.Y + 1);
5797 g_coord = save;
5798 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005799}
5800
5801
5802/*
5803 * Clear to end of line
5804 */
5805 static void
5806clear_to_end_of_line(void)
5807{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005808 COORD save = g_coord;
5809
5810 if (!USE_VTP)
5811 clear_chars(g_coord, Columns - g_coord.X);
5812 else
5813 {
5814 set_console_color_rgb();
5815 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5816 vtp_printf("\033[0K");
5817
5818 gotoxy(save.X + 1, save.Y + 1);
5819 g_coord = save;
5820 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005821}
5822
5823
5824/*
5825 * Scroll the scroll region up by `cLines' lines
5826 */
5827 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005828scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005829{
5830 COORD oldcoord = g_coord;
5831
5832 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5833 delete_lines(cLines);
5834
5835 g_coord = oldcoord;
5836}
5837
5838
5839/*
5840 * Set the scroll region
5841 */
5842 static void
5843set_scroll_region(
5844 unsigned left,
5845 unsigned top,
5846 unsigned right,
5847 unsigned bottom)
5848{
5849 if (left >= right
5850 || top >= bottom
5851 || right > (unsigned) Columns - 1
5852 || bottom > (unsigned) Rows - 1)
5853 return;
5854
5855 g_srScrollRegion.Left = left;
5856 g_srScrollRegion.Top = top;
5857 g_srScrollRegion.Right = right;
5858 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005859}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005860
Bram Moolenaar6982f422019-02-16 16:48:01 +01005861 static void
5862set_scroll_region_tb(
5863 unsigned top,
5864 unsigned bottom)
5865{
5866 if (top >= bottom || bottom > (unsigned)Rows - 1)
5867 return;
5868
5869 g_srScrollRegion.Top = top;
5870 g_srScrollRegion.Bottom = bottom;
5871}
5872
5873 static void
5874set_scroll_region_lr(
5875 unsigned left,
5876 unsigned right)
5877{
5878 if (left >= right || right > (unsigned)Columns - 1)
5879 return;
5880
5881 g_srScrollRegion.Left = left;
5882 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005883}
5884
5885
5886/*
5887 * Insert `cLines' lines at the current cursor position
5888 */
5889 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005890insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005891{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005892 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005893 COORD dest;
5894 CHAR_INFO fill;
5895
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005896 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5897
Bram Moolenaar6982f422019-02-16 16:48:01 +01005898 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005899 dest.Y = g_coord.Y + cLines;
5900
Bram Moolenaar6982f422019-02-16 16:48:01 +01005901 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005902 source.Top = g_coord.Y;
5903 source.Right = g_srScrollRegion.Right;
5904 source.Bottom = g_srScrollRegion.Bottom - cLines;
5905
Bram Moolenaar6982f422019-02-16 16:48:01 +01005906 clip.Left = g_srScrollRegion.Left;
5907 clip.Top = g_coord.Y;
5908 clip.Right = g_srScrollRegion.Right;
5909 clip.Bottom = g_srScrollRegion.Bottom;
5910
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005911 fill.Char.AsciiChar = ' ';
5912 if (!USE_VTP)
5913 fill.Attributes = g_attrCurrent;
5914 else
5915 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005916
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005917 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005918
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005919 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5920
Bram Moolenaar6982f422019-02-16 16:48:01 +01005921 // Here we have to deal with a win32 console flake: If the scroll
5922 // region looks like abc and we scroll c to a and fill with d we get
5923 // cbd... if we scroll block c one line at a time to a, we get cdd...
5924 // vim expects cdd consistently... So we have to deal with that
5925 // here... (this also occurs scrolling the same way in the other
5926 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005927
5928 if (source.Bottom < dest.Y)
5929 {
5930 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005931 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005932
Bram Moolenaar6982f422019-02-16 16:48:01 +01005933 coord.X = source.Left;
5934 for (i = clip.Top; i < dest.Y; ++i)
5935 {
5936 coord.Y = i;
5937 clear_chars(coord, source.Right - source.Left + 1);
5938 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005939 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02005940
5941 if (USE_WT)
5942 {
5943 COORD coord;
5944 int i;
5945
5946 coord.X = source.Left;
5947 for (i = source.Top; i < dest.Y; ++i)
5948 {
5949 coord.Y = i;
5950 clear_chars(coord, source.Right - source.Left + 1);
5951 }
5952 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005953}
5954
5955
5956/*
5957 * Delete `cLines' lines at the current cursor position
5958 */
5959 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005960delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005961{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005962 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005963 COORD dest;
5964 CHAR_INFO fill;
5965 int nb;
5966
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005967 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5968
Bram Moolenaar6982f422019-02-16 16:48:01 +01005969 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005970 dest.Y = g_coord.Y;
5971
Bram Moolenaar6982f422019-02-16 16:48:01 +01005972 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005973 source.Top = g_coord.Y + cLines;
5974 source.Right = g_srScrollRegion.Right;
5975 source.Bottom = g_srScrollRegion.Bottom;
5976
Bram Moolenaar6982f422019-02-16 16:48:01 +01005977 clip.Left = g_srScrollRegion.Left;
5978 clip.Top = g_coord.Y;
5979 clip.Right = g_srScrollRegion.Right;
5980 clip.Bottom = g_srScrollRegion.Bottom;
5981
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005982 fill.Char.AsciiChar = ' ';
5983 if (!USE_VTP)
5984 fill.Attributes = g_attrCurrent;
5985 else
5986 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005987
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005988 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005989
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005990 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5991
Bram Moolenaar6982f422019-02-16 16:48:01 +01005992 // Here we have to deal with a win32 console flake; See insert_lines()
5993 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005994
5995 nb = dest.Y + (source.Bottom - source.Top) + 1;
5996
5997 if (nb < source.Top)
5998 {
5999 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006000 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006001
Bram Moolenaar6982f422019-02-16 16:48:01 +01006002 coord.X = source.Left;
6003 for (i = nb; i < clip.Bottom; ++i)
6004 {
6005 coord.Y = i;
6006 clear_chars(coord, source.Right - source.Left + 1);
6007 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006008 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006009
6010 if (USE_WT)
6011 {
6012 COORD coord;
6013 int i;
6014
6015 coord.X = source.Left;
6016 for (i = nb; i <= source.Bottom; ++i)
6017 {
6018 coord.Y = i;
6019 clear_chars(coord, source.Right - source.Left + 1);
6020 }
6021 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006022}
6023
6024
6025/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006026 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006027 */
6028 static void
6029gotoxy(
6030 unsigned x,
6031 unsigned y)
6032{
6033 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6034 return;
6035
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006036 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006037 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006038 // There are reports of double-width characters not displayed
6039 // correctly. This workaround should fix it, similar to how it's done
6040 // for VTP.
6041 g_coord.X = 0;
6042 SetConsoleCursorPosition(g_hConOut, g_coord);
6043
Bram Moolenaar2313b612019-09-27 14:14:32 +02006044 // external cursor coords are 1-based; internal are 0-based
6045 g_coord.X = x - 1;
6046 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006047 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006048 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006049 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006050 {
6051 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006052 // destruction. Insider build bug. Always enabled because it's cheap
6053 // and avoids mistakes with recognizing the build.
6054 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006055
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006056 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006057
6058 g_coord.X = x - 1;
6059 g_coord.Y = y - 1;
6060 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006061}
6062
6063
6064/*
6065 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006066 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006067 */
6068 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006069textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006070{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006071 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006072
6073 SetConsoleTextAttribute(g_hConOut, wAttr);
6074}
6075
6076
6077 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006078textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006079{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006080 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006081
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006082 if (!USE_VTP)
6083 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6084 else
6085 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006086}
6087
6088
6089 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006090textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006091{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006092 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006093
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006094 if (!USE_VTP)
6095 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6096 else
6097 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006098}
6099
6100
6101/*
6102 * restore the default text attribute (whatever we started with)
6103 */
6104 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006105normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006106{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006107 if (!USE_VTP)
6108 textattr(g_attrDefault);
6109 else
6110 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006111}
6112
6113
6114static WORD g_attrPreStandout = 0;
6115
6116/*
6117 * Make the text standout, by brightening it
6118 */
6119 static void
6120standout(void)
6121{
6122 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006123
Bram Moolenaar071d4272004-06-13 20:20:40 +00006124 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6125}
6126
6127
6128/*
6129 * Turn off standout mode
6130 */
6131 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006132standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006133{
6134 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006135 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006136
6137 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006138}
6139
6140
6141/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006142 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006143 */
6144 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006145mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006146{
6147 char_u *p;
6148 int n;
6149
6150 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6151 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006152 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006153# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006154 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006155# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006156 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006157 {
6158 p = T_ME + 2;
6159 n = getdigits(&p);
6160 if (*p == 'm' && n > 0)
6161 {
6162 cterm_normal_fg_color = (n & 0xf) + 1;
6163 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6164 }
6165 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006166# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006167 cterm_normal_fg_gui_color = INVALCOLOR;
6168 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006169# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006170}
6171
6172
6173/*
6174 * visual bell: flash the screen
6175 */
6176 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006177visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006178{
6179 COORD coordOrigin = {0, 0};
6180 WORD attrFlash = ~g_attrCurrent & 0xff;
6181
6182 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006183 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006184
6185 if (oldattrs == NULL)
6186 return;
6187 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6188 coordOrigin, &dwDummy);
6189 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6190 coordOrigin, &dwDummy);
6191
Bram Moolenaar0f873732019-12-05 20:28:46 +01006192 Sleep(15); // wait for 15 msec
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006193 if (!USE_VTP)
6194 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006195 coordOrigin, &dwDummy);
6196 vim_free(oldattrs);
6197}
6198
6199
6200/*
6201 * Make the cursor visible or invisible
6202 */
6203 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006204cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006205{
6206 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006207
6208 if (USE_VTP)
6209 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6210
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006211# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006212 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006213# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006214}
6215
6216
6217/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006218 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006219 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006220 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006221 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006222write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006223 char_u *pchBuf,
6224 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006225{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006226 COORD coord = g_coord;
6227 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006228 DWORD n, cchwritten;
6229 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006230 static WCHAR *unicodebuf = NULL;
6231 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006232 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006233 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006234 static WCHAR *utf8spbuf = NULL;
6235 static int utf8splength;
6236 static DWORD utf8spcells;
6237 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006238
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006239 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006240 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006241 utf8usingbuf = &unicodebuf;
6242 do
6243 {
6244 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6245 unicodebuf, unibuflen);
6246 if (length && length <= unibuflen)
6247 break;
6248 vim_free(unicodebuf);
6249 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6250 unibuflen = unibuflen ? 0 : length;
6251 } while(1);
6252 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006253 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006254 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6255 {
6256 if (utf8usingbuf != &utf8spbuf)
6257 {
6258 if (utf8spbuf == NULL)
6259 {
6260 cells = mb_string2cells((char_u *)" ", 1);
6261 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6262 utf8spbuf = LALLOC_MULT(WCHAR, length);
6263 if (utf8spbuf != NULL)
6264 {
6265 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6266 utf8usingbuf = &utf8spbuf;
6267 utf8splength = length;
6268 utf8spcells = cells;
6269 }
6270 }
6271 else
6272 {
6273 utf8usingbuf = &utf8spbuf;
6274 length = utf8splength;
6275 cells = utf8spcells;
6276 }
6277 }
6278 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006279
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006280 if (!USE_VTP)
6281 {
6282 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6283 coord, &written);
6284 // When writing fails or didn't write a single character, pretend one
6285 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006286 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006287 coord, &cchwritten) == 0
6288 || cchwritten == 0 || cchwritten == (DWORD)-1)
6289 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006290 }
6291 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006292 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006293 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006294 NULL) == 0 || cchwritten == 0)
6295 cchwritten = 1;
6296 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006297
K.Takata135e1522022-01-29 15:27:58 +00006298 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006299 {
6300 written = cbToWrite;
6301 g_coord.X += (SHORT)cells;
6302 }
6303 else
6304 {
6305 char_u *p = pchBuf;
6306 for (n = 0; n < cchwritten; n++)
6307 MB_CPTR_ADV(p);
6308 written = p - pchBuf;
6309 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006310 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006311
6312 while (g_coord.X > g_srScrollRegion.Right)
6313 {
6314 g_coord.X -= (SHORT) Columns;
6315 if (g_coord.Y < g_srScrollRegion.Bottom)
6316 g_coord.Y++;
6317 }
6318
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006319 // Cursor under VTP is always in the correct position, no need to reset.
6320 if (!USE_VTP)
6321 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006322
6323 return written;
6324}
6325
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006326 static char_u *
6327get_seq(
6328 int *args,
6329 int *count,
6330 char_u *head)
6331{
6332 int argc;
6333 char_u *p;
6334
6335 if (head == NULL || *head != '\033')
6336 return NULL;
6337
6338 argc = 0;
6339 p = head;
6340 ++p;
6341 do
6342 {
6343 ++p;
6344 args[argc] = getdigits(&p);
6345 argc += (argc < 15) ? 1 : 0;
6346 } while (*p == ';');
6347 *count = argc;
6348
6349 return p;
6350}
6351
6352 static char_u *
6353get_sgr(
6354 int *args,
6355 int *count,
6356 char_u *head)
6357{
6358 char_u *p = get_seq(args, count, head);
6359
6360 return (p && *p == 'm') ? ++p : NULL;
6361}
6362
6363/*
6364 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6365 */
6366 static char_u *
6367sgrn2(
6368 char_u *head,
6369 int n)
6370{
6371 int argc;
6372 int args[16];
6373 char_u *p = get_sgr(args, &argc, head);
6374
6375 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6376}
6377
6378/*
6379 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6380 */
6381 static char_u *
6382sgrnc(
6383 char_u *head,
6384 int n)
6385{
6386 int argc;
6387 int args[16];
6388 char_u *p = get_sgr(args, &argc, head);
6389
6390 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6391 ? p : NULL;
6392}
6393
6394 static char_u *
6395skipblank(char_u *q)
6396{
6397 char_u *p = q;
6398
6399 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6400 ++p;
6401 return p;
6402}
6403
6404/*
6405 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6406 * NULL.
6407 */
6408 static char_u *
6409sgrn2c(
6410 char_u *head,
6411 int n)
6412{
6413 char_u *p = sgrn2(head, n);
6414
6415 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6416}
6417
6418/*
6419 * If there is only a newline between the sequence immediately following it,
6420 * a pointer to the character following the newline is returned.
6421 * Otherwise NULL.
6422 */
6423 static char_u *
6424sgrn2cn(
6425 char_u *head,
6426 int n)
6427{
6428 char_u *p = sgrn2(head, n);
6429
6430 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6431}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006432
6433/*
6434 * mch_write(): write the output buffer to the screen, translating ESC
6435 * sequences into calls to console output routines.
6436 */
6437 void
6438mch_write(
6439 char_u *s,
6440 int len)
6441{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006442 char_u *end = s + len;
6443
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006444# ifdef VIMDLL
6445 if (gui.in_use)
6446 return;
6447# endif
6448
Bram Moolenaar071d4272004-06-13 20:20:40 +00006449 if (!term_console)
6450 {
6451 write(1, s, (unsigned)len);
6452 return;
6453 }
6454
Bram Moolenaar0f873732019-12-05 20:28:46 +01006455 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00006456 while (len--)
6457 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006458 int prefix = -1;
6459 char_u ch;
6460
6461 // While processing a sequence, on rare occasions it seems that another
6462 // sequence may be inserted asynchronously.
6463 if (len < 0)
6464 {
6465 redraw_all_later(CLEAR);
6466 return;
6467 }
6468
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006469 while (s + ++prefix < end)
6470 {
6471 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006472 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6473 && ch != '\a' && ch != '\033'))
6474 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006475 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006476
6477 if (p_wd)
6478 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006479 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006480 if (prefix != 0)
6481 prefix = 1;
6482 }
6483
6484 if (prefix != 0)
6485 {
6486 DWORD nWritten;
6487
6488 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006489# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006490 if (fdDump)
6491 {
6492 fputc('>', fdDump);
6493 fwrite(s, sizeof(char_u), nWritten, fdDump);
6494 fputs("<\n", fdDump);
6495 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006496# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006497 len -= (nWritten - 1);
6498 s += nWritten;
6499 }
6500 else if (s[0] == '\n')
6501 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006502 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00006503 if (g_coord.Y == g_srScrollRegion.Bottom)
6504 {
6505 scroll(1);
6506 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6507 }
6508 else
6509 {
6510 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6511 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006512# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006513 if (fdDump)
6514 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006515# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006516 s++;
6517 }
6518 else if (s[0] == '\r')
6519 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006520 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00006521 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006522# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006523 if (fdDump)
6524 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006525# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006526 s++;
6527 }
6528 else if (s[0] == '\b')
6529 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006530 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00006531 if (g_coord.X > g_srScrollRegion.Left)
6532 g_coord.X--;
6533 else if (g_coord.Y > g_srScrollRegion.Top)
6534 {
6535 g_coord.X = g_srScrollRegion.Right;
6536 g_coord.Y--;
6537 }
6538 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006539# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006540 if (fdDump)
6541 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006542# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006543 s++;
6544 }
6545 else if (s[0] == '\a')
6546 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006547 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00006548 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006549# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006550 if (fdDump)
6551 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006552# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006553 s++;
6554 }
6555 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6556 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006557# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006558 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006559# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006560 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006561 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006562 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006563
6564 switch (s[2])
6565 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006566 case '0': case '1': case '2': case '3': case '4':
6567 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006568 if (*(p = get_seq(args, &argc, s)) != 'm')
6569 goto notsgr;
6570
6571 p = s;
6572
6573 // Handling frequent optional sequences. Output to the screen
6574 // takes too long, so do not output as much as possible.
6575
6576 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
6577 // resetFG,FG,BG are omitted.
6578 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006579 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006580 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
6581 len = len + 1 - (int)(p - s);
6582 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006583 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006584 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006585
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006586 // If FG,BG,BG,FG of SGR are connected, the first FG can be
6587 // omitted.
6588 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
6589 p = sp;
6590
6591 // If FG,BG,FG,BG of SGR are connected, the first FG can be
6592 // omitted.
6593 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
6594 p = sp;
6595
6596 // If BG,BG of SGR are connected, the first BG can be omitted.
6597 if (sgrn2((sp = sgrn2(p, 48)), 48))
6598 p = sp;
6599
6600 // If restoreFG and FG are connected, the restoreFG can be
6601 // omitted.
6602 if (sgrn2((sp = sgrnc(p, 39)), 38))
6603 p = sp;
6604
6605 p = get_seq(args, &argc, p);
6606
6607notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006608 arg1 = args[0];
6609 arg2 = args[1];
6610 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006611 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006612 if (argc == 1 && args[0] == 0)
6613 normvideo();
6614 else if (argc == 1)
6615 {
6616 if (USE_VTP)
6617 textcolor((WORD) arg1);
6618 else
6619 textattr((WORD) arg1);
6620 }
6621 else if (USE_VTP)
6622 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006623 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006624 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006625 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006626 gotoxy(arg2, arg1);
6627 }
6628 else if (argc == 2 && *p == 'r')
6629 {
6630 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6631 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006632 else if (argc == 2 && *p == 'R')
6633 {
6634 set_scroll_region_tb(arg1, arg2);
6635 }
6636 else if (argc == 2 && *p == 'V')
6637 {
6638 set_scroll_region_lr(arg1, arg2);
6639 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006640 else if (argc == 1 && *p == 'A')
6641 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006642 gotoxy(g_coord.X + 1,
6643 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6644 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006645 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006646 {
6647 textbackground((WORD) arg1);
6648 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006649 else if (argc == 1 && *p == 'C')
6650 {
6651 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6652 g_coord.Y + 1);
6653 }
6654 else if (argc == 1 && *p == 'f')
6655 {
6656 textcolor((WORD) arg1);
6657 }
6658 else if (argc == 1 && *p == 'H')
6659 {
6660 gotoxy(1, arg1);
6661 }
6662 else if (argc == 1 && *p == 'L')
6663 {
6664 insert_lines(arg1);
6665 }
6666 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006667 {
6668 delete_lines(arg1);
6669 }
6670
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006671 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006672 s = p + 1;
6673 break;
6674
Bram Moolenaar071d4272004-06-13 20:20:40 +00006675 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006676 gotoxy(g_coord.X + 1,
6677 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6678 goto got3;
6679
6680 case 'B':
6681 visual_bell();
6682 goto got3;
6683
6684 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006685 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6686 g_coord.Y + 1);
6687 goto got3;
6688
6689 case 'E':
6690 termcap_mode_end();
6691 goto got3;
6692
6693 case 'F':
6694 standout();
6695 goto got3;
6696
6697 case 'f':
6698 standend();
6699 goto got3;
6700
6701 case 'H':
6702 gotoxy(1, 1);
6703 goto got3;
6704
6705 case 'j':
6706 clear_to_end_of_display();
6707 goto got3;
6708
6709 case 'J':
6710 clear_screen();
6711 goto got3;
6712
6713 case 'K':
6714 clear_to_end_of_line();
6715 goto got3;
6716
6717 case 'L':
6718 insert_lines(1);
6719 goto got3;
6720
6721 case 'M':
6722 delete_lines(1);
6723 goto got3;
6724
6725 case 'S':
6726 termcap_mode_start();
6727 goto got3;
6728
6729 case 'V':
6730 cursor_visible(TRUE);
6731 goto got3;
6732
6733 case 'v':
6734 cursor_visible(FALSE);
6735 goto got3;
6736
6737 got3:
6738 s += 3;
6739 len -= 2;
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 {
6745 fputs("ESC | ", fdDump);
6746 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6747 fputc('\n', fdDump);
6748 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006749# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006750 }
6751 else
6752 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006753 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00006754 DWORD nWritten;
6755
6756 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006757# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006758 if (fdDump)
6759 {
6760 fputc('>', fdDump);
6761 fwrite(s, sizeof(char_u), nWritten, fdDump);
6762 fputs("<\n", fdDump);
6763 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006764# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006765
6766 len -= (nWritten - 1);
6767 s += nWritten;
6768 }
6769 }
6770
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006771# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006772 if (fdDump)
6773 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006774# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006775}
6776
Bram Moolenaar0f873732019-12-05 20:28:46 +01006777#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006778
6779
6780/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006781 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006782 */
6783 void
6784mch_delay(
6785 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02006786 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006787{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006788#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006789 Sleep((int)msec); // never wait for input
6790#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006791# ifdef VIMDLL
6792 if (gui.in_use)
6793 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006794 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006795 return;
6796 }
6797# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02006798 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006799# ifdef FEAT_MZSCHEME
6800 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6801 {
6802 int towait = p_mzq;
6803
Bram Moolenaar0f873732019-12-05 20:28:46 +01006804 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006805 while (msec > 0)
6806 {
6807 mzvim_check_threads();
6808 if (msec < towait)
6809 towait = msec;
6810 Sleep(towait);
6811 msec -= towait;
6812 }
6813 }
6814 else
6815# endif
6816 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006817 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006818 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006819#endif
6820}
6821
6822
6823/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006824 * This version of remove is not scared by a readonly (backup) file.
6825 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006826 * Return 0 for success, -1 for failure.
6827 */
6828 int
6829mch_remove(char_u *name)
6830{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006831 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006832 int n;
6833
Bram Moolenaar203258c2016-01-17 22:15:16 +01006834 /*
6835 * On Windows, deleting a directory's symbolic link is done by
6836 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6837 */
6838 if (mch_isdir(name) && mch_is_symbolic_link(name))
6839 return mch_rmdir(name);
6840
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006841 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6842
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006843 wn = enc_to_utf16(name, NULL);
6844 if (wn == NULL)
6845 return -1;
6846
6847 n = DeleteFileW(wn) ? 0 : -1;
6848 vim_free(wn);
6849 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006850}
6851
6852
6853/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006854 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006855 */
6856 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006857mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006858{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006859#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
6860# ifdef VIMDLL
6861 if (!gui.in_use)
6862# endif
6863 if (g_fCtrlCPressed || g_fCBrkPressed)
6864 {
6865 ctrl_break_was_pressed = g_fCBrkPressed;
6866 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6867 got_int = TRUE;
6868 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006869#endif
6870}
6871
Bram Moolenaar0f873732019-12-05 20:28:46 +01006872// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01006873#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006874
6875/*
6876 * How much main memory in KiB that can be used by VIM.
6877 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006878 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006879mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006880{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006881 MEMORYSTATUSEX ms;
6882
Bram Moolenaar0f873732019-12-05 20:28:46 +01006883 // Need to use GlobalMemoryStatusEx() when there is more memory than
6884 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006885 ms.dwLength = sizeof(MEMORYSTATUSEX);
6886 GlobalMemoryStatusEx(&ms);
6887 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006888 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006889 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006890 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006891 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006892 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006893 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006894 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006895 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006896 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01006897 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006898 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006899}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006900
Bram Moolenaar071d4272004-06-13 20:20:40 +00006901/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006902 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00006903 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6904 * file whose short file name is "FOO.BAR" (its long file name will
6905 * be correct: "foo.bar~"). Because a file can be accessed by
6906 * either its SFN or its LFN, "foo.bar" has effectively been
6907 * renamed to "foo.bar", which is not at all what was wanted. This
6908 * seems to happen only when renaming files with three-character
6909 * extensions by appending a suffix that does not include ".".
6910 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6911 *
6912 * There is another problem, which isn't really a bug but isn't right either:
6913 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6914 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6915 * service pack 6. Doesn't seem to happen on Windows 98.
6916 *
6917 * Like rename(), returns 0 upon success, non-zero upon failure.
6918 * Should probably set errno appropriately when errors occur.
6919 */
6920 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006921mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006922{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006923 WCHAR *p;
6924 int i;
6925 WCHAR szTempFile[_MAX_PATH + 1];
6926 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006927 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006928
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006929 // No need to play tricks unless the file name contains a "~" as the
6930 // seventh character.
6931 p = wold;
6932 for (i = 0; wold[i] != NUL; ++i)
6933 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6934 && wold[i + 1] != 0)
6935 p = wold + i + 1;
6936 if ((int)(wold + i - p) < 8 || p[6] != '~')
6937 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006938
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006939 // Get base path of new file name. Undocumented feature: If pszNewFile is
6940 // a directory, no error is returned and pszFilePart will be NULL.
6941 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006942 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006943 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006944
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006945 // Get (and create) a unique temporary file name in directory of new file
6946 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006947 return -2;
6948
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006949 // blow the temp file away
6950 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006951 return -3;
6952
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006953 // rename old file to the temp file
6954 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006955 return -4;
6956
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006957 // now create an empty file called pszOldFile; this prevents the operating
6958 // system using pszOldFile as an alias (SFN) if we're renaming within the
6959 // same directory. For example, we're editing a file called
6960 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6961 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
6962 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
6963 // cause all sorts of problems later in buf_write(). So, we create an
6964 // empty file called filena~1.txt and the system will have to find some
6965 // other SFN for filena~1.txt~, such as filena~2.txt
6966 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006967 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6968 return -5;
6969 if (!CloseHandle(hf))
6970 return -6;
6971
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006972 // rename the temp file to the new file
6973 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006974 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006975 // Renaming failed. Rename the file back to its old name, so that it
6976 // looks like nothing happened.
6977 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006978 return -7;
6979 }
6980
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006981 // Seems to be left around on Novell filesystems
6982 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006983
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006984 // finally, remove the empty old file
6985 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006986 return -8;
6987
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006988 return 0;
6989}
6990
6991
6992/*
6993 * Converts the filenames to UTF-16, then call mch_wrename().
6994 * Like rename(), returns 0 upon success, non-zero upon failure.
6995 */
6996 int
6997mch_rename(
6998 const char *pszOldFile,
6999 const char *pszNewFile)
7000{
7001 WCHAR *wold = NULL;
7002 WCHAR *wnew = NULL;
7003 int retval = -1;
7004
7005 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7006 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7007 if (wold != NULL && wnew != NULL)
7008 retval = mch_wrename(wold, wnew);
7009 vim_free(wold);
7010 vim_free(wnew);
7011 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007012}
7013
7014/*
7015 * Get the default shell for the current hardware platform
7016 */
7017 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007018default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007019{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007020 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007021}
7022
7023/*
7024 * mch_access() extends access() to do more detailed check on network drives.
7025 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7026 */
7027 int
7028mch_access(char *n, int p)
7029{
7030 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007031 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007032 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007033
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007034 wn = enc_to_utf16((char_u *)n, NULL);
7035 if (wn == NULL)
7036 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007037
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007038 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007039 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007040 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007041
7042 if (p & R_OK)
7043 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007044 // Read check is performed by seeing if we can do a find file on
7045 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007046 int i;
7047 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007048
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007049 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7050 TempNameW[i] = wn[i];
7051 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7052 TempNameW[i++] = '\\';
7053 TempNameW[i++] = '*';
7054 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007055
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007056 hFile = FindFirstFileW(TempNameW, &d);
7057 if (hFile == INVALID_HANDLE_VALUE)
7058 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007059 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007060 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007061 }
7062
7063 if (p & W_OK)
7064 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007065 // Trying to create a temporary file in the directory should catch
7066 // directories on read-only network shares. However, in
7067 // directories whose ACL allows writes but denies deletes will end
7068 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007069 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7070 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007071 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007072 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007073 }
7074 }
7075 else
7076 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007077 // Don't consider a file read-only if another process has opened it.
7078 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7079
Bram Moolenaar0f873732019-12-05 20:28:46 +01007080 // Trying to open the file for the required access does ACL, read-only
7081 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007082 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7083 | ((p & R_OK) ? GENERIC_READ : 0);
7084
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007085 hFile = CreateFileW(wn, access_mode, share_mode,
7086 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007087 if (hFile == INVALID_HANDLE_VALUE)
7088 goto getout;
7089 CloseHandle(hFile);
7090 }
7091
Bram Moolenaar0f873732019-12-05 20:28:46 +01007092 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007093getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007094 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007095 return retval;
7096}
7097
Bram Moolenaar071d4272004-06-13 20:20:40 +00007098/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007099 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007100 */
7101 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007102mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007103{
7104 WCHAR *wn;
7105 int f;
7106
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007107 wn = enc_to_utf16((char_u *)name, NULL);
7108 if (wn == NULL)
7109 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007110
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007111 f = _wopen(wn, flags, mode);
7112 vim_free(wn);
7113 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007114}
7115
7116/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007117 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007118 */
7119 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007120mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007121{
7122 WCHAR *wn, *wm;
7123 FILE *f = NULL;
7124
Bram Moolenaara12a1612019-01-24 16:39:02 +01007125#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007126 // Work around an annoying assertion in the Microsoft debug CRT
7127 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007128 char newMode = mode[strlen(mode) - 1];
7129 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007130
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007131 _get_fmode(&oldMode);
7132 if (newMode == 't')
7133 _set_fmode(_O_TEXT);
7134 else if (newMode == 'b')
7135 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007136#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007137 wn = enc_to_utf16((char_u *)name, NULL);
7138 wm = enc_to_utf16((char_u *)mode, NULL);
7139 if (wn != NULL && wm != NULL)
7140 f = _wfopen(wn, wm);
7141 vim_free(wn);
7142 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007143
Bram Moolenaara12a1612019-01-24 16:39:02 +01007144#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007145 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007146#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007147 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007148}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007149
Bram Moolenaar071d4272004-06-13 20:20:40 +00007150/*
7151 * SUB STREAM (aka info stream) handling:
7152 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007153 * NTFS can have sub streams for each file. The normal contents of a file is
7154 * stored in the main stream, and extra contents (author information, title and
7155 * so on) can be stored in a sub stream. After Windows 2000, the user can
7156 * access and store this information in sub streams via an explorer's property
7157 * menu item in the right click menu. This information in sub streams was lost
7158 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007159 *
7160 * Incomplete explanation:
7161 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7162 * More useful info and an example:
7163 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7164 */
7165
7166/*
7167 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7168 * and write to stream "substream" of file "to".
7169 * Errors are ignored.
7170 */
7171 static void
7172copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7173{
7174 HANDLE hTo;
7175 WCHAR *to_name;
7176
7177 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7178 wcscpy(to_name, to);
7179 wcscat(to_name, substream);
7180
7181 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7182 FILE_ATTRIBUTE_NORMAL, NULL);
7183 if (hTo != INVALID_HANDLE_VALUE)
7184 {
7185 long done;
7186 DWORD todo;
7187 DWORD readcnt, written;
7188 char buf[4096];
7189
Bram Moolenaar0f873732019-12-05 20:28:46 +01007190 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007191 for (done = 0; done < len; done += written)
7192 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007193 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007194 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7195 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007196 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7197 FALSE, FALSE, context)
7198 || readcnt != todo
7199 || !WriteFile(hTo, buf, todo, &written, NULL)
7200 || written != todo)
7201 break;
7202 }
7203 CloseHandle(hTo);
7204 }
7205
7206 free(to_name);
7207}
7208
7209/*
7210 * Copy info streams from file "from" to file "to".
7211 */
7212 static void
7213copy_infostreams(char_u *from, char_u *to)
7214{
7215 WCHAR *fromw;
7216 WCHAR *tow;
7217 HANDLE sh;
7218 WIN32_STREAM_ID sid;
7219 int headersize;
7220 WCHAR streamname[_MAX_PATH];
7221 DWORD readcount;
7222 void *context = NULL;
7223 DWORD lo, hi;
7224 int len;
7225
Bram Moolenaar0f873732019-12-05 20:28:46 +01007226 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007227 fromw = enc_to_utf16(from, NULL);
7228 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007229 if (fromw != NULL && tow != NULL)
7230 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007231 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007232 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7233 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7234 if (sh != INVALID_HANDLE_VALUE)
7235 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007236 // Use BackupRead() to find the info streams. Repeat until we
7237 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007238 for (;;)
7239 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007240 // Get the header to find the length of the stream name. If
7241 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007242 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007243 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007244 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7245 &readcount, FALSE, FALSE, &context)
7246 || readcount == 0)
7247 break;
7248
Bram Moolenaar0f873732019-12-05 20:28:46 +01007249 // We only deal with streams that have a name. The normal
7250 // file data appears to be without a name, even though docs
7251 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007252 if (sid.dwStreamNameSize > 0)
7253 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007254 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007255 if (!BackupRead(sh, (LPBYTE)streamname,
7256 sid.dwStreamNameSize,
7257 &readcount, FALSE, FALSE, &context))
7258 break;
7259
Bram Moolenaar0f873732019-12-05 20:28:46 +01007260 // Copy an info stream with a name ":anything:$DATA".
7261 // Skip "::$DATA", it has no stream name (examples suggest
7262 // it might be used for the normal file contents).
7263 // Note that BackupRead() counts bytes, but the name is in
7264 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007265 len = readcount / sizeof(WCHAR);
7266 streamname[len] = 0;
7267 if (len > 7 && wcsicmp(streamname + len - 6,
7268 L":$DATA") == 0)
7269 {
7270 streamname[len - 6] = 0;
7271 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007272 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007273 }
7274 }
7275
Bram Moolenaar0f873732019-12-05 20:28:46 +01007276 // Advance to the next stream. We might try seeking too far,
7277 // but BackupSeek() doesn't skip over stream borders, thus
7278 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007279 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007280 &lo, &hi, &context);
7281 }
7282
Bram Moolenaar0f873732019-12-05 20:28:46 +01007283 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007284 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7285
7286 CloseHandle(sh);
7287 }
7288 }
7289 vim_free(fromw);
7290 vim_free(tow);
7291}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007292
7293/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007294 * ntdll.dll definitions
7295 */
7296#define FileEaInformation 7
7297#ifndef STATUS_SUCCESS
7298# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7299#endif
7300
7301typedef struct _FILE_FULL_EA_INFORMATION_ {
7302 ULONG NextEntryOffset;
7303 UCHAR Flags;
7304 UCHAR EaNameLength;
7305 USHORT EaValueLength;
7306 CHAR EaName[1];
7307} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7308
7309typedef struct _FILE_EA_INFORMATION_ {
7310 ULONG EaSize;
7311} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7312
7313typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7314 PHANDLE FileHandle,
7315 ACCESS_MASK DesiredAccess,
7316 POBJECT_ATTRIBUTES ObjectAttributes,
7317 PIO_STATUS_BLOCK IoStatusBlock,
7318 ULONG ShareAccess,
7319 ULONG OpenOptions);
7320typedef NTSTATUS (NTAPI *PfnNtClose)(
7321 HANDLE Handle);
7322typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
7323 HANDLE FileHandle,
7324 PIO_STATUS_BLOCK IoStatusBlock,
7325 PVOID Buffer,
7326 ULONG Length);
7327typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7328 HANDLE FileHandle,
7329 PIO_STATUS_BLOCK IoStatusBlock,
7330 PVOID Buffer,
7331 ULONG Length,
7332 BOOLEAN ReturnSingleEntry,
7333 PVOID EaList,
7334 ULONG EaListLength,
7335 PULONG EaIndex,
7336 BOOLEAN RestartScan);
7337typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
7338 HANDLE FileHandle,
7339 PIO_STATUS_BLOCK IoStatusBlock,
7340 PVOID FileInformation,
7341 ULONG Length,
7342 FILE_INFORMATION_CLASS FileInformationClass);
7343typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7344 PUNICODE_STRING DestinationString,
7345 PCWSTR SourceString);
7346
7347PfnNtOpenFile pNtOpenFile = NULL;
7348PfnNtClose pNtClose = NULL;
7349PfnNtSetEaFile pNtSetEaFile = NULL;
7350PfnNtQueryEaFile pNtQueryEaFile = NULL;
7351PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7352PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
7353
7354/*
7355 * Load ntdll.dll functions.
7356 */
7357 static BOOL
7358load_ntdll(void)
7359{
7360 static int loaded = -1;
7361
7362 if (loaded == -1)
7363 {
7364 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7365 if (hNtdll != NULL)
7366 {
7367 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7368 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7369 pNtSetEaFile = (PfnNtSetEaFile)
7370 GetProcAddress(hNtdll, "NtSetEaFile");
7371 pNtQueryEaFile = (PfnNtQueryEaFile)
7372 GetProcAddress(hNtdll, "NtQueryEaFile");
7373 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7374 GetProcAddress(hNtdll, "NtQueryInformationFile");
7375 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7376 GetProcAddress(hNtdll, "RtlInitUnicodeString");
7377 }
7378 if (pNtOpenFile == NULL
7379 || pNtClose == NULL
7380 || pNtSetEaFile == NULL
7381 || pNtQueryEaFile == NULL
7382 || pNtQueryInformationFile == NULL
7383 || pRtlInitUnicodeString == NULL)
7384 loaded = FALSE;
7385 else
7386 loaded = TRUE;
7387 }
7388 return (BOOL) loaded;
7389}
7390
7391/*
7392 * Copy extended attributes (EA) from file "from" to file "to".
7393 */
7394 static void
7395copy_extattr(char_u *from, char_u *to)
7396{
7397 char_u *fromf = NULL;
7398 char_u *tof = NULL;
7399 WCHAR *fromw = NULL;
7400 WCHAR *tow = NULL;
7401 UNICODE_STRING u;
7402 HANDLE h;
7403 OBJECT_ATTRIBUTES oa;
7404 IO_STATUS_BLOCK iosb;
7405 FILE_EA_INFORMATION_ eainfo = {0};
7406 void *ea = NULL;
7407
7408 if (!load_ntdll())
7409 return;
7410
7411 // Convert the file names to the fully qualified object names.
7412 fromf = alloc(STRLEN(from) + 5);
7413 tof = alloc(STRLEN(to) + 5);
7414 if (fromf == NULL || tof == NULL)
7415 goto theend;
7416 STRCPY(fromf, "\\??\\");
7417 STRCAT(fromf, from);
7418 STRCPY(tof, "\\??\\");
7419 STRCAT(tof, to);
7420
7421 // Convert the names to wide characters.
7422 fromw = enc_to_utf16(fromf, NULL);
7423 tow = enc_to_utf16(tof, NULL);
7424 if (fromw == NULL || tow == NULL)
7425 goto theend;
7426
7427 // Get the EA.
7428 pRtlInitUnicodeString(&u, fromw);
7429 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7430 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7431 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7432 goto theend;
7433 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7434 FileEaInformation);
7435 if (eainfo.EaSize != 0)
7436 {
7437 ea = alloc(eainfo.EaSize);
7438 if (ea != NULL)
7439 {
7440 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7441 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7442 {
7443 vim_free(ea);
7444 ea = NULL;
7445 }
7446 }
7447 }
7448 pNtClose(h);
7449
7450 // Set the EA.
7451 if (ea != NULL)
7452 {
7453 pRtlInitUnicodeString(&u, tow);
7454 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7455 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7456 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7457 goto theend;
7458
7459 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
7460 pNtClose(h);
7461 }
7462
7463theend:
7464 vim_free(fromf);
7465 vim_free(tof);
7466 vim_free(fromw);
7467 vim_free(tow);
7468 vim_free(ea);
7469}
7470
7471/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007472 * Copy file attributes from file "from" to file "to".
7473 * For Windows NT and later we copy info streams.
7474 * Always returns zero, errors are ignored.
7475 */
7476 int
7477mch_copy_file_attribute(char_u *from, char_u *to)
7478{
Bram Moolenaar0f873732019-12-05 20:28:46 +01007479 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007480 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007481 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007482 return 0;
7483}
7484
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007485
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007486/*
K.Takatadc73b4b2021-06-08 18:32:36 +02007487 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007488 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007489static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007490static LPWSTR *ArglistW = NULL;
7491static int global_argc = 0;
7492static char **global_argv;
7493
Bram Moolenaar0f873732019-12-05 20:28:46 +01007494static int used_file_argc = 0; // last argument in global_argv[] used
7495 // for the argument list.
7496static int *used_file_indexes = NULL; // indexes in global_argv[] for
7497 // command line arguments added to
7498 // the argument list
7499static int used_file_count = 0; // nr of entries in used_file_indexes
7500static int used_file_literal = FALSE; // take file names literally
7501static int used_file_full_path = FALSE; // file name was full path
7502static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007503static int used_alist_count = 0;
7504
7505
7506/*
7507 * Get the command line arguments. Unicode version.
7508 * Returns argc. Zero when something fails.
7509 */
7510 int
7511get_cmd_argsW(char ***argvp)
7512{
7513 char **argv = NULL;
7514 int argc = 0;
7515 int i;
7516
Bram Moolenaar14993322014-09-09 12:25:33 +02007517 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007518 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7519 if (ArglistW != NULL)
7520 {
7521 argv = malloc((nArgsW + 1) * sizeof(char *));
7522 if (argv != NULL)
7523 {
7524 argc = nArgsW;
7525 argv[argc] = NULL;
7526 for (i = 0; i < argc; ++i)
7527 {
7528 int len;
7529
K.Takatadc73b4b2021-06-08 18:32:36 +02007530 // Convert each Unicode argument to UTF-8.
7531 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007532 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007533 (LPSTR *)&argv[i], &len, 0, 0);
7534 if (argv[i] == NULL)
7535 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007536 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007537 while (i > 0)
7538 free(argv[--i]);
7539 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007540 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007541 argc = 0;
7542 }
7543 }
7544 }
7545 }
7546
7547 global_argc = argc;
7548 global_argv = argv;
7549 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007550 {
7551 if (used_file_indexes != NULL)
7552 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007553 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007554 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007555
7556 if (argvp != NULL)
7557 *argvp = argv;
7558 return argc;
7559}
7560
7561 void
7562free_cmd_argsW(void)
7563{
7564 if (ArglistW != NULL)
7565 {
7566 GlobalFree(ArglistW);
7567 ArglistW = NULL;
7568 }
7569}
7570
7571/*
7572 * Remember "name" is an argument that was added to the argument list.
7573 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7574 * is called.
7575 */
7576 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007577used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007578{
7579 int i;
7580
7581 if (used_file_indexes == NULL)
7582 return;
7583 for (i = used_file_argc + 1; i < global_argc; ++i)
7584 if (STRCMP(global_argv[i], name) == 0)
7585 {
7586 used_file_argc = i;
7587 used_file_indexes[used_file_count++] = i;
7588 break;
7589 }
7590 used_file_literal = literal;
7591 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007592 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007593}
7594
7595/*
7596 * Remember the length of the argument list as it was. If it changes then we
7597 * leave it alone when 'encoding' is set.
7598 */
7599 void
7600set_alist_count(void)
7601{
7602 used_alist_count = GARGCOUNT;
7603}
7604
7605/*
7606 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02007607 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007608 * and convert them to 'encoding'.
7609 */
7610 void
7611fix_arg_enc(void)
7612{
7613 int i;
7614 int idx;
7615 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007616 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007617
Bram Moolenaar0f873732019-12-05 20:28:46 +01007618 // Safety checks:
7619 // - if argument count differs between the wide and non-wide argument
7620 // list, something must be wrong.
7621 // - the file name arguments must have been located.
7622 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007623 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007624 || ArglistW == NULL
7625 || used_file_indexes == NULL
7626 || used_file_count == 0
7627 || used_alist_count != GARGCOUNT)
7628 return;
7629
Bram Moolenaar0f873732019-12-05 20:28:46 +01007630 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007631 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007632 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007633 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00007634 for (i = 0; i < GARGCOUNT; ++i)
7635 fnum_list[i] = GARGLIST[i].ae_fnum;
7636
Bram Moolenaar0f873732019-12-05 20:28:46 +01007637 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007638 alist_clear(&global_alist);
7639 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007640 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007641
7642 for (i = 0; i < used_file_count; ++i)
7643 {
7644 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007645 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007646 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007647 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007648 int literal = used_file_literal;
7649
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007650#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01007651 // When using diff mode may need to concatenate file name to
7652 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007653 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7654 && !mch_isdir(alist_name(&GARGLIST[0])))
7655 {
7656 char_u *r;
7657
7658 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7659 if (r != NULL)
7660 {
7661 vim_free(str);
7662 str = r;
7663 }
7664 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007665#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01007666 // Re-use the old buffer by renaming it. When not using literal
7667 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00007668 if (used_file_literal)
7669 buf_set_name(fnum_list[i], str);
7670
Bram Moolenaar0f873732019-12-05 20:28:46 +01007671 // Check backtick literal. backtick literal is already expanded in
7672 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007673 if (literal == FALSE)
7674 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007675 size_t len = STRLEN(str);
7676
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007677 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7678 literal = TRUE;
7679 }
7680 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007681 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007682 }
7683
7684 if (!used_file_literal)
7685 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007686 // Now expand wildcards in the arguments.
7687 // Temporarily add '(' and ')' to 'isfname'. These are valid
7688 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00007689 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01007690 // Also, unset wildignore to not be influenced by this option.
7691 // The arguments specified in command-line should be kept even if
7692 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00007693 // Use :legacy so that it also works when in Vim9 script.
7694 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
7695 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007696 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00007697 do_cmdline_cmd(
7698 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
7699 do_cmdline_cmd(
7700 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007701 }
7702
Bram Moolenaar0f873732019-12-05 20:28:46 +01007703 // If wildcard expansion failed, we are editing the first file of the
7704 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007705 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7706 {
7707 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00007708 if (GARGCOUNT == 1 && used_file_full_path
7709 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
7710 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007711 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007712
7713 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007714}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007715
7716 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007717mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007718{
7719 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007720 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007721
Bram Moolenaar964b3742019-05-24 18:54:09 +02007722 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007723 if (envbuf == NULL)
7724 return -1;
7725
7726 sprintf((char *)envbuf, "%s=%s", var, value);
7727
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007728 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007729
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007730 vim_free(envbuf);
7731 if (p == NULL)
7732 return -1;
7733 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007734#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007735 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007736#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007737 // Unlike Un*x systems, we can free the string for _wputenv().
7738 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007739
7740 return 0;
7741}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007742
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007743/*
7744 * Support for 256 colors and 24-bit colors was added in Windows 10
7745 * version 1703 (Creators update).
7746 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007747#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7748
7749/*
7750 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02007751 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007752 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007753#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007754
7755/*
7756 * ConPTY differences between versions, need different logic.
7757 * version 1903 (May 2019 update).
7758 */
7759#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
7760
7761/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007762 * version 1909 (November 2019 update).
7763 */
7764#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
7765
7766/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007767 * Stay ahead of the next update, and when it's done, fix this.
7768 * version ? (2020 update, temporarily use the build number of insider preview)
7769 */
7770#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
7771
7772/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02007773 * Confirm until this version. Also the logic changes.
7774 * insider preview.
7775 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02007776#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007777
7778/*
7779 * Not stable now.
7780 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007781#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007782
7783 static void
7784vtp_flag_init(void)
7785{
7786 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007787#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007788 DWORD mode;
7789 HANDLE out;
7790
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007791# ifdef VIMDLL
7792 if (!gui.in_use)
7793# endif
7794 {
7795 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007796
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007797 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7798 GetConsoleMode(out, &mode);
7799 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7800 if (SetConsoleMode(out, mode) == 0)
7801 vtp_working = 0;
7802 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007803#endif
7804
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007805 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007806 conpty_working = 1;
7807 if (ver >= CONPTY_STABLE_BUILD)
7808 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007809
Bram Moolenaar57da6982019-09-13 22:30:11 +02007810 if (ver <= CONPTY_INSIDER_BUILD)
7811 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007812 if (ver <= CONPTY_1909_BUILD)
7813 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02007814 if (ver <= CONPTY_1903_BUILD)
7815 conpty_type = 2;
7816 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
7817 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007818
7819 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
7820 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007821}
7822
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007823#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007824
7825 static void
7826vtp_init(void)
7827{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007828 HMODULE hKerneldll;
7829 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007830# ifdef FEAT_TERMGUICOLORS
7831 COLORREF fg, bg;
7832# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007833
Bram Moolenaar0f873732019-12-05 20:28:46 +01007834 // Use functions supported from Vista
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007835 hKerneldll = GetModuleHandle("kernel32.dll");
7836 if (hKerneldll != NULL)
7837 {
7838 pGetConsoleScreenBufferInfoEx =
7839 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7840 hKerneldll, "GetConsoleScreenBufferInfoEx");
7841 pSetConsoleScreenBufferInfoEx =
7842 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7843 hKerneldll, "SetConsoleScreenBufferInfoEx");
7844 if (pGetConsoleScreenBufferInfoEx != NULL
7845 && pSetConsoleScreenBufferInfoEx != NULL)
7846 has_csbiex = TRUE;
7847 }
7848
7849 csbi.cbSize = sizeof(csbi);
7850 if (has_csbiex)
7851 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007852 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7853 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
Bram Moolenaardf543822020-01-30 11:53:59 +01007854 store_console_bg_rgb = save_console_bg_rgb;
7855 store_console_fg_rgb = save_console_fg_rgb;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007856
7857# ifdef FEAT_TERMGUICOLORS
7858 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7859 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7860 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7861 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7862 default_console_color_bg = bg;
7863 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007864# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007865
7866 set_console_color_rgb();
7867}
7868
7869 static void
7870vtp_exit(void)
7871{
Bram Moolenaardf543822020-01-30 11:53:59 +01007872 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007873}
7874
Bram Moolenaar06b7b582020-05-30 17:49:25 +02007875 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007876vtp_printf(
7877 char *format,
7878 ...)
7879{
7880 char_u buf[100];
7881 va_list list;
7882 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007883 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007884
7885 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007886 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007887 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007888 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007889 return (int)result;
7890}
7891
7892 static void
7893vtp_sgr_bulk(
7894 int arg)
7895{
7896 int args[1];
7897
7898 args[0] = arg;
7899 vtp_sgr_bulks(1, args);
7900}
7901
K.Takata6e1d31e2022-02-03 13:05:32 +00007902# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007903 if ((*p-- = "0123456789"[(n = x % 10)]) \
7904 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
7905 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
7906
K.Takata6e1d31e2022-02-03 13:05:32 +00007907# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007908 case x: \
7909 FAST256(newargs[x - 1]);
7910
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007911 static void
7912vtp_sgr_bulks(
7913 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007914 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007915{
K.Takata6e1d31e2022-02-03 13:05:32 +00007916# define MAXSGR 16
7917# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007918 char_u buf[SGRBUFSIZE];
7919 char_u *p;
7920 int in, out;
7921 int newargs[16];
7922 static int sgrfgr = -1, sgrfgg, sgrfgb;
7923 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007924
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007925 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007926 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007927 sgrfgr = sgrbgr = -1;
7928 vtp_printf("033[m");
7929 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007930 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007931
7932 in = out = 0;
7933 while (in < argc)
7934 {
7935 int s = args[in];
7936 int copylen = 1;
7937
7938 if (s == 38)
7939 {
7940 if (argc - in >= 5 && args[in + 1] == 2)
7941 {
7942 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
7943 && sgrfgb == args[in + 4])
7944 {
7945 in += 5;
7946 copylen = 0;
7947 }
7948 else
7949 {
7950 sgrfgr = args[in + 2];
7951 sgrfgg = args[in + 3];
7952 sgrfgb = args[in + 4];
7953 copylen = 5;
7954 }
7955 }
7956 else if (argc - in >= 3 && args[in + 1] == 5)
7957 {
7958 sgrfgr = -1;
7959 copylen = 3;
7960 }
7961 }
7962 else if (s == 48)
7963 {
7964 if (argc - in >= 5 && args[in + 1] == 2)
7965 {
7966 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
7967 && sgrbgb == args[in + 4])
7968 {
7969 in += 5;
7970 copylen = 0;
7971 }
7972 else
7973 {
7974 sgrbgr = args[in + 2];
7975 sgrbgg = args[in + 3];
7976 sgrbgb = args[in + 4];
7977 copylen = 5;
7978 }
7979 }
7980 else if (argc - in >= 3 && args[in + 1] == 5)
7981 {
7982 sgrbgr = -1;
7983 copylen = 3;
7984 }
7985 }
7986 else if (30 <= s && s <= 39)
7987 sgrfgr = -1;
7988 else if (90 <= s && s <= 97)
7989 sgrfgr = -1;
7990 else if (40 <= s && s <= 49)
7991 sgrbgr = -1;
7992 else if (100 <= s && s <= 107)
7993 sgrbgr = -1;
7994 else if (s == 0)
7995 sgrfgr = sgrbgr = -1;
7996
7997 while (copylen--)
7998 newargs[out++] = args[in++];
7999 }
8000
8001 p = &buf[sizeof(buf) - 1];
8002 *p-- = 'm';
8003
8004 switch (out)
8005 {
8006 int n, m;
8007 DWORD r;
8008
8009 FAST256CASE(16);
8010 *p-- = ';';
8011 FAST256CASE(15);
8012 *p-- = ';';
8013 FAST256CASE(14);
8014 *p-- = ';';
8015 FAST256CASE(13);
8016 *p-- = ';';
8017 FAST256CASE(12);
8018 *p-- = ';';
8019 FAST256CASE(11);
8020 *p-- = ';';
8021 FAST256CASE(10);
8022 *p-- = ';';
8023 FAST256CASE(9);
8024 *p-- = ';';
8025 FAST256CASE(8);
8026 *p-- = ';';
8027 FAST256CASE(7);
8028 *p-- = ';';
8029 FAST256CASE(6);
8030 *p-- = ';';
8031 FAST256CASE(5);
8032 *p-- = ';';
8033 FAST256CASE(4);
8034 *p-- = ';';
8035 FAST256CASE(3);
8036 *p-- = ';';
8037 FAST256CASE(2);
8038 *p-- = ';';
8039 FAST256CASE(1);
8040 *p-- = '[';
8041 *p = '\033';
8042 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8043 default:
8044 break;
8045 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008046}
8047
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008048 static void
8049wt_init(void)
8050{
8051 wt_working = (mch_getenv("WT_SESSION") != NULL);
8052}
8053
8054 int
8055use_wt(void)
8056{
8057 return USE_WT;
8058}
8059
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008060# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008061 static int
8062ctermtoxterm(
8063 int cterm)
8064{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008065 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008066
8067 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8068 return (((int)r << 16) | ((int)g << 8) | (int)b);
8069}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008070# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008071
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008072 static void
8073set_console_color_rgb(void)
8074{
8075# ifdef FEAT_TERMGUICOLORS
8076 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008077 guicolor_T fg, bg;
8078 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008079
8080 if (!USE_VTP)
8081 return;
8082
Bram Moolenaara050b942019-12-02 21:35:31 +01008083 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8084
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008085 if (USE_WT)
8086 {
8087 term_fg_rgb_color(fg);
8088 term_bg_rgb_color(bg);
8089 return;
8090 }
8091
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008092 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8093 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8094
8095 csbi.cbSize = sizeof(csbi);
8096 if (has_csbiex)
8097 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8098
8099 csbi.cbSize = sizeof(csbi);
8100 csbi.srWindow.Right += 1;
8101 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008102 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8103 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008104 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8105 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008106 if (has_csbiex)
8107 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8108# endif
8109}
8110
Bram Moolenaara050b942019-12-02 21:35:31 +01008111# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8112 void
8113get_default_console_color(
8114 int *cterm_fg,
8115 int *cterm_bg,
8116 guicolor_T *gui_fg,
8117 guicolor_T *gui_bg)
8118{
8119 int id;
8120 guicolor_T guifg = INVALCOLOR;
8121 guicolor_T guibg = INVALCOLOR;
8122 int ctermfg = 0;
8123 int ctermbg = 0;
8124
8125 id = syn_name2id((char_u *)"Normal");
8126 if (id > 0 && p_tgc)
8127 syn_id2colors(id, &guifg, &guibg);
8128 if (guifg == INVALCOLOR)
8129 {
8130 ctermfg = -1;
8131 if (id > 0)
8132 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8133 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
8134 : default_console_color_fg;
8135 cterm_normal_fg_gui_color = guifg;
8136 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8137 }
8138 if (guibg == INVALCOLOR)
8139 {
8140 ctermbg = -1;
8141 if (id > 0)
8142 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8143 guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8144 : default_console_color_bg;
8145 cterm_normal_bg_gui_color = guibg;
8146 ctermbg = ctermbg < 0 ? 0 : ctermbg;
8147 }
8148
8149 *cterm_fg = ctermfg;
8150 *cterm_bg = ctermbg;
8151 *gui_fg = guifg;
8152 *gui_bg = guibg;
8153}
8154# endif
8155
Bram Moolenaardf543822020-01-30 11:53:59 +01008156/*
8157 * Set the console colors to the original colors or the last set colors.
8158 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008159 static void
8160reset_console_color_rgb(void)
8161{
8162# ifdef FEAT_TERMGUICOLORS
8163 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8164
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008165 if (USE_WT)
8166 return;
8167
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008168 csbi.cbSize = sizeof(csbi);
8169 if (has_csbiex)
8170 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8171
8172 csbi.cbSize = sizeof(csbi);
8173 csbi.srWindow.Right += 1;
8174 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008175 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8176 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
8177 if (has_csbiex)
8178 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8179# endif
8180}
8181
8182/*
8183 * Set the console colors to the original colors.
8184 */
8185 static void
8186restore_console_color_rgb(void)
8187{
8188# ifdef FEAT_TERMGUICOLORS
8189 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8190
8191 csbi.cbSize = sizeof(csbi);
8192 if (has_csbiex)
8193 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8194
8195 csbi.cbSize = sizeof(csbi);
8196 csbi.srWindow.Right += 1;
8197 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008198 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8199 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008200 if (has_csbiex)
8201 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8202# endif
8203}
8204
8205 void
8206control_console_color_rgb(void)
8207{
8208 if (USE_VTP)
8209 set_console_color_rgb();
8210 else
8211 reset_console_color_rgb();
8212}
8213
8214 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008215use_vtp(void)
8216{
8217 return USE_VTP;
8218}
8219
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008220 int
8221is_term_win32(void)
8222{
8223 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8224}
8225
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008226 int
8227has_vtp_working(void)
8228{
8229 return vtp_working;
8230}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008231
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008232#endif
8233
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008234 int
8235has_conpty_working(void)
8236{
8237 return conpty_working;
8238}
8239
8240 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008241get_conpty_type(void)
8242{
8243 return conpty_type;
8244}
8245
8246 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008247is_conpty_stable(void)
8248{
8249 return conpty_stable;
8250}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008251
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008252 int
8253get_conpty_fix_type(void)
8254{
8255 return conpty_fix_type;
8256}
8257
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008258#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008259 void
8260resize_console_buf(void)
8261{
8262 CONSOLE_SCREEN_BUFFER_INFO csbi;
8263 COORD coord;
8264 SMALL_RECT newsize;
8265
8266 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8267 {
8268 coord.X = SRWIDTH(csbi.srWindow);
8269 coord.Y = SRHEIGHT(csbi.srWindow);
8270 SetConsoleScreenBufferSize(g_hConOut, coord);
8271
8272 newsize.Left = 0;
8273 newsize.Top = 0;
8274 newsize.Right = coord.X - 1;
8275 newsize.Bottom = coord.Y - 1;
8276 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8277
8278 SetConsoleScreenBufferSize(g_hConOut, coord);
8279 }
8280}
8281#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008282
8283 char *
8284GetWin32Error(void)
8285{
K.Takatad68b2fc2022-02-12 11:18:37 +00008286 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008287 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008288
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008289 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8290 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008291 if (oldmsg != NULL)
8292 LocalFree(oldmsg);
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008293 if (msg != NULL)
8294 {
8295 // remove trailing \r\n
8296 char *pcrlf = strstr(msg, "\r\n");
8297 if (pcrlf != NULL)
8298 *pcrlf = '\0';
K.Takatad68b2fc2022-02-12 11:18:37 +00008299 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008300 }
8301 return msg;
8302}