blob: 97595d6ebaab8ae5214d6a1054462f42f86a15f0 [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 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002240
2241 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2242 STRCPY(pathbuf, ".;");
2243 else
2244 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002245 STRCAT(pathbuf, p);
2246 }
2247 }
2248
2249 /*
2250 * Walk through all entries in $PATH to check if "name" exists there and
2251 * is an executable file.
2252 */
2253 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2254 while (*p)
2255 {
2256 if (*p == ';') // Skip empty entry
2257 {
2258 ++p;
2259 continue;
2260 }
2261 e = vim_strchr(p, ';');
2262 if (e == NULL)
2263 e = p + STRLEN(p);
2264
2265 if (e - p + len + 2 > sizeof(buf))
2266 {
2267 retval = FALSE;
2268 goto theend;
2269 }
2270 // A single "." that means current dir.
2271 if (e - p == 1 && *p == '.')
2272 STRCPY(buf, name);
2273 else
2274 {
2275 vim_strncpy(buf, p, e - p);
2276 add_pathsep(buf);
2277 STRCAT(buf, name);
2278 }
2279 tmplen = STRLEN(buf);
2280
2281 /*
2282 * Loop over all extensions in $PATHEXT.
2283 * Check "name" with extension added.
2284 */
2285 p = pathext;
2286 while (*p)
2287 {
2288 if (*p == ';')
2289 {
2290 // Skip empty entry
2291 ++p;
2292 continue;
2293 }
2294 e2 = vim_strchr(p, (int)';');
2295 if (e2 == NULL)
2296 e2 = p + STRLEN(p);
2297
2298 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2299 {
2300 // Not a single "." that means no extension is added.
2301 if (e2 - p + tmplen + 1 > sizeof(buf))
2302 {
2303 retval = FALSE;
2304 goto theend;
2305 }
2306 vim_strncpy(buf + tmplen, p, e2 - p);
2307 }
2308 if (executable_file((char *)buf, path))
2309 {
2310 retval = TRUE;
2311 goto theend;
2312 }
2313
2314 p = e2;
2315 }
2316
2317 p = e;
2318 }
2319
2320theend:
2321 free(pathextbuf);
2322 free(pathbuf);
2323 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002324}
2325
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002326#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2327 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002328/*
2329 * Bad parameter handler.
2330 *
2331 * Certain MS CRT functions will intentionally crash when passed invalid
2332 * parameters to highlight possible security holes. Setting this function as
2333 * the bad parameter handler will prevent the crash.
2334 *
2335 * In debug builds the parameters contain CRT information that might help track
2336 * down the source of a problem, but in non-debug builds the arguments are all
2337 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2338 * worth allowing these to make debugging of issues easier.
2339 */
2340 static void
2341bad_param_handler(const wchar_t *expression,
2342 const wchar_t *function,
2343 const wchar_t *file,
2344 unsigned int line,
2345 uintptr_t pReserved)
2346{
2347}
2348
2349# define SET_INVALID_PARAM_HANDLER \
2350 ((void)_set_invalid_parameter_handler(bad_param_handler))
2351#else
2352# define SET_INVALID_PARAM_HANDLER
2353#endif
2354
Bram Moolenaar4f974752019-02-17 17:44:42 +01002355#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002356
2357/*
2358 * GUI version of mch_init().
2359 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002360 static void
2361mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002362{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002363# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002364 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002365# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002366
Bram Moolenaar0f873732019-12-05 20:28:46 +01002367 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002368 SET_INVALID_PARAM_HANDLER;
2369
Bram Moolenaar0f873732019-12-05 20:28:46 +01002370 // Let critical errors result in a failure, not in a dialog box. Required
2371 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002372 SetErrorMode(SEM_FAILCRITICALERRORS);
2373
Bram Moolenaar0f873732019-12-05 20:28:46 +01002374 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002375
Bram Moolenaar0f873732019-12-05 20:28:46 +01002376 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002377 Rows = 25;
2378 Columns = 80;
2379
Bram Moolenaar0f873732019-12-05 20:28:46 +01002380 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002381 {
2382 char_u vimrun_location[_MAX_PATH + 4];
2383
Bram Moolenaar0f873732019-12-05 20:28:46 +01002384 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002385 STRCPY(vimrun_location, exe_name);
2386 STRCPY(gettail(vimrun_location), "vimrun.exe");
2387 if (mch_getperm(vimrun_location) >= 0)
2388 {
2389 if (*skiptowhite(vimrun_location) != NUL)
2390 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002391 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002392 mch_memmove(vimrun_location + 1, vimrun_location,
2393 STRLEN(vimrun_location) + 1);
2394 *vimrun_location = '"';
2395 STRCPY(gettail(vimrun_location), "vimrun\" ");
2396 }
2397 else
2398 STRCPY(gettail(vimrun_location), "vimrun ");
2399
2400 vimrun_path = (char *)vim_strsave(vimrun_location);
2401 s_dont_use_vimrun = FALSE;
2402 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002403 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002404 s_dont_use_vimrun = FALSE;
2405
Bram Moolenaar0f873732019-12-05 20:28:46 +01002406 // Don't give the warning for a missing vimrun.exe right now, but only
2407 // when vimrun was supposed to be used. Don't bother people that do
2408 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002409 if (s_dont_use_vimrun)
2410 need_vimrun_warning = TRUE;
2411 }
2412
2413 /*
2414 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2415 * Otherwise the default "findstr /n" is used.
2416 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002417 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01002418 set_option_value_give_err((char_u *)"grepprg",
2419 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002420
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002421# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002422 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002423# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002424
2425 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002426}
2427
2428
Bram Moolenaar0f873732019-12-05 20:28:46 +01002429#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002430
2431#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002432
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002433# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2434# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002435
2436/*
2437 * ClearConsoleBuffer()
2438 * Description:
2439 * Clears the entire contents of the console screen buffer, using the
2440 * specified attribute.
2441 * Returns:
2442 * TRUE on success
2443 */
2444 static BOOL
2445ClearConsoleBuffer(WORD wAttribute)
2446{
2447 CONSOLE_SCREEN_BUFFER_INFO csbi;
2448 COORD coord;
2449 DWORD NumCells, dummy;
2450
2451 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2452 return FALSE;
2453
2454 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2455 coord.X = 0;
2456 coord.Y = 0;
2457 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2458 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002459 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002460 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2461 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002462 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002463
2464 return TRUE;
2465}
2466
2467/*
2468 * FitConsoleWindow()
2469 * Description:
2470 * Checks if the console window will fit within given buffer dimensions.
2471 * Also, if requested, will shrink the window to fit.
2472 * Returns:
2473 * TRUE on success
2474 */
2475 static BOOL
2476FitConsoleWindow(
2477 COORD dwBufferSize,
2478 BOOL WantAdjust)
2479{
2480 CONSOLE_SCREEN_BUFFER_INFO csbi;
2481 COORD dwWindowSize;
2482 BOOL NeedAdjust = FALSE;
2483
2484 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2485 {
2486 /*
2487 * A buffer resize will fail if the current console window does
2488 * not lie completely within that buffer. To avoid this, we might
2489 * have to move and possibly shrink the window.
2490 */
2491 if (csbi.srWindow.Right >= dwBufferSize.X)
2492 {
2493 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2494 if (dwWindowSize.X > dwBufferSize.X)
2495 dwWindowSize.X = dwBufferSize.X;
2496 csbi.srWindow.Right = dwBufferSize.X - 1;
2497 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2498 NeedAdjust = TRUE;
2499 }
2500 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2501 {
2502 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2503 if (dwWindowSize.Y > dwBufferSize.Y)
2504 dwWindowSize.Y = dwBufferSize.Y;
2505 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2506 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2507 NeedAdjust = TRUE;
2508 }
2509 if (NeedAdjust && WantAdjust)
2510 {
2511 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2512 return FALSE;
2513 }
2514 return TRUE;
2515 }
2516
2517 return FALSE;
2518}
2519
2520typedef struct ConsoleBufferStruct
2521{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002522 BOOL IsValid;
2523 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002524 PCHAR_INFO Buffer;
2525 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002526 PSMALL_RECT Regions;
2527 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002528} ConsoleBuffer;
2529
2530/*
2531 * SaveConsoleBuffer()
2532 * Description:
2533 * Saves important information about the console buffer, including the
2534 * actual buffer contents. The saved information is suitable for later
2535 * restoration by RestoreConsoleBuffer().
2536 * Returns:
2537 * TRUE if all information was saved; FALSE otherwise
2538 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2539 */
2540 static BOOL
2541SaveConsoleBuffer(
2542 ConsoleBuffer *cb)
2543{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002544 DWORD NumCells;
2545 COORD BufferCoord;
2546 SMALL_RECT ReadRegion;
2547 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002548 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002549
Bram Moolenaar071d4272004-06-13 20:20:40 +00002550 if (cb == NULL)
2551 return FALSE;
2552
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002553 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002554 {
2555 cb->IsValid = FALSE;
2556 return FALSE;
2557 }
2558 cb->IsValid = TRUE;
2559
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002560 /*
2561 * Allocate a buffer large enough to hold the entire console screen
2562 * buffer. If this ConsoleBuffer structure has already been initialized
2563 * with a buffer of the correct size, then just use that one.
2564 */
2565 if (!cb->IsValid || cb->Buffer == NULL ||
2566 cb->BufferSize.X != cb->Info.dwSize.X ||
2567 cb->BufferSize.Y != cb->Info.dwSize.Y)
2568 {
2569 cb->BufferSize.X = cb->Info.dwSize.X;
2570 cb->BufferSize.Y = cb->Info.dwSize.Y;
2571 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2572 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002573 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002574 if (cb->Buffer == NULL)
2575 return FALSE;
2576 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002577
2578 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002579 * We will now copy the console screen buffer into our buffer.
2580 * ReadConsoleOutput() seems to be limited as far as how much you
2581 * can read at a time. Empirically, this number seems to be about
2582 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2583 * in chunks until it is all copied. The chunks will all have the
2584 * same horizontal characteristics, so initialize them now. The
2585 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002586 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002587 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002588 ReadRegion.Left = 0;
2589 ReadRegion.Right = cb->Info.dwSize.X - 1;
2590 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002591
2592 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2593 if (cb->Regions == NULL || numregions != cb->NumRegions)
2594 {
2595 cb->NumRegions = numregions;
2596 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002597 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002598 if (cb->Regions == NULL)
2599 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002600 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002601 return FALSE;
2602 }
2603 }
2604
2605 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002606 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002607 /*
2608 * Read into position (0, Y) in our buffer.
2609 */
2610 BufferCoord.Y = Y;
2611 /*
2612 * Read the region whose top left corner is (0, Y) and whose bottom
2613 * right corner is (width - 1, Y + Y_incr - 1). This should define
2614 * a region of size width by Y_incr. Don't worry if this region is
2615 * too large for the remaining buffer; it will be cropped.
2616 */
2617 ReadRegion.Top = Y;
2618 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002619 if (!ReadConsoleOutputW(g_hConOut, // output handle
2620 cb->Buffer, // our buffer
2621 cb->BufferSize, // dimensions of our buffer
2622 BufferCoord, // offset in our buffer
2623 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002624 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002625 VIM_CLEAR(cb->Buffer);
2626 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002627 return FALSE;
2628 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002629 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002630 }
2631
2632 return TRUE;
2633}
2634
2635/*
2636 * RestoreConsoleBuffer()
2637 * Description:
2638 * Restores important information about the console buffer, including the
2639 * actual buffer contents, if desired. The information to restore is in
2640 * the same format used by SaveConsoleBuffer().
2641 * Returns:
2642 * TRUE on success
2643 */
2644 static BOOL
2645RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002646 ConsoleBuffer *cb,
2647 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002648{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002649 COORD BufferCoord;
2650 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002651 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002652
2653 if (cb == NULL || !cb->IsValid)
2654 return FALSE;
2655
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002656 /*
2657 * Before restoring the buffer contents, clear the current buffer, and
2658 * restore the cursor position and window information. Doing this now
2659 * prevents old buffer contents from "flashing" onto the screen.
2660 */
2661 if (RestoreScreen)
2662 ClearConsoleBuffer(cb->Info.wAttributes);
2663
2664 FitConsoleWindow(cb->Info.dwSize, TRUE);
2665 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2666 return FALSE;
2667 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2668 return FALSE;
2669
2670 if (!RestoreScreen)
2671 {
2672 /*
2673 * No need to restore the screen buffer contents, so we're done.
2674 */
2675 return TRUE;
2676 }
2677
2678 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2679 return FALSE;
2680 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2681 return FALSE;
2682
2683 /*
2684 * Restore the screen buffer contents.
2685 */
2686 if (cb->Buffer != NULL)
2687 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002688 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002689 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002690 BufferCoord.X = cb->Regions[i].Left;
2691 BufferCoord.Y = cb->Regions[i].Top;
2692 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01002693 if (!WriteConsoleOutputW(g_hConOut, // output handle
2694 cb->Buffer, // our buffer
2695 cb->BufferSize, // dimensions of our buffer
2696 BufferCoord, // offset in our buffer
2697 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02002698 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002699 }
2700 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002701
2702 return TRUE;
2703}
2704
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002705# define FEAT_RESTORE_ORIG_SCREEN
2706# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002707static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002708# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002709static ConsoleBuffer g_cbNonTermcap = { 0 };
2710static ConsoleBuffer g_cbTermcap = { 0 };
2711
Bram Moolenaar071d4272004-06-13 20:20:40 +00002712char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01002713HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00002714static HICON g_hOrigIconSmall = NULL;
2715static HICON g_hOrigIcon = NULL;
2716static HICON g_hVimIcon = NULL;
2717static BOOL g_fCanChangeIcon = FALSE;
2718
Bram Moolenaar071d4272004-06-13 20:20:40 +00002719/*
2720 * GetConsoleIcon()
2721 * Description:
2722 * Attempts to retrieve the small icon and/or the big icon currently in
2723 * use by a given window.
2724 * Returns:
2725 * TRUE on success
2726 */
2727 static BOOL
2728GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002729 HWND hWnd,
2730 HICON *phIconSmall,
2731 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002732{
2733 if (hWnd == NULL)
2734 return FALSE;
2735
2736 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002737 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2738 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002739 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002740 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2741 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002742 return TRUE;
2743}
2744
2745/*
2746 * SetConsoleIcon()
2747 * Description:
2748 * Attempts to change the small icon and/or the big icon currently in
2749 * use by a given window.
2750 * Returns:
2751 * TRUE on success
2752 */
2753 static BOOL
2754SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002755 HWND hWnd,
2756 HICON hIconSmall,
2757 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002758{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002759 if (hWnd == NULL)
2760 return FALSE;
2761
2762 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002763 SendMessage(hWnd, WM_SETICON,
2764 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002765 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002766 SendMessage(hWnd, WM_SETICON,
2767 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002768 return TRUE;
2769}
2770
2771/*
2772 * SaveConsoleTitleAndIcon()
2773 * Description:
2774 * Saves the current console window title in g_szOrigTitle, for later
2775 * restoration. Also, attempts to obtain a handle to the console window,
2776 * and use it to save the small and big icons currently in use by the
2777 * console window. This is not always possible on some versions of Windows;
2778 * nor is it possible when running Vim remotely using Telnet (since the
2779 * console window the user sees is owned by a remote process).
2780 */
2781 static void
2782SaveConsoleTitleAndIcon(void)
2783{
Bram Moolenaar0f873732019-12-05 20:28:46 +01002784 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002785 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2786 return;
2787
2788 /*
2789 * Obtain a handle to the console window using GetConsoleWindow() from
2790 * KERNEL32.DLL; we need to handle in order to change the window icon.
2791 * This function only exists on NT-based Windows, starting with Windows
2792 * 2000. On older operating systems, we can't change the window icon
2793 * anyway.
2794 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002795 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002796 if (g_hWnd == NULL)
2797 return;
2798
Bram Moolenaar0f873732019-12-05 20:28:46 +01002799 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002800 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2801 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2802 return;
2803
Bram Moolenaar0f873732019-12-05 20:28:46 +01002804 // Extract the first icon contained in the Vim executable.
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002805 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002806 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002807 if (g_hVimIcon != NULL)
2808 g_fCanChangeIcon = TRUE;
2809}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002810
2811static int g_fWindInitCalled = FALSE;
2812static int g_fTermcapMode = FALSE;
2813static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002814
2815/*
2816 * non-GUI version of mch_init().
2817 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002818 static void
2819mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002820{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002821# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002822 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002823# endif
2824# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002825 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002826# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002827
Bram Moolenaar0f873732019-12-05 20:28:46 +01002828 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002829 SET_INVALID_PARAM_HANDLER;
2830
Bram Moolenaar0f873732019-12-05 20:28:46 +01002831 // Let critical errors result in a failure, not in a dialog box. Required
2832 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002833 SetErrorMode(SEM_FAILCRITICALERRORS);
2834
Bram Moolenaar0f873732019-12-05 20:28:46 +01002835 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002836 out_flush();
2837
Bram Moolenaar0f873732019-12-05 20:28:46 +01002838 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00002839 if (read_cmd_fd == 0)
2840 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2841 else
2842 create_conin();
2843 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2844
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002845# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01002846 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002847 SaveConsoleBuffer(&g_cbOrig);
2848 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002849# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01002850 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002851 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2852 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002853# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002854 if (cterm_normal_fg_color == 0)
2855 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2856 if (cterm_normal_bg_color == 0)
2857 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2858
Bram Moolenaarbdace832019-03-02 10:13:42 +01002859 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002860 g_color_index_fg = g_attrDefault & 0xf;
2861 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2862
Bram Moolenaar0f873732019-12-05 20:28:46 +01002863 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00002864 update_tcap(g_attrCurrent);
2865
2866 GetConsoleCursorInfo(g_hConOut, &g_cci);
2867 GetConsoleMode(g_hConIn, &g_cmodein);
2868 GetConsoleMode(g_hConOut, &g_cmodeout);
2869
Bram Moolenaar071d4272004-06-13 20:20:40 +00002870 SaveConsoleTitleAndIcon();
2871 /*
2872 * Set both the small and big icons of the console window to Vim's icon.
2873 * Note that Vim presently only has one size of icon (32x32), but it
2874 * automatically gets scaled down to 16x16 when setting the small icon.
2875 */
2876 if (g_fCanChangeIcon)
2877 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002878
2879 ui_get_shellsize();
2880
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002881# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002882 fdDump = fopen("dump", "wt");
2883
2884 if (fdDump)
2885 {
2886 time_t t;
2887
2888 time(&t);
2889 fputs(ctime(&t), fdDump);
2890 fflush(fdDump);
2891 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002892# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002893
2894 g_fWindInitCalled = TRUE;
2895
Bram Moolenaar071d4272004-06-13 20:20:40 +00002896 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002897
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002898# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002899 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002900# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002901
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02002902 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002903 vtp_init();
Bram Moolenaar06b7b582020-05-30 17:49:25 +02002904 wt_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002905}
2906
2907/*
2908 * non-GUI version of mch_exit().
2909 * Shut down and exit with status `r'
2910 * Careful: mch_exit() may be called before mch_init()!
2911 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002912 static void
2913mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002914{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002915 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002916
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002917 vtp_exit();
2918
Bram Moolenaar955f1982017-02-05 15:10:51 +01002919 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002920 if (g_fWindInitCalled)
2921 settmode(TMODE_COOK);
2922
Bram Moolenaar0f873732019-12-05 20:28:46 +01002923 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00002924
2925 if (g_fWindInitCalled)
2926 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02002927 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002928 /*
2929 * Restore both the small and big icons of the console window to
2930 * what they were at startup. Don't do this when the window is
2931 * closed, Vim would hang here.
2932 */
2933 if (g_fCanChangeIcon && !g_fForceExit)
2934 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002935
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002936# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002937 if (fdDump)
2938 {
2939 time_t t;
2940
2941 time(&t);
2942 fputs(ctime(&t), fdDump);
2943 fclose(fdDump);
2944 }
2945 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002946# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002947 }
2948
2949 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02002950 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002951 SetConsoleMode(g_hConOut, g_cmodeout);
2952
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002953# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00002954 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002955# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002956
2957 exit(r);
2958}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002959#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002960
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002961 void
2962mch_init(void)
2963{
2964#ifdef VIMDLL
2965 if (gui.starting)
2966 mch_init_g();
2967 else
2968 mch_init_c();
2969#elif defined(FEAT_GUI_MSWIN)
2970 mch_init_g();
2971#else
2972 mch_init_c();
2973#endif
2974}
2975
2976 void
2977mch_exit(int r)
2978{
Bram Moolenaar173d8412020-04-19 14:02:26 +02002979#ifdef FEAT_NETBEANS_INTG
2980 netbeans_send_disconnect();
2981#endif
2982
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002983#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02002984 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002985 mch_exit_g(r);
2986 else
2987 mch_exit_c(r);
2988#elif defined(FEAT_GUI_MSWIN)
2989 mch_exit_g(r);
2990#else
2991 mch_exit_c(r);
2992#endif
2993}
2994
Bram Moolenaar071d4272004-06-13 20:20:40 +00002995/*
2996 * Do we have an interactive window?
2997 */
2998 int
2999mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003000 int argc UNUSED,
3001 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003002{
3003 get_exe_name();
3004
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003005#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003006 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003007#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003008# ifdef VIMDLL
3009 if (gui.in_use)
3010 return OK;
3011# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003012 if (isatty(1))
3013 return OK;
3014 return FAIL;
3015#endif
3016}
3017
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003018/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003019 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003020 * When "len" is > 0, also expand short to long filenames.
3021 */
3022 void
3023fname_case(
3024 char_u *name,
3025 int len)
3026{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003027 int flen;
3028 WCHAR *p;
3029 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003030
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003031 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003032 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003033 return;
3034
3035 slash_adjust(name);
3036
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003037 p = enc_to_utf16(name, NULL);
3038 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003039 return;
3040
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003041 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003042 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003043 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003044
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003045 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003046 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003047 if (len > 0 || flen >= (int)STRLEN(q))
3048 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3049 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003050 }
3051 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003052 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003053}
3054
3055
3056/*
3057 * Insert user name in s[len].
3058 */
3059 int
3060mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003061 char_u *s,
3062 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003063{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003064 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003065 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003066
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003067 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003068 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003069 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003070
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003071 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003072 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003073 vim_strncpy(s, p, len - 1);
3074 vim_free(p);
3075 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003076 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003077 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003078 s[0] = NUL;
3079 return FAIL;
3080}
3081
3082
3083/*
3084 * Insert host name in s[len].
3085 */
3086 void
3087mch_get_host_name(
3088 char_u *s,
3089 int len)
3090{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003091 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003092 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003093
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003094 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003095 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003096 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003097
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003098 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003099 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003100 vim_strncpy(s, p, len - 1);
3101 vim_free(p);
3102 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003103 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003104 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003105}
3106
3107
3108/*
3109 * return process ID
3110 */
3111 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003112mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003113{
3114 return (long)GetCurrentProcessId();
3115}
3116
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003117/*
3118 * return TRUE if process "pid" is still running
3119 */
3120 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003121mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003122{
3123 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3124 DWORD status = 0;
3125 int ret = FALSE;
3126
3127 if (hProcess == NULL)
3128 return FALSE; // might not have access
3129 if (GetExitCodeProcess(hProcess, &status) )
3130 ret = status == STILL_ACTIVE;
3131 CloseHandle(hProcess);
3132 return ret;
3133}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003134
3135/*
3136 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3137 * Return OK for success, FAIL for failure.
3138 */
3139 int
3140mch_dirname(
3141 char_u *buf,
3142 int len)
3143{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003144 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003145
Bram Moolenaar071d4272004-06-13 20:20:40 +00003146 /*
3147 * Originally this was:
3148 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3149 * But the Win32s known bug list says that getcwd() doesn't work
3150 * so use the Win32 system call instead. <Negri>
3151 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003152 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003153 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003154 WCHAR wcbuf[_MAX_PATH + 1];
3155 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003156
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003157 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003158 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003159 p = utf16_to_enc(wcbuf, NULL);
3160 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003161 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003162 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003163 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003164 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003165 }
3166 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003167 if (p == NULL)
3168 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003169
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003170 if (p != NULL)
3171 {
3172 vim_strncpy(buf, p, len - 1);
3173 vim_free(p);
3174 return OK;
3175 }
3176 }
3177 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003178}
3179
3180/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003181 * Get file permissions for "name".
3182 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003183 */
3184 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003185mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003186{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003187 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003188 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003189
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003190 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003191 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003192}
3193
3194
3195/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003196 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003197 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003198 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003199 */
3200 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003201mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003202{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003203 long n;
3204 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003205
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003206 p = enc_to_utf16(name, NULL);
3207 if (p == NULL)
3208 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003209
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003210 n = _wchmod(p, perm);
3211 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003212 if (n == -1)
3213 return FAIL;
3214
3215 win32_set_archive(name);
3216
3217 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003218}
3219
3220/*
3221 * Set hidden flag for "name".
3222 */
3223 void
3224mch_hide(char_u *name)
3225{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003226 int attrs = win32_getattrs(name);
3227 if (attrs == -1)
3228 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003229
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003230 attrs |= FILE_ATTRIBUTE_HIDDEN;
3231 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003232}
3233
3234/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003235 * Return TRUE if file "name" exists and is hidden.
3236 */
3237 int
3238mch_ishidden(char_u *name)
3239{
3240 int f = win32_getattrs(name);
3241
3242 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003243 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003244
3245 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3246}
3247
3248/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003249 * return TRUE if "name" is a directory
3250 * return FALSE if "name" is not a directory or upon error
3251 */
3252 int
3253mch_isdir(char_u *name)
3254{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003255 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003256
3257 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003258 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003259
3260 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3261}
3262
3263/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003264 * return TRUE if "name" is a directory, NOT a symlink to a directory
3265 * return FALSE if "name" is not a directory
3266 * return FALSE for error
3267 */
3268 int
3269mch_isrealdir(char_u *name)
3270{
3271 return mch_isdir(name) && !mch_is_symbolic_link(name);
3272}
3273
3274/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003275 * Create directory "name".
3276 * Return 0 on success, -1 on error.
3277 */
3278 int
3279mch_mkdir(char_u *name)
3280{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003281 WCHAR *p;
3282 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003283
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003284 p = enc_to_utf16(name, NULL);
3285 if (p == NULL)
3286 return -1;
3287 retval = _wmkdir(p);
3288 vim_free(p);
3289 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003290}
3291
3292/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003293 * Delete directory "name".
3294 * Return 0 on success, -1 on error.
3295 */
3296 int
3297mch_rmdir(char_u *name)
3298{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003299 WCHAR *p;
3300 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003301
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003302 p = enc_to_utf16(name, NULL);
3303 if (p == NULL)
3304 return -1;
3305 retval = _wrmdir(p);
3306 vim_free(p);
3307 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003308}
3309
3310/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003311 * Return TRUE if file "fname" has more than one link.
3312 */
3313 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003314mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003315{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003316 BY_HANDLE_FILE_INFORMATION info;
3317
3318 return win32_fileinfo(fname, &info) == FILEINFO_OK
3319 && info.nNumberOfLinks > 1;
3320}
3321
3322/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003323 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003324 */
3325 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003326mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003327{
3328 HANDLE hFind;
3329 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003330 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003331 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003332 WIN32_FIND_DATAW findDataW;
3333
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003334 wn = enc_to_utf16(name, NULL);
3335 if (wn == NULL)
3336 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003337
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003338 hFind = FindFirstFileW(wn, &findDataW);
3339 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003340 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003341 {
3342 fileFlags = findDataW.dwFileAttributes;
3343 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003344 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003345 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003346
3347 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003348 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3349 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003350 res = TRUE;
3351
3352 return res;
3353}
3354
3355/*
3356 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3357 * link.
3358 */
3359 int
3360mch_is_linked(char_u *fname)
3361{
3362 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3363 return TRUE;
3364 return FALSE;
3365}
3366
3367/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003368 * Get the by-handle-file-information for "fname".
3369 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003370 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003371 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3372 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3373 */
3374 int
3375win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3376{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003377 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003378 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003379 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003380
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003381 wn = enc_to_utf16(fname, NULL);
3382 if (wn == NULL)
3383 return FILEINFO_ENC_FAIL;
3384
3385 hFile = CreateFileW(wn, // file name
3386 GENERIC_READ, // access mode
3387 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3388 NULL, // security descriptor
3389 OPEN_EXISTING, // creation disposition
3390 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3391 NULL); // handle to template file
3392 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003393
3394 if (hFile != INVALID_HANDLE_VALUE)
3395 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003396 if (GetFileInformationByHandle(hFile, info) != 0)
3397 res = FILEINFO_OK;
3398 else
3399 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003400 CloseHandle(hFile);
3401 }
3402
Bram Moolenaar03f48552006-02-28 23:52:23 +00003403 return res;
3404}
3405
3406/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003407 * get file attributes for `name'
3408 * -1 : error
3409 * else FILE_ATTRIBUTE_* defined in winnt.h
3410 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003411 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003412win32_getattrs(char_u *name)
3413{
3414 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003415 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003416
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003417 p = enc_to_utf16(name, NULL);
3418 if (p == NULL)
3419 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003420
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003421 attr = GetFileAttributesW(p);
3422 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003423
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003424 return attr;
3425}
3426
3427/*
3428 * set file attributes for `name' to `attrs'
3429 *
3430 * return -1 for failure, 0 otherwise
3431 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003432 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003433win32_setattrs(char_u *name, int attrs)
3434{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003435 int res;
3436 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003437
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003438 p = enc_to_utf16(name, NULL);
3439 if (p == NULL)
3440 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003441
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003442 res = SetFileAttributesW(p, attrs);
3443 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003444
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003445 return res ? 0 : -1;
3446}
3447
3448/*
3449 * Set archive flag for "name".
3450 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003451 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003452win32_set_archive(char_u *name)
3453{
3454 int attrs = win32_getattrs(name);
3455 if (attrs == -1)
3456 return -1;
3457
3458 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3459 return win32_setattrs(name, attrs);
3460}
3461
3462/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003463 * Return TRUE if file or directory "name" is writable (not readonly).
3464 * Strange semantics of Win32: a readonly directory is writable, but you can't
3465 * delete a file. Let's say this means it is writable.
3466 */
3467 int
3468mch_writable(char_u *name)
3469{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003470 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003471
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003472 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3473 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003474}
3475
Bram Moolenaar071d4272004-06-13 20:20:40 +00003476/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003477 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003478 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003479 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3480 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003481 */
3482 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003483mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003484{
Bram Moolenaar95da1362020-05-30 18:37:55 +02003485 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003486}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003487
3488/*
3489 * Check what "name" is:
3490 * NODE_NORMAL: file or directory (or doesn't exist)
3491 * NODE_WRITABLE: writable device, socket, fifo, etc.
3492 * NODE_OTHER: non-writable things
3493 */
3494 int
3495mch_nodetype(char_u *name)
3496{
3497 HANDLE hFile;
3498 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003499 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003500
Bram Moolenaar0f873732019-12-05 20:28:46 +01003501 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3502 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3503 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00003504 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3505 return NODE_WRITABLE;
3506
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003507 wn = enc_to_utf16(name, NULL);
3508 if (wn == NULL)
3509 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003510
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003511 hFile = CreateFileW(wn, // file name
3512 GENERIC_WRITE, // access mode
3513 0, // share mode
3514 NULL, // security descriptor
3515 OPEN_EXISTING, // creation disposition
3516 0, // file attributes
3517 NULL); // handle to template file
3518 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003519 if (hFile == INVALID_HANDLE_VALUE)
3520 return NODE_NORMAL;
3521
3522 type = GetFileType(hFile);
3523 CloseHandle(hFile);
3524 if (type == FILE_TYPE_CHAR)
3525 return NODE_WRITABLE;
3526 if (type == FILE_TYPE_DISK)
3527 return NODE_NORMAL;
3528 return NODE_OTHER;
3529}
3530
3531#ifdef HAVE_ACL
3532struct my_acl
3533{
3534 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3535 PSID pSidOwner;
3536 PSID pSidGroup;
3537 PACL pDacl;
3538 PACL pSacl;
3539};
3540#endif
3541
3542/*
3543 * Return a pointer to the ACL of file "fname" in allocated memory.
3544 * Return NULL if the ACL is not available for whatever reason.
3545 */
3546 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003547mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003548{
3549#ifndef HAVE_ACL
3550 return (vim_acl_T)NULL;
3551#else
3552 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003553 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003554
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003555 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003556 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003557 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003558 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003559
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003560 wn = enc_to_utf16(fname, NULL);
3561 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003562 {
3563 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003564 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003565 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003566
3567 // Try to retrieve the entire security descriptor.
3568 err = GetNamedSecurityInfoW(
3569 wn, // Abstract filename
3570 SE_FILE_OBJECT, // File Object
3571 OWNER_SECURITY_INFORMATION |
3572 GROUP_SECURITY_INFORMATION |
3573 DACL_SECURITY_INFORMATION |
3574 SACL_SECURITY_INFORMATION,
3575 &p->pSidOwner, // Ownership information.
3576 &p->pSidGroup, // Group membership.
3577 &p->pDacl, // Discretionary information.
3578 &p->pSacl, // For auditing purposes.
3579 &p->pSecurityDescriptor);
3580 if (err == ERROR_ACCESS_DENIED ||
3581 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003582 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003583 // Retrieve only DACL.
3584 (void)GetNamedSecurityInfoW(
3585 wn,
3586 SE_FILE_OBJECT,
3587 DACL_SECURITY_INFORMATION,
3588 NULL,
3589 NULL,
3590 &p->pDacl,
3591 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003592 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003593 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003594 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003595 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003596 mch_free_acl((vim_acl_T)p);
3597 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003598 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003599 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003600 }
3601
3602 return (vim_acl_T)p;
3603#endif
3604}
3605
Bram Moolenaar27515922013-06-29 15:36:26 +02003606#ifdef HAVE_ACL
3607/*
3608 * Check if "acl" contains inherited ACE.
3609 */
3610 static BOOL
3611is_acl_inherited(PACL acl)
3612{
3613 DWORD i;
3614 ACL_SIZE_INFORMATION acl_info;
3615 PACCESS_ALLOWED_ACE ace;
3616
3617 acl_info.AceCount = 0;
3618 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3619 for (i = 0; i < acl_info.AceCount; i++)
3620 {
3621 GetAce(acl, i, (LPVOID *)&ace);
3622 if (ace->Header.AceFlags & INHERITED_ACE)
3623 return TRUE;
3624 }
3625 return FALSE;
3626}
3627#endif
3628
Bram Moolenaar071d4272004-06-13 20:20:40 +00003629/*
3630 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3631 * Errors are ignored.
3632 * This must only be called with "acl" equal to what mch_get_acl() returned.
3633 */
3634 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003635mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003636{
3637#ifdef HAVE_ACL
3638 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003639 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003640 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003641
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003642 if (p == NULL)
3643 return;
3644
3645 wn = enc_to_utf16(fname, NULL);
3646 if (wn == NULL)
3647 return;
3648
3649 // Set security flags
3650 if (p->pSidOwner)
3651 sec_info |= OWNER_SECURITY_INFORMATION;
3652 if (p->pSidGroup)
3653 sec_info |= GROUP_SECURITY_INFORMATION;
3654 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003655 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003656 sec_info |= DACL_SECURITY_INFORMATION;
3657 // Do not inherit its parent's DACL.
3658 // If the DACL is inherited, Cygwin permissions would be changed.
3659 if (!is_acl_inherited(p->pDacl))
3660 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003661 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003662 if (p->pSacl)
3663 sec_info |= SACL_SECURITY_INFORMATION;
3664
3665 (void)SetNamedSecurityInfoW(
3666 wn, // Abstract filename
3667 SE_FILE_OBJECT, // File Object
3668 sec_info,
3669 p->pSidOwner, // Ownership information.
3670 p->pSidGroup, // Group membership.
3671 p->pDacl, // Discretionary information.
3672 p->pSacl // For auditing purposes.
3673 );
3674 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003675#endif
3676}
3677
3678 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003679mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003680{
3681#ifdef HAVE_ACL
3682 struct my_acl *p = (struct my_acl *)acl;
3683
3684 if (p != NULL)
3685 {
3686 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3687 vim_free(p);
3688 }
3689#endif
3690}
3691
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003692#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003693
3694/*
3695 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3696 */
3697 static BOOL WINAPI
3698handler_routine(
3699 DWORD dwCtrlType)
3700{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003701 INPUT_RECORD ir;
3702 DWORD out;
3703
Bram Moolenaar071d4272004-06-13 20:20:40 +00003704 switch (dwCtrlType)
3705 {
3706 case CTRL_C_EVENT:
3707 if (ctrl_c_interrupts)
3708 g_fCtrlCPressed = TRUE;
3709 return TRUE;
3710
3711 case CTRL_BREAK_EVENT:
3712 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003713 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003714 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02003715 ir.EventType = KEY_EVENT;
3716 ir.Event.KeyEvent.bKeyDown = TRUE;
3717 ir.Event.KeyEvent.wRepeatCount = 1;
3718 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3719 ir.Event.KeyEvent.wVirtualScanCode = 0;
3720 ir.Event.KeyEvent.dwControlKeyState = 0;
3721 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3722 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003723 return TRUE;
3724
Bram Moolenaar0f873732019-12-05 20:28:46 +01003725 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00003726 case CTRL_CLOSE_EVENT:
3727 case CTRL_LOGOFF_EVENT:
3728 case CTRL_SHUTDOWN_EVENT:
3729 windgoto((int)Rows - 1, 0);
3730 g_fForceExit = TRUE;
3731
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003732 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003733 (dwCtrlType == CTRL_CLOSE_EVENT
3734 ? _("close")
3735 : dwCtrlType == CTRL_LOGOFF_EVENT
3736 ? _("logoff")
3737 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003738# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00003739 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003740# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003741
Bram Moolenaar0f873732019-12-05 20:28:46 +01003742 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00003743
Bram Moolenaar0f873732019-12-05 20:28:46 +01003744 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00003745
3746 default:
3747 return FALSE;
3748 }
3749}
3750
3751
3752/*
3753 * set the tty in (raw) ? "raw" : "cooked" mode
3754 */
3755 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02003756mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003757{
3758 DWORD cmodein;
3759 DWORD cmodeout;
3760 BOOL bEnableHandler;
3761
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003762# ifdef VIMDLL
3763 if (gui.in_use)
3764 return;
3765# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003766 GetConsoleMode(g_hConIn, &cmodein);
3767 GetConsoleMode(g_hConOut, &cmodeout);
3768 if (tmode == TMODE_RAW)
3769 {
3770 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3771 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003772 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003773 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003774 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003775 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
3776 }
3777 else
3778 {
3779 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
3780 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003781 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003782# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01003783 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
3784 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003785 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003786# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003787 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003788# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003789 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003790 bEnableHandler = TRUE;
3791 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01003792 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00003793 {
3794 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3795 ENABLE_ECHO_INPUT);
3796 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3797 bEnableHandler = FALSE;
3798 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003799 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003800 SetConsoleMode(g_hConOut, cmodeout);
3801 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3802
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003803# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003804 if (fdDump)
3805 {
3806 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3807 tmode == TMODE_RAW ? "raw" :
3808 tmode == TMODE_COOK ? "cooked" : "normal",
3809 cmodein, cmodeout);
3810 fflush(fdDump);
3811 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003812# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003813}
3814
3815
3816/*
3817 * Get the size of the current window in `Rows' and `Columns'
3818 * Return OK when size could be determined, FAIL otherwise.
3819 */
3820 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003821mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003822{
3823 CONSOLE_SCREEN_BUFFER_INFO csbi;
3824
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003825# ifdef VIMDLL
3826 if (gui.in_use)
3827 return OK;
3828# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003829 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3830 {
3831 /*
3832 * For some reason, we are trying to get the screen dimensions
3833 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3834 * variables are really intended to mean the size of Vim screen
3835 * while in termcap mode.
3836 */
3837 Rows = g_cbTermcap.Info.dwSize.Y;
3838 Columns = g_cbTermcap.Info.dwSize.X;
3839 }
3840 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3841 {
3842 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3843 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3844 }
3845 else
3846 {
3847 Rows = 25;
3848 Columns = 80;
3849 }
3850 return OK;
3851}
3852
3853/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003854 * Resize console buffer to 'COORD'
3855 */
3856 static void
3857ResizeConBuf(
3858 HANDLE hConsole,
3859 COORD coordScreen)
3860{
3861 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3862 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003863# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003864 if (fdDump)
3865 {
3866 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3867 GetLastError());
3868 fflush(fdDump);
3869 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003870# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003871 }
3872}
3873
3874/*
3875 * Resize console window size to 'srWindowRect'
3876 */
3877 static void
3878ResizeWindow(
3879 HANDLE hConsole,
3880 SMALL_RECT srWindowRect)
3881{
3882 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
3883 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003884# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003885 if (fdDump)
3886 {
3887 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3888 GetLastError());
3889 fflush(fdDump);
3890 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003891# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003892 }
3893}
3894
3895/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003896 * Set a console window to `xSize' * `ySize'
3897 */
3898 static void
3899ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003900 HANDLE hConsole,
3901 int xSize,
3902 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003903{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003904 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
3905 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003906 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003907 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02003908 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003909
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003910# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003911 if (fdDump)
3912 {
3913 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3914 fflush(fdDump);
3915 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003916# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003917
Bram Moolenaar0f873732019-12-05 20:28:46 +01003918 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00003919 coordScreen = GetLargestConsoleWindowSize(hConsole);
3920
Bram Moolenaar0f873732019-12-05 20:28:46 +01003921 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00003922 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3923 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3924 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3925
3926 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3927 {
3928 int sx, sy;
3929
3930 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3931 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3932 if (sy < ySize || sx < xSize)
3933 {
3934 /*
3935 * Increasing number of lines/columns, do buffer first.
3936 * Use the maximal size in x and y direction.
3937 */
3938 if (sy < ySize)
3939 coordScreen.Y = ySize;
3940 else
3941 coordScreen.Y = sy;
3942 if (sx < xSize)
3943 coordScreen.X = xSize;
3944 else
3945 coordScreen.X = sx;
3946 SetConsoleScreenBufferSize(hConsole, coordScreen);
3947 }
3948 }
3949
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003950 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003951 coordScreen.X = xSize;
3952 coordScreen.Y = ySize;
3953
Bram Moolenaar2551c032018-08-23 22:38:31 +02003954 // In the new console call API, only the first time in reverse order
3955 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003956 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003957 ResizeWindow(hConsole, srWindowRect);
3958 ResizeConBuf(hConsole, coordScreen);
3959 }
3960 else
3961 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003962 // Workaround for a Windows 10 bug
3963 cursor.X = srWindowRect.Left;
3964 cursor.Y = srWindowRect.Top;
3965 SetConsoleCursorPosition(hConsole, cursor);
3966
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003967 ResizeConBuf(hConsole, coordScreen);
3968 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02003969 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003970 }
3971}
3972
3973
3974/*
3975 * Set the console window to `Rows' * `Columns'
3976 */
3977 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003978mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003979{
3980 COORD coordScreen;
3981
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003982# ifdef VIMDLL
3983 if (gui.in_use)
3984 return;
3985# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01003986 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00003987 if (suppress_winsize != 0)
3988 {
3989 suppress_winsize = 2;
3990 return;
3991 }
3992
3993 if (term_console)
3994 {
3995 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3996
Bram Moolenaar0f873732019-12-05 20:28:46 +01003997 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00003998 if (Rows > coordScreen.Y)
3999 Rows = coordScreen.Y;
4000 if (Columns > coordScreen.X)
4001 Columns = coordScreen.X;
4002
4003 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4004 }
4005}
4006
4007/*
4008 * Rows and/or Columns has changed.
4009 */
4010 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004011mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004012{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004013# ifdef VIMDLL
4014 if (gui.in_use)
4015 return;
4016# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004017 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4018}
4019
4020
4021/*
4022 * Called when started up, to set the winsize that was delayed.
4023 */
4024 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004025mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004026{
4027 if (suppress_winsize == 2)
4028 {
4029 suppress_winsize = 0;
4030 mch_set_shellsize();
4031 shell_resized();
4032 }
4033 suppress_winsize = 0;
4034}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004035#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004036
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004037 static BOOL
4038vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004039 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004040 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004041 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004042 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004043 PROCESS_INFORMATION *pi,
4044 LPVOID *env,
4045 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004046{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004047 BOOL ret = FALSE;
4048 WCHAR *wcmd, *wcwd = NULL;
4049
4050 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4051 if (wcmd == NULL)
4052 return FALSE;
4053 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004054 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004055 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4056 if (wcwd == NULL)
4057 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004058 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004059
4060 ret = CreateProcessW(
4061 NULL, // Executable name
4062 wcmd, // Command to execute
4063 NULL, // Process security attributes
4064 NULL, // Thread security attributes
4065 inherit_handles, // Inherit handles
4066 flags, // Creation flags
4067 env, // Environment
4068 wcwd, // Current directory
4069 (LPSTARTUPINFOW)si, // Startup information
4070 pi); // Process information
4071theend:
4072 vim_free(wcmd);
4073 vim_free(wcwd);
4074 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004075}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004076
4077
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004078 static HINSTANCE
4079vim_shell_execute(
4080 char *cmd,
4081 INT n_show_cmd)
4082{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004083 HINSTANCE ret;
4084 WCHAR *wcmd;
4085
4086 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4087 if (wcmd == NULL)
4088 return (HINSTANCE) 0;
4089
4090 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4091 vim_free(wcmd);
4092 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004093}
4094
4095
Bram Moolenaar4f974752019-02-17 17:44:42 +01004096#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004097
4098/*
4099 * Specialised version of system() for Win32 GUI mode.
4100 * This version proceeds as follows:
4101 * 1. Create a console window for use by the subprocess
4102 * 2. Run the subprocess (it gets the allocated console by default)
4103 * 3. Wait for the subprocess to terminate and get its exit code
4104 * 4. Prompt the user to press a key to close the console window
4105 */
4106 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004107mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004108{
4109 STARTUPINFO si;
4110 PROCESS_INFORMATION pi;
4111 DWORD ret = 0;
4112 HWND hwnd = GetFocus();
4113
4114 si.cb = sizeof(si);
4115 si.lpReserved = NULL;
4116 si.lpDesktop = NULL;
4117 si.lpTitle = NULL;
4118 si.dwFlags = STARTF_USESHOWWINDOW;
4119 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004120 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004121 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004122 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004123 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004124 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004125 else
4126 si.wShowWindow = SW_SHOWNORMAL;
4127 si.cbReserved2 = 0;
4128 si.lpReserved2 = NULL;
4129
Bram Moolenaar0f873732019-12-05 20:28:46 +01004130 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004131 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004132 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4133 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004134
Bram Moolenaar0f873732019-12-05 20:28:46 +01004135 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004136 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004137# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004138 int delay = 1;
4139
Bram Moolenaar0f873732019-12-05 20:28:46 +01004140 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004141 for (;;)
4142 {
4143 MSG msg;
4144
K.Takatab7057bd2022-01-21 11:37:07 +00004145 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004146 {
4147 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004148 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004149 delay = 1;
4150 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004151 }
4152 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4153 break;
4154
Bram Moolenaar0f873732019-12-05 20:28:46 +01004155 // We start waiting for a very short time and then increase it, so
4156 // that we respond quickly when the process is quick, and don't
4157 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004158 if (delay < 50)
4159 delay += 10;
4160 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004161# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004162 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004163# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004164
Bram Moolenaar0f873732019-12-05 20:28:46 +01004165 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004166 GetExitCodeProcess(pi.hProcess, &ret);
4167 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004168
Bram Moolenaar0f873732019-12-05 20:28:46 +01004169 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004170 CloseHandle(pi.hThread);
4171 CloseHandle(pi.hProcess);
4172
Bram Moolenaar0f873732019-12-05 20:28:46 +01004173 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004174 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4175
4176 return ret;
4177}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004178
4179/*
4180 * Thread launched by the gui to send the current buffer data to the
4181 * process. This way avoid to hang up vim totally if the children
4182 * process take a long time to process the lines.
4183 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004184 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004185sub_process_writer(LPVOID param)
4186{
4187 HANDLE g_hChildStd_IN_Wr = param;
4188 linenr_T lnum = curbuf->b_op_start.lnum;
4189 DWORD len = 0;
4190 DWORD l;
4191 char_u *lp = ml_get(lnum);
4192 char_u *s;
4193 int written = 0;
4194
4195 for (;;)
4196 {
4197 l = (DWORD)STRLEN(lp + written);
4198 if (l == 0)
4199 len = 0;
4200 else if (lp[written] == NL)
4201 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004202 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004203 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4204 }
4205 else
4206 {
4207 s = vim_strchr(lp + written, NL);
4208 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4209 s == NULL ? l : (DWORD)(s - (lp + written)),
4210 &len, NULL);
4211 }
4212 if (len == (int)l)
4213 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004214 // Finished a line, add a NL, unless this line should not have
4215 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004216 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004217 || (!curbuf->b_p_bin
4218 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004219 || (lnum != curbuf->b_no_eol_lnum
4220 && (lnum != curbuf->b_ml.ml_line_count
4221 || curbuf->b_p_eol)))
4222 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004223 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4224 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004225 }
4226
4227 ++lnum;
4228 if (lnum > curbuf->b_op_end.lnum)
4229 break;
4230
4231 lp = ml_get(lnum);
4232 written = 0;
4233 }
4234 else if (len > 0)
4235 written += len;
4236 }
4237
Bram Moolenaar0f873732019-12-05 20:28:46 +01004238 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004239 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004240 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004241}
4242
4243
Bram Moolenaar0f873732019-12-05 20:28:46 +01004244# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004245
4246/*
4247 * This function read from the children's stdout and write the
4248 * data on screen or in the buffer accordingly.
4249 */
4250 static void
4251dump_pipe(int options,
4252 HANDLE g_hChildStd_OUT_Rd,
4253 garray_T *ga,
4254 char_u buffer[],
4255 DWORD *buffer_off)
4256{
4257 DWORD availableBytes = 0;
4258 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004259 int ret;
4260 DWORD len;
4261 DWORD toRead;
4262 int repeatCount;
4263
Bram Moolenaar0f873732019-12-05 20:28:46 +01004264 // we query the pipe to see if there is any data to read
4265 // to avoid to perform a blocking read
4266 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4267 NULL, // optional buffer
4268 0, // buffer size
4269 NULL, // number of read bytes
4270 &availableBytes, // available bytes total
4271 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004272
4273 repeatCount = 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004274 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004275 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004276 {
4277 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004278 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004279 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004280 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004281
Bram Moolenaar0f873732019-12-05 20:28:46 +01004282 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004283 if (len == 0)
4284 break;
4285
4286 availableBytes -= len;
4287
4288 if (options & SHELL_READ)
4289 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004290 // Do NUL -> NL translation, append NL separated
4291 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004292 for (i = 0; i < len; ++i)
4293 {
4294 if (buffer[i] == NL)
4295 append_ga_line(ga);
4296 else if (buffer[i] == NUL)
4297 ga_append(ga, NL);
4298 else
4299 ga_append(ga, buffer[i]);
4300 }
4301 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004302 else if (has_mbyte)
4303 {
4304 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004305 int c;
4306 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004307
4308 len += *buffer_off;
4309 buffer[len] = NUL;
4310
Bram Moolenaar0f873732019-12-05 20:28:46 +01004311 // Check if the last character in buffer[] is
4312 // incomplete, keep these bytes for the next
4313 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004314 for (p = buffer; p < buffer + len; p += l)
4315 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004316 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004317 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004318 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004319 else if (MB_BYTE2LEN(*p) != l)
4320 break;
4321 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004322 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004323 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004324 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004325 if (len >= 12)
4326 ++p;
4327 else
4328 {
4329 *buffer_off = len;
4330 return;
4331 }
4332 }
4333 c = *p;
4334 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004335 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004336 if (p < buffer + len)
4337 {
4338 *p = c;
4339 *buffer_off = (DWORD)((buffer + len) - p);
4340 mch_memmove(buffer, p, *buffer_off);
4341 return;
4342 }
4343 *buffer_off = 0;
4344 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004345 else
4346 {
4347 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004348 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004349 }
4350
4351 windgoto(msg_row, msg_col);
4352 cursor_on();
4353 out_flush();
4354 }
4355}
4356
4357/*
4358 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4359 * for communication and doesn't open any new window.
4360 */
4361 static int
4362mch_system_piped(char *cmd, int options)
4363{
4364 STARTUPINFO si;
4365 PROCESS_INFORMATION pi;
4366 DWORD ret = 0;
4367
4368 HANDLE g_hChildStd_IN_Rd = NULL;
4369 HANDLE g_hChildStd_IN_Wr = NULL;
4370 HANDLE g_hChildStd_OUT_Rd = NULL;
4371 HANDLE g_hChildStd_OUT_Wr = NULL;
4372
Bram Moolenaar0f873732019-12-05 20:28:46 +01004373 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004374 DWORD len;
4375
Bram Moolenaar0f873732019-12-05 20:28:46 +01004376 // buffer used to receive keys
4377 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4378 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004379
4380 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004381 int noread_cnt = 0;
4382 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004383 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004384 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004385 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004386
4387 SECURITY_ATTRIBUTES saAttr;
4388
Bram Moolenaar0f873732019-12-05 20:28:46 +01004389 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004390 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4391 saAttr.bInheritHandle = TRUE;
4392 saAttr.lpSecurityDescriptor = NULL;
4393
4394 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004395 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004396 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004397 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004398 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004399 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004400 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004401 {
4402 CloseHandle(g_hChildStd_IN_Rd);
4403 CloseHandle(g_hChildStd_IN_Wr);
4404 CloseHandle(g_hChildStd_OUT_Rd);
4405 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004406 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004407 }
4408
4409 si.cb = sizeof(si);
4410 si.lpReserved = NULL;
4411 si.lpDesktop = NULL;
4412 si.lpTitle = NULL;
4413 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4414
Bram Moolenaar0f873732019-12-05 20:28:46 +01004415 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004416 si.hStdError = g_hChildStd_OUT_Wr;
4417 si.hStdOutput = g_hChildStd_OUT_Wr;
4418 si.hStdInput = g_hChildStd_IN_Rd;
4419 si.wShowWindow = SW_HIDE;
4420 si.cbReserved2 = 0;
4421 si.lpReserved2 = NULL;
4422
4423 if (options & SHELL_READ)
4424 ga_init2(&ga, 1, BUFLEN);
4425
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004426 if (cmd != NULL)
4427 {
4428 p = (char *)vim_strsave((char_u *)cmd);
4429 if (p != NULL)
4430 unescape_shellxquote((char_u *)p, p_sxe);
4431 else
4432 p = cmd;
4433 }
4434
Bram Moolenaar0f873732019-12-05 20:28:46 +01004435 // Now, run the command.
4436 // About "Inherit handles" being TRUE: this command can be litigious,
4437 // handle inheritance was deactivated for pending temp file, but, if we
4438 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004439 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4440 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004441
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004442 if (p != cmd)
4443 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004444
Bram Moolenaar0f873732019-12-05 20:28:46 +01004445 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004446 CloseHandle(g_hChildStd_IN_Rd);
4447 CloseHandle(g_hChildStd_OUT_Wr);
4448
4449 if (options & SHELL_WRITE)
4450 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004451 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004452 _beginthreadex(NULL, // security attributes
4453 0, // default stack size
4454 sub_process_writer, // function to be executed
4455 g_hChildStd_IN_Wr, // parameter
4456 0, // creation flag, start immediately
4457 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004458 CloseHandle(thread);
4459 g_hChildStd_IN_Wr = NULL;
4460 }
4461
Bram Moolenaar0f873732019-12-05 20:28:46 +01004462 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004463 for (;;)
4464 {
4465 MSG msg;
4466
K.Takatab7057bd2022-01-21 11:37:07 +00004467 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004468 {
4469 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004470 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004471 }
4472
Bram Moolenaar0f873732019-12-05 20:28:46 +01004473 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004474 if ((options & (SHELL_READ|SHELL_WRITE))
4475# ifdef FEAT_GUI
4476 || gui.in_use
4477# endif
4478 )
4479 {
4480 len = 0;
4481 if (!(options & SHELL_EXPAND)
4482 && ((options &
4483 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4484 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4485# ifdef FEAT_GUI
4486 || gui.in_use
4487# endif
4488 )
4489 && (ta_len > 0 || noread_cnt > 4))
4490 {
4491 if (ta_len == 0)
4492 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004493 // Get extra characters when we don't have any. Reset the
4494 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004495 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004496 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4497 }
4498 if (ta_len > 0 || len > 0)
4499 {
4500 /*
4501 * For pipes: Check for CTRL-C: send interrupt signal to
4502 * child. Check for CTRL-D: EOF, close pipe to child.
4503 */
4504 if (len == 1 && cmd != NULL)
4505 {
4506 if (ta_buf[ta_len] == Ctrl_C)
4507 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004508 // Learn what exit code is expected, for
4509 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004510 TerminateProcess(pi.hProcess, 9);
4511 }
4512 if (ta_buf[ta_len] == Ctrl_D)
4513 {
4514 CloseHandle(g_hChildStd_IN_Wr);
4515 g_hChildStd_IN_Wr = NULL;
4516 }
4517 }
4518
Bram Moolenaarf4140482020-02-15 23:06:45 +01004519 term_replace_bs_del_keycode(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004520
4521 /*
4522 * For pipes: echo the typed characters. For a pty this
4523 * does not seem to work.
4524 */
4525 for (i = ta_len; i < ta_len + len; ++i)
4526 {
4527 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4528 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004529 else if (has_mbyte)
4530 {
4531 int l = (*mb_ptr2len)(ta_buf + i);
4532
4533 msg_outtrans_len(ta_buf + i, l);
4534 i += l - 1;
4535 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004536 else
4537 msg_outtrans_len(ta_buf + i, 1);
4538 }
4539 windgoto(msg_row, msg_col);
4540 out_flush();
4541
4542 ta_len += len;
4543
4544 /*
4545 * Write the characters to the child, unless EOF has been
4546 * typed for pipes. Write one character at a time, to
4547 * avoid losing too much typeahead. When writing buffer
4548 * lines, drop the typed characters (only check for
4549 * CTRL-C).
4550 */
4551 if (options & SHELL_WRITE)
4552 ta_len = 0;
4553 else if (g_hChildStd_IN_Wr != NULL)
4554 {
4555 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4556 1, &len, NULL);
4557 // if we are typing in, we want to keep things reactive
4558 delay = 1;
4559 if (len > 0)
4560 {
4561 ta_len -= len;
4562 mch_memmove(ta_buf, ta_buf + len, ta_len);
4563 }
4564 }
4565 }
4566 }
4567 }
4568
4569 if (ta_len)
4570 ui_inchar_undo(ta_buf, ta_len);
4571
4572 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4573 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004574 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004575 break;
4576 }
4577
4578 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004579 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004580
Bram Moolenaar0f873732019-12-05 20:28:46 +01004581 // We start waiting for a very short time and then increase it, so
4582 // that we respond quickly when the process is quick, and don't
4583 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004584 if (delay < 50)
4585 delay += 10;
4586 }
4587
Bram Moolenaar0f873732019-12-05 20:28:46 +01004588 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004589 CloseHandle(g_hChildStd_OUT_Rd);
4590 if (g_hChildStd_IN_Wr != NULL)
4591 CloseHandle(g_hChildStd_IN_Wr);
4592
4593 WaitForSingleObject(pi.hProcess, INFINITE);
4594
Bram Moolenaar0f873732019-12-05 20:28:46 +01004595 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004596 GetExitCodeProcess(pi.hProcess, &ret);
4597
4598 if (options & SHELL_READ)
4599 {
4600 if (ga.ga_len > 0)
4601 {
4602 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01004603 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004604 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4605 }
4606 else
4607 curbuf->b_no_eol_lnum = 0;
4608 ga_clear(&ga);
4609 }
4610
Bram Moolenaar0f873732019-12-05 20:28:46 +01004611 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004612 CloseHandle(pi.hThread);
4613 CloseHandle(pi.hProcess);
4614
4615 return ret;
4616}
4617
4618 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004619mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004620{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004621 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004622 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004623 return mch_system_piped(cmd, options);
4624 else
4625 return mch_system_classic(cmd, options);
4626}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004627#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004628
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004629#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004630 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02004631mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004632{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004633 int ret;
4634 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004635 char_u *buf;
4636 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004637
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004638 // If the command starts and ends with double quotes, enclose the command
4639 // in parentheses.
4640 len = STRLEN(cmd);
4641 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
4642 {
4643 len += 3;
4644 buf = alloc(len);
4645 if (buf == NULL)
4646 return -1;
4647 vim_snprintf((char *)buf, len, "(%s)", cmd);
4648 wcmd = enc_to_utf16(buf, NULL);
4649 free(buf);
4650 }
4651 else
4652 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4653
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004654 if (wcmd == NULL)
4655 return -1;
4656
4657 ret = _wsystem(wcmd);
4658 vim_free(wcmd);
4659 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004660}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004661
4662#endif
4663
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004664 static int
4665mch_system(char *cmd, int options)
4666{
4667#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004668 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004669 return mch_system_g(cmd, options);
4670 else
4671 return mch_system_c(cmd, options);
4672#elif defined(FEAT_GUI_MSWIN)
4673 return mch_system_g(cmd, options);
4674#else
4675 return mch_system_c(cmd, options);
4676#endif
4677}
4678
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004679#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4680/*
4681 * Use a terminal window to run a shell command in.
4682 */
4683 static int
4684mch_call_shell_terminal(
4685 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004686 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004687{
4688 jobopt_T opt;
4689 char_u *newcmd = NULL;
4690 typval_T argvar[2];
4691 long_u cmdlen;
4692 int retval = -1;
4693 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004694 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004695 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004696 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004697
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004698 if (cmd == NULL)
4699 cmdlen = STRLEN(p_sh) + 1;
4700 else
4701 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004702 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004703 if (newcmd == NULL)
4704 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004705 if (cmd == NULL)
4706 {
4707 STRCPY(newcmd, p_sh);
4708 ch_log(NULL, "starting terminal to run a shell");
4709 }
4710 else
4711 {
4712 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4713 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4714 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004715
4716 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004717
4718 argvar[0].v_type = VAR_STRING;
4719 argvar[0].vval.v_string = newcmd;
4720 argvar[1].v_type = VAR_UNKNOWN;
4721 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004722 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004723 {
4724 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004725 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004726 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004727
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004728 job = term_getjob(buf->b_term);
4729 ++job->jv_refcount;
4730
Bram Moolenaar0f873732019-12-05 20:28:46 +01004731 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004732 aucmd_prepbuf(&aco, buf);
4733
4734 clear_oparg(&oa);
4735 while (term_use_loop())
4736 {
4737 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4738 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004739 // If terminal_loop() returns OK we got a key that is handled
4740 // in Normal model. We don't do redrawing anyway.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004741 if (terminal_loop(TRUE) == OK)
4742 normal_cmd(&oa, TRUE);
4743 }
4744 else
4745 normal_cmd(&oa, TRUE);
4746 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004747 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004748 ch_log(NULL, "system command finished");
4749
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004750 job_unref(job);
4751
Bram Moolenaar0f873732019-12-05 20:28:46 +01004752 // restore curwin/curbuf and a few other things
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004753 aucmd_restbuf(&aco);
4754
4755 wait_return(TRUE);
4756 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4757
4758 vim_free(newcmd);
4759 return retval;
4760}
4761#endif
4762
Bram Moolenaar071d4272004-06-13 20:20:40 +00004763/*
4764 * Either execute a command by calling the shell or start a new shell
4765 */
4766 int
4767mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004768 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004769 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00004770{
4771 int x = 0;
4772 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004773 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004774
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01004775#ifdef FEAT_JOB_CHANNEL
4776 ch_log(NULL, "executing shell command: %s", cmd);
4777#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004778 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02004779 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004780 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004781 if (cmd == NULL)
4782 wcscat(szShellTitle, L" :sh");
4783 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004784 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004785 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004786
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004787 if (wn != NULL)
4788 {
4789 wcscat(szShellTitle, L" - !");
4790 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02004791 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004792 wcscat(szShellTitle, wn);
4793 SetConsoleTitleW(szShellTitle);
4794 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004795 }
4796 }
4797 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004798
4799 out_flush();
4800
4801#ifdef MCH_WRITE_DUMP
4802 if (fdDump)
4803 {
4804 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4805 fflush(fdDump);
4806 }
4807#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004808#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004809 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004810 if (
4811# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004812 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004813# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004814 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004815 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4816 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004817 char_u *cmdbase = cmd;
4818
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004819 if (cmdbase != NULL)
4820 // Skip a leading quote and (.
4821 while (*cmdbase == '"' || *cmdbase == '(')
4822 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004823
4824 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01004825 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
4826 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004827 {
4828 // Use a terminal window to run the command in.
4829 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004830 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004831 return x;
4832 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004833 }
4834#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004835
4836 /*
4837 * Catch all deadly signals while running the external command, because a
4838 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4839 */
4840 signal(SIGINT, SIG_IGN);
4841#if defined(__GNUC__) && !defined(__MINGW32__)
4842 signal(SIGKILL, SIG_IGN);
4843#else
4844 signal(SIGBREAK, SIG_IGN);
4845#endif
4846 signal(SIGILL, SIG_IGN);
4847 signal(SIGFPE, SIG_IGN);
4848 signal(SIGSEGV, SIG_IGN);
4849 signal(SIGTERM, SIG_IGN);
4850 signal(SIGABRT, SIG_IGN);
4851
4852 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004853 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00004854
4855 if (cmd == NULL)
4856 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004857 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004858 }
4859 else
4860 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004861 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004862 char_u *newcmd = NULL;
4863 char_u *cmdbase = cmd;
4864 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004865
Bram Moolenaar0f873732019-12-05 20:28:46 +01004866 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004867 if (*cmdbase == '"' )
4868 ++cmdbase;
4869 if (*cmdbase == '(')
4870 ++cmdbase;
4871
Bram Moolenaar1c465442017-03-12 20:10:05 +01004872 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004873 {
4874 STARTUPINFO si;
4875 PROCESS_INFORMATION pi;
4876 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004877 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004878 char_u *p;
4879
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004880 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004881 si.cb = sizeof(si);
4882 si.lpReserved = NULL;
4883 si.lpDesktop = NULL;
4884 si.lpTitle = NULL;
4885 si.dwFlags = 0;
4886 si.cbReserved2 = 0;
4887 si.lpReserved2 = NULL;
4888
4889 cmdbase = skipwhite(cmdbase + 5);
4890 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004891 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004892 {
4893 cmdbase = skipwhite(cmdbase + 4);
4894 si.dwFlags = STARTF_USESHOWWINDOW;
4895 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004896 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004897 }
4898 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004899 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004900 {
4901 cmdbase = skipwhite(cmdbase + 2);
4902 flags = CREATE_NO_WINDOW;
4903 si.dwFlags = STARTF_USESTDHANDLES;
4904 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004905 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004906 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004907 NULL, // Security att.
4908 OPEN_EXISTING, // Open flags
4909 FILE_ATTRIBUTE_NORMAL, // File att.
4910 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004911 si.hStdOutput = si.hStdInput;
4912 si.hStdError = si.hStdInput;
4913 }
4914
Bram Moolenaar0f873732019-12-05 20:28:46 +01004915 // Remove a trailing ", ) and )" if they have a match
4916 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004917 if (cmdbase > cmd)
4918 {
4919 p = cmdbase + STRLEN(cmdbase);
4920 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4921 *--p = NUL;
4922 if (p > cmdbase && p[-1] == ')'
4923 && (*cmd =='(' || cmd[1] == '('))
4924 *--p = NUL;
4925 }
4926
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004927 newcmd = cmdbase;
4928 unescape_shellxquote(cmdbase, p_sxe);
4929
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004930 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004931 * If creating new console, arguments are passed to the
4932 * 'cmd.exe' as-is. If it's not, arguments are not treated
4933 * correctly for current 'cmd.exe'. So unescape characters in
4934 * shellxescape except '|' for avoiding to be treated as
4935 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004936 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004937 if (flags != CREATE_NEW_CONSOLE)
4938 {
4939 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004940 char_u *cmd_shell = mch_getenv("COMSPEC");
4941
4942 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004943 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004944
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004945 subcmd = vim_strsave_escaped_ext(cmdbase,
4946 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004947 if (subcmd != NULL)
4948 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004949 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004950 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004951 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004952 if (newcmd != NULL)
4953 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004954 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004955 else
4956 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004957 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004958 }
4959 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004960
4961 /*
4962 * Now, start the command as a process, so that it doesn't
4963 * inherit our handles which causes unpleasant dangling swap
4964 * files if we exit before the spawned process
4965 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004966 if (vim_create_process((char *)newcmd, FALSE, flags,
4967 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004968 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004969 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4970 > (HINSTANCE)32)
4971 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004972 else
4973 {
4974 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01004975#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004976# ifdef VIMDLL
4977 if (gui.in_use)
4978# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00004979 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004980#endif
4981 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004982
4983 if (newcmd != cmdbase)
4984 vim_free(newcmd);
4985
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004986 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004987 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004988 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004989 CloseHandle(si.hStdInput);
4990 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004991 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004992 CloseHandle(pi.hThread);
4993 CloseHandle(pi.hProcess);
4994 }
4995 else
4996 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004997 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01004998#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004999 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005000 (!s_dont_use_vimrun && p_stmp ?
5001 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5002 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005003#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005004 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005005
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005006 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005007 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005008 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005009#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005010 if (
5011# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005012 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005013# endif
5014 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005015 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005016 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5017 "External commands will not pause after completion.\n"
5018 "See :help win32-vimrun for more information.");
5019 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005020 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5021 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005022
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005023 if (wmsg != NULL && wtitle != NULL)
5024 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5025 vim_free(wmsg);
5026 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005027 need_vimrun_warning = FALSE;
5028 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005029 if (
5030# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005031 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005032# endif
5033 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005034 // Use vimrun to execute the command. It opens a console
5035 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005036 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005037 vimrun_path,
5038 (msg_silent != 0 || (options & SHELL_DOOUT))
5039 ? "-s " : "",
5040 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005041 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005042# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005043 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005044# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005045 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005046 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005047 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5048 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005049 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005050#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005051 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005052 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005053 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005054 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005055 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005056 }
5057 }
5058
5059 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005060 {
5061 // The shell may have messed with the mode, always set it.
5062 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005063 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005064 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005065
Bram Moolenaar0f873732019-12-05 20:28:46 +01005066 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005067 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005068#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005069 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005070 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005071#endif
5072 )
5073 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005074 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005075 msg_putchar('\n');
5076 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005077 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005078
5079 signal(SIGINT, SIG_DFL);
5080#if defined(__GNUC__) && !defined(__MINGW32__)
5081 signal(SIGKILL, SIG_DFL);
5082#else
5083 signal(SIGBREAK, SIG_DFL);
5084#endif
5085 signal(SIGILL, SIG_DFL);
5086 signal(SIGFPE, SIG_DFL);
5087 signal(SIGSEGV, SIG_DFL);
5088 signal(SIGTERM, SIG_DFL);
5089 signal(SIGABRT, SIG_DFL);
5090
5091 return x;
5092}
5093
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005094#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005095 static HANDLE
5096job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005097 char_u *fname,
5098 DWORD dwDesiredAccess,
5099 DWORD dwShareMode,
5100 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5101 DWORD dwCreationDisposition,
5102 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005103{
5104 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005105 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005106
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005107 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005108 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005109 return INVALID_HANDLE_VALUE;
5110
5111 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5112 lpSecurityAttributes, dwCreationDisposition,
5113 dwFlagsAndAttributes, NULL);
5114 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005115 return h;
5116}
5117
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005118/*
5119 * Turn the dictionary "env" into a NUL separated list that can be used as the
5120 * environment argument of vim_create_process().
5121 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005122 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005123win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005124{
5125 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005126 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005127 LPVOID base = GetEnvironmentStringsW();
5128
Bram Moolenaar0f873732019-12-05 20:28:46 +01005129 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005130 if (ga_grow(gap, 1) == FAIL)
5131 return;
5132
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005133 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005134 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005135 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005136 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005137 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005138 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005139 typval_T *item = &dict_lookup(hi)->di_tv;
5140 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005141 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005142 --todo;
5143 if (wkey != NULL && wval != NULL)
5144 {
5145 size_t n;
5146 size_t lkey = wcslen(wkey);
5147 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005148
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005149 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5150 continue;
5151 for (n = 0; n < lkey; n++)
5152 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5153 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5154 for (n = 0; n < lval; n++)
5155 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5156 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5157 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005158 vim_free(wkey);
5159 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005160 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005161 }
5162 }
5163
Bram Moolenaar355757a2020-02-10 22:06:32 +01005164 if (base)
5165 {
5166 WCHAR *p = (WCHAR*) base;
5167
5168 // for last \0
5169 if (ga_grow(gap, 1) == FAIL)
5170 return;
5171
5172 while (*p != 0 || *(p + 1) != 0)
5173 {
5174 if (ga_grow(gap, 1) == OK)
5175 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5176 p++;
5177 }
5178 FreeEnvironmentStrings(base);
5179 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5180 }
5181
Bram Moolenaar493359e2018-06-12 20:25:52 +02005182# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005183 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005184# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005185 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005186 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005187# endif
5188# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005189 char_u *version = get_vim_var_str(VV_VERSION);
5190 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005191# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005192 // size of "VIM_SERVERNAME=" and value,
5193 // plus "VIM_TERMINAL=" and value,
5194 // plus two terminating NULs
5195 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005196# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005197 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005198# endif
5199# ifdef FEAT_TERMINAL
5200 + 13 + version_len + 2
5201# endif
5202 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005203
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005204 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005205 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005206# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005207 for (n = 0; n < 15; n++)
5208 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5209 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005210 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005211 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5212 (WCHAR)servername[n];
5213 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005214# endif
5215# ifdef FEAT_TERMINAL
5216 if (is_terminal)
5217 {
5218 for (n = 0; n < 13; n++)
5219 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5220 (WCHAR)"VIM_TERMINAL="[n];
5221 for (n = 0; n < version_len; n++)
5222 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5223 (WCHAR)version[n];
5224 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5225 }
5226# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005227 }
5228 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005229# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005230}
5231
Bram Moolenaarb091f302019-01-19 14:37:00 +01005232/*
5233 * Create a pair of pipes.
5234 * Return TRUE for success, FALSE for failure.
5235 */
5236 static BOOL
5237create_pipe_pair(HANDLE handles[2])
5238{
5239 static LONG s;
5240 char name[64];
5241 SECURITY_ATTRIBUTES sa;
5242
5243 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5244 GetCurrentProcessId(),
5245 InterlockedIncrement(&s));
5246
5247 // Create named pipe. Max size of named pipe is 65535.
5248 handles[1] = CreateNamedPipe(
5249 name,
5250 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5251 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005252 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005253
5254 if (handles[1] == INVALID_HANDLE_VALUE)
5255 return FALSE;
5256
5257 sa.nLength = sizeof(sa);
5258 sa.bInheritHandle = TRUE;
5259 sa.lpSecurityDescriptor = NULL;
5260
5261 handles[0] = CreateFile(name,
5262 FILE_GENERIC_READ,
5263 FILE_SHARE_READ, &sa,
5264 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5265
5266 if (handles[0] == INVALID_HANDLE_VALUE)
5267 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005268 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005269 return FALSE;
5270 }
5271
5272 return TRUE;
5273}
5274
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005275 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005276mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005277{
5278 STARTUPINFO si;
5279 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005280 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005281 SECURITY_ATTRIBUTES saAttr;
5282 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005283 HANDLE ifd[2];
5284 HANDLE ofd[2];
5285 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005286 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005287
5288 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5289 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5290 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5291 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5292 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5293 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5294 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5295
5296 if (use_out_for_err && use_null_for_out)
5297 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005298
5299 ifd[0] = INVALID_HANDLE_VALUE;
5300 ifd[1] = INVALID_HANDLE_VALUE;
5301 ofd[0] = INVALID_HANDLE_VALUE;
5302 ofd[1] = INVALID_HANDLE_VALUE;
5303 efd[0] = INVALID_HANDLE_VALUE;
5304 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005305 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005306
Bram Moolenaar14207f42016-10-27 21:13:10 +02005307 jo = CreateJobObject(NULL, NULL);
5308 if (jo == NULL)
5309 {
5310 job->jv_status = JOB_FAILED;
5311 goto failed;
5312 }
5313
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005314 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005315 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005316
Bram Moolenaar76467df2016-02-12 19:30:26 +01005317 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005318 ZeroMemory(&si, sizeof(si));
5319 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005320 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005321 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005322
Bram Moolenaard8070362016-02-15 21:56:54 +01005323 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5324 saAttr.bInheritHandle = TRUE;
5325 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005326
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005327 if (use_file_for_in)
5328 {
5329 char_u *fname = options->jo_io_name[PART_IN];
5330
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005331 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5332 FILE_SHARE_READ | FILE_SHARE_WRITE,
5333 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5334 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005335 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005336 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005337 goto failed;
5338 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005339 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005340 else if (!use_null_for_in
5341 && (!create_pipe_pair(ifd)
5342 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005343 goto failed;
5344
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005345 if (use_file_for_out)
5346 {
5347 char_u *fname = options->jo_io_name[PART_OUT];
5348
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005349 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5350 FILE_SHARE_READ | FILE_SHARE_WRITE,
5351 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5352 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005353 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005354 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005355 goto failed;
5356 }
5357 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005358 else if (!use_null_for_out &&
5359 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005360 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005361 goto failed;
5362
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005363 if (use_file_for_err)
5364 {
5365 char_u *fname = options->jo_io_name[PART_ERR];
5366
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005367 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5368 FILE_SHARE_READ | FILE_SHARE_WRITE,
5369 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5370 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005371 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005372 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005373 goto failed;
5374 }
5375 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005376 else if (!use_out_for_err && !use_null_for_err &&
5377 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005378 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005379 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005380
Bram Moolenaard8070362016-02-15 21:56:54 +01005381 si.dwFlags |= STARTF_USESTDHANDLES;
5382 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005383 si.hStdOutput = ofd[1];
5384 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5385
5386 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5387 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005388 if (options->jo_set & JO_CHANNEL)
5389 {
5390 channel = options->jo_channel;
5391 if (channel != NULL)
5392 ++channel->ch_refcount;
5393 }
5394 else
5395 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005396 if (channel == NULL)
5397 goto failed;
5398 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005399
5400 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005401 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005402 CREATE_DEFAULT_ERROR_MODE |
5403 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005404 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005405 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005406 &si, &pi,
5407 ga.ga_data,
5408 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005409 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005410 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005411 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005412 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005413 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005414
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005415 ga_clear(&ga);
5416
Bram Moolenaar14207f42016-10-27 21:13:10 +02005417 if (!AssignProcessToJobObject(jo, pi.hProcess))
5418 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005419 // if failing, switch the way to terminate
5420 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005421 CloseHandle(jo);
5422 jo = NULL;
5423 }
5424 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005425 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005426 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005427 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005428 job->jv_status = JOB_STARTED;
5429
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005430 CloseHandle(ifd[0]);
5431 CloseHandle(ofd[1]);
5432 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005433 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005434
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005435 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005436 if (channel != NULL)
5437 {
5438 channel_set_pipes(channel,
5439 use_file_for_in || use_null_for_in
5440 ? INVALID_FD : (sock_T)ifd[1],
5441 use_file_for_out || use_null_for_out
5442 ? INVALID_FD : (sock_T)ofd[0],
5443 use_out_for_err || use_file_for_err || use_null_for_err
5444 ? INVALID_FD : (sock_T)efd[0]);
5445 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005446 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005447 return;
5448
5449failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005450 CloseHandle(ifd[0]);
5451 CloseHandle(ofd[0]);
5452 CloseHandle(efd[0]);
5453 CloseHandle(ifd[1]);
5454 CloseHandle(ofd[1]);
5455 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005456 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005457 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005458}
5459
5460 char *
5461mch_job_status(job_T *job)
5462{
5463 DWORD dwExitCode = 0;
5464
Bram Moolenaar76467df2016-02-12 19:30:26 +01005465 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5466 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005467 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005468 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005469 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005470 {
5471 ch_log(job->jv_channel, "Job ended");
5472 job->jv_status = JOB_ENDED;
5473 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005474 return "dead";
5475 }
5476 return "run";
5477}
5478
Bram Moolenaar97792de2016-10-15 18:36:49 +02005479 job_T *
5480mch_detect_ended_job(job_T *job_list)
5481{
5482 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5483 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5484 job_T *job = job_list;
5485
5486 while (job != NULL)
5487 {
5488 DWORD n;
5489 DWORD result;
5490
5491 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5492 && job != NULL; job = job->jv_next)
5493 {
5494 if (job->jv_status == JOB_STARTED)
5495 {
5496 jobHandles[n] = job->jv_proc_info.hProcess;
5497 jobArray[n] = job;
5498 ++n;
5499 }
5500 }
5501 if (n == 0)
5502 continue;
5503 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5504 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5505 {
5506 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5507
5508 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5509 return wait_job;
5510 }
5511 }
5512 return NULL;
5513}
5514
Bram Moolenaarfb630902016-10-29 14:55:00 +02005515 static BOOL
5516terminate_all(HANDLE process, int code)
5517{
5518 PROCESSENTRY32 pe;
5519 HANDLE h = INVALID_HANDLE_VALUE;
5520 DWORD pid = GetProcessId(process);
5521
5522 if (pid != 0)
5523 {
5524 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5525 if (h != INVALID_HANDLE_VALUE)
5526 {
5527 pe.dwSize = sizeof(PROCESSENTRY32);
5528 if (!Process32First(h, &pe))
5529 goto theend;
5530
5531 do
5532 {
5533 if (pe.th32ParentProcessID == pid)
5534 {
5535 HANDLE ph = OpenProcess(
5536 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5537 if (ph != NULL)
5538 {
5539 terminate_all(ph, code);
5540 CloseHandle(ph);
5541 }
5542 }
5543 } while (Process32Next(h, &pe));
5544
5545 CloseHandle(h);
5546 }
5547 }
5548
5549theend:
5550 return TerminateProcess(process, code);
5551}
5552
5553/*
5554 * Send a (deadly) signal to "job".
5555 * Return FAIL if it didn't work.
5556 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005557 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005558mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005559{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005560 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005561
Bram Moolenaar923d9262016-02-25 20:56:01 +01005562 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005563 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005564 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02005565 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005566 {
5567 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5568 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00005569 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005570 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01005571 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005572 }
5573
5574 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5575 return FAIL;
5576 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005577 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5578 job->jv_proc_info.dwProcessId)
5579 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005580 FreeConsole();
5581 return ret;
5582}
5583
5584/*
5585 * Clear the data related to "job".
5586 */
5587 void
5588mch_clear_job(job_T *job)
5589{
5590 if (job->jv_status != JOB_FAILED)
5591 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005592 if (job->jv_job_object != NULL)
5593 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005594 CloseHandle(job->jv_proc_info.hProcess);
5595 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005596}
5597#endif
5598
Bram Moolenaar071d4272004-06-13 20:20:40 +00005599
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005600#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005601
5602/*
5603 * Start termcap mode
5604 */
5605 static void
5606termcap_mode_start(void)
5607{
5608 DWORD cmodein;
5609
5610 if (g_fTermcapMode)
5611 return;
5612
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005613 if (!p_rs && USE_VTP)
5614 vtp_printf("\033[?1049h");
5615
Bram Moolenaar071d4272004-06-13 20:20:40 +00005616 SaveConsoleBuffer(&g_cbNonTermcap);
5617
5618 if (g_cbTermcap.IsValid)
5619 {
5620 /*
5621 * We've been in termcap mode before. Restore certain screen
5622 * characteristics, including the buffer size and the window
5623 * size. Since we will be redrawing the screen, we don't need
5624 * to restore the actual contents of the buffer.
5625 */
5626 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005627 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005628 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5629 Rows = g_cbTermcap.Info.dwSize.Y;
5630 Columns = g_cbTermcap.Info.dwSize.X;
5631 }
5632 else
5633 {
5634 /*
5635 * This is our first time entering termcap mode. Clear the console
5636 * screen buffer, and resize the buffer to match the current window
5637 * size. We will use this as the size of our editing environment.
5638 */
5639 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005640 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005641 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5642 }
5643
Bram Moolenaar071d4272004-06-13 20:20:40 +00005644 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005645
5646 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005647 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005648 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005649 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005650 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
5651 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005652 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005653 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005654 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005655 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5656 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005657 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005658 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005659
5660 redraw_later_clear();
5661 g_fTermcapMode = TRUE;
5662}
5663
5664
5665/*
5666 * End termcap mode
5667 */
5668 static void
5669termcap_mode_end(void)
5670{
5671 DWORD cmodein;
5672 ConsoleBuffer *cb;
5673 COORD coord;
5674 DWORD dwDummy;
5675
5676 if (!g_fTermcapMode)
5677 return;
5678
5679 SaveConsoleBuffer(&g_cbTermcap);
5680
5681 GetConsoleMode(g_hConIn, &cmodein);
5682 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005683 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5684 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005685
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005686# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005687 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005688# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005689 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005690# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005691 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01005692 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005693 SetConsoleCursorInfo(g_hConOut, &g_cci);
5694
5695 if (p_rs || exiting)
5696 {
5697 /*
5698 * Clear anything that happens to be on the current line.
5699 */
5700 coord.X = 0;
5701 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5702 FillConsoleOutputCharacter(g_hConOut, ' ',
5703 cb->Info.dwSize.X, coord, &dwDummy);
5704 /*
5705 * The following is just for aesthetics. If we are exiting without
5706 * restoring the screen, then we want to have a prompt string
5707 * appear at the bottom line. However, the command interpreter
5708 * seems to always advance the cursor one line before displaying
5709 * the prompt string, which causes the screen to scroll. To
5710 * counter this, move the cursor up one line before exiting.
5711 */
5712 if (exiting && !p_rs)
5713 coord.Y--;
5714 /*
5715 * Position the cursor at the leftmost column of the desired row.
5716 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005717 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005718 }
5719
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005720 if (!p_rs && USE_VTP)
Bram Moolenaar0afdcf82020-04-01 18:29:10 +02005721 vtp_printf("\033[?1049l");
5722
Bram Moolenaar071d4272004-06-13 20:20:40 +00005723 g_fTermcapMode = FALSE;
5724}
Bram Moolenaar0f873732019-12-05 20:28:46 +01005725#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005726
5727
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005728#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005729 void
5730mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005731 char_u *s UNUSED,
5732 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005733{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005734 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00005735}
5736
5737#else
5738
5739/*
5740 * clear `n' chars, starting from `coord'
5741 */
5742 static void
5743clear_chars(
5744 COORD coord,
5745 DWORD n)
5746{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005747 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02005748 {
5749 DWORD dwDummy;
5750
5751 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5752 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
5753 &dwDummy);
5754 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005755 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005756 {
5757 set_console_color_rgb();
5758 gotoxy(coord.X + 1, coord.Y + 1);
5759 vtp_printf("\033[%dX", n);
5760 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005761}
5762
5763
5764/*
5765 * Clear the screen
5766 */
5767 static void
5768clear_screen(void)
5769{
5770 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005771
5772 if (!USE_VTP)
5773 clear_chars(g_coord, Rows * Columns);
5774 else
5775 {
5776 set_console_color_rgb();
5777 gotoxy(1, 1);
5778 vtp_printf("\033[2J");
5779 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005780}
5781
5782
5783/*
5784 * Clear to end of display
5785 */
5786 static void
5787clear_to_end_of_display(void)
5788{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005789 COORD save = g_coord;
5790
5791 if (!USE_VTP)
5792 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005793 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005794 else
5795 {
5796 set_console_color_rgb();
5797 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5798 vtp_printf("\033[0J");
5799
5800 gotoxy(save.X + 1, save.Y + 1);
5801 g_coord = save;
5802 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005803}
5804
5805
5806/*
5807 * Clear to end of line
5808 */
5809 static void
5810clear_to_end_of_line(void)
5811{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005812 COORD save = g_coord;
5813
5814 if (!USE_VTP)
5815 clear_chars(g_coord, Columns - g_coord.X);
5816 else
5817 {
5818 set_console_color_rgb();
5819 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5820 vtp_printf("\033[0K");
5821
5822 gotoxy(save.X + 1, save.Y + 1);
5823 g_coord = save;
5824 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005825}
5826
5827
5828/*
5829 * Scroll the scroll region up by `cLines' lines
5830 */
5831 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005832scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005833{
5834 COORD oldcoord = g_coord;
5835
5836 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5837 delete_lines(cLines);
5838
5839 g_coord = oldcoord;
5840}
5841
5842
5843/*
5844 * Set the scroll region
5845 */
5846 static void
5847set_scroll_region(
5848 unsigned left,
5849 unsigned top,
5850 unsigned right,
5851 unsigned bottom)
5852{
5853 if (left >= right
5854 || top >= bottom
5855 || right > (unsigned) Columns - 1
5856 || bottom > (unsigned) Rows - 1)
5857 return;
5858
5859 g_srScrollRegion.Left = left;
5860 g_srScrollRegion.Top = top;
5861 g_srScrollRegion.Right = right;
5862 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005863}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005864
Bram Moolenaar6982f422019-02-16 16:48:01 +01005865 static void
5866set_scroll_region_tb(
5867 unsigned top,
5868 unsigned bottom)
5869{
5870 if (top >= bottom || bottom > (unsigned)Rows - 1)
5871 return;
5872
5873 g_srScrollRegion.Top = top;
5874 g_srScrollRegion.Bottom = bottom;
5875}
5876
5877 static void
5878set_scroll_region_lr(
5879 unsigned left,
5880 unsigned right)
5881{
5882 if (left >= right || right > (unsigned)Columns - 1)
5883 return;
5884
5885 g_srScrollRegion.Left = left;
5886 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005887}
5888
5889
5890/*
5891 * Insert `cLines' lines at the current cursor position
5892 */
5893 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005894insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005895{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005896 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005897 COORD dest;
5898 CHAR_INFO fill;
5899
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005900 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5901
Bram Moolenaar6982f422019-02-16 16:48:01 +01005902 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005903 dest.Y = g_coord.Y + cLines;
5904
Bram Moolenaar6982f422019-02-16 16:48:01 +01005905 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005906 source.Top = g_coord.Y;
5907 source.Right = g_srScrollRegion.Right;
5908 source.Bottom = g_srScrollRegion.Bottom - cLines;
5909
Bram Moolenaar6982f422019-02-16 16:48:01 +01005910 clip.Left = g_srScrollRegion.Left;
5911 clip.Top = g_coord.Y;
5912 clip.Right = g_srScrollRegion.Right;
5913 clip.Bottom = g_srScrollRegion.Bottom;
5914
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005915 fill.Char.AsciiChar = ' ';
5916 if (!USE_VTP)
5917 fill.Attributes = g_attrCurrent;
5918 else
5919 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005920
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005921 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005922
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005923 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5924
Bram Moolenaar6982f422019-02-16 16:48:01 +01005925 // Here we have to deal with a win32 console flake: If the scroll
5926 // region looks like abc and we scroll c to a and fill with d we get
5927 // cbd... if we scroll block c one line at a time to a, we get cdd...
5928 // vim expects cdd consistently... So we have to deal with that
5929 // here... (this also occurs scrolling the same way in the other
5930 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005931
5932 if (source.Bottom < dest.Y)
5933 {
5934 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005935 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005936
Bram Moolenaar6982f422019-02-16 16:48:01 +01005937 coord.X = source.Left;
5938 for (i = clip.Top; i < dest.Y; ++i)
5939 {
5940 coord.Y = i;
5941 clear_chars(coord, source.Right - source.Left + 1);
5942 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005943 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02005944
5945 if (USE_WT)
5946 {
5947 COORD coord;
5948 int i;
5949
5950 coord.X = source.Left;
5951 for (i = source.Top; i < dest.Y; ++i)
5952 {
5953 coord.Y = i;
5954 clear_chars(coord, source.Right - source.Left + 1);
5955 }
5956 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005957}
5958
5959
5960/*
5961 * Delete `cLines' lines at the current cursor position
5962 */
5963 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005964delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005965{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005966 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005967 COORD dest;
5968 CHAR_INFO fill;
5969 int nb;
5970
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005971 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5972
Bram Moolenaar6982f422019-02-16 16:48:01 +01005973 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005974 dest.Y = g_coord.Y;
5975
Bram Moolenaar6982f422019-02-16 16:48:01 +01005976 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005977 source.Top = g_coord.Y + cLines;
5978 source.Right = g_srScrollRegion.Right;
5979 source.Bottom = g_srScrollRegion.Bottom;
5980
Bram Moolenaar6982f422019-02-16 16:48:01 +01005981 clip.Left = g_srScrollRegion.Left;
5982 clip.Top = g_coord.Y;
5983 clip.Right = g_srScrollRegion.Right;
5984 clip.Bottom = g_srScrollRegion.Bottom;
5985
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005986 fill.Char.AsciiChar = ' ';
5987 if (!USE_VTP)
5988 fill.Attributes = g_attrCurrent;
5989 else
5990 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005991
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005992 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005993
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005994 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5995
Bram Moolenaar6982f422019-02-16 16:48:01 +01005996 // Here we have to deal with a win32 console flake; See insert_lines()
5997 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005998
5999 nb = dest.Y + (source.Bottom - source.Top) + 1;
6000
6001 if (nb < source.Top)
6002 {
6003 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006004 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006005
Bram Moolenaar6982f422019-02-16 16:48:01 +01006006 coord.X = source.Left;
6007 for (i = nb; i < clip.Bottom; ++i)
6008 {
6009 coord.Y = i;
6010 clear_chars(coord, source.Right - source.Left + 1);
6011 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006012 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006013
6014 if (USE_WT)
6015 {
6016 COORD coord;
6017 int i;
6018
6019 coord.X = source.Left;
6020 for (i = nb; i <= source.Bottom; ++i)
6021 {
6022 coord.Y = i;
6023 clear_chars(coord, source.Right - source.Left + 1);
6024 }
6025 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006026}
6027
6028
6029/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006030 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006031 */
6032 static void
6033gotoxy(
6034 unsigned x,
6035 unsigned y)
6036{
6037 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6038 return;
6039
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006040 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006041 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006042 // There are reports of double-width characters not displayed
6043 // correctly. This workaround should fix it, similar to how it's done
6044 // for VTP.
6045 g_coord.X = 0;
6046 SetConsoleCursorPosition(g_hConOut, g_coord);
6047
Bram Moolenaar2313b612019-09-27 14:14:32 +02006048 // external cursor coords are 1-based; internal are 0-based
6049 g_coord.X = x - 1;
6050 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006051 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006052 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006053 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006054 {
6055 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006056 // destruction. Insider build bug. Always enabled because it's cheap
6057 // and avoids mistakes with recognizing the build.
6058 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006059
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006060 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006061
6062 g_coord.X = x - 1;
6063 g_coord.Y = y - 1;
6064 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006065}
6066
6067
6068/*
6069 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006070 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006071 */
6072 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006073textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006074{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006075 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006076
6077 SetConsoleTextAttribute(g_hConOut, wAttr);
6078}
6079
6080
6081 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006082textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006083{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006084 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006085
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006086 if (!USE_VTP)
6087 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6088 else
6089 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006090}
6091
6092
6093 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006094textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006095{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006096 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006097
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006098 if (!USE_VTP)
6099 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6100 else
6101 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006102}
6103
6104
6105/*
6106 * restore the default text attribute (whatever we started with)
6107 */
6108 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006109normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006110{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006111 if (!USE_VTP)
6112 textattr(g_attrDefault);
6113 else
6114 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006115}
6116
6117
6118static WORD g_attrPreStandout = 0;
6119
6120/*
6121 * Make the text standout, by brightening it
6122 */
6123 static void
6124standout(void)
6125{
6126 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006127
Bram Moolenaar071d4272004-06-13 20:20:40 +00006128 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6129}
6130
6131
6132/*
6133 * Turn off standout mode
6134 */
6135 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006136standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006137{
6138 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006139 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006140
6141 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006142}
6143
6144
6145/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006146 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006147 */
6148 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006149mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006150{
6151 char_u *p;
6152 int n;
6153
6154 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6155 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006156 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006157# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006158 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006159# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006160 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006161 {
6162 p = T_ME + 2;
6163 n = getdigits(&p);
6164 if (*p == 'm' && n > 0)
6165 {
6166 cterm_normal_fg_color = (n & 0xf) + 1;
6167 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6168 }
6169 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006170# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006171 cterm_normal_fg_gui_color = INVALCOLOR;
6172 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006173# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006174}
6175
6176
6177/*
6178 * visual bell: flash the screen
6179 */
6180 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006181visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006182{
6183 COORD coordOrigin = {0, 0};
6184 WORD attrFlash = ~g_attrCurrent & 0xff;
6185
6186 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006187 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006188
6189 if (oldattrs == NULL)
6190 return;
6191 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6192 coordOrigin, &dwDummy);
6193 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6194 coordOrigin, &dwDummy);
6195
Bram Moolenaar0f873732019-12-05 20:28:46 +01006196 Sleep(15); // wait for 15 msec
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006197 if (!USE_VTP)
6198 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006199 coordOrigin, &dwDummy);
6200 vim_free(oldattrs);
6201}
6202
6203
6204/*
6205 * Make the cursor visible or invisible
6206 */
6207 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006208cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006209{
6210 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006211
6212 if (USE_VTP)
6213 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6214
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006215# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006216 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006217# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006218}
6219
6220
6221/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006222 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006223 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006224 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006225 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006226write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006227 char_u *pchBuf,
6228 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006229{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006230 COORD coord = g_coord;
6231 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006232 DWORD n, cchwritten;
6233 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006234 static WCHAR *unicodebuf = NULL;
6235 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006236 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006237 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006238 static WCHAR *utf8spbuf = NULL;
6239 static int utf8splength;
6240 static DWORD utf8spcells;
6241 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006242
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006243 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006244 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006245 utf8usingbuf = &unicodebuf;
6246 do
6247 {
6248 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6249 unicodebuf, unibuflen);
6250 if (length && length <= unibuflen)
6251 break;
6252 vim_free(unicodebuf);
6253 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6254 unibuflen = unibuflen ? 0 : length;
6255 } while(1);
6256 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006257 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006258 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6259 {
6260 if (utf8usingbuf != &utf8spbuf)
6261 {
6262 if (utf8spbuf == NULL)
6263 {
6264 cells = mb_string2cells((char_u *)" ", 1);
6265 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6266 utf8spbuf = LALLOC_MULT(WCHAR, length);
6267 if (utf8spbuf != NULL)
6268 {
6269 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6270 utf8usingbuf = &utf8spbuf;
6271 utf8splength = length;
6272 utf8spcells = cells;
6273 }
6274 }
6275 else
6276 {
6277 utf8usingbuf = &utf8spbuf;
6278 length = utf8splength;
6279 cells = utf8spcells;
6280 }
6281 }
6282 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006283
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006284 if (!USE_VTP)
6285 {
6286 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6287 coord, &written);
6288 // When writing fails or didn't write a single character, pretend one
6289 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006290 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006291 coord, &cchwritten) == 0
6292 || cchwritten == 0 || cchwritten == (DWORD)-1)
6293 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006294 }
6295 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006296 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006297 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006298 NULL) == 0 || cchwritten == 0)
6299 cchwritten = 1;
6300 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006301
K.Takata135e1522022-01-29 15:27:58 +00006302 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006303 {
6304 written = cbToWrite;
6305 g_coord.X += (SHORT)cells;
6306 }
6307 else
6308 {
6309 char_u *p = pchBuf;
6310 for (n = 0; n < cchwritten; n++)
6311 MB_CPTR_ADV(p);
6312 written = p - pchBuf;
6313 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006314 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006315
6316 while (g_coord.X > g_srScrollRegion.Right)
6317 {
6318 g_coord.X -= (SHORT) Columns;
6319 if (g_coord.Y < g_srScrollRegion.Bottom)
6320 g_coord.Y++;
6321 }
6322
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006323 // Cursor under VTP is always in the correct position, no need to reset.
6324 if (!USE_VTP)
6325 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006326
6327 return written;
6328}
6329
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006330 static char_u *
6331get_seq(
6332 int *args,
6333 int *count,
6334 char_u *head)
6335{
6336 int argc;
6337 char_u *p;
6338
6339 if (head == NULL || *head != '\033')
6340 return NULL;
6341
6342 argc = 0;
6343 p = head;
6344 ++p;
6345 do
6346 {
6347 ++p;
6348 args[argc] = getdigits(&p);
6349 argc += (argc < 15) ? 1 : 0;
6350 } while (*p == ';');
6351 *count = argc;
6352
6353 return p;
6354}
6355
6356 static char_u *
6357get_sgr(
6358 int *args,
6359 int *count,
6360 char_u *head)
6361{
6362 char_u *p = get_seq(args, count, head);
6363
6364 return (p && *p == 'm') ? ++p : NULL;
6365}
6366
6367/*
6368 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6369 */
6370 static char_u *
6371sgrn2(
6372 char_u *head,
6373 int n)
6374{
6375 int argc;
6376 int args[16];
6377 char_u *p = get_sgr(args, &argc, head);
6378
6379 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6380}
6381
6382/*
6383 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6384 */
6385 static char_u *
6386sgrnc(
6387 char_u *head,
6388 int n)
6389{
6390 int argc;
6391 int args[16];
6392 char_u *p = get_sgr(args, &argc, head);
6393
6394 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6395 ? p : NULL;
6396}
6397
6398 static char_u *
6399skipblank(char_u *q)
6400{
6401 char_u *p = q;
6402
6403 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6404 ++p;
6405 return p;
6406}
6407
6408/*
6409 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6410 * NULL.
6411 */
6412 static char_u *
6413sgrn2c(
6414 char_u *head,
6415 int n)
6416{
6417 char_u *p = sgrn2(head, n);
6418
6419 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6420}
6421
6422/*
6423 * If there is only a newline between the sequence immediately following it,
6424 * a pointer to the character following the newline is returned.
6425 * Otherwise NULL.
6426 */
6427 static char_u *
6428sgrn2cn(
6429 char_u *head,
6430 int n)
6431{
6432 char_u *p = sgrn2(head, n);
6433
6434 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6435}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006436
6437/*
6438 * mch_write(): write the output buffer to the screen, translating ESC
6439 * sequences into calls to console output routines.
6440 */
6441 void
6442mch_write(
6443 char_u *s,
6444 int len)
6445{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006446 char_u *end = s + len;
6447
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006448# ifdef VIMDLL
6449 if (gui.in_use)
6450 return;
6451# endif
6452
Bram Moolenaar071d4272004-06-13 20:20:40 +00006453 if (!term_console)
6454 {
6455 write(1, s, (unsigned)len);
6456 return;
6457 }
6458
Bram Moolenaar0f873732019-12-05 20:28:46 +01006459 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00006460 while (len--)
6461 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006462 int prefix = -1;
6463 char_u ch;
6464
6465 // While processing a sequence, on rare occasions it seems that another
6466 // sequence may be inserted asynchronously.
6467 if (len < 0)
6468 {
6469 redraw_all_later(CLEAR);
6470 return;
6471 }
6472
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006473 while (s + ++prefix < end)
6474 {
6475 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006476 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6477 && ch != '\a' && ch != '\033'))
6478 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006479 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006480
6481 if (p_wd)
6482 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006483 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006484 if (prefix != 0)
6485 prefix = 1;
6486 }
6487
6488 if (prefix != 0)
6489 {
6490 DWORD nWritten;
6491
6492 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006493# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006494 if (fdDump)
6495 {
6496 fputc('>', fdDump);
6497 fwrite(s, sizeof(char_u), nWritten, fdDump);
6498 fputs("<\n", fdDump);
6499 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006500# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006501 len -= (nWritten - 1);
6502 s += nWritten;
6503 }
6504 else if (s[0] == '\n')
6505 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006506 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00006507 if (g_coord.Y == g_srScrollRegion.Bottom)
6508 {
6509 scroll(1);
6510 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6511 }
6512 else
6513 {
6514 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6515 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006516# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006517 if (fdDump)
6518 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006519# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006520 s++;
6521 }
6522 else if (s[0] == '\r')
6523 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006524 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00006525 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006526# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006527 if (fdDump)
6528 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006529# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006530 s++;
6531 }
6532 else if (s[0] == '\b')
6533 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006534 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00006535 if (g_coord.X > g_srScrollRegion.Left)
6536 g_coord.X--;
6537 else if (g_coord.Y > g_srScrollRegion.Top)
6538 {
6539 g_coord.X = g_srScrollRegion.Right;
6540 g_coord.Y--;
6541 }
6542 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006543# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006544 if (fdDump)
6545 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006546# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006547 s++;
6548 }
6549 else if (s[0] == '\a')
6550 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006551 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00006552 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006553# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006554 if (fdDump)
6555 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006556# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006557 s++;
6558 }
6559 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6560 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006561# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006562 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006563# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006564 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006565 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006566 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006567
6568 switch (s[2])
6569 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006570 case '0': case '1': case '2': case '3': case '4':
6571 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006572 if (*(p = get_seq(args, &argc, s)) != 'm')
6573 goto notsgr;
6574
6575 p = s;
6576
6577 // Handling frequent optional sequences. Output to the screen
6578 // takes too long, so do not output as much as possible.
6579
6580 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
6581 // resetFG,FG,BG are omitted.
6582 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006583 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006584 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
6585 len = len + 1 - (int)(p - s);
6586 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006587 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006588 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006589
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006590 // If FG,BG,BG,FG of SGR are connected, the first FG can be
6591 // omitted.
6592 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
6593 p = sp;
6594
6595 // If FG,BG,FG,BG of SGR are connected, the first FG can be
6596 // omitted.
6597 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
6598 p = sp;
6599
6600 // If BG,BG of SGR are connected, the first BG can be omitted.
6601 if (sgrn2((sp = sgrn2(p, 48)), 48))
6602 p = sp;
6603
6604 // If restoreFG and FG are connected, the restoreFG can be
6605 // omitted.
6606 if (sgrn2((sp = sgrnc(p, 39)), 38))
6607 p = sp;
6608
6609 p = get_seq(args, &argc, p);
6610
6611notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006612 arg1 = args[0];
6613 arg2 = args[1];
6614 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006615 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006616 if (argc == 1 && args[0] == 0)
6617 normvideo();
6618 else if (argc == 1)
6619 {
6620 if (USE_VTP)
6621 textcolor((WORD) arg1);
6622 else
6623 textattr((WORD) arg1);
6624 }
6625 else if (USE_VTP)
6626 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006627 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006628 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006629 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006630 gotoxy(arg2, arg1);
6631 }
6632 else if (argc == 2 && *p == 'r')
6633 {
6634 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6635 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006636 else if (argc == 2 && *p == 'R')
6637 {
6638 set_scroll_region_tb(arg1, arg2);
6639 }
6640 else if (argc == 2 && *p == 'V')
6641 {
6642 set_scroll_region_lr(arg1, arg2);
6643 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006644 else if (argc == 1 && *p == 'A')
6645 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006646 gotoxy(g_coord.X + 1,
6647 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6648 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006649 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006650 {
6651 textbackground((WORD) arg1);
6652 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006653 else if (argc == 1 && *p == 'C')
6654 {
6655 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6656 g_coord.Y + 1);
6657 }
6658 else if (argc == 1 && *p == 'f')
6659 {
6660 textcolor((WORD) arg1);
6661 }
6662 else if (argc == 1 && *p == 'H')
6663 {
6664 gotoxy(1, arg1);
6665 }
6666 else if (argc == 1 && *p == 'L')
6667 {
6668 insert_lines(arg1);
6669 }
6670 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006671 {
6672 delete_lines(arg1);
6673 }
6674
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006675 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006676 s = p + 1;
6677 break;
6678
Bram Moolenaar071d4272004-06-13 20:20:40 +00006679 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006680 gotoxy(g_coord.X + 1,
6681 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6682 goto got3;
6683
6684 case 'B':
6685 visual_bell();
6686 goto got3;
6687
6688 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006689 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6690 g_coord.Y + 1);
6691 goto got3;
6692
6693 case 'E':
6694 termcap_mode_end();
6695 goto got3;
6696
6697 case 'F':
6698 standout();
6699 goto got3;
6700
6701 case 'f':
6702 standend();
6703 goto got3;
6704
6705 case 'H':
6706 gotoxy(1, 1);
6707 goto got3;
6708
6709 case 'j':
6710 clear_to_end_of_display();
6711 goto got3;
6712
6713 case 'J':
6714 clear_screen();
6715 goto got3;
6716
6717 case 'K':
6718 clear_to_end_of_line();
6719 goto got3;
6720
6721 case 'L':
6722 insert_lines(1);
6723 goto got3;
6724
6725 case 'M':
6726 delete_lines(1);
6727 goto got3;
6728
6729 case 'S':
6730 termcap_mode_start();
6731 goto got3;
6732
6733 case 'V':
6734 cursor_visible(TRUE);
6735 goto got3;
6736
6737 case 'v':
6738 cursor_visible(FALSE);
6739 goto got3;
6740
6741 got3:
6742 s += 3;
6743 len -= 2;
6744 }
6745
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006746# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006747 if (fdDump)
6748 {
6749 fputs("ESC | ", fdDump);
6750 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6751 fputc('\n', fdDump);
6752 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006753# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006754 }
6755 else
6756 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006757 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00006758 DWORD nWritten;
6759
6760 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006761# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006762 if (fdDump)
6763 {
6764 fputc('>', fdDump);
6765 fwrite(s, sizeof(char_u), nWritten, fdDump);
6766 fputs("<\n", fdDump);
6767 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006768# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006769
6770 len -= (nWritten - 1);
6771 s += nWritten;
6772 }
6773 }
6774
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006775# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006776 if (fdDump)
6777 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006778# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006779}
6780
Bram Moolenaar0f873732019-12-05 20:28:46 +01006781#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006782
6783
6784/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006785 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006786 */
6787 void
6788mch_delay(
6789 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02006790 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006791{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006792#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006793 Sleep((int)msec); // never wait for input
6794#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006795# ifdef VIMDLL
6796 if (gui.in_use)
6797 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006798 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006799 return;
6800 }
6801# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02006802 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006803# ifdef FEAT_MZSCHEME
6804 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6805 {
6806 int towait = p_mzq;
6807
Bram Moolenaar0f873732019-12-05 20:28:46 +01006808 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006809 while (msec > 0)
6810 {
6811 mzvim_check_threads();
6812 if (msec < towait)
6813 towait = msec;
6814 Sleep(towait);
6815 msec -= towait;
6816 }
6817 }
6818 else
6819# endif
6820 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006821 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006822 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006823#endif
6824}
6825
6826
6827/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006828 * This version of remove is not scared by a readonly (backup) file.
6829 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006830 * Return 0 for success, -1 for failure.
6831 */
6832 int
6833mch_remove(char_u *name)
6834{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006835 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006836 int n;
6837
Bram Moolenaar203258c2016-01-17 22:15:16 +01006838 /*
6839 * On Windows, deleting a directory's symbolic link is done by
6840 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6841 */
6842 if (mch_isdir(name) && mch_is_symbolic_link(name))
6843 return mch_rmdir(name);
6844
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006845 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6846
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006847 wn = enc_to_utf16(name, NULL);
6848 if (wn == NULL)
6849 return -1;
6850
6851 n = DeleteFileW(wn) ? 0 : -1;
6852 vim_free(wn);
6853 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006854}
6855
6856
6857/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006858 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006859 */
6860 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006861mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006862{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006863#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
6864# ifdef VIMDLL
6865 if (!gui.in_use)
6866# endif
6867 if (g_fCtrlCPressed || g_fCBrkPressed)
6868 {
6869 ctrl_break_was_pressed = g_fCBrkPressed;
6870 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6871 got_int = TRUE;
6872 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006873#endif
6874}
6875
Bram Moolenaar0f873732019-12-05 20:28:46 +01006876// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01006877#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006878
6879/*
6880 * How much main memory in KiB that can be used by VIM.
6881 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006882 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006883mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006884{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006885 MEMORYSTATUSEX ms;
6886
Bram Moolenaar0f873732019-12-05 20:28:46 +01006887 // Need to use GlobalMemoryStatusEx() when there is more memory than
6888 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006889 ms.dwLength = sizeof(MEMORYSTATUSEX);
6890 GlobalMemoryStatusEx(&ms);
6891 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006892 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006893 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006894 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006895 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006896 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006897 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006898 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006899 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006900 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01006901 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006902 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006903}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006904
Bram Moolenaar071d4272004-06-13 20:20:40 +00006905/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006906 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00006907 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6908 * file whose short file name is "FOO.BAR" (its long file name will
6909 * be correct: "foo.bar~"). Because a file can be accessed by
6910 * either its SFN or its LFN, "foo.bar" has effectively been
6911 * renamed to "foo.bar", which is not at all what was wanted. This
6912 * seems to happen only when renaming files with three-character
6913 * extensions by appending a suffix that does not include ".".
6914 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6915 *
6916 * There is another problem, which isn't really a bug but isn't right either:
6917 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6918 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6919 * service pack 6. Doesn't seem to happen on Windows 98.
6920 *
6921 * Like rename(), returns 0 upon success, non-zero upon failure.
6922 * Should probably set errno appropriately when errors occur.
6923 */
6924 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006925mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006926{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006927 WCHAR *p;
6928 int i;
6929 WCHAR szTempFile[_MAX_PATH + 1];
6930 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006931 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006932
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006933 // No need to play tricks unless the file name contains a "~" as the
6934 // seventh character.
6935 p = wold;
6936 for (i = 0; wold[i] != NUL; ++i)
6937 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6938 && wold[i + 1] != 0)
6939 p = wold + i + 1;
6940 if ((int)(wold + i - p) < 8 || p[6] != '~')
6941 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006942
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006943 // Get base path of new file name. Undocumented feature: If pszNewFile is
6944 // a directory, no error is returned and pszFilePart will be NULL.
6945 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006946 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006947 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006948
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006949 // Get (and create) a unique temporary file name in directory of new file
6950 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006951 return -2;
6952
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006953 // blow the temp file away
6954 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006955 return -3;
6956
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006957 // rename old file to the temp file
6958 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006959 return -4;
6960
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006961 // now create an empty file called pszOldFile; this prevents the operating
6962 // system using pszOldFile as an alias (SFN) if we're renaming within the
6963 // same directory. For example, we're editing a file called
6964 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6965 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
6966 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
6967 // cause all sorts of problems later in buf_write(). So, we create an
6968 // empty file called filena~1.txt and the system will have to find some
6969 // other SFN for filena~1.txt~, such as filena~2.txt
6970 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006971 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6972 return -5;
6973 if (!CloseHandle(hf))
6974 return -6;
6975
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006976 // rename the temp file to the new file
6977 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006978 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006979 // Renaming failed. Rename the file back to its old name, so that it
6980 // looks like nothing happened.
6981 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006982 return -7;
6983 }
6984
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006985 // Seems to be left around on Novell filesystems
6986 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006987
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006988 // finally, remove the empty old file
6989 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006990 return -8;
6991
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006992 return 0;
6993}
6994
6995
6996/*
6997 * Converts the filenames to UTF-16, then call mch_wrename().
6998 * Like rename(), returns 0 upon success, non-zero upon failure.
6999 */
7000 int
7001mch_rename(
7002 const char *pszOldFile,
7003 const char *pszNewFile)
7004{
7005 WCHAR *wold = NULL;
7006 WCHAR *wnew = NULL;
7007 int retval = -1;
7008
7009 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7010 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7011 if (wold != NULL && wnew != NULL)
7012 retval = mch_wrename(wold, wnew);
7013 vim_free(wold);
7014 vim_free(wnew);
7015 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007016}
7017
7018/*
7019 * Get the default shell for the current hardware platform
7020 */
7021 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007022default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007023{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007024 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007025}
7026
7027/*
7028 * mch_access() extends access() to do more detailed check on network drives.
7029 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7030 */
7031 int
7032mch_access(char *n, int p)
7033{
7034 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007035 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007036 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007037
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007038 wn = enc_to_utf16((char_u *)n, NULL);
7039 if (wn == NULL)
7040 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007041
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007042 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007043 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007044 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007045
7046 if (p & R_OK)
7047 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007048 // Read check is performed by seeing if we can do a find file on
7049 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007050 int i;
7051 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007052
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007053 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7054 TempNameW[i] = wn[i];
7055 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7056 TempNameW[i++] = '\\';
7057 TempNameW[i++] = '*';
7058 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007059
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007060 hFile = FindFirstFileW(TempNameW, &d);
7061 if (hFile == INVALID_HANDLE_VALUE)
7062 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007063 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007064 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007065 }
7066
7067 if (p & W_OK)
7068 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007069 // Trying to create a temporary file in the directory should catch
7070 // directories on read-only network shares. However, in
7071 // directories whose ACL allows writes but denies deletes will end
7072 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007073 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7074 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007075 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007076 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007077 }
7078 }
7079 else
7080 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007081 // Don't consider a file read-only if another process has opened it.
7082 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7083
Bram Moolenaar0f873732019-12-05 20:28:46 +01007084 // Trying to open the file for the required access does ACL, read-only
7085 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007086 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7087 | ((p & R_OK) ? GENERIC_READ : 0);
7088
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007089 hFile = CreateFileW(wn, access_mode, share_mode,
7090 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007091 if (hFile == INVALID_HANDLE_VALUE)
7092 goto getout;
7093 CloseHandle(hFile);
7094 }
7095
Bram Moolenaar0f873732019-12-05 20:28:46 +01007096 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007097getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007098 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007099 return retval;
7100}
7101
Bram Moolenaar071d4272004-06-13 20:20:40 +00007102/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007103 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007104 */
7105 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007106mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007107{
7108 WCHAR *wn;
7109 int f;
7110
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007111 wn = enc_to_utf16((char_u *)name, NULL);
7112 if (wn == NULL)
7113 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007114
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007115 f = _wopen(wn, flags, mode);
7116 vim_free(wn);
7117 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007118}
7119
7120/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007121 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007122 */
7123 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007124mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007125{
7126 WCHAR *wn, *wm;
7127 FILE *f = NULL;
7128
Bram Moolenaara12a1612019-01-24 16:39:02 +01007129#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007130 // Work around an annoying assertion in the Microsoft debug CRT
7131 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007132 char newMode = mode[strlen(mode) - 1];
7133 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007134
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007135 _get_fmode(&oldMode);
7136 if (newMode == 't')
7137 _set_fmode(_O_TEXT);
7138 else if (newMode == 'b')
7139 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007140#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007141 wn = enc_to_utf16((char_u *)name, NULL);
7142 wm = enc_to_utf16((char_u *)mode, NULL);
7143 if (wn != NULL && wm != NULL)
7144 f = _wfopen(wn, wm);
7145 vim_free(wn);
7146 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007147
Bram Moolenaara12a1612019-01-24 16:39:02 +01007148#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007149 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007150#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007151 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007152}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007153
Bram Moolenaar071d4272004-06-13 20:20:40 +00007154/*
7155 * SUB STREAM (aka info stream) handling:
7156 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007157 * NTFS can have sub streams for each file. The normal contents of a file is
7158 * stored in the main stream, and extra contents (author information, title and
7159 * so on) can be stored in a sub stream. After Windows 2000, the user can
7160 * access and store this information in sub streams via an explorer's property
7161 * menu item in the right click menu. This information in sub streams was lost
7162 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007163 *
7164 * Incomplete explanation:
7165 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7166 * More useful info and an example:
7167 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7168 */
7169
7170/*
7171 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7172 * and write to stream "substream" of file "to".
7173 * Errors are ignored.
7174 */
7175 static void
7176copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7177{
7178 HANDLE hTo;
7179 WCHAR *to_name;
7180
7181 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7182 wcscpy(to_name, to);
7183 wcscat(to_name, substream);
7184
7185 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7186 FILE_ATTRIBUTE_NORMAL, NULL);
7187 if (hTo != INVALID_HANDLE_VALUE)
7188 {
7189 long done;
7190 DWORD todo;
7191 DWORD readcnt, written;
7192 char buf[4096];
7193
Bram Moolenaar0f873732019-12-05 20:28:46 +01007194 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007195 for (done = 0; done < len; done += written)
7196 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007197 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007198 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7199 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007200 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7201 FALSE, FALSE, context)
7202 || readcnt != todo
7203 || !WriteFile(hTo, buf, todo, &written, NULL)
7204 || written != todo)
7205 break;
7206 }
7207 CloseHandle(hTo);
7208 }
7209
7210 free(to_name);
7211}
7212
7213/*
7214 * Copy info streams from file "from" to file "to".
7215 */
7216 static void
7217copy_infostreams(char_u *from, char_u *to)
7218{
7219 WCHAR *fromw;
7220 WCHAR *tow;
7221 HANDLE sh;
7222 WIN32_STREAM_ID sid;
7223 int headersize;
7224 WCHAR streamname[_MAX_PATH];
7225 DWORD readcount;
7226 void *context = NULL;
7227 DWORD lo, hi;
7228 int len;
7229
Bram Moolenaar0f873732019-12-05 20:28:46 +01007230 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007231 fromw = enc_to_utf16(from, NULL);
7232 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007233 if (fromw != NULL && tow != NULL)
7234 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007235 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007236 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7237 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7238 if (sh != INVALID_HANDLE_VALUE)
7239 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007240 // Use BackupRead() to find the info streams. Repeat until we
7241 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007242 for (;;)
7243 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007244 // Get the header to find the length of the stream name. If
7245 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007246 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007247 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007248 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7249 &readcount, FALSE, FALSE, &context)
7250 || readcount == 0)
7251 break;
7252
Bram Moolenaar0f873732019-12-05 20:28:46 +01007253 // We only deal with streams that have a name. The normal
7254 // file data appears to be without a name, even though docs
7255 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007256 if (sid.dwStreamNameSize > 0)
7257 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007258 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007259 if (!BackupRead(sh, (LPBYTE)streamname,
7260 sid.dwStreamNameSize,
7261 &readcount, FALSE, FALSE, &context))
7262 break;
7263
Bram Moolenaar0f873732019-12-05 20:28:46 +01007264 // Copy an info stream with a name ":anything:$DATA".
7265 // Skip "::$DATA", it has no stream name (examples suggest
7266 // it might be used for the normal file contents).
7267 // Note that BackupRead() counts bytes, but the name is in
7268 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007269 len = readcount / sizeof(WCHAR);
7270 streamname[len] = 0;
7271 if (len > 7 && wcsicmp(streamname + len - 6,
7272 L":$DATA") == 0)
7273 {
7274 streamname[len - 6] = 0;
7275 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007276 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007277 }
7278 }
7279
Bram Moolenaar0f873732019-12-05 20:28:46 +01007280 // Advance to the next stream. We might try seeking too far,
7281 // but BackupSeek() doesn't skip over stream borders, thus
7282 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007283 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007284 &lo, &hi, &context);
7285 }
7286
Bram Moolenaar0f873732019-12-05 20:28:46 +01007287 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007288 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7289
7290 CloseHandle(sh);
7291 }
7292 }
7293 vim_free(fromw);
7294 vim_free(tow);
7295}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007296
7297/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007298 * ntdll.dll definitions
7299 */
7300#define FileEaInformation 7
7301#ifndef STATUS_SUCCESS
7302# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7303#endif
7304
7305typedef struct _FILE_FULL_EA_INFORMATION_ {
7306 ULONG NextEntryOffset;
7307 UCHAR Flags;
7308 UCHAR EaNameLength;
7309 USHORT EaValueLength;
7310 CHAR EaName[1];
7311} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7312
7313typedef struct _FILE_EA_INFORMATION_ {
7314 ULONG EaSize;
7315} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7316
7317typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7318 PHANDLE FileHandle,
7319 ACCESS_MASK DesiredAccess,
7320 POBJECT_ATTRIBUTES ObjectAttributes,
7321 PIO_STATUS_BLOCK IoStatusBlock,
7322 ULONG ShareAccess,
7323 ULONG OpenOptions);
7324typedef NTSTATUS (NTAPI *PfnNtClose)(
7325 HANDLE Handle);
7326typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
7327 HANDLE FileHandle,
7328 PIO_STATUS_BLOCK IoStatusBlock,
7329 PVOID Buffer,
7330 ULONG Length);
7331typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7332 HANDLE FileHandle,
7333 PIO_STATUS_BLOCK IoStatusBlock,
7334 PVOID Buffer,
7335 ULONG Length,
7336 BOOLEAN ReturnSingleEntry,
7337 PVOID EaList,
7338 ULONG EaListLength,
7339 PULONG EaIndex,
7340 BOOLEAN RestartScan);
7341typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
7342 HANDLE FileHandle,
7343 PIO_STATUS_BLOCK IoStatusBlock,
7344 PVOID FileInformation,
7345 ULONG Length,
7346 FILE_INFORMATION_CLASS FileInformationClass);
7347typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7348 PUNICODE_STRING DestinationString,
7349 PCWSTR SourceString);
7350
7351PfnNtOpenFile pNtOpenFile = NULL;
7352PfnNtClose pNtClose = NULL;
7353PfnNtSetEaFile pNtSetEaFile = NULL;
7354PfnNtQueryEaFile pNtQueryEaFile = NULL;
7355PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7356PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
7357
7358/*
7359 * Load ntdll.dll functions.
7360 */
7361 static BOOL
7362load_ntdll(void)
7363{
7364 static int loaded = -1;
7365
7366 if (loaded == -1)
7367 {
7368 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7369 if (hNtdll != NULL)
7370 {
7371 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7372 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7373 pNtSetEaFile = (PfnNtSetEaFile)
7374 GetProcAddress(hNtdll, "NtSetEaFile");
7375 pNtQueryEaFile = (PfnNtQueryEaFile)
7376 GetProcAddress(hNtdll, "NtQueryEaFile");
7377 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7378 GetProcAddress(hNtdll, "NtQueryInformationFile");
7379 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7380 GetProcAddress(hNtdll, "RtlInitUnicodeString");
7381 }
7382 if (pNtOpenFile == NULL
7383 || pNtClose == NULL
7384 || pNtSetEaFile == NULL
7385 || pNtQueryEaFile == NULL
7386 || pNtQueryInformationFile == NULL
7387 || pRtlInitUnicodeString == NULL)
7388 loaded = FALSE;
7389 else
7390 loaded = TRUE;
7391 }
7392 return (BOOL) loaded;
7393}
7394
7395/*
7396 * Copy extended attributes (EA) from file "from" to file "to".
7397 */
7398 static void
7399copy_extattr(char_u *from, char_u *to)
7400{
7401 char_u *fromf = NULL;
7402 char_u *tof = NULL;
7403 WCHAR *fromw = NULL;
7404 WCHAR *tow = NULL;
7405 UNICODE_STRING u;
7406 HANDLE h;
7407 OBJECT_ATTRIBUTES oa;
7408 IO_STATUS_BLOCK iosb;
7409 FILE_EA_INFORMATION_ eainfo = {0};
7410 void *ea = NULL;
7411
7412 if (!load_ntdll())
7413 return;
7414
7415 // Convert the file names to the fully qualified object names.
7416 fromf = alloc(STRLEN(from) + 5);
7417 tof = alloc(STRLEN(to) + 5);
7418 if (fromf == NULL || tof == NULL)
7419 goto theend;
7420 STRCPY(fromf, "\\??\\");
7421 STRCAT(fromf, from);
7422 STRCPY(tof, "\\??\\");
7423 STRCAT(tof, to);
7424
7425 // Convert the names to wide characters.
7426 fromw = enc_to_utf16(fromf, NULL);
7427 tow = enc_to_utf16(tof, NULL);
7428 if (fromw == NULL || tow == NULL)
7429 goto theend;
7430
7431 // Get the EA.
7432 pRtlInitUnicodeString(&u, fromw);
7433 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7434 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7435 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7436 goto theend;
7437 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7438 FileEaInformation);
7439 if (eainfo.EaSize != 0)
7440 {
7441 ea = alloc(eainfo.EaSize);
7442 if (ea != NULL)
7443 {
7444 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7445 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7446 {
7447 vim_free(ea);
7448 ea = NULL;
7449 }
7450 }
7451 }
7452 pNtClose(h);
7453
7454 // Set the EA.
7455 if (ea != NULL)
7456 {
7457 pRtlInitUnicodeString(&u, tow);
7458 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7459 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7460 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7461 goto theend;
7462
7463 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
7464 pNtClose(h);
7465 }
7466
7467theend:
7468 vim_free(fromf);
7469 vim_free(tof);
7470 vim_free(fromw);
7471 vim_free(tow);
7472 vim_free(ea);
7473}
7474
7475/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007476 * Copy file attributes from file "from" to file "to".
7477 * For Windows NT and later we copy info streams.
7478 * Always returns zero, errors are ignored.
7479 */
7480 int
7481mch_copy_file_attribute(char_u *from, char_u *to)
7482{
Bram Moolenaar0f873732019-12-05 20:28:46 +01007483 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007484 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007485 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007486 return 0;
7487}
7488
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007489
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007490/*
K.Takatadc73b4b2021-06-08 18:32:36 +02007491 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007492 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007493static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007494static LPWSTR *ArglistW = NULL;
7495static int global_argc = 0;
7496static char **global_argv;
7497
Bram Moolenaar0f873732019-12-05 20:28:46 +01007498static int used_file_argc = 0; // last argument in global_argv[] used
7499 // for the argument list.
7500static int *used_file_indexes = NULL; // indexes in global_argv[] for
7501 // command line arguments added to
7502 // the argument list
7503static int used_file_count = 0; // nr of entries in used_file_indexes
7504static int used_file_literal = FALSE; // take file names literally
7505static int used_file_full_path = FALSE; // file name was full path
7506static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007507static int used_alist_count = 0;
7508
7509
7510/*
7511 * Get the command line arguments. Unicode version.
7512 * Returns argc. Zero when something fails.
7513 */
7514 int
7515get_cmd_argsW(char ***argvp)
7516{
7517 char **argv = NULL;
7518 int argc = 0;
7519 int i;
7520
Bram Moolenaar14993322014-09-09 12:25:33 +02007521 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007522 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7523 if (ArglistW != NULL)
7524 {
7525 argv = malloc((nArgsW + 1) * sizeof(char *));
7526 if (argv != NULL)
7527 {
7528 argc = nArgsW;
7529 argv[argc] = NULL;
7530 for (i = 0; i < argc; ++i)
7531 {
7532 int len;
7533
K.Takatadc73b4b2021-06-08 18:32:36 +02007534 // Convert each Unicode argument to UTF-8.
7535 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007536 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007537 (LPSTR *)&argv[i], &len, 0, 0);
7538 if (argv[i] == NULL)
7539 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007540 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007541 while (i > 0)
7542 free(argv[--i]);
7543 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007544 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007545 argc = 0;
7546 }
7547 }
7548 }
7549 }
7550
7551 global_argc = argc;
7552 global_argv = argv;
7553 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007554 {
7555 if (used_file_indexes != NULL)
7556 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007557 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007558 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007559
7560 if (argvp != NULL)
7561 *argvp = argv;
7562 return argc;
7563}
7564
7565 void
7566free_cmd_argsW(void)
7567{
7568 if (ArglistW != NULL)
7569 {
7570 GlobalFree(ArglistW);
7571 ArglistW = NULL;
7572 }
7573}
7574
7575/*
7576 * Remember "name" is an argument that was added to the argument list.
7577 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7578 * is called.
7579 */
7580 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007581used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007582{
7583 int i;
7584
7585 if (used_file_indexes == NULL)
7586 return;
7587 for (i = used_file_argc + 1; i < global_argc; ++i)
7588 if (STRCMP(global_argv[i], name) == 0)
7589 {
7590 used_file_argc = i;
7591 used_file_indexes[used_file_count++] = i;
7592 break;
7593 }
7594 used_file_literal = literal;
7595 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007596 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007597}
7598
7599/*
7600 * Remember the length of the argument list as it was. If it changes then we
7601 * leave it alone when 'encoding' is set.
7602 */
7603 void
7604set_alist_count(void)
7605{
7606 used_alist_count = GARGCOUNT;
7607}
7608
7609/*
7610 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02007611 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007612 * and convert them to 'encoding'.
7613 */
7614 void
7615fix_arg_enc(void)
7616{
7617 int i;
7618 int idx;
7619 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007620 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007621
Bram Moolenaar0f873732019-12-05 20:28:46 +01007622 // Safety checks:
7623 // - if argument count differs between the wide and non-wide argument
7624 // list, something must be wrong.
7625 // - the file name arguments must have been located.
7626 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007627 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007628 || ArglistW == NULL
7629 || used_file_indexes == NULL
7630 || used_file_count == 0
7631 || used_alist_count != GARGCOUNT)
7632 return;
7633
Bram Moolenaar0f873732019-12-05 20:28:46 +01007634 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007635 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007636 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007637 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00007638 for (i = 0; i < GARGCOUNT; ++i)
7639 fnum_list[i] = GARGLIST[i].ae_fnum;
7640
Bram Moolenaar0f873732019-12-05 20:28:46 +01007641 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007642 alist_clear(&global_alist);
7643 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007644 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007645
7646 for (i = 0; i < used_file_count; ++i)
7647 {
7648 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007649 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007650 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007651 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007652 int literal = used_file_literal;
7653
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007654#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01007655 // When using diff mode may need to concatenate file name to
7656 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007657 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7658 && !mch_isdir(alist_name(&GARGLIST[0])))
7659 {
7660 char_u *r;
7661
7662 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7663 if (r != NULL)
7664 {
7665 vim_free(str);
7666 str = r;
7667 }
7668 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007669#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01007670 // Re-use the old buffer by renaming it. When not using literal
7671 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00007672 if (used_file_literal)
7673 buf_set_name(fnum_list[i], str);
7674
Bram Moolenaar0f873732019-12-05 20:28:46 +01007675 // Check backtick literal. backtick literal is already expanded in
7676 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007677 if (literal == FALSE)
7678 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007679 size_t len = STRLEN(str);
7680
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007681 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7682 literal = TRUE;
7683 }
7684 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007685 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007686 }
7687
7688 if (!used_file_literal)
7689 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007690 // Now expand wildcards in the arguments.
7691 // Temporarily add '(' and ')' to 'isfname'. These are valid
7692 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00007693 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01007694 // Also, unset wildignore to not be influenced by this option.
7695 // The arguments specified in command-line should be kept even if
7696 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00007697 // Use :legacy so that it also works when in Vim9 script.
7698 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
7699 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007700 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00007701 do_cmdline_cmd(
7702 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
7703 do_cmdline_cmd(
7704 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007705 }
7706
Bram Moolenaar0f873732019-12-05 20:28:46 +01007707 // If wildcard expansion failed, we are editing the first file of the
7708 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007709 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7710 {
7711 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00007712 if (GARGCOUNT == 1 && used_file_full_path
7713 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
7714 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007715 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007716
7717 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007718}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007719
7720 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007721mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007722{
7723 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007724 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007725
Bram Moolenaar964b3742019-05-24 18:54:09 +02007726 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007727 if (envbuf == NULL)
7728 return -1;
7729
7730 sprintf((char *)envbuf, "%s=%s", var, value);
7731
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007732 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007733
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007734 vim_free(envbuf);
7735 if (p == NULL)
7736 return -1;
7737 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007738#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007739 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007740#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007741 // Unlike Un*x systems, we can free the string for _wputenv().
7742 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007743
7744 return 0;
7745}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007746
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007747/*
7748 * Support for 256 colors and 24-bit colors was added in Windows 10
7749 * version 1703 (Creators update).
7750 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007751#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7752
7753/*
7754 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02007755 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007756 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007757#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007758
7759/*
7760 * ConPTY differences between versions, need different logic.
7761 * version 1903 (May 2019 update).
7762 */
7763#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
7764
7765/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007766 * version 1909 (November 2019 update).
7767 */
7768#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
7769
7770/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007771 * Stay ahead of the next update, and when it's done, fix this.
7772 * version ? (2020 update, temporarily use the build number of insider preview)
7773 */
7774#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
7775
7776/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02007777 * Confirm until this version. Also the logic changes.
7778 * insider preview.
7779 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02007780#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007781
7782/*
7783 * Not stable now.
7784 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007785#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007786
7787 static void
7788vtp_flag_init(void)
7789{
7790 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007791#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007792 DWORD mode;
7793 HANDLE out;
7794
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007795# ifdef VIMDLL
7796 if (!gui.in_use)
7797# endif
7798 {
7799 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007800
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007801 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7802 GetConsoleMode(out, &mode);
7803 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7804 if (SetConsoleMode(out, mode) == 0)
7805 vtp_working = 0;
7806 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007807#endif
7808
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007809 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007810 conpty_working = 1;
7811 if (ver >= CONPTY_STABLE_BUILD)
7812 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007813
Bram Moolenaar57da6982019-09-13 22:30:11 +02007814 if (ver <= CONPTY_INSIDER_BUILD)
7815 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007816 if (ver <= CONPTY_1909_BUILD)
7817 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02007818 if (ver <= CONPTY_1903_BUILD)
7819 conpty_type = 2;
7820 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
7821 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007822
7823 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
7824 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007825}
7826
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007827#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007828
7829 static void
7830vtp_init(void)
7831{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007832 HMODULE hKerneldll;
7833 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007834# ifdef FEAT_TERMGUICOLORS
7835 COLORREF fg, bg;
7836# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007837
Bram Moolenaar0f873732019-12-05 20:28:46 +01007838 // Use functions supported from Vista
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007839 hKerneldll = GetModuleHandle("kernel32.dll");
7840 if (hKerneldll != NULL)
7841 {
7842 pGetConsoleScreenBufferInfoEx =
7843 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7844 hKerneldll, "GetConsoleScreenBufferInfoEx");
7845 pSetConsoleScreenBufferInfoEx =
7846 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7847 hKerneldll, "SetConsoleScreenBufferInfoEx");
7848 if (pGetConsoleScreenBufferInfoEx != NULL
7849 && pSetConsoleScreenBufferInfoEx != NULL)
7850 has_csbiex = TRUE;
7851 }
7852
7853 csbi.cbSize = sizeof(csbi);
7854 if (has_csbiex)
7855 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007856 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7857 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
Bram Moolenaardf543822020-01-30 11:53:59 +01007858 store_console_bg_rgb = save_console_bg_rgb;
7859 store_console_fg_rgb = save_console_fg_rgb;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007860
7861# ifdef FEAT_TERMGUICOLORS
7862 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7863 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7864 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7865 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7866 default_console_color_bg = bg;
7867 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007868# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007869
7870 set_console_color_rgb();
7871}
7872
7873 static void
7874vtp_exit(void)
7875{
Bram Moolenaardf543822020-01-30 11:53:59 +01007876 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007877}
7878
Bram Moolenaar06b7b582020-05-30 17:49:25 +02007879 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007880vtp_printf(
7881 char *format,
7882 ...)
7883{
7884 char_u buf[100];
7885 va_list list;
7886 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007887 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007888
7889 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007890 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007891 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007892 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007893 return (int)result;
7894}
7895
7896 static void
7897vtp_sgr_bulk(
7898 int arg)
7899{
7900 int args[1];
7901
7902 args[0] = arg;
7903 vtp_sgr_bulks(1, args);
7904}
7905
K.Takata6e1d31e2022-02-03 13:05:32 +00007906# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007907 if ((*p-- = "0123456789"[(n = x % 10)]) \
7908 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
7909 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
7910
K.Takata6e1d31e2022-02-03 13:05:32 +00007911# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007912 case x: \
7913 FAST256(newargs[x - 1]);
7914
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007915 static void
7916vtp_sgr_bulks(
7917 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007918 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007919{
K.Takata6e1d31e2022-02-03 13:05:32 +00007920# define MAXSGR 16
7921# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007922 char_u buf[SGRBUFSIZE];
7923 char_u *p;
7924 int in, out;
7925 int newargs[16];
7926 static int sgrfgr = -1, sgrfgg, sgrfgb;
7927 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007928
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007929 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007930 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007931 sgrfgr = sgrbgr = -1;
7932 vtp_printf("033[m");
7933 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007934 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007935
7936 in = out = 0;
7937 while (in < argc)
7938 {
7939 int s = args[in];
7940 int copylen = 1;
7941
7942 if (s == 38)
7943 {
7944 if (argc - in >= 5 && args[in + 1] == 2)
7945 {
7946 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
7947 && sgrfgb == args[in + 4])
7948 {
7949 in += 5;
7950 copylen = 0;
7951 }
7952 else
7953 {
7954 sgrfgr = args[in + 2];
7955 sgrfgg = args[in + 3];
7956 sgrfgb = args[in + 4];
7957 copylen = 5;
7958 }
7959 }
7960 else if (argc - in >= 3 && args[in + 1] == 5)
7961 {
7962 sgrfgr = -1;
7963 copylen = 3;
7964 }
7965 }
7966 else if (s == 48)
7967 {
7968 if (argc - in >= 5 && args[in + 1] == 2)
7969 {
7970 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
7971 && sgrbgb == args[in + 4])
7972 {
7973 in += 5;
7974 copylen = 0;
7975 }
7976 else
7977 {
7978 sgrbgr = args[in + 2];
7979 sgrbgg = args[in + 3];
7980 sgrbgb = args[in + 4];
7981 copylen = 5;
7982 }
7983 }
7984 else if (argc - in >= 3 && args[in + 1] == 5)
7985 {
7986 sgrbgr = -1;
7987 copylen = 3;
7988 }
7989 }
7990 else if (30 <= s && s <= 39)
7991 sgrfgr = -1;
7992 else if (90 <= s && s <= 97)
7993 sgrfgr = -1;
7994 else if (40 <= s && s <= 49)
7995 sgrbgr = -1;
7996 else if (100 <= s && s <= 107)
7997 sgrbgr = -1;
7998 else if (s == 0)
7999 sgrfgr = sgrbgr = -1;
8000
8001 while (copylen--)
8002 newargs[out++] = args[in++];
8003 }
8004
8005 p = &buf[sizeof(buf) - 1];
8006 *p-- = 'm';
8007
8008 switch (out)
8009 {
8010 int n, m;
8011 DWORD r;
8012
8013 FAST256CASE(16);
8014 *p-- = ';';
8015 FAST256CASE(15);
8016 *p-- = ';';
8017 FAST256CASE(14);
8018 *p-- = ';';
8019 FAST256CASE(13);
8020 *p-- = ';';
8021 FAST256CASE(12);
8022 *p-- = ';';
8023 FAST256CASE(11);
8024 *p-- = ';';
8025 FAST256CASE(10);
8026 *p-- = ';';
8027 FAST256CASE(9);
8028 *p-- = ';';
8029 FAST256CASE(8);
8030 *p-- = ';';
8031 FAST256CASE(7);
8032 *p-- = ';';
8033 FAST256CASE(6);
8034 *p-- = ';';
8035 FAST256CASE(5);
8036 *p-- = ';';
8037 FAST256CASE(4);
8038 *p-- = ';';
8039 FAST256CASE(3);
8040 *p-- = ';';
8041 FAST256CASE(2);
8042 *p-- = ';';
8043 FAST256CASE(1);
8044 *p-- = '[';
8045 *p = '\033';
8046 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8047 default:
8048 break;
8049 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008050}
8051
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008052 static void
8053wt_init(void)
8054{
8055 wt_working = (mch_getenv("WT_SESSION") != NULL);
8056}
8057
8058 int
8059use_wt(void)
8060{
8061 return USE_WT;
8062}
8063
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008064# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008065 static int
8066ctermtoxterm(
8067 int cterm)
8068{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008069 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008070
8071 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8072 return (((int)r << 16) | ((int)g << 8) | (int)b);
8073}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008074# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008075
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008076 static void
8077set_console_color_rgb(void)
8078{
8079# ifdef FEAT_TERMGUICOLORS
8080 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008081 guicolor_T fg, bg;
8082 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008083
8084 if (!USE_VTP)
8085 return;
8086
Bram Moolenaara050b942019-12-02 21:35:31 +01008087 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8088
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008089 if (USE_WT)
8090 {
8091 term_fg_rgb_color(fg);
8092 term_bg_rgb_color(bg);
8093 return;
8094 }
8095
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008096 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8097 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8098
8099 csbi.cbSize = sizeof(csbi);
8100 if (has_csbiex)
8101 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8102
8103 csbi.cbSize = sizeof(csbi);
8104 csbi.srWindow.Right += 1;
8105 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008106 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8107 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008108 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8109 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008110 if (has_csbiex)
8111 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8112# endif
8113}
8114
Bram Moolenaara050b942019-12-02 21:35:31 +01008115# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8116 void
8117get_default_console_color(
8118 int *cterm_fg,
8119 int *cterm_bg,
8120 guicolor_T *gui_fg,
8121 guicolor_T *gui_bg)
8122{
8123 int id;
8124 guicolor_T guifg = INVALCOLOR;
8125 guicolor_T guibg = INVALCOLOR;
8126 int ctermfg = 0;
8127 int ctermbg = 0;
8128
8129 id = syn_name2id((char_u *)"Normal");
8130 if (id > 0 && p_tgc)
8131 syn_id2colors(id, &guifg, &guibg);
8132 if (guifg == INVALCOLOR)
8133 {
8134 ctermfg = -1;
8135 if (id > 0)
8136 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8137 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
8138 : default_console_color_fg;
8139 cterm_normal_fg_gui_color = guifg;
8140 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8141 }
8142 if (guibg == INVALCOLOR)
8143 {
8144 ctermbg = -1;
8145 if (id > 0)
8146 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8147 guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8148 : default_console_color_bg;
8149 cterm_normal_bg_gui_color = guibg;
8150 ctermbg = ctermbg < 0 ? 0 : ctermbg;
8151 }
8152
8153 *cterm_fg = ctermfg;
8154 *cterm_bg = ctermbg;
8155 *gui_fg = guifg;
8156 *gui_bg = guibg;
8157}
8158# endif
8159
Bram Moolenaardf543822020-01-30 11:53:59 +01008160/*
8161 * Set the console colors to the original colors or the last set colors.
8162 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008163 static void
8164reset_console_color_rgb(void)
8165{
8166# ifdef FEAT_TERMGUICOLORS
8167 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8168
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008169 if (USE_WT)
8170 return;
8171
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008172 csbi.cbSize = sizeof(csbi);
8173 if (has_csbiex)
8174 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8175
8176 csbi.cbSize = sizeof(csbi);
8177 csbi.srWindow.Right += 1;
8178 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008179 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8180 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
8181 if (has_csbiex)
8182 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8183# endif
8184}
8185
8186/*
8187 * Set the console colors to the original colors.
8188 */
8189 static void
8190restore_console_color_rgb(void)
8191{
8192# ifdef FEAT_TERMGUICOLORS
8193 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8194
8195 csbi.cbSize = sizeof(csbi);
8196 if (has_csbiex)
8197 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8198
8199 csbi.cbSize = sizeof(csbi);
8200 csbi.srWindow.Right += 1;
8201 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008202 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8203 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008204 if (has_csbiex)
8205 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8206# endif
8207}
8208
8209 void
8210control_console_color_rgb(void)
8211{
8212 if (USE_VTP)
8213 set_console_color_rgb();
8214 else
8215 reset_console_color_rgb();
8216}
8217
8218 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008219use_vtp(void)
8220{
8221 return USE_VTP;
8222}
8223
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008224 int
8225is_term_win32(void)
8226{
8227 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8228}
8229
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008230 int
8231has_vtp_working(void)
8232{
8233 return vtp_working;
8234}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008235
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008236#endif
8237
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008238 int
8239has_conpty_working(void)
8240{
8241 return conpty_working;
8242}
8243
8244 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008245get_conpty_type(void)
8246{
8247 return conpty_type;
8248}
8249
8250 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008251is_conpty_stable(void)
8252{
8253 return conpty_stable;
8254}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008255
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008256 int
8257get_conpty_fix_type(void)
8258{
8259 return conpty_fix_type;
8260}
8261
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008262#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008263 void
8264resize_console_buf(void)
8265{
8266 CONSOLE_SCREEN_BUFFER_INFO csbi;
8267 COORD coord;
8268 SMALL_RECT newsize;
8269
8270 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8271 {
8272 coord.X = SRWIDTH(csbi.srWindow);
8273 coord.Y = SRHEIGHT(csbi.srWindow);
8274 SetConsoleScreenBufferSize(g_hConOut, coord);
8275
8276 newsize.Left = 0;
8277 newsize.Top = 0;
8278 newsize.Right = coord.X - 1;
8279 newsize.Bottom = coord.Y - 1;
8280 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8281
8282 SetConsoleScreenBufferSize(g_hConOut, coord);
8283 }
8284}
8285#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008286
8287 char *
8288GetWin32Error(void)
8289{
K.Takatad68b2fc2022-02-12 11:18:37 +00008290 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008291 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008292
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008293 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8294 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008295 if (oldmsg != NULL)
8296 LocalFree(oldmsg);
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008297 if (msg != NULL)
8298 {
8299 // remove trailing \r\n
8300 char *pcrlf = strstr(msg, "\r\n");
8301 if (pcrlf != NULL)
8302 *pcrlf = '\0';
K.Takatad68b2fc2022-02-12 11:18:37 +00008303 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008304 }
8305 return msg;
8306}