blob: 6a02fe283e4a4a4ed56c359532f410ef32cf1f89 [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
12 * Used for both the console version and the Win32 GUI. A lot of code is for
Bram Moolenaar4f974752019-02-17 17:44:42 +010013 * the console version only, so there is a lot of "#ifndef FEAT_GUI_MSWIN".
Bram Moolenaar071d4272004-06-13 20:20:40 +000014 *
15 * Win32 (Windows NT and Windows 95) system-dependent routines.
16 * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17 * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18 *
19 * George V. Reilly <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
Bram Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010032
Bram Moolenaar0f873732019-12-05 20:28:46 +010033// cproto fails on missing include files
Bram Moolenaar82881492012-11-20 16:53:39 +010034#ifndef PROTO
35# include <process.h>
Bram Moolenaare7bebc42021-02-01 20:50:37 +010036# include <winternl.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010037#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000038
39#undef chdir
40#ifdef __GNUC__
41# ifndef __MINGW32__
42# include <dirent.h>
43# endif
44#else
45# include <direct.h>
46#endif
47
Bram Moolenaar82881492012-11-20 16:53:39 +010048#ifndef PROTO
Bram Moolenaar651fca82021-11-29 20:39:38 +000049# if !defined(FEAT_GUI_MSWIN)
Bram Moolenaar82881492012-11-20 16:53:39 +010050# include <shellapi.h>
51# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000052#endif
53
Bram Moolenaarfb630902016-10-29 14:55:00 +020054#ifdef FEAT_JOB_CHANNEL
55# include <tlhelp32.h>
56#endif
57
Bram Moolenaar071d4272004-06-13 20:20:40 +000058#ifdef __MINGW32__
59# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
60# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
61# endif
62# ifndef RIGHTMOST_BUTTON_PRESSED
63# define RIGHTMOST_BUTTON_PRESSED 0x0002
64# endif
65# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
66# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
67# endif
68# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
69# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
70# endif
71# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
72# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
73# endif
74
75/*
76 * EventFlags
77 */
78# ifndef MOUSE_MOVED
79# define MOUSE_MOVED 0x0001
80# endif
81# ifndef DOUBLE_CLICK
82# define DOUBLE_CLICK 0x0002
83# endif
84#endif
85
Bram Moolenaar0f873732019-12-05 20:28:46 +010086// Record all output and all keyboard & mouse input
87// #define MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +000088
89#ifdef MCH_WRITE_DUMP
90FILE* fdDump = NULL;
91#endif
92
93/*
94 * When generating prototypes for Win32 on Unix, these lines make the syntax
95 * errors disappear. They do not need to be correct.
96 */
97#ifdef PROTO
Bram Moolenaar912bc4a2019-12-01 18:58:11 +010098# define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000099typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000100typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000101typedef int ACCESS_MASK;
102typedef int BOOL;
Paul Ollis65745772022-06-05 16:55:54 +0100103typedef int BOOLEAN;
104typedef int CALLBACK;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000105typedef int COLORREF;
106typedef int CONSOLE_CURSOR_INFO;
107typedef int COORD;
108typedef int DWORD;
109typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100110typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000111typedef int HDC;
112typedef int HFONT;
113typedef int HICON;
114typedef int HINSTANCE;
115typedef int HWND;
116typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200117typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000118typedef int KEY_EVENT_RECORD;
119typedef int LOGFONT;
120typedef int LPBOOL;
121typedef int LPCTSTR;
122typedef int LPDWORD;
123typedef int LPSTR;
124typedef int LPTSTR;
125typedef int LPVOID;
126typedef int MOUSE_EVENT_RECORD;
127typedef int PACL;
128typedef int PDWORD;
129typedef int PHANDLE;
130typedef int PRINTDLG;
131typedef int PSECURITY_DESCRIPTOR;
132typedef int PSID;
133typedef int SECURITY_INFORMATION;
134typedef int SHORT;
135typedef int SMALL_RECT;
136typedef int TEXTMETRIC;
137typedef int TOKEN_INFORMATION_CLASS;
138typedef int TRUSTEE;
139typedef int WORD;
140typedef int WCHAR;
141typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100142typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200143typedef int SE_OBJECT_TYPE;
144typedef int PSNSECINFO;
145typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100146typedef int STARTUPINFO;
147typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200148typedef int LPSECURITY_ATTRIBUTES;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100149# define __stdcall // empty
Bram Moolenaar071d4272004-06-13 20:20:40 +0000150#endif
151
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200152#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100153// Win32 Console handles for input and output
Bram Moolenaar071d4272004-06-13 20:20:40 +0000154static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
155static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
156
Bram Moolenaar0f873732019-12-05 20:28:46 +0100157// Win32 Screen buffer,coordinate,console I/O information
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158static SMALL_RECT g_srScrollRegion;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100159static COORD g_coord; // 0-based, but external coords are 1-based
Bram Moolenaar071d4272004-06-13 20:20:40 +0000160
Bram Moolenaar0f873732019-12-05 20:28:46 +0100161// The attribute of the screen when the editor was started
162static WORD g_attrDefault = 7; // lightgray text on black background
Bram Moolenaar071d4272004-06-13 20:20:40 +0000163static WORD g_attrCurrent;
164
Bram Moolenaar0f873732019-12-05 20:28:46 +0100165static int g_fCBrkPressed = FALSE; // set by ctrl-break interrupt
166static int g_fCtrlCPressed = FALSE; // set when ctrl-C or ctrl-break detected
167static int g_fForceExit = FALSE; // set when forcefully exiting
Bram Moolenaar071d4272004-06-13 20:20:40 +0000168
Bram Moolenaar071d4272004-06-13 20:20:40 +0000169static void scroll(unsigned cLines);
170static void set_scroll_region(unsigned left, unsigned top,
171 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100172static void set_scroll_region_tb(unsigned top, unsigned bottom);
173static void set_scroll_region_lr(unsigned left, unsigned right);
174static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000175static void delete_lines(unsigned cLines);
176static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000177static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000178static int s_cursor_visible = TRUE;
179static int did_create_conin = FALSE;
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200180#endif
181#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000182static int s_dont_use_vimrun = TRUE;
183static int need_vimrun_warning = FALSE;
184static char *vimrun_path = "vimrun ";
185#endif
186
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200187static int win32_getattrs(char_u *name);
188static int win32_setattrs(char_u *name, int attrs);
189static int win32_set_archive(char_u *name);
190
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100191static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200192static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100193static int conpty_stable = 0;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +0200194static int conpty_fix_type = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100195static void vtp_flag_init();
196
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200197#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100198static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100199static void vtp_init();
200static void vtp_exit();
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100201static void vtp_sgr_bulk(int arg);
202static void vtp_sgr_bulks(int argc, int *argv);
203
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200204static int wt_working = 0;
205static void wt_init();
206
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100207static guicolor_T save_console_bg_rgb;
208static guicolor_T save_console_fg_rgb;
Bram Moolenaardf543822020-01-30 11:53:59 +0100209static guicolor_T store_console_bg_rgb;
210static guicolor_T store_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100211
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200212static int g_color_index_bg = 0;
213static int g_color_index_fg = 7;
214
215# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200216static int default_console_color_fg = 0xc0c0c0; // white
217# endif
218
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100219# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200220# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200221# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100222# else
223# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200224# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100225# endif
226
227static void set_console_color_rgb(void);
228static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100229static void restore_console_color_rgb(void);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100230#endif
231
Bram Moolenaar0f873732019-12-05 20:28:46 +0100232// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100233#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
234# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
235#endif
236
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200237#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100238static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000239#endif
240
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200241static char_u *exe_path = NULL;
242
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100243static BOOL win8_or_later = FALSE;
244
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200245#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100246// Dynamic loading for portability
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100247typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
248{
249 ULONG cbSize;
250 COORD dwSize;
251 COORD dwCursorPosition;
252 WORD wAttributes;
253 SMALL_RECT srWindow;
254 COORD dwMaximumWindowSize;
255 WORD wPopupAttributes;
256 BOOL bFullscreenSupported;
257 COLORREF ColorTable[16];
258} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
259typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
260static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
261typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
262static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
263static BOOL has_csbiex = FALSE;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100264#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100265
266/*
267 * Get version number including build number
268 */
269typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100270#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100271 (((major) << 24) | ((minor) << 16) | (build))
272
273 static DWORD
274get_build_number(void)
275{
276 OSVERSIONINFOW osver = {sizeof(OSVERSIONINFOW)};
277 HMODULE hNtdll;
278 PfnRtlGetVersion pRtlGetVersion;
279 DWORD ver = MAKE_VER(0, 0, 0);
280
281 hNtdll = GetModuleHandle("ntdll.dll");
282 if (hNtdll != NULL)
283 {
284 pRtlGetVersion =
285 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
286 pRtlGetVersion(&osver);
287 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
288 min(osver.dwMinorVersion, 255),
289 min(osver.dwBuildNumber, 32767));
290 }
291 return ver;
292}
293
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200294#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200295 static BOOL
296is_ambiwidth_event(
297 INPUT_RECORD *ir)
298{
299 return ir->EventType == KEY_EVENT
300 && ir->Event.KeyEvent.bKeyDown
301 && ir->Event.KeyEvent.wRepeatCount == 1
302 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
303 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000304 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200305 && ir->Event.KeyEvent.dwControlKeyState == 2;
306}
307
308 static void
309make_ambiwidth_event(
310 INPUT_RECORD *down,
311 INPUT_RECORD *up)
312{
313 down->Event.KeyEvent.wVirtualKeyCode = 0;
314 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000315 down->Event.KeyEvent.uChar.UnicodeChar
316 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200317 down->Event.KeyEvent.dwControlKeyState = 0;
318}
319
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100320/*
321 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100322 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100323 */
324 static BOOL
325read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100326 HANDLE hInput,
327 INPUT_RECORD *lpBuffer,
328 DWORD nLength,
329 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100330{
331 enum
332 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100333 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100334 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100335 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100336 static DWORD s_dwIndex = 0;
337 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100338 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100339 int head;
340 int tail;
341 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200342 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100343
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200344 if (nLength == -2)
345 return (s_dwMax > 0) ? TRUE : FALSE;
346
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100347 if (!win8_or_later)
348 {
349 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200350 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
351 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100352 }
353
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100354 if (s_dwMax == 0)
355 {
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200356 if (!USE_WT && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200357 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200358 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
359 if (dwEvents == 0 && nLength == -1)
360 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
361 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100362 s_dwIndex = 0;
363 s_dwMax = dwEvents;
364 if (dwEvents == 0)
365 {
366 *lpEvents = 0;
367 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100368 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100369
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200370 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
371 if (is_ambiwidth_event(&s_irCache[i]))
372 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
373
Bram Moolenaardd415a62014-02-05 14:02:27 +0100374 if (s_dwMax > 1)
375 {
376 head = 0;
377 tail = s_dwMax - 1;
378 while (head != tail)
379 {
380 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
381 && s_irCache[head + 1].EventType
382 == WINDOW_BUFFER_SIZE_EVENT)
383 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100384 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100385 for (i = head; i < tail; ++i)
386 s_irCache[i] = s_irCache[i + 1];
387 --tail;
388 continue;
389 }
390 head++;
391 }
392 s_dwMax = tail + 1;
393 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100394 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100395
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200396 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
397 {
398 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
399 {
400 s_irPseudo = s_irCache[s_dwIndex];
401 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
402 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
403 *lpBuffer = s_irPseudo;
404 *lpEvents = 1;
405 return TRUE;
406 }
407 }
408
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100409 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200410 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100411 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100412 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100413 return TRUE;
414}
415
416/*
417 * Version of PeekConsoleInput() that works with IME.
418 */
419 static BOOL
420peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100421 HANDLE hInput,
422 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200423 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100424 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100425{
K.Takata135e1522022-01-29 15:27:58 +0000426 return read_console_input(hInput, lpBuffer, (DWORD)-1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100427}
428
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100429# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200430 static DWORD
431msg_wait_for_multiple_objects(
432 DWORD nCount,
433 LPHANDLE pHandles,
434 BOOL fWaitAll,
435 DWORD dwMilliseconds,
436 DWORD dwWakeMask)
437{
K.Takata135e1522022-01-29 15:27:58 +0000438 if (read_console_input(NULL, NULL, (DWORD)-2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200439 return WAIT_OBJECT_0;
440 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
441 dwMilliseconds, dwWakeMask);
442}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100443# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200444
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100445# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200446 static DWORD
447wait_for_single_object(
448 HANDLE hHandle,
449 DWORD dwMilliseconds)
450{
K.Takata54119102022-02-03 13:33:03 +0000451 if (read_console_input(NULL, NULL, (DWORD)-2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200452 return WAIT_OBJECT_0;
453 return WaitForSingleObject(hHandle, dwMilliseconds);
454}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100455# endif
456#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200457
Bram Moolenaar071d4272004-06-13 20:20:40 +0000458 static void
459get_exe_name(void)
460{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100461 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
462 // as the maximum length that works (plus a NUL byte).
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100463#define MAX_ENV_PATH_LEN 8192
464 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200465 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000466
467 if (exe_name == NULL)
468 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100469 // store the name of the executable, may be used for $VIM
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100470 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000471 if (*temp != NUL)
472 exe_name = FullName_save((char_u *)temp, FALSE);
473 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000474
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200475 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000476 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200477 exe_path = vim_strnsave(exe_name, gettail_sep(exe_name) - exe_name);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200478 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000479 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100480 // Append our starting directory to $PATH, so that when doing
481 // "!xxd" it's found in our starting directory. Needed because
482 // SearchPath() also looks there.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200483 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100484 if (p == NULL
485 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200486 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100487 if (p == NULL || *p == NUL)
488 temp[0] = NUL;
489 else
490 {
491 STRCPY(temp, p);
492 STRCAT(temp, ";");
493 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200494 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100495 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200496 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000497 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000498 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000499}
500
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200501/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100502 * Unescape characters in "p" that appear in "escaped".
503 */
504 static void
505unescape_shellxquote(char_u *p, char_u *escaped)
506{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100507 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100508 int n;
509
510 while (*p != NUL)
511 {
512 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
513 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100514 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100515 p += n;
516 l -= n;
517 }
518}
519
520/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200521 * Load library "name".
522 */
523 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000524vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200525{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200526 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200527
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200528 // No need to load any library when registering OLE.
529 if (found_register_arg)
530 return dll;
531
Bram Moolenaar0f873732019-12-05 20:28:46 +0100532 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
533 // vimLoadLib() recursively, which causes a stack overflow.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200534 if (exe_path == NULL)
535 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200536 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200537 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200538 WCHAR old_dirw[MAXPATHL];
539
540 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
541 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100542 // Change directory to where the executable is, both to make
543 // sure we find a .dll there and to avoid looking for a .dll
544 // in the current directory.
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100545 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200546 dll = LoadLibrary(name);
547 SetCurrentDirectoryW(old_dirw);
548 return dll;
549 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200550 }
551 return dll;
552}
553
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200554#if defined(VIMDLL) || defined(PROTO)
555/*
556 * Check if the current executable file is for the GUI subsystem.
557 */
558 int
559mch_is_gui_executable(void)
560{
561 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
562 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
563 PIMAGE_NT_HEADERS pPE;
564
565 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
566 return FALSE;
567 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
568 if (pPE->Signature != IMAGE_NT_SIGNATURE)
569 return FALSE;
570 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
571 return TRUE;
572 return FALSE;
573}
574#endif
575
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000576#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
577 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100578/*
579 * Get related information about 'funcname' which is imported by 'hInst'.
580 * If 'info' is 0, return the function address.
581 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000582 * If 'info' is 2, hook the function with 'ptr', and return the original
583 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100584 */
585 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000586get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
587 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100588{
589 PBYTE pImage = (PBYTE)hInst;
590 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
591 PIMAGE_NT_HEADERS pPE;
592 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100593 PIMAGE_THUNK_DATA pIAT; // Import Address Table
594 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100595 PIMAGE_IMPORT_BY_NAME pImpName;
596
597 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
598 return NULL;
599 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
600 if (pPE->Signature != IMAGE_NT_SIGNATURE)
601 return NULL;
602 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
603 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
604 .VirtualAddress);
605 for (; pImpDesc->FirstThunk; ++pImpDesc)
606 {
607 if (!pImpDesc->OriginalFirstThunk)
608 continue;
609 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
610 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
611 for (; pIAT->u1.Function; ++pIAT, ++pINT)
612 {
613 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
614 continue;
615 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
616 + (UINT_PTR)(pINT->u1.AddressOfData));
617 if (strcmp((char *)pImpName->Name, funcname) == 0)
618 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000619 void *original;
620 DWORD old, new = PAGE_READWRITE;
621
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100622 switch (info)
623 {
624 case 0:
625 return (void *)pIAT->u1.Function;
626 case 1:
627 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000628 case 2:
629 original = (void *)pIAT->u1.Function;
630 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
631 new, &old);
632 pIAT->u1.Function = (UINT_PTR)ptr;
633 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
634 old, &new);
635 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100636 default:
637 return NULL;
638 }
639 }
640 }
641 }
642 return NULL;
643}
644
645/*
646 * Get the module handle which 'funcname' in 'hInst' is imported from.
647 */
648 HINSTANCE
649find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
650{
651 char *modulename;
652
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000653 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100654 if (modulename != NULL)
655 return GetModuleHandleA(modulename);
656 return NULL;
657}
658
659/*
660 * Get the address of 'funcname' which is imported by 'hInst' DLL.
661 */
662 void *
663get_dll_import_func(HINSTANCE hInst, const char *funcname)
664{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000665 return get_imported_func_info(hInst, funcname, 0, NULL);
666}
667
668/*
669 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
670 * and return the original function address.
671 */
672 void *
673hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
674{
675 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100676}
677#endif
678
Bram Moolenaar071d4272004-06-13 20:20:40 +0000679#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
680# ifndef GETTEXT_DLL
681# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200682# define GETTEXT_DLL_ALT1 "libintl-8.dll"
683# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000684# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100685// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000686static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200687static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000688static char *null_libintl_textdomain(const char *);
689static char *null_libintl_bindtextdomain(const char *, const char *);
690static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100691static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000692
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200693static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000694char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200695char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
696 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000697char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
698char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000699 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000700char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
701 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100702int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000703
704 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100705dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000706{
707 int i;
708 static struct
709 {
710 char *name;
711 FARPROC *ptr;
712 } libintl_entry[] =
713 {
714 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200715 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000716 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
717 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
718 {NULL, NULL}
719 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100720 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000721
Bram Moolenaar7554c542018-10-06 15:03:15 +0200722 // No need to initialize twice.
723 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000724 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200725 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100726 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100727# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100728 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200729 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100730# endif
731# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200732 if (!hLibintlDLL)
733 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100734# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100735 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000736 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200737 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000738 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200739 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000740 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200741 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000742 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200743 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000744 }
745 for (i = 0; libintl_entry[i].name != NULL
746 && libintl_entry[i].ptr != NULL; ++i)
747 {
K.Takata54119102022-02-03 13:33:03 +0000748 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000749 libintl_entry[i].name)) == NULL)
750 {
751 dyn_libintl_end();
752 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000753 {
754 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000755 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000756 verbose_leave();
757 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000758 return 0;
759 }
760 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000761
Bram Moolenaar0f873732019-12-05 20:28:46 +0100762 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000763 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000764 "bind_textdomain_codeset");
765 if (dyn_libintl_bind_textdomain_codeset == NULL)
766 dyn_libintl_bind_textdomain_codeset =
767 null_libintl_bind_textdomain_codeset;
768
Bram Moolenaar0f873732019-12-05 20:28:46 +0100769 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100770 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
771 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100772 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100773 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
774 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100775
Bram Moolenaar071d4272004-06-13 20:20:40 +0000776 return 1;
777}
778
779 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100780dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000781{
782 if (hLibintlDLL)
783 FreeLibrary(hLibintlDLL);
784 hLibintlDLL = NULL;
785 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200786 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000787 dyn_libintl_textdomain = null_libintl_textdomain;
788 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000789 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100790 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000791}
792
793 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000794null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000795{
796 return (char*)msgid;
797}
798
799 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200800null_libintl_ngettext(
801 const char *msgid,
802 const char *msgid_plural,
803 unsigned long n)
804{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200805 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200806}
807
Bram Moolenaaree695f72016-08-03 22:08:45 +0200808 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100809null_libintl_bindtextdomain(
810 const char *domainname UNUSED,
811 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000812{
813 return NULL;
814}
815
816 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100817null_libintl_bind_textdomain_codeset(
818 const char *domainname UNUSED,
819 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000820{
821 return NULL;
822}
823
824 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100825null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000826{
827 return NULL;
828}
829
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200830 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100831null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100832{
833 return 0;
834}
835
Bram Moolenaar0f873732019-12-05 20:28:46 +0100836#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000837
Bram Moolenaar0f873732019-12-05 20:28:46 +0100838// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000839
840#ifndef VER_PLATFORM_WIN32_WINDOWS
841# define VER_PLATFORM_WIN32_WINDOWS 1
842#endif
843
Bram Moolenaar071d4272004-06-13 20:20:40 +0000844#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100845# ifndef PROTO
846# include <aclapi.h>
847# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200848# ifndef PROTECTED_DACL_SECURITY_INFORMATION
849# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
850# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000851#endif
852
Bram Moolenaar27515922013-06-29 15:36:26 +0200853#ifdef HAVE_ACL
854/*
855 * Enables or disables the specified privilege.
856 */
857 static BOOL
858win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
859{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100860 BOOL bResult;
861 LUID luid;
862 HANDLE hToken;
863 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200864
865 if (!OpenProcessToken(GetCurrentProcess(),
866 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
867 return FALSE;
868
869 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
870 {
871 CloseHandle(hToken);
872 return FALSE;
873 }
874
Bram Moolenaar45500912014-07-09 20:51:07 +0200875 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200876 tokenPrivileges.Privileges[0].Luid = luid;
877 tokenPrivileges.Privileges[0].Attributes = bEnable ?
878 SE_PRIVILEGE_ENABLED : 0;
879
880 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
881 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
882
883 CloseHandle(hToken);
884
885 return bResult && GetLastError() == ERROR_SUCCESS;
886}
887#endif
888
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100889#ifdef _MSC_VER
890// Suppress the deprecation warning for using GetVersionEx().
891// It is needed for implementing "windowsversion()".
892# pragma warning(push)
893# pragma warning(disable: 4996)
894#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000895/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200896 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000897 */
898 void
899PlatformId(void)
900{
901 static int done = FALSE;
902
903 if (!done)
904 {
905 OSVERSIONINFO ovi;
906
907 ovi.dwOSVersionInfoSize = sizeof(ovi);
908 GetVersionEx(&ovi);
909
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200910#ifdef FEAT_EVAL
Bram Moolenaar0c1e3742019-12-27 13:49:24 +0100911 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
912 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200913#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100914 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
915 || ovi.dwMajorVersion > 6)
916 win8_or_later = TRUE;
917
Bram Moolenaar071d4272004-06-13 20:20:40 +0000918#ifdef HAVE_ACL
Bram Moolenaar0f873732019-12-05 20:28:46 +0100919 // Enable privilege for getting or setting SACLs.
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200920 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000921#endif
922 done = TRUE;
923 }
924}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100925#ifdef _MSC_VER
926# pragma warning(pop)
927#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000928
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200929#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000930
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100931# define SHIFT (SHIFT_PRESSED)
932# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
933# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
934# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000935
936
Bram Moolenaar0f873732019-12-05 20:28:46 +0100937// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
938// We map function keys to their ANSI terminal equivalents, as produced
939// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
940// ANSI key with a value >= '\300' is nonstandard, but provided anyway
941// so that the user can have access to all SHIFT-, CTRL-, and ALT-
942// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000943
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000944static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000945{
946 WORD wVirtKey;
947 BOOL fAnsiKey;
948 int chAlone;
949 int chShift;
950 int chCtrl;
951 int chAlt;
952} VirtKeyMap[] =
953{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200954// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000955 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
956
957 { VK_F1, TRUE, ';', 'T', '^', 'h', },
958 { VK_F2, TRUE, '<', 'U', '_', 'i', },
959 { VK_F3, TRUE, '=', 'V', '`', 'j', },
960 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
961 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
962 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
963 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
964 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
965 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
966 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200967 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
968 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000969
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200970 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
971 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
972 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
973 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
974 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
975 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
976 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
977 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
978 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
979 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100980 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000981
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200982 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000983
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100984# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200985 // Most people don't have F13-F20, but what the hell...
986 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
987 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
988 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
989 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
990 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
991 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
992 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
993 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100994# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200995 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
996 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
997 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
998 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000999
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001000 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
1001 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
1002 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
1003 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
1004 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
1005 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
1006 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
1007 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
1008 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
1009 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001010 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001011};
1012
1013
Bram Moolenaar0f873732019-12-05 20:28:46 +01001014/*
1015 * The return code indicates key code size.
1016 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001017 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001018win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001019 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001020{
1021 UINT uMods = pker->dwControlKeyState;
1022 static int s_iIsDead = 0;
1023 static WORD awAnsiCode[2];
1024 static BYTE abKeystate[256];
1025
1026
1027 if (s_iIsDead == 2)
1028 {
K.Takata972db232022-02-04 10:45:38 +00001029 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001030 s_iIsDead = 0;
1031 return 1;
1032 }
1033
K.Takata972db232022-02-04 10:45:38 +00001034 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001035 return 1;
1036
Bram Moolenaara80faa82020-04-12 19:37:17 +02001037 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001038
Bram Moolenaar0f873732019-12-05 20:28:46 +01001039 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001040 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001041
1042 if (uMods & SHIFT_PRESSED)
1043 abKeystate[VK_SHIFT] = 0x80;
1044 if (uMods & CAPSLOCK_ON)
1045 abKeystate[VK_CAPITAL] = 1;
1046
1047 if ((uMods & ALT_GR) == ALT_GR)
1048 {
1049 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1050 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1051 }
1052
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001053 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1054 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001055
1056 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001057 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001058
1059 return s_iIsDead;
1060}
1061
Bram Moolenaar071d4272004-06-13 20:20:40 +00001062static BOOL g_fJustGotFocus = FALSE;
1063
1064/*
1065 * Decode a KEY_EVENT into one or two keystrokes
1066 */
1067 static BOOL
1068decode_key_event(
1069 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001070 WCHAR *pch,
1071 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001072 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001073 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001074{
1075 int i;
1076 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1077
1078 *pch = *pch2 = NUL;
1079 g_fJustGotFocus = FALSE;
1080
Bram Moolenaar0f873732019-12-05 20:28:46 +01001081 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001082 if (!pker->bKeyDown)
1083 return FALSE;
1084
Bram Moolenaar0f873732019-12-05 20:28:46 +01001085 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001086 switch (pker->wVirtualKeyCode)
1087 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001088 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001089 case VK_SHIFT:
1090 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001091 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001092 return FALSE;
1093
1094 default:
1095 break;
1096 }
1097
Bram Moolenaar0f873732019-12-05 20:28:46 +01001098 // special cases
K.Takata972db232022-02-04 10:45:38 +00001099 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0
1100 && pker->uChar.UnicodeChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001101 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001102 // Ctrl-6 is Ctrl-^
Bram Moolenaar071d4272004-06-13 20:20:40 +00001103 if (pker->wVirtualKeyCode == '6')
1104 {
1105 *pch = Ctrl_HAT;
1106 return TRUE;
1107 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001108 // Ctrl-2 is Ctrl-@
Bram Moolenaar071d4272004-06-13 20:20:40 +00001109 else if (pker->wVirtualKeyCode == '2')
1110 {
1111 *pch = NUL;
1112 return TRUE;
1113 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001114 // Ctrl-- is Ctrl-_
Bram Moolenaar071d4272004-06-13 20:20:40 +00001115 else if (pker->wVirtualKeyCode == 0xBD)
1116 {
1117 *pch = Ctrl__;
1118 return TRUE;
1119 }
1120 }
1121
Bram Moolenaar0f873732019-12-05 20:28:46 +01001122 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001123 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1124 {
1125 *pch = K_NUL;
1126 *pch2 = '\017';
1127 return TRUE;
1128 }
1129
K.Takataeeec2542021-06-02 13:28:16 +02001130 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001131 {
1132 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1133 {
1134 if (nModifs == 0)
1135 *pch = VirtKeyMap[i].chAlone;
1136 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1137 *pch = VirtKeyMap[i].chShift;
1138 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1139 *pch = VirtKeyMap[i].chCtrl;
1140 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1141 *pch = VirtKeyMap[i].chAlt;
1142
1143 if (*pch != 0)
1144 {
1145 if (VirtKeyMap[i].fAnsiKey)
1146 {
1147 *pch2 = *pch;
1148 *pch = K_NUL;
1149 }
1150
1151 return TRUE;
1152 }
1153 }
1154 }
1155
1156 i = win32_kbd_patch_key(pker);
1157
1158 if (i < 0)
1159 *pch = NUL;
1160 else
1161 {
K.Takata972db232022-02-04 10:45:38 +00001162 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001163
1164 if (pmodifiers != NULL)
1165 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001166 // Pass on the ALT key as a modifier, but only when not combined
1167 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001168 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1169 *pmodifiers |= MOD_MASK_ALT;
1170
Bram Moolenaar0f873732019-12-05 20:28:46 +01001171 // Pass on SHIFT only for special keys, because we don't know when
1172 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001173 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1174 *pmodifiers |= MOD_MASK_SHIFT;
1175
Bram Moolenaar0f873732019-12-05 20:28:46 +01001176 // Pass on CTRL only for non-special keys, because we don't know
1177 // when it's already included with the character. And not when
1178 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001179 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1180 && *pch >= 0x20 && *pch < 0x80)
1181 *pmodifiers |= MOD_MASK_CTRL;
1182 }
1183 }
1184
1185 return (*pch != NUL);
1186}
1187
Bram Moolenaar0f873732019-12-05 20:28:46 +01001188#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001189
1190
Bram Moolenaar071d4272004-06-13 20:20:40 +00001191/*
1192 * For the GUI the mouse handling is in gui_w32.c.
1193 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001194#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001195 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001196mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001197{
1198}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001199#else
Bram Moolenaar0f873732019-12-05 20:28:46 +01001200static int g_fMouseAvail = FALSE; // mouse present
1201static int g_fMouseActive = FALSE; // mouse enabled
1202static int g_nMouseClick = -1; // mouse status
1203static int g_xMouse; // mouse x coordinate
1204static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001205static DWORD g_cmodein = 0; // Original console input mode
1206static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001207
1208/*
1209 * Enable or disable mouse input
1210 */
1211 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001212mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001213{
1214 DWORD cmodein;
1215
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001216# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001217 if (gui.in_use)
1218 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001219# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001220 if (!g_fMouseAvail)
1221 return;
1222
1223 g_fMouseActive = on;
1224 GetConsoleMode(g_hConIn, &cmodein);
1225
1226 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001227 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001228 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001229 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1230 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001231 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001232 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001233 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001234 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1235 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001236
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001237 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001238}
1239
Bram Moolenaar157d8132018-03-06 17:09:20 +01001240
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001241# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001242/*
1243 * Called when 'balloonevalterm' changed.
1244 */
1245 void
1246mch_bevalterm_changed(void)
1247{
1248 mch_setmouse(g_fMouseActive);
1249}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001250# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001251
Bram Moolenaar071d4272004-06-13 20:20:40 +00001252/*
1253 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1254 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1255 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1256 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1257 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1258 * and we return the mouse position in g_xMouse and g_yMouse.
1259 *
1260 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1261 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1262 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1263 *
1264 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1265 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1266 *
1267 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1268 * moves, even if it stays within the same character cell. We ignore
1269 * all MOUSE_MOVED messages if the position hasn't really changed, and
1270 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1271 * we're only interested in MOUSE_DRAG).
1272 *
1273 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1274 * 2-button mouses by pressing the left & right buttons simultaneously.
1275 * In practice, it's almost impossible to click both at the same time,
1276 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1277 * in such cases, if the user is clicking quickly.
1278 */
1279 static BOOL
1280decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001281 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001282{
1283 static int s_nOldButton = -1;
1284 static int s_nOldMouseClick = -1;
1285 static int s_xOldMouse = -1;
1286 static int s_yOldMouse = -1;
1287 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001288# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001289 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001290# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001291 static int s_cClicks = 1;
1292 static BOOL s_fReleased = TRUE;
1293 static DWORD s_dwLastClickTime = 0;
1294 static BOOL s_fNextIsMiddle = FALSE;
1295
Bram Moolenaar0f873732019-12-05 20:28:46 +01001296 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001297
1298 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1299 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1300 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1301 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1302
1303 int nButton;
1304
1305 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1306 cButtons = 2;
1307
1308 if (!g_fMouseAvail || !g_fMouseActive)
1309 {
1310 g_nMouseClick = -1;
1311 return FALSE;
1312 }
1313
Bram Moolenaar0f873732019-12-05 20:28:46 +01001314 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001315 if (g_fJustGotFocus)
1316 {
1317 g_fJustGotFocus = FALSE;
1318 return FALSE;
1319 }
1320
Bram Moolenaar0f873732019-12-05 20:28:46 +01001321 // unprocessed mouse click?
Bram Moolenaar071d4272004-06-13 20:20:40 +00001322 if (g_nMouseClick != -1)
1323 return TRUE;
1324
1325 nButton = -1;
1326 g_xMouse = pmer->dwMousePosition.X;
1327 g_yMouse = pmer->dwMousePosition.Y;
1328
1329 if (pmer->dwEventFlags == MOUSE_MOVED)
1330 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001331 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1332 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001333 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1334 return FALSE;
1335 }
1336
Bram Moolenaar0f873732019-12-05 20:28:46 +01001337 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001338 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1339 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001340 nButton = MOUSE_RELEASE;
1341
Bram Moolenaar0f873732019-12-05 20:28:46 +01001342 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001343 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001344 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001345# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001346 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001347 if (p_bevalterm)
1348 nButton = MOUSE_DRAG;
1349 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001350# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001351 return FALSE;
1352 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001353
Bram Moolenaar071d4272004-06-13 20:20:40 +00001354 s_fReleased = TRUE;
1355 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001356 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001357 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001358 // on a 2-button mouse, hold down left and right buttons
1359 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001360
1361 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1362 {
1363 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1364
Bram Moolenaar0f873732019-12-05 20:28:46 +01001365 // if either left or right button only is pressed, see if the
1366 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001367 if (dwLR == LEFT || dwLR == RIGHT)
1368 {
1369 for (;;)
1370 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001371 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001372 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1373 != WAIT_OBJECT_0)
1374 break;
1375 else
1376 {
1377 DWORD cRecords = 0;
1378 INPUT_RECORD ir;
1379 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1380
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001381 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001382
1383 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1384 || !(pmer2->dwButtonState & LEFT_RIGHT))
1385 break;
1386 else
1387 {
1388 if (pmer2->dwEventFlags != MOUSE_MOVED)
1389 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001390 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001391
1392 return decode_mouse_event(pmer2);
1393 }
1394 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1395 s_yOldMouse == pmer2->dwMousePosition.Y)
1396 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001397 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001398 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001399
Bram Moolenaar0f873732019-12-05 20:28:46 +01001400 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001401 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001402
1403 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1404 break;
1405 }
1406 else
1407 break;
1408 }
1409 }
1410 }
1411 }
1412 }
1413
1414 if (s_fNextIsMiddle)
1415 {
1416 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1417 ? MOUSE_DRAG : MOUSE_MIDDLE;
1418 s_fNextIsMiddle = FALSE;
1419 }
1420 else if (cButtons == 2 &&
1421 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1422 {
1423 nButton = MOUSE_MIDDLE;
1424
1425 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1426 {
1427 s_fNextIsMiddle = TRUE;
1428 nButton = MOUSE_RELEASE;
1429 }
1430 }
1431 else if ((pmer->dwButtonState & LEFT) == LEFT)
1432 nButton = MOUSE_LEFT;
1433 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1434 nButton = MOUSE_MIDDLE;
1435 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1436 nButton = MOUSE_RIGHT;
1437
1438 if (! s_fReleased && ! s_fNextIsMiddle
1439 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1440 return FALSE;
1441
1442 s_fReleased = s_fNextIsMiddle;
1443 }
1444
1445 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1446 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001447 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001448 if (nButton != -1 && nButton != MOUSE_RELEASE)
1449 {
1450 DWORD dwCurrentTime = GetTickCount();
1451
1452 if (s_xOldMouse != g_xMouse
1453 || s_yOldMouse != g_yMouse
1454 || s_nOldButton != nButton
1455 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001456# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001457 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001458# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001459 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1460 {
1461 s_cClicks = 1;
1462 }
1463 else if (++s_cClicks > 4)
1464 {
1465 s_cClicks = 1;
1466 }
1467
1468 s_dwLastClickTime = dwCurrentTime;
1469 }
1470 }
1471 else if (pmer->dwEventFlags == MOUSE_MOVED)
1472 {
1473 if (nButton != -1 && nButton != MOUSE_RELEASE)
1474 nButton = MOUSE_DRAG;
1475
1476 s_cClicks = 1;
1477 }
1478
1479 if (nButton == -1)
1480 return FALSE;
1481
1482 if (nButton != MOUSE_RELEASE)
1483 s_nOldButton = nButton;
1484
1485 g_nMouseClick = nButton;
1486
1487 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1488 g_nMouseClick |= MOUSE_SHIFT;
1489 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1490 g_nMouseClick |= MOUSE_CTRL;
1491 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1492 g_nMouseClick |= MOUSE_ALT;
1493
1494 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1495 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1496
Bram Moolenaar0f873732019-12-05 20:28:46 +01001497 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001498 if (s_xOldMouse == g_xMouse
1499 && s_yOldMouse == g_yMouse
1500 && s_nOldMouseClick == g_nMouseClick)
1501 {
1502 g_nMouseClick = -1;
1503 return FALSE;
1504 }
1505
1506 s_xOldMouse = g_xMouse;
1507 s_yOldMouse = g_yMouse;
1508 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001509# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001510 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001511# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001512 s_nOldMouseClick = g_nMouseClick;
1513
1514 return TRUE;
1515}
1516
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001517#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001518
1519
1520#ifdef MCH_CURSOR_SHAPE
1521/*
1522 * Set the shape of the cursor.
1523 * 'thickness' can be from 1 (thin) to 99 (block)
1524 */
1525 static void
1526mch_set_cursor_shape(int thickness)
1527{
1528 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1529 ConsoleCursorInfo.dwSize = thickness;
1530 ConsoleCursorInfo.bVisible = s_cursor_visible;
1531
1532 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1533 if (s_cursor_visible)
1534 SetConsoleCursorPosition(g_hConOut, g_coord);
1535}
1536
1537 void
1538mch_update_cursor(void)
1539{
1540 int idx;
1541 int thickness;
1542
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001543# ifdef VIMDLL
1544 if (gui.in_use)
1545 return;
1546# endif
1547
Bram Moolenaar071d4272004-06-13 20:20:40 +00001548 /*
1549 * How the cursor is drawn depends on the current mode.
1550 */
1551 idx = get_shape_idx(FALSE);
1552
1553 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001554 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00001555 else
1556 thickness = shape_table[idx].percentage;
1557 mch_set_cursor_shape(thickness);
1558}
1559#endif
1560
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001561#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001562/*
1563 * Handle FOCUS_EVENT.
1564 */
1565 static void
1566handle_focus_event(INPUT_RECORD ir)
1567{
1568 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1569 ui_focus_change((int)g_fJustGotFocus);
1570}
1571
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001572static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1573
Bram Moolenaar071d4272004-06-13 20:20:40 +00001574/*
1575 * Wait until console input from keyboard or mouse is available,
1576 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001577 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001578 * Return TRUE if something is available FALSE if not.
1579 */
1580 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001581WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001582{
1583 DWORD dwNow = 0, dwEndTime = 0;
1584 INPUT_RECORD ir;
1585 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001586 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001587# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001588 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001589# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001590
1591 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001592 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001593 dwEndTime = GetTickCount() + msec;
1594 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001595 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001596 dwEndTime = INFINITE;
1597
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001598 // We need to loop until the end of the time period, because
1599 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001600 for (;;)
1601 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001602 // Only process messages when waiting.
1603 if (msec != 0)
1604 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001605# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001606 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001607# endif
1608# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001609 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001610# endif
1611# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001612 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001613# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001614 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001615
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001616 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001617# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001618 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001619# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001620 )
1621 return TRUE;
1622
1623 if (msec > 0)
1624 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001625 // If the specified wait time has passed, return. Beware that
1626 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001627 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001628 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001629 break;
1630 }
1631 if (msec != 0)
1632 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001633 DWORD dwWaitTime = dwEndTime - dwNow;
1634
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001635 // Don't wait for more than 11 msec to avoid dropping characters,
1636 // check channel while waiting for input and handle a callback from
1637 // 'balloonexpr'.
1638 if (dwWaitTime > 11)
1639 dwWaitTime = 11;
1640
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001641# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001642 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001643 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001644# endif
1645# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001646 // When waiting very briefly don't trigger timers.
1647 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001648 {
1649 long due_time;
1650
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001651 // Trigger timers and then get the time in msec until the next
1652 // one is due. Wait up to that time.
1653 due_time = check_due_timer();
1654 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001655 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001656 // timer may have used feedkeys().
1657 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001658 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001659 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1660 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001661 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001662# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001663 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001664# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001665 // Wait for either an event on the console input or a
1666 // message in the client-server window.
1667 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1668 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001669# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001670 wait_for_single_object(g_hConIn, dwWaitTime)
1671 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001672# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001673 )
1674 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001675 }
1676
1677 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001678 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001679
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001680# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02001681 // May have to redraw if the cursor ends up in the wrong place.
1682 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01001683 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001684 {
1685 CONSOLE_SCREEN_BUFFER_INFO csbi;
1686
1687 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1688 {
1689 if (csbi.dwCursorPosition.Y != msg_row)
1690 {
matveyte08795e2021-05-07 15:00:17 +02001691 // The screen is now messed up, must redraw the command
1692 // line and later all the windows.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001693 redraw_all_later(CLEAR);
matveyte08795e2021-05-07 15:00:17 +02001694 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001695 redrawcmd();
1696 }
1697 }
1698 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001699# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001700
1701 if (cRecords > 0)
1702 {
1703 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1704 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001705# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01001706 // Windows IME sends two '\n's with only one 'ENTER'. First:
1707 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00001708 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001709 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1710 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001711 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001712 continue;
1713 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001714# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001715 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1716 NULL, FALSE))
1717 return TRUE;
1718 }
1719
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001720 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001721
1722 if (ir.EventType == FOCUS_EVENT)
1723 handle_focus_event(ir);
1724 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001725 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001726 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1727
Bram Moolenaar36698e32019-12-11 22:57:40 +01001728 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001729 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001730 if (dwSize.X != Columns || dwSize.Y != Rows)
1731 {
1732 CONSOLE_SCREEN_BUFFER_INFO csbi;
1733 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01001734 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001735 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01001736 if (dwSize.X != Columns || dwSize.Y != Rows)
1737 {
1738 ResizeConBuf(g_hConOut, dwSize);
1739 shell_resized();
1740 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001741 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001742 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001743 else if (ir.EventType == MOUSE_EVENT
1744 && decode_mouse_event(&ir.Event.MouseEvent))
1745 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001746 }
1747 else if (msec == 0)
1748 break;
1749 }
1750
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001751# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01001752 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001753 if (input_available())
1754 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001755# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001756
Bram Moolenaar071d4272004-06-13 20:20:40 +00001757 return FALSE;
1758}
1759
Bram Moolenaar071d4272004-06-13 20:20:40 +00001760/*
1761 * return non-zero if a character is available
1762 */
1763 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001764mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001765{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001766# ifdef VIMDLL
1767 if (gui.in_use)
1768 return TRUE;
1769# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001770 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001771}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001772
1773# if defined(FEAT_TERMINAL) || defined(PROTO)
1774/*
1775 * Check for any pending input or messages.
1776 */
1777 int
1778mch_check_messages(void)
1779{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001780# ifdef VIMDLL
1781 if (gui.in_use)
1782 return TRUE;
1783# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001784 return WaitForChar(0L, TRUE);
1785}
1786# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001787
1788/*
1789 * Create the console input. Used when reading stdin doesn't work.
1790 */
1791 static void
1792create_conin(void)
1793{
1794 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1795 FILE_SHARE_READ|FILE_SHARE_WRITE,
1796 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001797 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001798 did_create_conin = TRUE;
1799}
1800
1801/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001802 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001803 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001804 static WCHAR
1805tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001806{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001807 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001808
1809 for (;;)
1810 {
1811 INPUT_RECORD ir;
1812 DWORD cRecords = 0;
1813
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001814# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001815 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001816 if (input_available())
1817 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001818 if (g_nMouseClick != -1)
1819 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001820# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001821 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001822 {
1823 if (did_create_conin)
1824 read_error_exit();
1825 create_conin();
1826 continue;
1827 }
1828
1829 if (ir.EventType == KEY_EVENT)
1830 {
1831 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1832 pmodifiers, TRUE))
1833 return ch;
1834 }
1835 else if (ir.EventType == FOCUS_EVENT)
1836 handle_focus_event(ir);
1837 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1838 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001839 else if (ir.EventType == MOUSE_EVENT)
1840 {
1841 if (decode_mouse_event(&ir.Event.MouseEvent))
1842 return 0;
1843 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001844 }
1845}
Bram Moolenaar0f873732019-12-05 20:28:46 +01001846#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001847
1848
1849/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001850 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001851 * Get one or more characters from the keyboard or the mouse.
1852 * If time == 0, do not wait for characters.
1853 * If time == n, wait a short time for characters.
1854 * If time == -1, wait forever for characters.
1855 * Returns the number of characters read into buf.
1856 */
1857 int
1858mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001859 char_u *buf UNUSED,
1860 int maxlen UNUSED,
1861 long time UNUSED,
1862 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001863{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001864#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001865
1866 int len;
1867 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001868# ifdef VIMDLL
1869// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
1870# define TYPEAHEADSPACE 6
1871# else
1872# define TYPEAHEADSPACE 0
1873# endif
1874# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001875 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001876 static int typeaheadlen = 0;
1877
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001878# ifdef VIMDLL
1879 if (gui.in_use)
1880 return 0;
1881# endif
1882
Bram Moolenaar0f873732019-12-05 20:28:46 +01001883 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001884 if (typeaheadlen > 0)
1885 goto theend;
1886
Bram Moolenaar071d4272004-06-13 20:20:40 +00001887 if (time >= 0)
1888 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001889 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00001890 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001891 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001892 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00001893 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001894 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00001895
Bram Moolenaar3918c952005-03-15 22:34:55 +00001896 /*
1897 * If there is no character available within 2 seconds (default)
1898 * write the autoscript file to disk. Or cause the CursorHold event
1899 * to be triggered.
1900 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001901 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001902 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001903 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001904 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001905 buf[0] = K_SPECIAL;
1906 buf[1] = KS_EXTRA;
1907 buf[2] = (int)KE_CURSORHOLD;
1908 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001909 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001910 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001911 }
1912 }
1913
1914 /*
1915 * Try to read as many characters as there are, until the buffer is full.
1916 */
1917
Bram Moolenaar0f873732019-12-05 20:28:46 +01001918 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001919 g_fCBrkPressed = FALSE;
1920
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001921# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001922 if (fdDump)
1923 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001924# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001925
Bram Moolenaar0f873732019-12-05 20:28:46 +01001926 // Keep looping until there is something in the typeahead buffer and more
1927 // to get and still room in the buffer (up to two bytes for a char and
1928 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001929 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001930 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001931 {
1932 if (typebuf_changed(tb_change_cnt))
1933 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001934 // "buf" may be invalid now if a client put something in the
1935 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001936 typeaheadlen = 0;
1937 break;
1938 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001939 if (g_nMouseClick != -1)
1940 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001941# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001942 if (fdDump)
1943 fprintf(fdDump, "{%02x @ %d, %d}",
1944 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001945# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001946 typeahead[typeaheadlen++] = ESC + 128;
1947 typeahead[typeaheadlen++] = 'M';
1948 typeahead[typeaheadlen++] = g_nMouseClick;
1949 typeahead[typeaheadlen++] = g_xMouse + '!';
1950 typeahead[typeaheadlen++] = g_yMouse + '!';
1951 g_nMouseClick = -1;
1952 }
1953 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001954 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001955 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001956 int modifiers = 0;
1957
1958 c = tgetch(&modifiers, &ch2);
1959
1960 if (typebuf_changed(tb_change_cnt))
1961 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001962 // "buf" may be invalid now if a client put something in the
1963 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001964 typeaheadlen = 0;
1965 break;
1966 }
1967
1968 if (c == Ctrl_C && ctrl_c_interrupts)
1969 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001970# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001971 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001972# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001973 got_int = TRUE;
1974 }
1975
Bram Moolenaar071d4272004-06-13 20:20:40 +00001976 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001977 {
1978 int n = 1;
1979
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001980 if (ch2 == NUL)
1981 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001982 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001983 char_u *p;
1984 WCHAR ch[2];
1985
1986 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01001987 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001988 {
1989 ch[1] = tgetch(&modifiers, &ch2);
1990 n++;
1991 }
1992 p = utf16_to_enc(ch, &n);
1993 if (p != NULL)
1994 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001995 for (i = 0, j = 0; i < n; i++)
1996 {
1997 typeahead[typeaheadlen + j++] = p[i];
1998# ifdef VIMDLL
1999 if (p[i] == CSI)
2000 {
2001 typeahead[typeaheadlen + j++] = KS_EXTRA;
2002 typeahead[typeaheadlen + j++] = KE_CSI;
2003 }
2004# endif
2005 }
2006 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002007 vim_free(p);
2008 }
2009 }
2010 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002011 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002012 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002013# ifdef VIMDLL
2014 if (c == CSI)
2015 {
2016 typeahead[typeaheadlen + 1] = KS_EXTRA;
2017 typeahead[typeaheadlen + 2] = KE_CSI;
2018 n = 3;
2019 }
2020# endif
2021 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002022 if (ch2 != NUL)
2023 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002024 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002025 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002026 switch (ch2)
2027 {
2028 case (WCHAR)'\324': // SHIFT+Insert
2029 case (WCHAR)'\325': // CTRL+Insert
2030 case (WCHAR)'\327': // SHIFT+Delete
2031 case (WCHAR)'\330': // CTRL+Delete
2032 typeahead[typeaheadlen + n] = (char_u)ch2;
2033 n++;
2034 break;
2035
2036 default:
2037 typeahead[typeaheadlen + n] = 3;
2038 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2039 n += 2;
2040 break;
2041 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002042 }
2043 else
2044 {
2045 typeahead[typeaheadlen + n] = 3;
2046 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2047 n += 2;
2048 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002049 }
2050
Bram Moolenaar0f873732019-12-05 20:28:46 +01002051 // Use the ALT key to set the 8th bit of the character
2052 // when it's one byte, the 8th bit isn't set yet and not
2053 // using a double-byte encoding (would become a lead
2054 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002055 if ((modifiers & MOD_MASK_ALT)
2056 && n == 1
2057 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002058 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002059 )
2060 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002061 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2062 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002063 modifiers &= ~MOD_MASK_ALT;
2064 }
2065
2066 if (modifiers != 0)
2067 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002068 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002069 mch_memmove(typeahead + typeaheadlen + 3,
2070 typeahead + typeaheadlen, n);
2071 typeahead[typeaheadlen++] = K_SPECIAL;
2072 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2073 typeahead[typeaheadlen++] = modifiers;
2074 }
2075
2076 typeaheadlen += n;
2077
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002078# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002079 if (fdDump)
2080 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002081# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002082 }
2083 }
2084 }
2085
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002086# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002087 if (fdDump)
2088 {
2089 fputs("]\n", fdDump);
2090 fflush(fdDump);
2091 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002092# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002093
Bram Moolenaar071d4272004-06-13 20:20:40 +00002094theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002095 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002096 len = 0;
2097 while (len < maxlen && typeaheadlen > 0)
2098 {
2099 buf[len++] = typeahead[0];
2100 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2101 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002102# ifdef FEAT_JOB_CHANNEL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002103 if (len > 0)
2104 {
2105 buf[len] = NUL;
2106 ch_log(NULL, "raw key input: \"%s\"", buf);
2107 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002108# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002109 return len;
2110
Bram Moolenaar0f873732019-12-05 20:28:46 +01002111#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002112 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002113#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002114}
2115
Bram Moolenaar82881492012-11-20 16:53:39 +01002116#ifndef PROTO
2117# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002118# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002119# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002120#endif
2121
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002122/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002123 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002124 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2125 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002126 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002127 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002128 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002129executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002130{
LemonBoy40fd7e62022-05-05 20:18:16 +01002131 int attrs = win32_getattrs((char_u *)name);
2132
2133 // The file doesn't exist or is a folder.
2134 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2135 return FALSE;
2136 // Check if the file is an AppExecLink, a special alias used by Windows
2137 // Store for its apps.
2138 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002139 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002140 char_u *res = resolve_appexeclink((char_u *)name);
2141 if (res == NULL)
2142 return FALSE;
2143 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002144 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002145 *path = res;
2146 else
2147 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002148 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002149 else if (path != NULL)
2150 *path = FullName_save((char_u *)name, FALSE);
2151 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002152}
2153
2154/*
2155 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2156 * If "use_path" is FALSE: Return TRUE if "name" exists.
2157 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2158 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2159 * the allocated memory.
2160 */
2161 static int
2162executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2163{
2164 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2165 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2166 // UTF-8.
2167 char_u buf[_MAX_PATH * 3];
2168 size_t len = STRLEN(name);
2169 size_t tmplen;
2170 char_u *p, *e, *e2;
2171 char_u *pathbuf = NULL;
2172 char_u *pathext = NULL;
2173 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002174 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002175 int noext = FALSE;
2176 int retval = FALSE;
2177
2178 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002179 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002180
2181 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002182 shname = gettail(p_sh);
2183 if (strstr((char *)shname, "sh") != NULL &&
2184 !(strstr((char *)shname, "powershell") != NULL
2185 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002186 noext = TRUE;
2187
2188 if (use_pathext)
2189 {
2190 pathext = mch_getenv("PATHEXT");
2191 if (pathext == NULL)
2192 pathext = (char_u *)".com;.exe;.bat;.cmd";
2193
2194 if (noext == FALSE)
2195 {
2196 /*
2197 * Loop over all extensions in $PATHEXT.
2198 * Check "name" ends with extension.
2199 */
2200 p = pathext;
2201 while (*p)
2202 {
2203 if (p[0] == ';'
2204 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2205 {
2206 // Skip empty or single ".".
2207 ++p;
2208 continue;
2209 }
2210 e = vim_strchr(p, ';');
2211 if (e == NULL)
2212 e = p + STRLEN(p);
2213 tmplen = e - p;
2214
2215 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2216 {
2217 noext = TRUE;
2218 break;
2219 }
2220
2221 p = e;
2222 }
2223 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002224 }
2225
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002226 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002227 if (pathext == NULL)
2228 pathext = (char_u *)".";
2229 else if (noext == TRUE)
2230 {
2231 if (pathextbuf == NULL)
2232 pathextbuf = alloc(STRLEN(pathext) + 3);
2233 if (pathextbuf == NULL)
2234 {
2235 retval = FALSE;
2236 goto theend;
2237 }
2238 STRCPY(pathextbuf, ".;");
2239 STRCAT(pathextbuf, pathext);
2240 pathext = pathextbuf;
2241 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002242
Bram Moolenaar95da1362020-05-30 18:37:55 +02002243 // Use $PATH when "use_path" is TRUE and "name" is basename.
2244 if (use_path && gettail((char_u *)name) == (char_u *)name)
2245 {
2246 p = mch_getenv("PATH");
2247 if (p != NULL)
2248 {
2249 pathbuf = alloc(STRLEN(p) + 3);
2250 if (pathbuf == NULL)
2251 {
2252 retval = FALSE;
2253 goto theend;
2254 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002255
2256 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2257 STRCPY(pathbuf, ".;");
2258 else
2259 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002260 STRCAT(pathbuf, p);
2261 }
2262 }
2263
2264 /*
2265 * Walk through all entries in $PATH to check if "name" exists there and
2266 * is an executable file.
2267 */
2268 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2269 while (*p)
2270 {
2271 if (*p == ';') // Skip empty entry
2272 {
2273 ++p;
2274 continue;
2275 }
2276 e = vim_strchr(p, ';');
2277 if (e == NULL)
2278 e = p + STRLEN(p);
2279
2280 if (e - p + len + 2 > sizeof(buf))
2281 {
2282 retval = FALSE;
2283 goto theend;
2284 }
2285 // A single "." that means current dir.
2286 if (e - p == 1 && *p == '.')
2287 STRCPY(buf, name);
2288 else
2289 {
2290 vim_strncpy(buf, p, e - p);
2291 add_pathsep(buf);
2292 STRCAT(buf, name);
2293 }
2294 tmplen = STRLEN(buf);
2295
2296 /*
2297 * Loop over all extensions in $PATHEXT.
2298 * Check "name" with extension added.
2299 */
2300 p = pathext;
2301 while (*p)
2302 {
2303 if (*p == ';')
2304 {
2305 // Skip empty entry
2306 ++p;
2307 continue;
2308 }
2309 e2 = vim_strchr(p, (int)';');
2310 if (e2 == NULL)
2311 e2 = p + STRLEN(p);
2312
2313 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2314 {
2315 // Not a single "." that means no extension is added.
2316 if (e2 - p + tmplen + 1 > sizeof(buf))
2317 {
2318 retval = FALSE;
2319 goto theend;
2320 }
2321 vim_strncpy(buf + tmplen, p, e2 - p);
2322 }
2323 if (executable_file((char *)buf, path))
2324 {
2325 retval = TRUE;
2326 goto theend;
2327 }
2328
2329 p = e2;
2330 }
2331
2332 p = e;
2333 }
2334
2335theend:
2336 free(pathextbuf);
2337 free(pathbuf);
2338 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002339}
2340
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002341#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2342 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002343/*
2344 * Bad parameter handler.
2345 *
2346 * Certain MS CRT functions will intentionally crash when passed invalid
2347 * parameters to highlight possible security holes. Setting this function as
2348 * the bad parameter handler will prevent the crash.
2349 *
2350 * In debug builds the parameters contain CRT information that might help track
2351 * down the source of a problem, but in non-debug builds the arguments are all
2352 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2353 * worth allowing these to make debugging of issues easier.
2354 */
2355 static void
2356bad_param_handler(const wchar_t *expression,
2357 const wchar_t *function,
2358 const wchar_t *file,
2359 unsigned int line,
2360 uintptr_t pReserved)
2361{
2362}
2363
2364# define SET_INVALID_PARAM_HANDLER \
2365 ((void)_set_invalid_parameter_handler(bad_param_handler))
2366#else
2367# define SET_INVALID_PARAM_HANDLER
2368#endif
2369
Bram Moolenaar4f974752019-02-17 17:44:42 +01002370#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002371
2372/*
2373 * GUI version of mch_init().
2374 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002375 static void
2376mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002377{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002378# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002379 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002380# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002381
Bram Moolenaar0f873732019-12-05 20:28:46 +01002382 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002383 SET_INVALID_PARAM_HANDLER;
2384
Bram Moolenaar0f873732019-12-05 20:28:46 +01002385 // Let critical errors result in a failure, not in a dialog box. Required
2386 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002387 SetErrorMode(SEM_FAILCRITICALERRORS);
2388
Bram Moolenaar0f873732019-12-05 20:28:46 +01002389 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002390
Bram Moolenaar0f873732019-12-05 20:28:46 +01002391 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002392 Rows = 25;
2393 Columns = 80;
2394
Bram Moolenaar0f873732019-12-05 20:28:46 +01002395 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002396 {
2397 char_u vimrun_location[_MAX_PATH + 4];
2398
Bram Moolenaar0f873732019-12-05 20:28:46 +01002399 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002400 STRCPY(vimrun_location, exe_name);
2401 STRCPY(gettail(vimrun_location), "vimrun.exe");
2402 if (mch_getperm(vimrun_location) >= 0)
2403 {
2404 if (*skiptowhite(vimrun_location) != NUL)
2405 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002406 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002407 mch_memmove(vimrun_location + 1, vimrun_location,
2408 STRLEN(vimrun_location) + 1);
2409 *vimrun_location = '"';
2410 STRCPY(gettail(vimrun_location), "vimrun\" ");
2411 }
2412 else
2413 STRCPY(gettail(vimrun_location), "vimrun ");
2414
2415 vimrun_path = (char *)vim_strsave(vimrun_location);
2416 s_dont_use_vimrun = FALSE;
2417 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002418 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002419 s_dont_use_vimrun = FALSE;
2420
Bram Moolenaar0f873732019-12-05 20:28:46 +01002421 // Don't give the warning for a missing vimrun.exe right now, but only
2422 // when vimrun was supposed to be used. Don't bother people that do
2423 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002424 if (s_dont_use_vimrun)
2425 need_vimrun_warning = TRUE;
2426 }
2427
2428 /*
2429 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2430 * Otherwise the default "findstr /n" is used.
2431 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002432 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01002433 set_option_value_give_err((char_u *)"grepprg",
2434 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002435
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002436# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002437 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002438# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002439
2440 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002441}
2442
2443
Bram Moolenaar0f873732019-12-05 20:28:46 +01002444#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002445
2446#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002447
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002448# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2449# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002450
2451/*
2452 * ClearConsoleBuffer()
2453 * Description:
2454 * Clears the entire contents of the console screen buffer, using the
2455 * specified attribute.
2456 * Returns:
2457 * TRUE on success
2458 */
2459 static BOOL
2460ClearConsoleBuffer(WORD wAttribute)
2461{
2462 CONSOLE_SCREEN_BUFFER_INFO csbi;
2463 COORD coord;
2464 DWORD NumCells, dummy;
2465
2466 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2467 return FALSE;
2468
2469 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2470 coord.X = 0;
2471 coord.Y = 0;
2472 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2473 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002474 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002475 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2476 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002477 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002478
2479 return TRUE;
2480}
2481
2482/*
2483 * FitConsoleWindow()
2484 * Description:
2485 * Checks if the console window will fit within given buffer dimensions.
2486 * Also, if requested, will shrink the window to fit.
2487 * Returns:
2488 * TRUE on success
2489 */
2490 static BOOL
2491FitConsoleWindow(
2492 COORD dwBufferSize,
2493 BOOL WantAdjust)
2494{
2495 CONSOLE_SCREEN_BUFFER_INFO csbi;
2496 COORD dwWindowSize;
2497 BOOL NeedAdjust = FALSE;
2498
2499 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2500 {
2501 /*
2502 * A buffer resize will fail if the current console window does
2503 * not lie completely within that buffer. To avoid this, we might
2504 * have to move and possibly shrink the window.
2505 */
2506 if (csbi.srWindow.Right >= dwBufferSize.X)
2507 {
2508 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2509 if (dwWindowSize.X > dwBufferSize.X)
2510 dwWindowSize.X = dwBufferSize.X;
2511 csbi.srWindow.Right = dwBufferSize.X - 1;
2512 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2513 NeedAdjust = TRUE;
2514 }
2515 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2516 {
2517 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2518 if (dwWindowSize.Y > dwBufferSize.Y)
2519 dwWindowSize.Y = dwBufferSize.Y;
2520 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2521 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2522 NeedAdjust = TRUE;
2523 }
2524 if (NeedAdjust && WantAdjust)
2525 {
2526 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2527 return FALSE;
2528 }
2529 return TRUE;
2530 }
2531
2532 return FALSE;
2533}
2534
2535typedef struct ConsoleBufferStruct
2536{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002537 BOOL IsValid;
2538 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002539 PCHAR_INFO Buffer;
2540 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002541 PSMALL_RECT Regions;
2542 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002543} ConsoleBuffer;
2544
2545/*
2546 * SaveConsoleBuffer()
2547 * Description:
2548 * Saves important information about the console buffer, including the
2549 * actual buffer contents. The saved information is suitable for later
2550 * restoration by RestoreConsoleBuffer().
2551 * Returns:
2552 * TRUE if all information was saved; FALSE otherwise
2553 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2554 */
2555 static BOOL
2556SaveConsoleBuffer(
2557 ConsoleBuffer *cb)
2558{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002559 DWORD NumCells;
2560 COORD BufferCoord;
2561 SMALL_RECT ReadRegion;
2562 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002563 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002564
Bram Moolenaar071d4272004-06-13 20:20:40 +00002565 if (cb == NULL)
2566 return FALSE;
2567
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002568 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002569 {
2570 cb->IsValid = FALSE;
2571 return FALSE;
2572 }
2573 cb->IsValid = TRUE;
2574
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002575 /*
2576 * Allocate a buffer large enough to hold the entire console screen
2577 * buffer. If this ConsoleBuffer structure has already been initialized
2578 * with a buffer of the correct size, then just use that one.
2579 */
2580 if (!cb->IsValid || cb->Buffer == NULL ||
2581 cb->BufferSize.X != cb->Info.dwSize.X ||
2582 cb->BufferSize.Y != cb->Info.dwSize.Y)
2583 {
2584 cb->BufferSize.X = cb->Info.dwSize.X;
2585 cb->BufferSize.Y = cb->Info.dwSize.Y;
2586 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2587 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002588 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002589 if (cb->Buffer == NULL)
2590 return FALSE;
2591 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002592
2593 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002594 * We will now copy the console screen buffer into our buffer.
2595 * ReadConsoleOutput() seems to be limited as far as how much you
2596 * can read at a time. Empirically, this number seems to be about
2597 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2598 * in chunks until it is all copied. The chunks will all have the
2599 * same horizontal characteristics, so initialize them now. The
2600 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002601 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002602 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002603 ReadRegion.Left = 0;
2604 ReadRegion.Right = cb->Info.dwSize.X - 1;
2605 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002606
2607 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2608 if (cb->Regions == NULL || numregions != cb->NumRegions)
2609 {
2610 cb->NumRegions = numregions;
2611 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002612 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002613 if (cb->Regions == NULL)
2614 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002615 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002616 return FALSE;
2617 }
2618 }
2619
2620 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002621 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002622 /*
2623 * Read into position (0, Y) in our buffer.
2624 */
2625 BufferCoord.Y = Y;
2626 /*
2627 * Read the region whose top left corner is (0, Y) and whose bottom
2628 * right corner is (width - 1, Y + Y_incr - 1). This should define
2629 * a region of size width by Y_incr. Don't worry if this region is
2630 * too large for the remaining buffer; it will be cropped.
2631 */
2632 ReadRegion.Top = Y;
2633 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002634 if (!ReadConsoleOutputW(g_hConOut, // output handle
2635 cb->Buffer, // our buffer
2636 cb->BufferSize, // dimensions of our buffer
2637 BufferCoord, // offset in our buffer
2638 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002639 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002640 VIM_CLEAR(cb->Buffer);
2641 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002642 return FALSE;
2643 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002644 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002645 }
2646
2647 return TRUE;
2648}
2649
2650/*
2651 * RestoreConsoleBuffer()
2652 * Description:
2653 * Restores important information about the console buffer, including the
2654 * actual buffer contents, if desired. The information to restore is in
2655 * the same format used by SaveConsoleBuffer().
2656 * Returns:
2657 * TRUE on success
2658 */
2659 static BOOL
2660RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002661 ConsoleBuffer *cb,
2662 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002663{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002664 COORD BufferCoord;
2665 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002666 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002667
2668 if (cb == NULL || !cb->IsValid)
2669 return FALSE;
2670
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002671 /*
2672 * Before restoring the buffer contents, clear the current buffer, and
2673 * restore the cursor position and window information. Doing this now
2674 * prevents old buffer contents from "flashing" onto the screen.
2675 */
2676 if (RestoreScreen)
2677 ClearConsoleBuffer(cb->Info.wAttributes);
2678
2679 FitConsoleWindow(cb->Info.dwSize, TRUE);
2680 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2681 return FALSE;
2682 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2683 return FALSE;
2684
2685 if (!RestoreScreen)
2686 {
2687 /*
2688 * No need to restore the screen buffer contents, so we're done.
2689 */
2690 return TRUE;
2691 }
2692
2693 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2694 return FALSE;
2695 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2696 return FALSE;
2697
2698 /*
2699 * Restore the screen buffer contents.
2700 */
2701 if (cb->Buffer != NULL)
2702 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002703 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002704 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002705 BufferCoord.X = cb->Regions[i].Left;
2706 BufferCoord.Y = cb->Regions[i].Top;
2707 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01002708 if (!WriteConsoleOutputW(g_hConOut, // output handle
2709 cb->Buffer, // our buffer
2710 cb->BufferSize, // dimensions of our buffer
2711 BufferCoord, // offset in our buffer
2712 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02002713 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002714 }
2715 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002716
2717 return TRUE;
2718}
2719
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002720# define FEAT_RESTORE_ORIG_SCREEN
2721# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002722static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002723# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002724static ConsoleBuffer g_cbNonTermcap = { 0 };
2725static ConsoleBuffer g_cbTermcap = { 0 };
2726
Bram Moolenaar071d4272004-06-13 20:20:40 +00002727char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01002728HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00002729static HICON g_hOrigIconSmall = NULL;
2730static HICON g_hOrigIcon = NULL;
2731static HICON g_hVimIcon = NULL;
2732static BOOL g_fCanChangeIcon = FALSE;
2733
Bram Moolenaar071d4272004-06-13 20:20:40 +00002734/*
2735 * GetConsoleIcon()
2736 * Description:
2737 * Attempts to retrieve the small icon and/or the big icon currently in
2738 * use by a given window.
2739 * Returns:
2740 * TRUE on success
2741 */
2742 static BOOL
2743GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002744 HWND hWnd,
2745 HICON *phIconSmall,
2746 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002747{
2748 if (hWnd == NULL)
2749 return FALSE;
2750
2751 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002752 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2753 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002754 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002755 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2756 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002757 return TRUE;
2758}
2759
2760/*
2761 * SetConsoleIcon()
2762 * Description:
2763 * Attempts to change the small icon and/or the big icon currently in
2764 * use by a given window.
2765 * Returns:
2766 * TRUE on success
2767 */
2768 static BOOL
2769SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002770 HWND hWnd,
2771 HICON hIconSmall,
2772 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002773{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002774 if (hWnd == NULL)
2775 return FALSE;
2776
2777 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002778 SendMessage(hWnd, WM_SETICON,
2779 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002780 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002781 SendMessage(hWnd, WM_SETICON,
2782 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002783 return TRUE;
2784}
2785
2786/*
2787 * SaveConsoleTitleAndIcon()
2788 * Description:
2789 * Saves the current console window title in g_szOrigTitle, for later
2790 * restoration. Also, attempts to obtain a handle to the console window,
2791 * and use it to save the small and big icons currently in use by the
2792 * console window. This is not always possible on some versions of Windows;
2793 * nor is it possible when running Vim remotely using Telnet (since the
2794 * console window the user sees is owned by a remote process).
2795 */
2796 static void
2797SaveConsoleTitleAndIcon(void)
2798{
Bram Moolenaar0f873732019-12-05 20:28:46 +01002799 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002800 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2801 return;
2802
2803 /*
2804 * Obtain a handle to the console window using GetConsoleWindow() from
2805 * KERNEL32.DLL; we need to handle in order to change the window icon.
2806 * This function only exists on NT-based Windows, starting with Windows
2807 * 2000. On older operating systems, we can't change the window icon
2808 * anyway.
2809 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002810 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002811 if (g_hWnd == NULL)
2812 return;
2813
Bram Moolenaar0f873732019-12-05 20:28:46 +01002814 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002815 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2816 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2817 return;
2818
Bram Moolenaar0f873732019-12-05 20:28:46 +01002819 // Extract the first icon contained in the Vim executable.
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002820 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002821 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002822 if (g_hVimIcon != NULL)
2823 g_fCanChangeIcon = TRUE;
2824}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002825
2826static int g_fWindInitCalled = FALSE;
2827static int g_fTermcapMode = FALSE;
2828static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002829
2830/*
2831 * non-GUI version of mch_init().
2832 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002833 static void
2834mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002835{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002836# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002837 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002838# endif
2839# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002840 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002841# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002842
Bram Moolenaar0f873732019-12-05 20:28:46 +01002843 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002844 SET_INVALID_PARAM_HANDLER;
2845
Bram Moolenaar0f873732019-12-05 20:28:46 +01002846 // Let critical errors result in a failure, not in a dialog box. Required
2847 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002848 SetErrorMode(SEM_FAILCRITICALERRORS);
2849
Bram Moolenaar0f873732019-12-05 20:28:46 +01002850 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002851 out_flush();
2852
Bram Moolenaar0f873732019-12-05 20:28:46 +01002853 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00002854 if (read_cmd_fd == 0)
2855 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2856 else
2857 create_conin();
2858 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2859
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002860# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01002861 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002862 SaveConsoleBuffer(&g_cbOrig);
2863 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002864# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01002865 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002866 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2867 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002868# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002869 if (cterm_normal_fg_color == 0)
2870 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2871 if (cterm_normal_bg_color == 0)
2872 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2873
Bram Moolenaarbdace832019-03-02 10:13:42 +01002874 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002875 g_color_index_fg = g_attrDefault & 0xf;
2876 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2877
Bram Moolenaar0f873732019-12-05 20:28:46 +01002878 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00002879 update_tcap(g_attrCurrent);
2880
2881 GetConsoleCursorInfo(g_hConOut, &g_cci);
2882 GetConsoleMode(g_hConIn, &g_cmodein);
2883 GetConsoleMode(g_hConOut, &g_cmodeout);
2884
Bram Moolenaar071d4272004-06-13 20:20:40 +00002885 SaveConsoleTitleAndIcon();
2886 /*
2887 * Set both the small and big icons of the console window to Vim's icon.
2888 * Note that Vim presently only has one size of icon (32x32), but it
2889 * automatically gets scaled down to 16x16 when setting the small icon.
2890 */
2891 if (g_fCanChangeIcon)
2892 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002893
2894 ui_get_shellsize();
2895
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002896# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002897 fdDump = fopen("dump", "wt");
2898
2899 if (fdDump)
2900 {
2901 time_t t;
2902
2903 time(&t);
2904 fputs(ctime(&t), fdDump);
2905 fflush(fdDump);
2906 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002907# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002908
2909 g_fWindInitCalled = TRUE;
2910
Bram Moolenaar071d4272004-06-13 20:20:40 +00002911 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002912
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002913# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002914 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002915# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002916
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02002917 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002918 vtp_init();
Bram Moolenaar06b7b582020-05-30 17:49:25 +02002919 wt_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002920}
2921
2922/*
2923 * non-GUI version of mch_exit().
2924 * Shut down and exit with status `r'
2925 * Careful: mch_exit() may be called before mch_init()!
2926 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002927 static void
2928mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002929{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002930 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002931
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002932 vtp_exit();
2933
Bram Moolenaar955f1982017-02-05 15:10:51 +01002934 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002935 if (g_fWindInitCalled)
2936 settmode(TMODE_COOK);
2937
Bram Moolenaar0f873732019-12-05 20:28:46 +01002938 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00002939
2940 if (g_fWindInitCalled)
2941 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02002942 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002943 /*
2944 * Restore both the small and big icons of the console window to
2945 * what they were at startup. Don't do this when the window is
2946 * closed, Vim would hang here.
2947 */
2948 if (g_fCanChangeIcon && !g_fForceExit)
2949 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002950
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002951# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002952 if (fdDump)
2953 {
2954 time_t t;
2955
2956 time(&t);
2957 fputs(ctime(&t), fdDump);
2958 fclose(fdDump);
2959 }
2960 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002961# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002962 }
2963
2964 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02002965 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002966 SetConsoleMode(g_hConOut, g_cmodeout);
2967
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002968# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00002969 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002970# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002971
2972 exit(r);
2973}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002974#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002975
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002976 void
2977mch_init(void)
2978{
2979#ifdef VIMDLL
2980 if (gui.starting)
2981 mch_init_g();
2982 else
2983 mch_init_c();
2984#elif defined(FEAT_GUI_MSWIN)
2985 mch_init_g();
2986#else
2987 mch_init_c();
2988#endif
2989}
2990
2991 void
2992mch_exit(int r)
2993{
Bram Moolenaar173d8412020-04-19 14:02:26 +02002994#ifdef FEAT_NETBEANS_INTG
2995 netbeans_send_disconnect();
2996#endif
2997
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002998#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02002999 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003000 mch_exit_g(r);
3001 else
3002 mch_exit_c(r);
3003#elif defined(FEAT_GUI_MSWIN)
3004 mch_exit_g(r);
3005#else
3006 mch_exit_c(r);
3007#endif
3008}
3009
Bram Moolenaar071d4272004-06-13 20:20:40 +00003010/*
3011 * Do we have an interactive window?
3012 */
3013 int
3014mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003015 int argc UNUSED,
3016 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003017{
3018 get_exe_name();
3019
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003020#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003021 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003022#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003023# ifdef VIMDLL
3024 if (gui.in_use)
3025 return OK;
3026# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003027 if (isatty(1))
3028 return OK;
3029 return FAIL;
3030#endif
3031}
3032
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003033/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003034 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003035 * When "len" is > 0, also expand short to long filenames.
3036 */
3037 void
3038fname_case(
3039 char_u *name,
3040 int len)
3041{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003042 int flen;
3043 WCHAR *p;
3044 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003045
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003046 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003047 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048 return;
3049
3050 slash_adjust(name);
3051
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003052 p = enc_to_utf16(name, NULL);
3053 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003054 return;
3055
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003056 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003057 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003058 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003059
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003060 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003061 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003062 if (len > 0 || flen >= (int)STRLEN(q))
3063 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3064 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003065 }
3066 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003067 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003068}
3069
3070
3071/*
3072 * Insert user name in s[len].
3073 */
3074 int
3075mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003076 char_u *s,
3077 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003078{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003079 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003080 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003081
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003082 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003083 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003084 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003085
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003086 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003087 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003088 vim_strncpy(s, p, len - 1);
3089 vim_free(p);
3090 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003091 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003092 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003093 s[0] = NUL;
3094 return FAIL;
3095}
3096
3097
3098/*
3099 * Insert host name in s[len].
3100 */
3101 void
3102mch_get_host_name(
3103 char_u *s,
3104 int len)
3105{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003106 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003107 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003108
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003109 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003110 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003111 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003112
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003113 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003114 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003115 vim_strncpy(s, p, len - 1);
3116 vim_free(p);
3117 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003118 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003119 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003120}
3121
3122
3123/*
3124 * return process ID
3125 */
3126 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003127mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003128{
3129 return (long)GetCurrentProcessId();
3130}
3131
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003132/*
3133 * return TRUE if process "pid" is still running
3134 */
3135 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003136mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003137{
3138 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3139 DWORD status = 0;
3140 int ret = FALSE;
3141
3142 if (hProcess == NULL)
3143 return FALSE; // might not have access
3144 if (GetExitCodeProcess(hProcess, &status) )
3145 ret = status == STILL_ACTIVE;
3146 CloseHandle(hProcess);
3147 return ret;
3148}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003149
3150/*
3151 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3152 * Return OK for success, FAIL for failure.
3153 */
3154 int
3155mch_dirname(
3156 char_u *buf,
3157 int len)
3158{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003159 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003160
Bram Moolenaar071d4272004-06-13 20:20:40 +00003161 /*
3162 * Originally this was:
3163 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3164 * But the Win32s known bug list says that getcwd() doesn't work
3165 * so use the Win32 system call instead. <Negri>
3166 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003167 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003168 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003169 WCHAR wcbuf[_MAX_PATH + 1];
3170 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003171
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003172 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003173 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003174 p = utf16_to_enc(wcbuf, NULL);
3175 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003176 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003177 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003178 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003179 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003180 }
3181 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003182 if (p == NULL)
3183 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003184
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003185 if (p != NULL)
3186 {
3187 vim_strncpy(buf, p, len - 1);
3188 vim_free(p);
3189 return OK;
3190 }
3191 }
3192 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003193}
3194
3195/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003196 * Get file permissions for "name".
3197 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003198 */
3199 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003200mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003201{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003202 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003203 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003204
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003205 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003206 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003207}
3208
3209
3210/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003211 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003212 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003213 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003214 */
3215 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003216mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003217{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003218 long n;
3219 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003220
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003221 p = enc_to_utf16(name, NULL);
3222 if (p == NULL)
3223 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003224
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003225 n = _wchmod(p, perm);
3226 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003227 if (n == -1)
3228 return FAIL;
3229
3230 win32_set_archive(name);
3231
3232 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003233}
3234
3235/*
3236 * Set hidden flag for "name".
3237 */
3238 void
3239mch_hide(char_u *name)
3240{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003241 int attrs = win32_getattrs(name);
3242 if (attrs == -1)
3243 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003244
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003245 attrs |= FILE_ATTRIBUTE_HIDDEN;
3246 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003247}
3248
3249/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003250 * Return TRUE if file "name" exists and is hidden.
3251 */
3252 int
3253mch_ishidden(char_u *name)
3254{
3255 int f = win32_getattrs(name);
3256
3257 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003258 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003259
3260 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3261}
3262
3263/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003264 * return TRUE if "name" is a directory
3265 * return FALSE if "name" is not a directory or upon error
3266 */
3267 int
3268mch_isdir(char_u *name)
3269{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003270 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003271
3272 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003273 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003274
3275 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3276}
3277
3278/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003279 * return TRUE if "name" is a directory, NOT a symlink to a directory
3280 * return FALSE if "name" is not a directory
3281 * return FALSE for error
3282 */
3283 int
3284mch_isrealdir(char_u *name)
3285{
3286 return mch_isdir(name) && !mch_is_symbolic_link(name);
3287}
3288
3289/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003290 * Create directory "name".
3291 * Return 0 on success, -1 on error.
3292 */
3293 int
3294mch_mkdir(char_u *name)
3295{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003296 WCHAR *p;
3297 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003298
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003299 p = enc_to_utf16(name, NULL);
3300 if (p == NULL)
3301 return -1;
3302 retval = _wmkdir(p);
3303 vim_free(p);
3304 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003305}
3306
3307/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003308 * Delete directory "name".
3309 * Return 0 on success, -1 on error.
3310 */
3311 int
3312mch_rmdir(char_u *name)
3313{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003314 WCHAR *p;
3315 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003316
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003317 p = enc_to_utf16(name, NULL);
3318 if (p == NULL)
3319 return -1;
3320 retval = _wrmdir(p);
3321 vim_free(p);
3322 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003323}
3324
3325/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003326 * Return TRUE if file "fname" has more than one link.
3327 */
3328 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003329mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003330{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003331 BY_HANDLE_FILE_INFORMATION info;
3332
3333 return win32_fileinfo(fname, &info) == FILEINFO_OK
3334 && info.nNumberOfLinks > 1;
3335}
3336
3337/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003338 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003339 */
3340 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003341mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003342{
3343 HANDLE hFind;
3344 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003345 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003346 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003347 WIN32_FIND_DATAW findDataW;
3348
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003349 wn = enc_to_utf16(name, NULL);
3350 if (wn == NULL)
3351 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003352
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003353 hFind = FindFirstFileW(wn, &findDataW);
3354 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003355 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003356 {
3357 fileFlags = findDataW.dwFileAttributes;
3358 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003359 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003360 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003361
3362 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003363 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3364 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003365 res = TRUE;
3366
3367 return res;
3368}
3369
3370/*
3371 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3372 * link.
3373 */
3374 int
3375mch_is_linked(char_u *fname)
3376{
3377 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3378 return TRUE;
3379 return FALSE;
3380}
3381
3382/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003383 * Get the by-handle-file-information for "fname".
3384 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003385 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003386 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3387 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3388 */
3389 int
3390win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3391{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003392 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003393 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003394 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003395
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003396 wn = enc_to_utf16(fname, NULL);
3397 if (wn == NULL)
3398 return FILEINFO_ENC_FAIL;
3399
3400 hFile = CreateFileW(wn, // file name
3401 GENERIC_READ, // access mode
3402 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3403 NULL, // security descriptor
3404 OPEN_EXISTING, // creation disposition
3405 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3406 NULL); // handle to template file
3407 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003408
3409 if (hFile != INVALID_HANDLE_VALUE)
3410 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003411 if (GetFileInformationByHandle(hFile, info) != 0)
3412 res = FILEINFO_OK;
3413 else
3414 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003415 CloseHandle(hFile);
3416 }
3417
Bram Moolenaar03f48552006-02-28 23:52:23 +00003418 return res;
3419}
3420
3421/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003422 * get file attributes for `name'
3423 * -1 : error
3424 * else FILE_ATTRIBUTE_* defined in winnt.h
3425 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003426 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003427win32_getattrs(char_u *name)
3428{
3429 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003430 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003431
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003432 p = enc_to_utf16(name, NULL);
3433 if (p == NULL)
3434 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003435
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003436 attr = GetFileAttributesW(p);
3437 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003438
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003439 return attr;
3440}
3441
3442/*
3443 * set file attributes for `name' to `attrs'
3444 *
3445 * return -1 for failure, 0 otherwise
3446 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003447 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003448win32_setattrs(char_u *name, int attrs)
3449{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003450 int res;
3451 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003452
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003453 p = enc_to_utf16(name, NULL);
3454 if (p == NULL)
3455 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003456
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003457 res = SetFileAttributesW(p, attrs);
3458 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003459
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003460 return res ? 0 : -1;
3461}
3462
3463/*
3464 * Set archive flag for "name".
3465 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003466 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003467win32_set_archive(char_u *name)
3468{
3469 int attrs = win32_getattrs(name);
3470 if (attrs == -1)
3471 return -1;
3472
3473 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3474 return win32_setattrs(name, attrs);
3475}
3476
3477/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003478 * Return TRUE if file or directory "name" is writable (not readonly).
3479 * Strange semantics of Win32: a readonly directory is writable, but you can't
3480 * delete a file. Let's say this means it is writable.
3481 */
3482 int
3483mch_writable(char_u *name)
3484{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003485 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003486
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003487 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3488 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003489}
3490
Bram Moolenaar071d4272004-06-13 20:20:40 +00003491/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003492 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003493 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003494 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3495 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003496 */
3497 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003498mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003499{
Bram Moolenaar95da1362020-05-30 18:37:55 +02003500 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003501}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003502
3503/*
3504 * Check what "name" is:
3505 * NODE_NORMAL: file or directory (or doesn't exist)
3506 * NODE_WRITABLE: writable device, socket, fifo, etc.
3507 * NODE_OTHER: non-writable things
3508 */
3509 int
3510mch_nodetype(char_u *name)
3511{
3512 HANDLE hFile;
3513 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003514 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003515
Bram Moolenaar0f873732019-12-05 20:28:46 +01003516 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3517 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3518 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00003519 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3520 return NODE_WRITABLE;
3521
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003522 wn = enc_to_utf16(name, NULL);
3523 if (wn == NULL)
3524 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003525
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003526 hFile = CreateFileW(wn, // file name
3527 GENERIC_WRITE, // access mode
3528 0, // share mode
3529 NULL, // security descriptor
3530 OPEN_EXISTING, // creation disposition
3531 0, // file attributes
3532 NULL); // handle to template file
3533 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003534 if (hFile == INVALID_HANDLE_VALUE)
3535 return NODE_NORMAL;
3536
3537 type = GetFileType(hFile);
3538 CloseHandle(hFile);
3539 if (type == FILE_TYPE_CHAR)
3540 return NODE_WRITABLE;
3541 if (type == FILE_TYPE_DISK)
3542 return NODE_NORMAL;
3543 return NODE_OTHER;
3544}
3545
3546#ifdef HAVE_ACL
3547struct my_acl
3548{
3549 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3550 PSID pSidOwner;
3551 PSID pSidGroup;
3552 PACL pDacl;
3553 PACL pSacl;
3554};
3555#endif
3556
3557/*
3558 * Return a pointer to the ACL of file "fname" in allocated memory.
3559 * Return NULL if the ACL is not available for whatever reason.
3560 */
3561 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003562mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003563{
3564#ifndef HAVE_ACL
3565 return (vim_acl_T)NULL;
3566#else
3567 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003568 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003569
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003570 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003571 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003572 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003573 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003574
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003575 wn = enc_to_utf16(fname, NULL);
3576 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003577 {
3578 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003579 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003580 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003581
3582 // Try to retrieve the entire security descriptor.
3583 err = GetNamedSecurityInfoW(
3584 wn, // Abstract filename
3585 SE_FILE_OBJECT, // File Object
3586 OWNER_SECURITY_INFORMATION |
3587 GROUP_SECURITY_INFORMATION |
3588 DACL_SECURITY_INFORMATION |
3589 SACL_SECURITY_INFORMATION,
3590 &p->pSidOwner, // Ownership information.
3591 &p->pSidGroup, // Group membership.
3592 &p->pDacl, // Discretionary information.
3593 &p->pSacl, // For auditing purposes.
3594 &p->pSecurityDescriptor);
3595 if (err == ERROR_ACCESS_DENIED ||
3596 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003597 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003598 // Retrieve only DACL.
3599 (void)GetNamedSecurityInfoW(
3600 wn,
3601 SE_FILE_OBJECT,
3602 DACL_SECURITY_INFORMATION,
3603 NULL,
3604 NULL,
3605 &p->pDacl,
3606 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003607 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003608 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003609 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003610 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003611 mch_free_acl((vim_acl_T)p);
3612 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003613 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003614 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003615 }
3616
3617 return (vim_acl_T)p;
3618#endif
3619}
3620
Bram Moolenaar27515922013-06-29 15:36:26 +02003621#ifdef HAVE_ACL
3622/*
3623 * Check if "acl" contains inherited ACE.
3624 */
3625 static BOOL
3626is_acl_inherited(PACL acl)
3627{
3628 DWORD i;
3629 ACL_SIZE_INFORMATION acl_info;
3630 PACCESS_ALLOWED_ACE ace;
3631
3632 acl_info.AceCount = 0;
3633 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3634 for (i = 0; i < acl_info.AceCount; i++)
3635 {
3636 GetAce(acl, i, (LPVOID *)&ace);
3637 if (ace->Header.AceFlags & INHERITED_ACE)
3638 return TRUE;
3639 }
3640 return FALSE;
3641}
3642#endif
3643
Bram Moolenaar071d4272004-06-13 20:20:40 +00003644/*
3645 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3646 * Errors are ignored.
3647 * This must only be called with "acl" equal to what mch_get_acl() returned.
3648 */
3649 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003650mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003651{
3652#ifdef HAVE_ACL
3653 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003654 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003655 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003656
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003657 if (p == NULL)
3658 return;
3659
3660 wn = enc_to_utf16(fname, NULL);
3661 if (wn == NULL)
3662 return;
3663
3664 // Set security flags
3665 if (p->pSidOwner)
3666 sec_info |= OWNER_SECURITY_INFORMATION;
3667 if (p->pSidGroup)
3668 sec_info |= GROUP_SECURITY_INFORMATION;
3669 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003670 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003671 sec_info |= DACL_SECURITY_INFORMATION;
3672 // Do not inherit its parent's DACL.
3673 // If the DACL is inherited, Cygwin permissions would be changed.
3674 if (!is_acl_inherited(p->pDacl))
3675 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003676 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003677 if (p->pSacl)
3678 sec_info |= SACL_SECURITY_INFORMATION;
3679
3680 (void)SetNamedSecurityInfoW(
3681 wn, // Abstract filename
3682 SE_FILE_OBJECT, // File Object
3683 sec_info,
3684 p->pSidOwner, // Ownership information.
3685 p->pSidGroup, // Group membership.
3686 p->pDacl, // Discretionary information.
3687 p->pSacl // For auditing purposes.
3688 );
3689 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003690#endif
3691}
3692
3693 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003694mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003695{
3696#ifdef HAVE_ACL
3697 struct my_acl *p = (struct my_acl *)acl;
3698
3699 if (p != NULL)
3700 {
3701 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3702 vim_free(p);
3703 }
3704#endif
3705}
3706
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003707#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003708
3709/*
3710 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3711 */
3712 static BOOL WINAPI
3713handler_routine(
3714 DWORD dwCtrlType)
3715{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003716 INPUT_RECORD ir;
3717 DWORD out;
3718
Bram Moolenaar071d4272004-06-13 20:20:40 +00003719 switch (dwCtrlType)
3720 {
3721 case CTRL_C_EVENT:
3722 if (ctrl_c_interrupts)
3723 g_fCtrlCPressed = TRUE;
3724 return TRUE;
3725
3726 case CTRL_BREAK_EVENT:
3727 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003728 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003729 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02003730 ir.EventType = KEY_EVENT;
3731 ir.Event.KeyEvent.bKeyDown = TRUE;
3732 ir.Event.KeyEvent.wRepeatCount = 1;
3733 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3734 ir.Event.KeyEvent.wVirtualScanCode = 0;
3735 ir.Event.KeyEvent.dwControlKeyState = 0;
3736 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3737 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003738 return TRUE;
3739
Bram Moolenaar0f873732019-12-05 20:28:46 +01003740 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00003741 case CTRL_CLOSE_EVENT:
3742 case CTRL_LOGOFF_EVENT:
3743 case CTRL_SHUTDOWN_EVENT:
3744 windgoto((int)Rows - 1, 0);
3745 g_fForceExit = TRUE;
3746
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003747 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003748 (dwCtrlType == CTRL_CLOSE_EVENT
3749 ? _("close")
3750 : dwCtrlType == CTRL_LOGOFF_EVENT
3751 ? _("logoff")
3752 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003753# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00003754 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003755# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003756
Bram Moolenaar0f873732019-12-05 20:28:46 +01003757 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00003758
Bram Moolenaar0f873732019-12-05 20:28:46 +01003759 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00003760
3761 default:
3762 return FALSE;
3763 }
3764}
3765
3766
3767/*
3768 * set the tty in (raw) ? "raw" : "cooked" mode
3769 */
3770 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02003771mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003772{
3773 DWORD cmodein;
3774 DWORD cmodeout;
3775 BOOL bEnableHandler;
3776
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003777# ifdef VIMDLL
3778 if (gui.in_use)
3779 return;
3780# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003781 GetConsoleMode(g_hConIn, &cmodein);
3782 GetConsoleMode(g_hConOut, &cmodeout);
3783 if (tmode == TMODE_RAW)
3784 {
3785 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3786 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003787 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003788 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003789 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003790 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
3791 }
3792 else
3793 {
3794 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
3795 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003796 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003797# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01003798 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
3799 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003800 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003801# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003802 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003803# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003804 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003805 bEnableHandler = TRUE;
3806 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01003807 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00003808 {
3809 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3810 ENABLE_ECHO_INPUT);
3811 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3812 bEnableHandler = FALSE;
3813 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003814 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003815 SetConsoleMode(g_hConOut, cmodeout);
3816 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3817
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003818# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003819 if (fdDump)
3820 {
3821 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3822 tmode == TMODE_RAW ? "raw" :
3823 tmode == TMODE_COOK ? "cooked" : "normal",
3824 cmodein, cmodeout);
3825 fflush(fdDump);
3826 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003827# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003828}
3829
3830
3831/*
3832 * Get the size of the current window in `Rows' and `Columns'
3833 * Return OK when size could be determined, FAIL otherwise.
3834 */
3835 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003836mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003837{
3838 CONSOLE_SCREEN_BUFFER_INFO csbi;
3839
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003840# ifdef VIMDLL
3841 if (gui.in_use)
3842 return OK;
3843# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003844 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3845 {
3846 /*
3847 * For some reason, we are trying to get the screen dimensions
3848 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3849 * variables are really intended to mean the size of Vim screen
3850 * while in termcap mode.
3851 */
3852 Rows = g_cbTermcap.Info.dwSize.Y;
3853 Columns = g_cbTermcap.Info.dwSize.X;
3854 }
3855 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3856 {
3857 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3858 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3859 }
3860 else
3861 {
3862 Rows = 25;
3863 Columns = 80;
3864 }
3865 return OK;
3866}
3867
3868/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003869 * Resize console buffer to 'COORD'
3870 */
3871 static void
3872ResizeConBuf(
3873 HANDLE hConsole,
3874 COORD coordScreen)
3875{
3876 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3877 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003878# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003879 if (fdDump)
3880 {
3881 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3882 GetLastError());
3883 fflush(fdDump);
3884 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003885# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003886 }
3887}
3888
3889/*
3890 * Resize console window size to 'srWindowRect'
3891 */
3892 static void
3893ResizeWindow(
3894 HANDLE hConsole,
3895 SMALL_RECT srWindowRect)
3896{
3897 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
3898 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003899# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003900 if (fdDump)
3901 {
3902 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3903 GetLastError());
3904 fflush(fdDump);
3905 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003906# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003907 }
3908}
3909
3910/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003911 * Set a console window to `xSize' * `ySize'
3912 */
3913 static void
3914ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003915 HANDLE hConsole,
3916 int xSize,
3917 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003918{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003919 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
3920 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003921 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003922 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02003923 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003924
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003925# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003926 if (fdDump)
3927 {
3928 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3929 fflush(fdDump);
3930 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003931# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003932
Bram Moolenaar0f873732019-12-05 20:28:46 +01003933 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00003934 coordScreen = GetLargestConsoleWindowSize(hConsole);
3935
Bram Moolenaar0f873732019-12-05 20:28:46 +01003936 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00003937 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3938 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3939 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3940
3941 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3942 {
3943 int sx, sy;
3944
3945 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3946 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3947 if (sy < ySize || sx < xSize)
3948 {
3949 /*
3950 * Increasing number of lines/columns, do buffer first.
3951 * Use the maximal size in x and y direction.
3952 */
3953 if (sy < ySize)
3954 coordScreen.Y = ySize;
3955 else
3956 coordScreen.Y = sy;
3957 if (sx < xSize)
3958 coordScreen.X = xSize;
3959 else
3960 coordScreen.X = sx;
3961 SetConsoleScreenBufferSize(hConsole, coordScreen);
3962 }
3963 }
3964
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003965 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003966 coordScreen.X = xSize;
3967 coordScreen.Y = ySize;
3968
Bram Moolenaar2551c032018-08-23 22:38:31 +02003969 // In the new console call API, only the first time in reverse order
3970 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003971 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003972 ResizeWindow(hConsole, srWindowRect);
3973 ResizeConBuf(hConsole, coordScreen);
3974 }
3975 else
3976 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003977 // Workaround for a Windows 10 bug
3978 cursor.X = srWindowRect.Left;
3979 cursor.Y = srWindowRect.Top;
3980 SetConsoleCursorPosition(hConsole, cursor);
3981
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003982 ResizeConBuf(hConsole, coordScreen);
3983 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02003984 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003985 }
3986}
3987
3988
3989/*
3990 * Set the console window to `Rows' * `Columns'
3991 */
3992 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003993mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003994{
3995 COORD coordScreen;
3996
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003997# ifdef VIMDLL
3998 if (gui.in_use)
3999 return;
4000# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004001 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004002 if (suppress_winsize != 0)
4003 {
4004 suppress_winsize = 2;
4005 return;
4006 }
4007
4008 if (term_console)
4009 {
4010 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4011
Bram Moolenaar0f873732019-12-05 20:28:46 +01004012 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004013 if (Rows > coordScreen.Y)
4014 Rows = coordScreen.Y;
4015 if (Columns > coordScreen.X)
4016 Columns = coordScreen.X;
4017
4018 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4019 }
4020}
4021
4022/*
4023 * Rows and/or Columns has changed.
4024 */
4025 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004026mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004027{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004028# ifdef VIMDLL
4029 if (gui.in_use)
4030 return;
4031# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004032 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4033}
4034
4035
4036/*
4037 * Called when started up, to set the winsize that was delayed.
4038 */
4039 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004040mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004041{
4042 if (suppress_winsize == 2)
4043 {
4044 suppress_winsize = 0;
4045 mch_set_shellsize();
4046 shell_resized();
4047 }
4048 suppress_winsize = 0;
4049}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004050#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004051
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004052 static BOOL
4053vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004054 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004055 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004056 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004057 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004058 PROCESS_INFORMATION *pi,
4059 LPVOID *env,
4060 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004061{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004062 BOOL ret = FALSE;
4063 WCHAR *wcmd, *wcwd = NULL;
4064
4065 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4066 if (wcmd == NULL)
4067 return FALSE;
4068 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004069 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004070 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4071 if (wcwd == NULL)
4072 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004073 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004074
4075 ret = CreateProcessW(
4076 NULL, // Executable name
4077 wcmd, // Command to execute
4078 NULL, // Process security attributes
4079 NULL, // Thread security attributes
4080 inherit_handles, // Inherit handles
4081 flags, // Creation flags
4082 env, // Environment
4083 wcwd, // Current directory
4084 (LPSTARTUPINFOW)si, // Startup information
4085 pi); // Process information
4086theend:
4087 vim_free(wcmd);
4088 vim_free(wcwd);
4089 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004090}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004091
4092
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004093 static HINSTANCE
4094vim_shell_execute(
4095 char *cmd,
4096 INT n_show_cmd)
4097{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004098 HINSTANCE ret;
4099 WCHAR *wcmd;
4100
4101 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4102 if (wcmd == NULL)
4103 return (HINSTANCE) 0;
4104
4105 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4106 vim_free(wcmd);
4107 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004108}
4109
4110
Bram Moolenaar4f974752019-02-17 17:44:42 +01004111#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004112
4113/*
4114 * Specialised version of system() for Win32 GUI mode.
4115 * This version proceeds as follows:
4116 * 1. Create a console window for use by the subprocess
4117 * 2. Run the subprocess (it gets the allocated console by default)
4118 * 3. Wait for the subprocess to terminate and get its exit code
4119 * 4. Prompt the user to press a key to close the console window
4120 */
4121 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004122mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004123{
4124 STARTUPINFO si;
4125 PROCESS_INFORMATION pi;
4126 DWORD ret = 0;
4127 HWND hwnd = GetFocus();
4128
4129 si.cb = sizeof(si);
4130 si.lpReserved = NULL;
4131 si.lpDesktop = NULL;
4132 si.lpTitle = NULL;
4133 si.dwFlags = STARTF_USESHOWWINDOW;
4134 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004135 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004136 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004137 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004138 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004139 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004140 else
4141 si.wShowWindow = SW_SHOWNORMAL;
4142 si.cbReserved2 = 0;
4143 si.lpReserved2 = NULL;
4144
Bram Moolenaar0f873732019-12-05 20:28:46 +01004145 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004146 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004147 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4148 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004149
Bram Moolenaar0f873732019-12-05 20:28:46 +01004150 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004151 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004152# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004153 int delay = 1;
4154
Bram Moolenaar0f873732019-12-05 20:28:46 +01004155 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004156 for (;;)
4157 {
4158 MSG msg;
4159
K.Takatab7057bd2022-01-21 11:37:07 +00004160 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004161 {
4162 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004163 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004164 delay = 1;
4165 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004166 }
4167 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4168 break;
4169
Bram Moolenaar0f873732019-12-05 20:28:46 +01004170 // We start waiting for a very short time and then increase it, so
4171 // that we respond quickly when the process is quick, and don't
4172 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004173 if (delay < 50)
4174 delay += 10;
4175 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004176# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004177 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004178# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004179
Bram Moolenaar0f873732019-12-05 20:28:46 +01004180 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004181 GetExitCodeProcess(pi.hProcess, &ret);
4182 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004183
Bram Moolenaar0f873732019-12-05 20:28:46 +01004184 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004185 CloseHandle(pi.hThread);
4186 CloseHandle(pi.hProcess);
4187
Bram Moolenaar0f873732019-12-05 20:28:46 +01004188 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004189 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4190
4191 return ret;
4192}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004193
4194/*
4195 * Thread launched by the gui to send the current buffer data to the
4196 * process. This way avoid to hang up vim totally if the children
4197 * process take a long time to process the lines.
4198 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004199 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004200sub_process_writer(LPVOID param)
4201{
4202 HANDLE g_hChildStd_IN_Wr = param;
4203 linenr_T lnum = curbuf->b_op_start.lnum;
4204 DWORD len = 0;
4205 DWORD l;
4206 char_u *lp = ml_get(lnum);
4207 char_u *s;
4208 int written = 0;
4209
4210 for (;;)
4211 {
4212 l = (DWORD)STRLEN(lp + written);
4213 if (l == 0)
4214 len = 0;
4215 else if (lp[written] == NL)
4216 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004217 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004218 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4219 }
4220 else
4221 {
4222 s = vim_strchr(lp + written, NL);
4223 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4224 s == NULL ? l : (DWORD)(s - (lp + written)),
4225 &len, NULL);
4226 }
4227 if (len == (int)l)
4228 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004229 // Finished a line, add a NL, unless this line should not have
4230 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004231 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004232 || (!curbuf->b_p_bin
4233 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004234 || (lnum != curbuf->b_no_eol_lnum
4235 && (lnum != curbuf->b_ml.ml_line_count
4236 || curbuf->b_p_eol)))
4237 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004238 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4239 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004240 }
4241
4242 ++lnum;
4243 if (lnum > curbuf->b_op_end.lnum)
4244 break;
4245
4246 lp = ml_get(lnum);
4247 written = 0;
4248 }
4249 else if (len > 0)
4250 written += len;
4251 }
4252
Bram Moolenaar0f873732019-12-05 20:28:46 +01004253 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004254 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004255 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004256}
4257
4258
Bram Moolenaar0f873732019-12-05 20:28:46 +01004259# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004260
4261/*
4262 * This function read from the children's stdout and write the
4263 * data on screen or in the buffer accordingly.
4264 */
4265 static void
4266dump_pipe(int options,
4267 HANDLE g_hChildStd_OUT_Rd,
4268 garray_T *ga,
4269 char_u buffer[],
4270 DWORD *buffer_off)
4271{
4272 DWORD availableBytes = 0;
4273 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004274 int ret;
4275 DWORD len;
4276 DWORD toRead;
4277 int repeatCount;
4278
Bram Moolenaar0f873732019-12-05 20:28:46 +01004279 // we query the pipe to see if there is any data to read
4280 // to avoid to perform a blocking read
4281 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4282 NULL, // optional buffer
4283 0, // buffer size
4284 NULL, // number of read bytes
4285 &availableBytes, // available bytes total
4286 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004287
4288 repeatCount = 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004289 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004290 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004291 {
4292 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004293 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004294 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004295 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004296
Bram Moolenaar0f873732019-12-05 20:28:46 +01004297 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004298 if (len == 0)
4299 break;
4300
4301 availableBytes -= len;
4302
4303 if (options & SHELL_READ)
4304 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004305 // Do NUL -> NL translation, append NL separated
4306 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004307 for (i = 0; i < len; ++i)
4308 {
4309 if (buffer[i] == NL)
4310 append_ga_line(ga);
4311 else if (buffer[i] == NUL)
4312 ga_append(ga, NL);
4313 else
4314 ga_append(ga, buffer[i]);
4315 }
4316 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004317 else if (has_mbyte)
4318 {
4319 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004320 int c;
4321 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004322
4323 len += *buffer_off;
4324 buffer[len] = NUL;
4325
Bram Moolenaar0f873732019-12-05 20:28:46 +01004326 // Check if the last character in buffer[] is
4327 // incomplete, keep these bytes for the next
4328 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004329 for (p = buffer; p < buffer + len; p += l)
4330 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004331 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004332 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004333 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004334 else if (MB_BYTE2LEN(*p) != l)
4335 break;
4336 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004337 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004338 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004339 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004340 if (len >= 12)
4341 ++p;
4342 else
4343 {
4344 *buffer_off = len;
4345 return;
4346 }
4347 }
4348 c = *p;
4349 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004350 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004351 if (p < buffer + len)
4352 {
4353 *p = c;
4354 *buffer_off = (DWORD)((buffer + len) - p);
4355 mch_memmove(buffer, p, *buffer_off);
4356 return;
4357 }
4358 *buffer_off = 0;
4359 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004360 else
4361 {
4362 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004363 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004364 }
4365
4366 windgoto(msg_row, msg_col);
4367 cursor_on();
4368 out_flush();
4369 }
4370}
4371
4372/*
4373 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4374 * for communication and doesn't open any new window.
4375 */
4376 static int
4377mch_system_piped(char *cmd, int options)
4378{
4379 STARTUPINFO si;
4380 PROCESS_INFORMATION pi;
4381 DWORD ret = 0;
4382
4383 HANDLE g_hChildStd_IN_Rd = NULL;
4384 HANDLE g_hChildStd_IN_Wr = NULL;
4385 HANDLE g_hChildStd_OUT_Rd = NULL;
4386 HANDLE g_hChildStd_OUT_Wr = NULL;
4387
Bram Moolenaar0f873732019-12-05 20:28:46 +01004388 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004389 DWORD len;
4390
Bram Moolenaar0f873732019-12-05 20:28:46 +01004391 // buffer used to receive keys
4392 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4393 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004394
4395 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004396 int noread_cnt = 0;
4397 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004398 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004399 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004400 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004401
4402 SECURITY_ATTRIBUTES saAttr;
4403
Bram Moolenaar0f873732019-12-05 20:28:46 +01004404 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004405 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4406 saAttr.bInheritHandle = TRUE;
4407 saAttr.lpSecurityDescriptor = NULL;
4408
4409 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004410 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004411 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004412 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004413 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004414 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004415 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004416 {
4417 CloseHandle(g_hChildStd_IN_Rd);
4418 CloseHandle(g_hChildStd_IN_Wr);
4419 CloseHandle(g_hChildStd_OUT_Rd);
4420 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004421 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004422 }
4423
4424 si.cb = sizeof(si);
4425 si.lpReserved = NULL;
4426 si.lpDesktop = NULL;
4427 si.lpTitle = NULL;
4428 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4429
Bram Moolenaar0f873732019-12-05 20:28:46 +01004430 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004431 si.hStdError = g_hChildStd_OUT_Wr;
4432 si.hStdOutput = g_hChildStd_OUT_Wr;
4433 si.hStdInput = g_hChildStd_IN_Rd;
4434 si.wShowWindow = SW_HIDE;
4435 si.cbReserved2 = 0;
4436 si.lpReserved2 = NULL;
4437
4438 if (options & SHELL_READ)
4439 ga_init2(&ga, 1, BUFLEN);
4440
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004441 if (cmd != NULL)
4442 {
4443 p = (char *)vim_strsave((char_u *)cmd);
4444 if (p != NULL)
4445 unescape_shellxquote((char_u *)p, p_sxe);
4446 else
4447 p = cmd;
4448 }
4449
Bram Moolenaar0f873732019-12-05 20:28:46 +01004450 // Now, run the command.
4451 // About "Inherit handles" being TRUE: this command can be litigious,
4452 // handle inheritance was deactivated for pending temp file, but, if we
4453 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004454 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4455 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004456
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004457 if (p != cmd)
4458 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004459
Bram Moolenaar0f873732019-12-05 20:28:46 +01004460 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004461 CloseHandle(g_hChildStd_IN_Rd);
4462 CloseHandle(g_hChildStd_OUT_Wr);
4463
4464 if (options & SHELL_WRITE)
4465 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004466 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004467 _beginthreadex(NULL, // security attributes
4468 0, // default stack size
4469 sub_process_writer, // function to be executed
4470 g_hChildStd_IN_Wr, // parameter
4471 0, // creation flag, start immediately
4472 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004473 CloseHandle(thread);
4474 g_hChildStd_IN_Wr = NULL;
4475 }
4476
Bram Moolenaar0f873732019-12-05 20:28:46 +01004477 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004478 for (;;)
4479 {
4480 MSG msg;
4481
K.Takatab7057bd2022-01-21 11:37:07 +00004482 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004483 {
4484 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004485 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004486 }
4487
Bram Moolenaar0f873732019-12-05 20:28:46 +01004488 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004489 if ((options & (SHELL_READ|SHELL_WRITE))
4490# ifdef FEAT_GUI
4491 || gui.in_use
4492# endif
4493 )
4494 {
4495 len = 0;
4496 if (!(options & SHELL_EXPAND)
4497 && ((options &
4498 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4499 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4500# ifdef FEAT_GUI
4501 || gui.in_use
4502# endif
4503 )
4504 && (ta_len > 0 || noread_cnt > 4))
4505 {
4506 if (ta_len == 0)
4507 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004508 // Get extra characters when we don't have any. Reset the
4509 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004510 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004511 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4512 }
4513 if (ta_len > 0 || len > 0)
4514 {
4515 /*
4516 * For pipes: Check for CTRL-C: send interrupt signal to
4517 * child. Check for CTRL-D: EOF, close pipe to child.
4518 */
4519 if (len == 1 && cmd != NULL)
4520 {
4521 if (ta_buf[ta_len] == Ctrl_C)
4522 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004523 // Learn what exit code is expected, for
4524 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004525 TerminateProcess(pi.hProcess, 9);
4526 }
4527 if (ta_buf[ta_len] == Ctrl_D)
4528 {
4529 CloseHandle(g_hChildStd_IN_Wr);
4530 g_hChildStd_IN_Wr = NULL;
4531 }
4532 }
4533
Bram Moolenaarf4140482020-02-15 23:06:45 +01004534 term_replace_bs_del_keycode(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004535
4536 /*
4537 * For pipes: echo the typed characters. For a pty this
4538 * does not seem to work.
4539 */
4540 for (i = ta_len; i < ta_len + len; ++i)
4541 {
4542 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4543 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004544 else if (has_mbyte)
4545 {
4546 int l = (*mb_ptr2len)(ta_buf + i);
4547
4548 msg_outtrans_len(ta_buf + i, l);
4549 i += l - 1;
4550 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004551 else
4552 msg_outtrans_len(ta_buf + i, 1);
4553 }
4554 windgoto(msg_row, msg_col);
4555 out_flush();
4556
4557 ta_len += len;
4558
4559 /*
4560 * Write the characters to the child, unless EOF has been
4561 * typed for pipes. Write one character at a time, to
4562 * avoid losing too much typeahead. When writing buffer
4563 * lines, drop the typed characters (only check for
4564 * CTRL-C).
4565 */
4566 if (options & SHELL_WRITE)
4567 ta_len = 0;
4568 else if (g_hChildStd_IN_Wr != NULL)
4569 {
4570 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4571 1, &len, NULL);
4572 // if we are typing in, we want to keep things reactive
4573 delay = 1;
4574 if (len > 0)
4575 {
4576 ta_len -= len;
4577 mch_memmove(ta_buf, ta_buf + len, ta_len);
4578 }
4579 }
4580 }
4581 }
4582 }
4583
4584 if (ta_len)
4585 ui_inchar_undo(ta_buf, ta_len);
4586
4587 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4588 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004589 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004590 break;
4591 }
4592
4593 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004594 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004595
Bram Moolenaar0f873732019-12-05 20:28:46 +01004596 // We start waiting for a very short time and then increase it, so
4597 // that we respond quickly when the process is quick, and don't
4598 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004599 if (delay < 50)
4600 delay += 10;
4601 }
4602
Bram Moolenaar0f873732019-12-05 20:28:46 +01004603 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004604 CloseHandle(g_hChildStd_OUT_Rd);
4605 if (g_hChildStd_IN_Wr != NULL)
4606 CloseHandle(g_hChildStd_IN_Wr);
4607
4608 WaitForSingleObject(pi.hProcess, INFINITE);
4609
Bram Moolenaar0f873732019-12-05 20:28:46 +01004610 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004611 GetExitCodeProcess(pi.hProcess, &ret);
4612
4613 if (options & SHELL_READ)
4614 {
4615 if (ga.ga_len > 0)
4616 {
4617 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01004618 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004619 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4620 }
4621 else
4622 curbuf->b_no_eol_lnum = 0;
4623 ga_clear(&ga);
4624 }
4625
Bram Moolenaar0f873732019-12-05 20:28:46 +01004626 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004627 CloseHandle(pi.hThread);
4628 CloseHandle(pi.hProcess);
4629
4630 return ret;
4631}
4632
4633 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004634mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004635{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004636 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004637 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004638 return mch_system_piped(cmd, options);
4639 else
4640 return mch_system_classic(cmd, options);
4641}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004642#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004643
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004644#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004645 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02004646mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004647{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004648 int ret;
4649 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004650 char_u *buf;
4651 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004652
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004653 // If the command starts and ends with double quotes, enclose the command
4654 // in parentheses.
4655 len = STRLEN(cmd);
4656 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
4657 {
4658 len += 3;
4659 buf = alloc(len);
4660 if (buf == NULL)
4661 return -1;
4662 vim_snprintf((char *)buf, len, "(%s)", cmd);
4663 wcmd = enc_to_utf16(buf, NULL);
4664 free(buf);
4665 }
4666 else
4667 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4668
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004669 if (wcmd == NULL)
4670 return -1;
4671
4672 ret = _wsystem(wcmd);
4673 vim_free(wcmd);
4674 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004675}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004676
4677#endif
4678
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004679 static int
4680mch_system(char *cmd, int options)
4681{
4682#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004683 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004684 return mch_system_g(cmd, options);
4685 else
4686 return mch_system_c(cmd, options);
4687#elif defined(FEAT_GUI_MSWIN)
4688 return mch_system_g(cmd, options);
4689#else
4690 return mch_system_c(cmd, options);
4691#endif
4692}
4693
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004694#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4695/*
4696 * Use a terminal window to run a shell command in.
4697 */
4698 static int
4699mch_call_shell_terminal(
4700 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004701 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004702{
4703 jobopt_T opt;
4704 char_u *newcmd = NULL;
4705 typval_T argvar[2];
4706 long_u cmdlen;
4707 int retval = -1;
4708 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004709 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004710 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004711 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004712
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004713 if (cmd == NULL)
4714 cmdlen = STRLEN(p_sh) + 1;
4715 else
4716 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004717 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004718 if (newcmd == NULL)
4719 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004720 if (cmd == NULL)
4721 {
4722 STRCPY(newcmd, p_sh);
4723 ch_log(NULL, "starting terminal to run a shell");
4724 }
4725 else
4726 {
4727 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4728 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4729 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004730
4731 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004732
4733 argvar[0].v_type = VAR_STRING;
4734 argvar[0].vval.v_string = newcmd;
4735 argvar[1].v_type = VAR_UNKNOWN;
4736 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004737 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004738 {
4739 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004740 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004741 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004742
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004743 job = term_getjob(buf->b_term);
4744 ++job->jv_refcount;
4745
Bram Moolenaar0f873732019-12-05 20:28:46 +01004746 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004747 aucmd_prepbuf(&aco, buf);
4748
4749 clear_oparg(&oa);
4750 while (term_use_loop())
4751 {
4752 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4753 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004754 // If terminal_loop() returns OK we got a key that is handled
4755 // in Normal model. We don't do redrawing anyway.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004756 if (terminal_loop(TRUE) == OK)
4757 normal_cmd(&oa, TRUE);
4758 }
4759 else
4760 normal_cmd(&oa, TRUE);
4761 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004762 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004763 ch_log(NULL, "system command finished");
4764
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004765 job_unref(job);
4766
Bram Moolenaar0f873732019-12-05 20:28:46 +01004767 // restore curwin/curbuf and a few other things
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004768 aucmd_restbuf(&aco);
4769
4770 wait_return(TRUE);
4771 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4772
4773 vim_free(newcmd);
4774 return retval;
4775}
4776#endif
4777
Bram Moolenaar071d4272004-06-13 20:20:40 +00004778/*
4779 * Either execute a command by calling the shell or start a new shell
4780 */
4781 int
4782mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004783 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004784 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00004785{
4786 int x = 0;
4787 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004788 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004789
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01004790#ifdef FEAT_JOB_CHANNEL
4791 ch_log(NULL, "executing shell command: %s", cmd);
4792#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004793 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02004794 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004795 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004796 if (cmd == NULL)
4797 wcscat(szShellTitle, L" :sh");
4798 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004799 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004800 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004801
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004802 if (wn != NULL)
4803 {
4804 wcscat(szShellTitle, L" - !");
4805 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02004806 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004807 wcscat(szShellTitle, wn);
4808 SetConsoleTitleW(szShellTitle);
4809 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004810 }
4811 }
4812 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004813
4814 out_flush();
4815
4816#ifdef MCH_WRITE_DUMP
4817 if (fdDump)
4818 {
4819 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4820 fflush(fdDump);
4821 }
4822#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004823#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004824 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004825 if (
4826# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004827 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004828# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004829 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004830 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4831 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004832 char_u *cmdbase = cmd;
4833
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004834 if (cmdbase != NULL)
4835 // Skip a leading quote and (.
4836 while (*cmdbase == '"' || *cmdbase == '(')
4837 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004838
4839 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01004840 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
4841 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004842 {
4843 // Use a terminal window to run the command in.
4844 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004845 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004846 return x;
4847 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004848 }
4849#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004850
4851 /*
4852 * Catch all deadly signals while running the external command, because a
4853 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4854 */
4855 signal(SIGINT, SIG_IGN);
4856#if defined(__GNUC__) && !defined(__MINGW32__)
4857 signal(SIGKILL, SIG_IGN);
4858#else
4859 signal(SIGBREAK, SIG_IGN);
4860#endif
4861 signal(SIGILL, SIG_IGN);
4862 signal(SIGFPE, SIG_IGN);
4863 signal(SIGSEGV, SIG_IGN);
4864 signal(SIGTERM, SIG_IGN);
4865 signal(SIGABRT, SIG_IGN);
4866
4867 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004868 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00004869
4870 if (cmd == NULL)
4871 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004872 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004873 }
4874 else
4875 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004876 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004877 char_u *newcmd = NULL;
4878 char_u *cmdbase = cmd;
4879 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004880
Bram Moolenaar0f873732019-12-05 20:28:46 +01004881 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004882 if (*cmdbase == '"' )
4883 ++cmdbase;
4884 if (*cmdbase == '(')
4885 ++cmdbase;
4886
Bram Moolenaar1c465442017-03-12 20:10:05 +01004887 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004888 {
4889 STARTUPINFO si;
4890 PROCESS_INFORMATION pi;
4891 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004892 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004893 char_u *p;
4894
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004895 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004896 si.cb = sizeof(si);
4897 si.lpReserved = NULL;
4898 si.lpDesktop = NULL;
4899 si.lpTitle = NULL;
4900 si.dwFlags = 0;
4901 si.cbReserved2 = 0;
4902 si.lpReserved2 = NULL;
4903
4904 cmdbase = skipwhite(cmdbase + 5);
4905 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004906 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004907 {
4908 cmdbase = skipwhite(cmdbase + 4);
4909 si.dwFlags = STARTF_USESHOWWINDOW;
4910 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004911 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004912 }
4913 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004914 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004915 {
4916 cmdbase = skipwhite(cmdbase + 2);
4917 flags = CREATE_NO_WINDOW;
4918 si.dwFlags = STARTF_USESTDHANDLES;
4919 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004920 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004921 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004922 NULL, // Security att.
4923 OPEN_EXISTING, // Open flags
4924 FILE_ATTRIBUTE_NORMAL, // File att.
4925 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004926 si.hStdOutput = si.hStdInput;
4927 si.hStdError = si.hStdInput;
4928 }
4929
Bram Moolenaar0f873732019-12-05 20:28:46 +01004930 // Remove a trailing ", ) and )" if they have a match
4931 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004932 if (cmdbase > cmd)
4933 {
4934 p = cmdbase + STRLEN(cmdbase);
4935 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4936 *--p = NUL;
4937 if (p > cmdbase && p[-1] == ')'
4938 && (*cmd =='(' || cmd[1] == '('))
4939 *--p = NUL;
4940 }
4941
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004942 newcmd = cmdbase;
4943 unescape_shellxquote(cmdbase, p_sxe);
4944
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004945 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004946 * If creating new console, arguments are passed to the
4947 * 'cmd.exe' as-is. If it's not, arguments are not treated
4948 * correctly for current 'cmd.exe'. So unescape characters in
4949 * shellxescape except '|' for avoiding to be treated as
4950 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004951 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004952 if (flags != CREATE_NEW_CONSOLE)
4953 {
4954 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004955 char_u *cmd_shell = mch_getenv("COMSPEC");
4956
4957 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004958 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004959
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004960 subcmd = vim_strsave_escaped_ext(cmdbase,
4961 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004962 if (subcmd != NULL)
4963 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004964 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004965 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004966 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004967 if (newcmd != NULL)
4968 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004969 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004970 else
4971 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004972 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004973 }
4974 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004975
4976 /*
4977 * Now, start the command as a process, so that it doesn't
4978 * inherit our handles which causes unpleasant dangling swap
4979 * files if we exit before the spawned process
4980 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004981 if (vim_create_process((char *)newcmd, FALSE, flags,
4982 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004983 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004984 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4985 > (HINSTANCE)32)
4986 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004987 else
4988 {
4989 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01004990#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004991# ifdef VIMDLL
4992 if (gui.in_use)
4993# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00004994 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004995#endif
4996 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004997
4998 if (newcmd != cmdbase)
4999 vim_free(newcmd);
5000
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005001 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005002 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005003 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005004 CloseHandle(si.hStdInput);
5005 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005006 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005007 CloseHandle(pi.hThread);
5008 CloseHandle(pi.hProcess);
5009 }
5010 else
5011 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005012 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005013#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005014 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005015 (!s_dont_use_vimrun && p_stmp ?
5016 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5017 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005018#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005019 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005020
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005021 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005022 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005023 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005024#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005025 if (
5026# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005027 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005028# endif
5029 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005030 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005031 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5032 "External commands will not pause after completion.\n"
5033 "See :help win32-vimrun for more information.");
5034 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005035 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5036 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005037
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005038 if (wmsg != NULL && wtitle != NULL)
5039 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5040 vim_free(wmsg);
5041 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005042 need_vimrun_warning = FALSE;
5043 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005044 if (
5045# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005046 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005047# endif
5048 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005049 // Use vimrun to execute the command. It opens a console
5050 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005051 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005052 vimrun_path,
5053 (msg_silent != 0 || (options & SHELL_DOOUT))
5054 ? "-s " : "",
5055 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005056 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005057# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005058 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005059# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005060 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005061 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005062 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5063 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005064 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005065#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005066 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005067 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005068 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005069 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005070 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005071 }
5072 }
5073
5074 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005075 {
5076 // The shell may have messed with the mode, always set it.
5077 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005078 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005079 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005080
Bram Moolenaar0f873732019-12-05 20:28:46 +01005081 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005082 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005083#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005084 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005085 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005086#endif
5087 )
5088 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005089 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005090 msg_putchar('\n');
5091 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005092 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005093
5094 signal(SIGINT, SIG_DFL);
5095#if defined(__GNUC__) && !defined(__MINGW32__)
5096 signal(SIGKILL, SIG_DFL);
5097#else
5098 signal(SIGBREAK, SIG_DFL);
5099#endif
5100 signal(SIGILL, SIG_DFL);
5101 signal(SIGFPE, SIG_DFL);
5102 signal(SIGSEGV, SIG_DFL);
5103 signal(SIGTERM, SIG_DFL);
5104 signal(SIGABRT, SIG_DFL);
5105
5106 return x;
5107}
5108
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005109#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005110 static HANDLE
5111job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005112 char_u *fname,
5113 DWORD dwDesiredAccess,
5114 DWORD dwShareMode,
5115 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5116 DWORD dwCreationDisposition,
5117 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005118{
5119 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005120 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005121
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005122 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005123 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005124 return INVALID_HANDLE_VALUE;
5125
5126 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5127 lpSecurityAttributes, dwCreationDisposition,
5128 dwFlagsAndAttributes, NULL);
5129 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005130 return h;
5131}
5132
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005133/*
5134 * Turn the dictionary "env" into a NUL separated list that can be used as the
5135 * environment argument of vim_create_process().
5136 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005137 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005138win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005139{
5140 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005141 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005142 LPVOID base = GetEnvironmentStringsW();
5143
Bram Moolenaar0f873732019-12-05 20:28:46 +01005144 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005145 if (ga_grow(gap, 1) == FAIL)
5146 return;
5147
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005148 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005149 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005150 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005151 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005152 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005153 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005154 typval_T *item = &dict_lookup(hi)->di_tv;
5155 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005156 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005157 --todo;
5158 if (wkey != NULL && wval != NULL)
5159 {
5160 size_t n;
5161 size_t lkey = wcslen(wkey);
5162 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005163
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005164 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5165 continue;
5166 for (n = 0; n < lkey; n++)
5167 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5168 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5169 for (n = 0; n < lval; n++)
5170 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5171 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5172 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005173 vim_free(wkey);
5174 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005175 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005176 }
5177 }
5178
Bram Moolenaar355757a2020-02-10 22:06:32 +01005179 if (base)
5180 {
5181 WCHAR *p = (WCHAR*) base;
5182
5183 // for last \0
5184 if (ga_grow(gap, 1) == FAIL)
5185 return;
5186
5187 while (*p != 0 || *(p + 1) != 0)
5188 {
5189 if (ga_grow(gap, 1) == OK)
5190 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5191 p++;
5192 }
5193 FreeEnvironmentStrings(base);
5194 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5195 }
5196
Bram Moolenaar493359e2018-06-12 20:25:52 +02005197# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005198 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005199# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005200 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005201 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005202# endif
5203# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005204 char_u *version = get_vim_var_str(VV_VERSION);
5205 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005206# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005207 // size of "VIM_SERVERNAME=" and value,
5208 // plus "VIM_TERMINAL=" and value,
5209 // plus two terminating NULs
5210 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005211# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005212 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005213# endif
5214# ifdef FEAT_TERMINAL
5215 + 13 + version_len + 2
5216# endif
5217 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005218
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005219 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005220 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005221# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005222 for (n = 0; n < 15; n++)
5223 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5224 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005225 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005226 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5227 (WCHAR)servername[n];
5228 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005229# endif
5230# ifdef FEAT_TERMINAL
5231 if (is_terminal)
5232 {
5233 for (n = 0; n < 13; n++)
5234 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5235 (WCHAR)"VIM_TERMINAL="[n];
5236 for (n = 0; n < version_len; n++)
5237 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5238 (WCHAR)version[n];
5239 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5240 }
5241# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005242 }
5243 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005244# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005245}
5246
Bram Moolenaarb091f302019-01-19 14:37:00 +01005247/*
5248 * Create a pair of pipes.
5249 * Return TRUE for success, FALSE for failure.
5250 */
5251 static BOOL
5252create_pipe_pair(HANDLE handles[2])
5253{
5254 static LONG s;
5255 char name[64];
5256 SECURITY_ATTRIBUTES sa;
5257
5258 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5259 GetCurrentProcessId(),
5260 InterlockedIncrement(&s));
5261
5262 // Create named pipe. Max size of named pipe is 65535.
5263 handles[1] = CreateNamedPipe(
5264 name,
5265 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5266 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005267 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005268
5269 if (handles[1] == INVALID_HANDLE_VALUE)
5270 return FALSE;
5271
5272 sa.nLength = sizeof(sa);
5273 sa.bInheritHandle = TRUE;
5274 sa.lpSecurityDescriptor = NULL;
5275
5276 handles[0] = CreateFile(name,
5277 FILE_GENERIC_READ,
5278 FILE_SHARE_READ, &sa,
5279 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5280
5281 if (handles[0] == INVALID_HANDLE_VALUE)
5282 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005283 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005284 return FALSE;
5285 }
5286
5287 return TRUE;
5288}
5289
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005290 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005291mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005292{
5293 STARTUPINFO si;
5294 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005295 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005296 SECURITY_ATTRIBUTES saAttr;
5297 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005298 HANDLE ifd[2];
5299 HANDLE ofd[2];
5300 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005301 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005302
5303 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5304 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5305 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5306 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5307 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5308 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5309 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5310
5311 if (use_out_for_err && use_null_for_out)
5312 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005313
5314 ifd[0] = INVALID_HANDLE_VALUE;
5315 ifd[1] = INVALID_HANDLE_VALUE;
5316 ofd[0] = INVALID_HANDLE_VALUE;
5317 ofd[1] = INVALID_HANDLE_VALUE;
5318 efd[0] = INVALID_HANDLE_VALUE;
5319 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005320 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005321
Bram Moolenaar14207f42016-10-27 21:13:10 +02005322 jo = CreateJobObject(NULL, NULL);
5323 if (jo == NULL)
5324 {
5325 job->jv_status = JOB_FAILED;
5326 goto failed;
5327 }
5328
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005329 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005330 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005331
Bram Moolenaar76467df2016-02-12 19:30:26 +01005332 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005333 ZeroMemory(&si, sizeof(si));
5334 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005335 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005336 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005337
Bram Moolenaard8070362016-02-15 21:56:54 +01005338 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5339 saAttr.bInheritHandle = TRUE;
5340 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005341
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005342 if (use_file_for_in)
5343 {
5344 char_u *fname = options->jo_io_name[PART_IN];
5345
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005346 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5347 FILE_SHARE_READ | FILE_SHARE_WRITE,
5348 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5349 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005350 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005351 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005352 goto failed;
5353 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005354 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005355 else if (!use_null_for_in
5356 && (!create_pipe_pair(ifd)
5357 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005358 goto failed;
5359
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005360 if (use_file_for_out)
5361 {
5362 char_u *fname = options->jo_io_name[PART_OUT];
5363
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005364 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5365 FILE_SHARE_READ | FILE_SHARE_WRITE,
5366 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5367 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005368 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005369 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005370 goto failed;
5371 }
5372 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005373 else if (!use_null_for_out &&
5374 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005375 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005376 goto failed;
5377
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005378 if (use_file_for_err)
5379 {
5380 char_u *fname = options->jo_io_name[PART_ERR];
5381
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005382 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5383 FILE_SHARE_READ | FILE_SHARE_WRITE,
5384 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5385 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005386 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005387 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005388 goto failed;
5389 }
5390 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005391 else if (!use_out_for_err && !use_null_for_err &&
5392 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005393 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005394 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005395
Bram Moolenaard8070362016-02-15 21:56:54 +01005396 si.dwFlags |= STARTF_USESTDHANDLES;
5397 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005398 si.hStdOutput = ofd[1];
5399 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5400
5401 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5402 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005403 if (options->jo_set & JO_CHANNEL)
5404 {
5405 channel = options->jo_channel;
5406 if (channel != NULL)
5407 ++channel->ch_refcount;
5408 }
5409 else
5410 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005411 if (channel == NULL)
5412 goto failed;
5413 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005414
5415 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005416 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005417 CREATE_DEFAULT_ERROR_MODE |
5418 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005419 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005420 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005421 &si, &pi,
5422 ga.ga_data,
5423 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005424 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005425 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005426 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005427 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005428 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005429
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005430 ga_clear(&ga);
5431
Bram Moolenaar14207f42016-10-27 21:13:10 +02005432 if (!AssignProcessToJobObject(jo, pi.hProcess))
5433 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005434 // if failing, switch the way to terminate
5435 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005436 CloseHandle(jo);
5437 jo = NULL;
5438 }
5439 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005440 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005441 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005442 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005443 job->jv_status = JOB_STARTED;
5444
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005445 CloseHandle(ifd[0]);
5446 CloseHandle(ofd[1]);
5447 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005448 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005449
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005450 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005451 if (channel != NULL)
5452 {
5453 channel_set_pipes(channel,
5454 use_file_for_in || use_null_for_in
5455 ? INVALID_FD : (sock_T)ifd[1],
5456 use_file_for_out || use_null_for_out
5457 ? INVALID_FD : (sock_T)ofd[0],
5458 use_out_for_err || use_file_for_err || use_null_for_err
5459 ? INVALID_FD : (sock_T)efd[0]);
5460 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005461 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005462 return;
5463
5464failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005465 CloseHandle(ifd[0]);
5466 CloseHandle(ofd[0]);
5467 CloseHandle(efd[0]);
5468 CloseHandle(ifd[1]);
5469 CloseHandle(ofd[1]);
5470 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005471 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005472 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005473}
5474
5475 char *
5476mch_job_status(job_T *job)
5477{
5478 DWORD dwExitCode = 0;
5479
Bram Moolenaar76467df2016-02-12 19:30:26 +01005480 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5481 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005482 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005483 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005484 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005485 {
5486 ch_log(job->jv_channel, "Job ended");
5487 job->jv_status = JOB_ENDED;
5488 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005489 return "dead";
5490 }
5491 return "run";
5492}
5493
Bram Moolenaar97792de2016-10-15 18:36:49 +02005494 job_T *
5495mch_detect_ended_job(job_T *job_list)
5496{
5497 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5498 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5499 job_T *job = job_list;
5500
5501 while (job != NULL)
5502 {
5503 DWORD n;
5504 DWORD result;
5505
5506 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5507 && job != NULL; job = job->jv_next)
5508 {
5509 if (job->jv_status == JOB_STARTED)
5510 {
5511 jobHandles[n] = job->jv_proc_info.hProcess;
5512 jobArray[n] = job;
5513 ++n;
5514 }
5515 }
5516 if (n == 0)
5517 continue;
5518 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5519 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5520 {
5521 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5522
5523 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5524 return wait_job;
5525 }
5526 }
5527 return NULL;
5528}
5529
Bram Moolenaarfb630902016-10-29 14:55:00 +02005530 static BOOL
5531terminate_all(HANDLE process, int code)
5532{
5533 PROCESSENTRY32 pe;
5534 HANDLE h = INVALID_HANDLE_VALUE;
5535 DWORD pid = GetProcessId(process);
5536
5537 if (pid != 0)
5538 {
5539 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5540 if (h != INVALID_HANDLE_VALUE)
5541 {
5542 pe.dwSize = sizeof(PROCESSENTRY32);
5543 if (!Process32First(h, &pe))
5544 goto theend;
5545
5546 do
5547 {
5548 if (pe.th32ParentProcessID == pid)
5549 {
5550 HANDLE ph = OpenProcess(
5551 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5552 if (ph != NULL)
5553 {
5554 terminate_all(ph, code);
5555 CloseHandle(ph);
5556 }
5557 }
5558 } while (Process32Next(h, &pe));
5559
5560 CloseHandle(h);
5561 }
5562 }
5563
5564theend:
5565 return TerminateProcess(process, code);
5566}
5567
5568/*
5569 * Send a (deadly) signal to "job".
5570 * Return FAIL if it didn't work.
5571 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005572 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005573mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005574{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005575 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005576
Bram Moolenaar923d9262016-02-25 20:56:01 +01005577 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005578 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005579 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02005580 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005581 {
5582 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5583 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00005584 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005585 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01005586 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005587 }
5588
5589 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5590 return FAIL;
5591 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005592 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5593 job->jv_proc_info.dwProcessId)
5594 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005595 FreeConsole();
5596 return ret;
5597}
5598
5599/*
5600 * Clear the data related to "job".
5601 */
5602 void
5603mch_clear_job(job_T *job)
5604{
5605 if (job->jv_status != JOB_FAILED)
5606 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005607 if (job->jv_job_object != NULL)
5608 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005609 CloseHandle(job->jv_proc_info.hProcess);
5610 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005611}
5612#endif
5613
Bram Moolenaar071d4272004-06-13 20:20:40 +00005614
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005615#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005616
5617/*
5618 * Start termcap mode
5619 */
5620 static void
5621termcap_mode_start(void)
5622{
5623 DWORD cmodein;
5624
5625 if (g_fTermcapMode)
5626 return;
5627
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005628 if (!p_rs && USE_VTP)
5629 vtp_printf("\033[?1049h");
5630
Bram Moolenaar071d4272004-06-13 20:20:40 +00005631 SaveConsoleBuffer(&g_cbNonTermcap);
5632
5633 if (g_cbTermcap.IsValid)
5634 {
5635 /*
5636 * We've been in termcap mode before. Restore certain screen
5637 * characteristics, including the buffer size and the window
5638 * size. Since we will be redrawing the screen, we don't need
5639 * to restore the actual contents of the buffer.
5640 */
5641 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005642 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005643 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5644 Rows = g_cbTermcap.Info.dwSize.Y;
5645 Columns = g_cbTermcap.Info.dwSize.X;
5646 }
5647 else
5648 {
5649 /*
5650 * This is our first time entering termcap mode. Clear the console
5651 * screen buffer, and resize the buffer to match the current window
5652 * size. We will use this as the size of our editing environment.
5653 */
5654 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005655 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005656 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5657 }
5658
Bram Moolenaar071d4272004-06-13 20:20:40 +00005659 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005660
5661 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005662 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005663 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005664 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005665 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
5666 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005667 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005668 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005669 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005670 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5671 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005672 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005673 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005674
5675 redraw_later_clear();
5676 g_fTermcapMode = TRUE;
5677}
5678
5679
5680/*
5681 * End termcap mode
5682 */
5683 static void
5684termcap_mode_end(void)
5685{
5686 DWORD cmodein;
5687 ConsoleBuffer *cb;
5688 COORD coord;
5689 DWORD dwDummy;
5690
5691 if (!g_fTermcapMode)
5692 return;
5693
5694 SaveConsoleBuffer(&g_cbTermcap);
5695
5696 GetConsoleMode(g_hConIn, &cmodein);
5697 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005698 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5699 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005700
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005701# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005702 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005703# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005704 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005705# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005706 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01005707 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005708 SetConsoleCursorInfo(g_hConOut, &g_cci);
5709
5710 if (p_rs || exiting)
5711 {
5712 /*
5713 * Clear anything that happens to be on the current line.
5714 */
5715 coord.X = 0;
5716 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5717 FillConsoleOutputCharacter(g_hConOut, ' ',
5718 cb->Info.dwSize.X, coord, &dwDummy);
5719 /*
5720 * The following is just for aesthetics. If we are exiting without
5721 * restoring the screen, then we want to have a prompt string
5722 * appear at the bottom line. However, the command interpreter
5723 * seems to always advance the cursor one line before displaying
5724 * the prompt string, which causes the screen to scroll. To
5725 * counter this, move the cursor up one line before exiting.
5726 */
5727 if (exiting && !p_rs)
5728 coord.Y--;
5729 /*
5730 * Position the cursor at the leftmost column of the desired row.
5731 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005732 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005733 }
5734
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005735 if (!p_rs && USE_VTP)
Bram Moolenaar0afdcf82020-04-01 18:29:10 +02005736 vtp_printf("\033[?1049l");
5737
Bram Moolenaar071d4272004-06-13 20:20:40 +00005738 g_fTermcapMode = FALSE;
5739}
Bram Moolenaar0f873732019-12-05 20:28:46 +01005740#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005741
5742
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005743#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005744 void
5745mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005746 char_u *s UNUSED,
5747 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005748{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005749 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00005750}
5751
5752#else
5753
5754/*
5755 * clear `n' chars, starting from `coord'
5756 */
5757 static void
5758clear_chars(
5759 COORD coord,
5760 DWORD n)
5761{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005762 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02005763 {
5764 DWORD dwDummy;
5765
5766 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5767 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
5768 &dwDummy);
5769 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005770 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005771 {
5772 set_console_color_rgb();
5773 gotoxy(coord.X + 1, coord.Y + 1);
5774 vtp_printf("\033[%dX", n);
5775 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005776}
5777
5778
5779/*
5780 * Clear the screen
5781 */
5782 static void
5783clear_screen(void)
5784{
5785 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005786
5787 if (!USE_VTP)
5788 clear_chars(g_coord, Rows * Columns);
5789 else
5790 {
5791 set_console_color_rgb();
5792 gotoxy(1, 1);
5793 vtp_printf("\033[2J");
5794 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005795}
5796
5797
5798/*
5799 * Clear to end of display
5800 */
5801 static void
5802clear_to_end_of_display(void)
5803{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005804 COORD save = g_coord;
5805
5806 if (!USE_VTP)
5807 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005808 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005809 else
5810 {
5811 set_console_color_rgb();
5812 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5813 vtp_printf("\033[0J");
5814
5815 gotoxy(save.X + 1, save.Y + 1);
5816 g_coord = save;
5817 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005818}
5819
5820
5821/*
5822 * Clear to end of line
5823 */
5824 static void
5825clear_to_end_of_line(void)
5826{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005827 COORD save = g_coord;
5828
5829 if (!USE_VTP)
5830 clear_chars(g_coord, Columns - g_coord.X);
5831 else
5832 {
5833 set_console_color_rgb();
5834 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5835 vtp_printf("\033[0K");
5836
5837 gotoxy(save.X + 1, save.Y + 1);
5838 g_coord = save;
5839 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005840}
5841
5842
5843/*
5844 * Scroll the scroll region up by `cLines' lines
5845 */
5846 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005847scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005848{
5849 COORD oldcoord = g_coord;
5850
5851 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5852 delete_lines(cLines);
5853
5854 g_coord = oldcoord;
5855}
5856
5857
5858/*
5859 * Set the scroll region
5860 */
5861 static void
5862set_scroll_region(
5863 unsigned left,
5864 unsigned top,
5865 unsigned right,
5866 unsigned bottom)
5867{
5868 if (left >= right
5869 || top >= bottom
5870 || right > (unsigned) Columns - 1
5871 || bottom > (unsigned) Rows - 1)
5872 return;
5873
5874 g_srScrollRegion.Left = left;
5875 g_srScrollRegion.Top = top;
5876 g_srScrollRegion.Right = right;
5877 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005878}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005879
Bram Moolenaar6982f422019-02-16 16:48:01 +01005880 static void
5881set_scroll_region_tb(
5882 unsigned top,
5883 unsigned bottom)
5884{
5885 if (top >= bottom || bottom > (unsigned)Rows - 1)
5886 return;
5887
5888 g_srScrollRegion.Top = top;
5889 g_srScrollRegion.Bottom = bottom;
5890}
5891
5892 static void
5893set_scroll_region_lr(
5894 unsigned left,
5895 unsigned right)
5896{
5897 if (left >= right || right > (unsigned)Columns - 1)
5898 return;
5899
5900 g_srScrollRegion.Left = left;
5901 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005902}
5903
5904
5905/*
5906 * Insert `cLines' lines at the current cursor position
5907 */
5908 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005909insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005910{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005911 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005912 COORD dest;
5913 CHAR_INFO fill;
5914
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005915 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5916
Bram Moolenaar6982f422019-02-16 16:48:01 +01005917 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005918 dest.Y = g_coord.Y + cLines;
5919
Bram Moolenaar6982f422019-02-16 16:48:01 +01005920 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005921 source.Top = g_coord.Y;
5922 source.Right = g_srScrollRegion.Right;
5923 source.Bottom = g_srScrollRegion.Bottom - cLines;
5924
Bram Moolenaar6982f422019-02-16 16:48:01 +01005925 clip.Left = g_srScrollRegion.Left;
5926 clip.Top = g_coord.Y;
5927 clip.Right = g_srScrollRegion.Right;
5928 clip.Bottom = g_srScrollRegion.Bottom;
5929
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005930 fill.Char.AsciiChar = ' ';
5931 if (!USE_VTP)
5932 fill.Attributes = g_attrCurrent;
5933 else
5934 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005935
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005936 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005937
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005938 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5939
Bram Moolenaar6982f422019-02-16 16:48:01 +01005940 // Here we have to deal with a win32 console flake: If the scroll
5941 // region looks like abc and we scroll c to a and fill with d we get
5942 // cbd... if we scroll block c one line at a time to a, we get cdd...
5943 // vim expects cdd consistently... So we have to deal with that
5944 // here... (this also occurs scrolling the same way in the other
5945 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005946
5947 if (source.Bottom < dest.Y)
5948 {
5949 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005950 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005951
Bram Moolenaar6982f422019-02-16 16:48:01 +01005952 coord.X = source.Left;
5953 for (i = clip.Top; i < dest.Y; ++i)
5954 {
5955 coord.Y = i;
5956 clear_chars(coord, source.Right - source.Left + 1);
5957 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005958 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02005959
5960 if (USE_WT)
5961 {
5962 COORD coord;
5963 int i;
5964
5965 coord.X = source.Left;
5966 for (i = source.Top; i < dest.Y; ++i)
5967 {
5968 coord.Y = i;
5969 clear_chars(coord, source.Right - source.Left + 1);
5970 }
5971 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005972}
5973
5974
5975/*
5976 * Delete `cLines' lines at the current cursor position
5977 */
5978 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005979delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005980{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005981 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005982 COORD dest;
5983 CHAR_INFO fill;
5984 int nb;
5985
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005986 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5987
Bram Moolenaar6982f422019-02-16 16:48:01 +01005988 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005989 dest.Y = g_coord.Y;
5990
Bram Moolenaar6982f422019-02-16 16:48:01 +01005991 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005992 source.Top = g_coord.Y + cLines;
5993 source.Right = g_srScrollRegion.Right;
5994 source.Bottom = g_srScrollRegion.Bottom;
5995
Bram Moolenaar6982f422019-02-16 16:48:01 +01005996 clip.Left = g_srScrollRegion.Left;
5997 clip.Top = g_coord.Y;
5998 clip.Right = g_srScrollRegion.Right;
5999 clip.Bottom = g_srScrollRegion.Bottom;
6000
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006001 fill.Char.AsciiChar = ' ';
6002 if (!USE_VTP)
6003 fill.Attributes = g_attrCurrent;
6004 else
6005 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006006
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006007 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006008
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006009 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6010
Bram Moolenaar6982f422019-02-16 16:48:01 +01006011 // Here we have to deal with a win32 console flake; See insert_lines()
6012 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006013
6014 nb = dest.Y + (source.Bottom - source.Top) + 1;
6015
6016 if (nb < source.Top)
6017 {
6018 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006019 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006020
Bram Moolenaar6982f422019-02-16 16:48:01 +01006021 coord.X = source.Left;
6022 for (i = nb; i < clip.Bottom; ++i)
6023 {
6024 coord.Y = i;
6025 clear_chars(coord, source.Right - source.Left + 1);
6026 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006027 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006028
6029 if (USE_WT)
6030 {
6031 COORD coord;
6032 int i;
6033
6034 coord.X = source.Left;
6035 for (i = nb; i <= source.Bottom; ++i)
6036 {
6037 coord.Y = i;
6038 clear_chars(coord, source.Right - source.Left + 1);
6039 }
6040 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006041}
6042
6043
6044/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006045 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006046 */
6047 static void
6048gotoxy(
6049 unsigned x,
6050 unsigned y)
6051{
6052 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6053 return;
6054
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006055 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006056 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006057 // There are reports of double-width characters not displayed
6058 // correctly. This workaround should fix it, similar to how it's done
6059 // for VTP.
6060 g_coord.X = 0;
6061 SetConsoleCursorPosition(g_hConOut, g_coord);
6062
Bram Moolenaar2313b612019-09-27 14:14:32 +02006063 // external cursor coords are 1-based; internal are 0-based
6064 g_coord.X = x - 1;
6065 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006066 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006067 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006068 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006069 {
6070 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006071 // destruction. Insider build bug. Always enabled because it's cheap
6072 // and avoids mistakes with recognizing the build.
6073 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006074
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006075 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006076
6077 g_coord.X = x - 1;
6078 g_coord.Y = y - 1;
6079 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006080}
6081
6082
6083/*
6084 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006085 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006086 */
6087 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006088textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006089{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006090 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006091
6092 SetConsoleTextAttribute(g_hConOut, wAttr);
6093}
6094
6095
6096 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006097textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006098{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006099 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006100
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006101 if (!USE_VTP)
6102 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6103 else
6104 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006105}
6106
6107
6108 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006109textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006110{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006111 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006112
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006113 if (!USE_VTP)
6114 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6115 else
6116 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006117}
6118
6119
6120/*
6121 * restore the default text attribute (whatever we started with)
6122 */
6123 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006124normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006125{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006126 if (!USE_VTP)
6127 textattr(g_attrDefault);
6128 else
6129 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006130}
6131
6132
6133static WORD g_attrPreStandout = 0;
6134
6135/*
6136 * Make the text standout, by brightening it
6137 */
6138 static void
6139standout(void)
6140{
6141 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006142
Bram Moolenaar071d4272004-06-13 20:20:40 +00006143 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6144}
6145
6146
6147/*
6148 * Turn off standout mode
6149 */
6150 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006151standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006152{
6153 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006154 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006155
6156 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006157}
6158
6159
6160/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006161 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006162 */
6163 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006164mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006165{
6166 char_u *p;
6167 int n;
6168
6169 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6170 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006171 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006172# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006173 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006174# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006175 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006176 {
6177 p = T_ME + 2;
6178 n = getdigits(&p);
6179 if (*p == 'm' && n > 0)
6180 {
6181 cterm_normal_fg_color = (n & 0xf) + 1;
6182 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6183 }
6184 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006185# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006186 cterm_normal_fg_gui_color = INVALCOLOR;
6187 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006188# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006189}
6190
6191
6192/*
6193 * visual bell: flash the screen
6194 */
6195 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006196visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006197{
6198 COORD coordOrigin = {0, 0};
6199 WORD attrFlash = ~g_attrCurrent & 0xff;
6200
6201 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006202 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006203
6204 if (oldattrs == NULL)
6205 return;
6206 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6207 coordOrigin, &dwDummy);
6208 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6209 coordOrigin, &dwDummy);
6210
Bram Moolenaar0f873732019-12-05 20:28:46 +01006211 Sleep(15); // wait for 15 msec
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006212 if (!USE_VTP)
6213 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006214 coordOrigin, &dwDummy);
6215 vim_free(oldattrs);
6216}
6217
6218
6219/*
6220 * Make the cursor visible or invisible
6221 */
6222 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006223cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006224{
6225 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006226
6227 if (USE_VTP)
6228 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6229
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006230# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006231 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006232# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006233}
6234
6235
6236/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006237 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006238 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006239 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006240 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006241write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006242 char_u *pchBuf,
6243 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006244{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006245 COORD coord = g_coord;
6246 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006247 DWORD n, cchwritten;
6248 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006249 static WCHAR *unicodebuf = NULL;
6250 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006251 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006252 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006253 static WCHAR *utf8spbuf = NULL;
6254 static int utf8splength;
6255 static DWORD utf8spcells;
6256 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006257
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006258 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006259 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006260 utf8usingbuf = &unicodebuf;
6261 do
6262 {
6263 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6264 unicodebuf, unibuflen);
6265 if (length && length <= unibuflen)
6266 break;
6267 vim_free(unicodebuf);
6268 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6269 unibuflen = unibuflen ? 0 : length;
6270 } while(1);
6271 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006272 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006273 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6274 {
6275 if (utf8usingbuf != &utf8spbuf)
6276 {
6277 if (utf8spbuf == NULL)
6278 {
6279 cells = mb_string2cells((char_u *)" ", 1);
6280 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6281 utf8spbuf = LALLOC_MULT(WCHAR, length);
6282 if (utf8spbuf != NULL)
6283 {
6284 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6285 utf8usingbuf = &utf8spbuf;
6286 utf8splength = length;
6287 utf8spcells = cells;
6288 }
6289 }
6290 else
6291 {
6292 utf8usingbuf = &utf8spbuf;
6293 length = utf8splength;
6294 cells = utf8spcells;
6295 }
6296 }
6297 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006298
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006299 if (!USE_VTP)
6300 {
6301 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6302 coord, &written);
6303 // When writing fails or didn't write a single character, pretend one
6304 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006305 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006306 coord, &cchwritten) == 0
6307 || cchwritten == 0 || cchwritten == (DWORD)-1)
6308 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006309 }
6310 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006311 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006312 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006313 NULL) == 0 || cchwritten == 0)
6314 cchwritten = 1;
6315 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006316
K.Takata135e1522022-01-29 15:27:58 +00006317 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006318 {
6319 written = cbToWrite;
6320 g_coord.X += (SHORT)cells;
6321 }
6322 else
6323 {
6324 char_u *p = pchBuf;
6325 for (n = 0; n < cchwritten; n++)
6326 MB_CPTR_ADV(p);
6327 written = p - pchBuf;
6328 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006329 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006330
6331 while (g_coord.X > g_srScrollRegion.Right)
6332 {
6333 g_coord.X -= (SHORT) Columns;
6334 if (g_coord.Y < g_srScrollRegion.Bottom)
6335 g_coord.Y++;
6336 }
6337
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006338 // Cursor under VTP is always in the correct position, no need to reset.
6339 if (!USE_VTP)
6340 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006341
6342 return written;
6343}
6344
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006345 static char_u *
6346get_seq(
6347 int *args,
6348 int *count,
6349 char_u *head)
6350{
6351 int argc;
6352 char_u *p;
6353
6354 if (head == NULL || *head != '\033')
6355 return NULL;
6356
6357 argc = 0;
6358 p = head;
6359 ++p;
6360 do
6361 {
6362 ++p;
6363 args[argc] = getdigits(&p);
6364 argc += (argc < 15) ? 1 : 0;
6365 } while (*p == ';');
6366 *count = argc;
6367
6368 return p;
6369}
6370
6371 static char_u *
6372get_sgr(
6373 int *args,
6374 int *count,
6375 char_u *head)
6376{
6377 char_u *p = get_seq(args, count, head);
6378
6379 return (p && *p == 'm') ? ++p : NULL;
6380}
6381
6382/*
6383 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6384 */
6385 static char_u *
6386sgrn2(
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 == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6395}
6396
6397/*
6398 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6399 */
6400 static char_u *
6401sgrnc(
6402 char_u *head,
6403 int n)
6404{
6405 int argc;
6406 int args[16];
6407 char_u *p = get_sgr(args, &argc, head);
6408
6409 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6410 ? p : NULL;
6411}
6412
6413 static char_u *
6414skipblank(char_u *q)
6415{
6416 char_u *p = q;
6417
6418 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6419 ++p;
6420 return p;
6421}
6422
6423/*
6424 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6425 * NULL.
6426 */
6427 static char_u *
6428sgrn2c(
6429 char_u *head,
6430 int n)
6431{
6432 char_u *p = sgrn2(head, n);
6433
6434 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6435}
6436
6437/*
6438 * If there is only a newline between the sequence immediately following it,
6439 * a pointer to the character following the newline is returned.
6440 * Otherwise NULL.
6441 */
6442 static char_u *
6443sgrn2cn(
6444 char_u *head,
6445 int n)
6446{
6447 char_u *p = sgrn2(head, n);
6448
6449 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6450}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006451
6452/*
6453 * mch_write(): write the output buffer to the screen, translating ESC
6454 * sequences into calls to console output routines.
6455 */
6456 void
6457mch_write(
6458 char_u *s,
6459 int len)
6460{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006461 char_u *end = s + len;
6462
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006463# ifdef VIMDLL
6464 if (gui.in_use)
6465 return;
6466# endif
6467
Bram Moolenaar071d4272004-06-13 20:20:40 +00006468 if (!term_console)
6469 {
6470 write(1, s, (unsigned)len);
6471 return;
6472 }
6473
Bram Moolenaar0f873732019-12-05 20:28:46 +01006474 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00006475 while (len--)
6476 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006477 int prefix = -1;
6478 char_u ch;
6479
6480 // While processing a sequence, on rare occasions it seems that another
6481 // sequence may be inserted asynchronously.
6482 if (len < 0)
6483 {
6484 redraw_all_later(CLEAR);
6485 return;
6486 }
6487
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006488 while (s + ++prefix < end)
6489 {
6490 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006491 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6492 && ch != '\a' && ch != '\033'))
6493 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006494 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006495
6496 if (p_wd)
6497 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006498 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006499 if (prefix != 0)
6500 prefix = 1;
6501 }
6502
6503 if (prefix != 0)
6504 {
6505 DWORD nWritten;
6506
6507 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006508# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006509 if (fdDump)
6510 {
6511 fputc('>', fdDump);
6512 fwrite(s, sizeof(char_u), nWritten, fdDump);
6513 fputs("<\n", fdDump);
6514 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006515# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006516 len -= (nWritten - 1);
6517 s += nWritten;
6518 }
6519 else if (s[0] == '\n')
6520 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006521 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00006522 if (g_coord.Y == g_srScrollRegion.Bottom)
6523 {
6524 scroll(1);
6525 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6526 }
6527 else
6528 {
6529 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6530 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006531# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006532 if (fdDump)
6533 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006534# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006535 s++;
6536 }
6537 else if (s[0] == '\r')
6538 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006539 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00006540 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006541# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006542 if (fdDump)
6543 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006544# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006545 s++;
6546 }
6547 else if (s[0] == '\b')
6548 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006549 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00006550 if (g_coord.X > g_srScrollRegion.Left)
6551 g_coord.X--;
6552 else if (g_coord.Y > g_srScrollRegion.Top)
6553 {
6554 g_coord.X = g_srScrollRegion.Right;
6555 g_coord.Y--;
6556 }
6557 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006558# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006559 if (fdDump)
6560 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006561# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006562 s++;
6563 }
6564 else if (s[0] == '\a')
6565 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006566 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00006567 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006568# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006569 if (fdDump)
6570 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006571# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006572 s++;
6573 }
6574 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6575 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006576# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006577 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006578# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006579 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006580 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006581 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006582
6583 switch (s[2])
6584 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006585 case '0': case '1': case '2': case '3': case '4':
6586 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006587 if (*(p = get_seq(args, &argc, s)) != 'm')
6588 goto notsgr;
6589
6590 p = s;
6591
6592 // Handling frequent optional sequences. Output to the screen
6593 // takes too long, so do not output as much as possible.
6594
6595 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
6596 // resetFG,FG,BG are omitted.
6597 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006598 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006599 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
6600 len = len + 1 - (int)(p - s);
6601 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006602 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006603 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006604
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006605 // If FG,BG,BG,FG of SGR are connected, the first FG can be
6606 // omitted.
6607 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
6608 p = sp;
6609
6610 // If FG,BG,FG,BG of SGR are connected, the first FG can be
6611 // omitted.
6612 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
6613 p = sp;
6614
6615 // If BG,BG of SGR are connected, the first BG can be omitted.
6616 if (sgrn2((sp = sgrn2(p, 48)), 48))
6617 p = sp;
6618
6619 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01006620 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006621 if (sgrn2((sp = sgrnc(p, 39)), 38))
6622 p = sp;
6623
6624 p = get_seq(args, &argc, p);
6625
6626notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006627 arg1 = args[0];
6628 arg2 = args[1];
6629 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006630 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006631 if (argc == 1 && args[0] == 0)
6632 normvideo();
6633 else if (argc == 1)
6634 {
6635 if (USE_VTP)
6636 textcolor((WORD) arg1);
6637 else
6638 textattr((WORD) arg1);
6639 }
6640 else if (USE_VTP)
6641 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006642 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006643 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006644 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006645 gotoxy(arg2, arg1);
6646 }
6647 else if (argc == 2 && *p == 'r')
6648 {
6649 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6650 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006651 else if (argc == 2 && *p == 'R')
6652 {
6653 set_scroll_region_tb(arg1, arg2);
6654 }
6655 else if (argc == 2 && *p == 'V')
6656 {
6657 set_scroll_region_lr(arg1, arg2);
6658 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006659 else if (argc == 1 && *p == 'A')
6660 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006661 gotoxy(g_coord.X + 1,
6662 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6663 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006664 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006665 {
6666 textbackground((WORD) arg1);
6667 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006668 else if (argc == 1 && *p == 'C')
6669 {
6670 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6671 g_coord.Y + 1);
6672 }
6673 else if (argc == 1 && *p == 'f')
6674 {
6675 textcolor((WORD) arg1);
6676 }
6677 else if (argc == 1 && *p == 'H')
6678 {
6679 gotoxy(1, arg1);
6680 }
6681 else if (argc == 1 && *p == 'L')
6682 {
6683 insert_lines(arg1);
6684 }
6685 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006686 {
6687 delete_lines(arg1);
6688 }
6689
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006690 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006691 s = p + 1;
6692 break;
6693
Bram Moolenaar071d4272004-06-13 20:20:40 +00006694 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006695 gotoxy(g_coord.X + 1,
6696 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6697 goto got3;
6698
6699 case 'B':
6700 visual_bell();
6701 goto got3;
6702
6703 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006704 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6705 g_coord.Y + 1);
6706 goto got3;
6707
6708 case 'E':
6709 termcap_mode_end();
6710 goto got3;
6711
6712 case 'F':
6713 standout();
6714 goto got3;
6715
6716 case 'f':
6717 standend();
6718 goto got3;
6719
6720 case 'H':
6721 gotoxy(1, 1);
6722 goto got3;
6723
6724 case 'j':
6725 clear_to_end_of_display();
6726 goto got3;
6727
6728 case 'J':
6729 clear_screen();
6730 goto got3;
6731
6732 case 'K':
6733 clear_to_end_of_line();
6734 goto got3;
6735
6736 case 'L':
6737 insert_lines(1);
6738 goto got3;
6739
6740 case 'M':
6741 delete_lines(1);
6742 goto got3;
6743
6744 case 'S':
6745 termcap_mode_start();
6746 goto got3;
6747
6748 case 'V':
6749 cursor_visible(TRUE);
6750 goto got3;
6751
6752 case 'v':
6753 cursor_visible(FALSE);
6754 goto got3;
6755
6756 got3:
6757 s += 3;
6758 len -= 2;
6759 }
6760
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006761# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006762 if (fdDump)
6763 {
6764 fputs("ESC | ", fdDump);
6765 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6766 fputc('\n', fdDump);
6767 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006768# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006769 }
6770 else
6771 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006772 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00006773 DWORD nWritten;
6774
6775 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006776# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006777 if (fdDump)
6778 {
6779 fputc('>', fdDump);
6780 fwrite(s, sizeof(char_u), nWritten, fdDump);
6781 fputs("<\n", fdDump);
6782 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006783# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006784
6785 len -= (nWritten - 1);
6786 s += nWritten;
6787 }
6788 }
6789
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006790# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006791 if (fdDump)
6792 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006793# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006794}
6795
Bram Moolenaar0f873732019-12-05 20:28:46 +01006796#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006797
6798
6799/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006800 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006801 */
6802 void
6803mch_delay(
6804 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02006805 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006806{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006807#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006808 Sleep((int)msec); // never wait for input
6809#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006810# ifdef VIMDLL
6811 if (gui.in_use)
6812 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006813 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006814 return;
6815 }
6816# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02006817 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006818# ifdef FEAT_MZSCHEME
6819 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6820 {
6821 int towait = p_mzq;
6822
Bram Moolenaar0f873732019-12-05 20:28:46 +01006823 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006824 while (msec > 0)
6825 {
6826 mzvim_check_threads();
6827 if (msec < towait)
6828 towait = msec;
6829 Sleep(towait);
6830 msec -= towait;
6831 }
6832 }
6833 else
6834# endif
6835 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006836 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006837 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006838#endif
6839}
6840
6841
6842/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006843 * This version of remove is not scared by a readonly (backup) file.
6844 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006845 * Return 0 for success, -1 for failure.
6846 */
6847 int
6848mch_remove(char_u *name)
6849{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006850 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006851 int n;
6852
Bram Moolenaar203258c2016-01-17 22:15:16 +01006853 /*
6854 * On Windows, deleting a directory's symbolic link is done by
6855 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6856 */
6857 if (mch_isdir(name) && mch_is_symbolic_link(name))
6858 return mch_rmdir(name);
6859
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006860 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6861
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006862 wn = enc_to_utf16(name, NULL);
6863 if (wn == NULL)
6864 return -1;
6865
6866 n = DeleteFileW(wn) ? 0 : -1;
6867 vim_free(wn);
6868 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006869}
6870
6871
6872/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006873 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006874 */
6875 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006876mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006877{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006878#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
6879# ifdef VIMDLL
6880 if (!gui.in_use)
6881# endif
6882 if (g_fCtrlCPressed || g_fCBrkPressed)
6883 {
6884 ctrl_break_was_pressed = g_fCBrkPressed;
6885 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6886 got_int = TRUE;
6887 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006888#endif
6889}
6890
Bram Moolenaar0f873732019-12-05 20:28:46 +01006891// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01006892#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006893
6894/*
6895 * How much main memory in KiB that can be used by VIM.
6896 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006897 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006898mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006899{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006900 MEMORYSTATUSEX ms;
6901
Bram Moolenaar0f873732019-12-05 20:28:46 +01006902 // Need to use GlobalMemoryStatusEx() when there is more memory than
6903 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006904 ms.dwLength = sizeof(MEMORYSTATUSEX);
6905 GlobalMemoryStatusEx(&ms);
6906 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006907 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006908 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006909 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006910 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006911 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006912 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006913 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006914 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006915 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01006916 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006917 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006918}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006919
Bram Moolenaar071d4272004-06-13 20:20:40 +00006920/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006921 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00006922 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6923 * file whose short file name is "FOO.BAR" (its long file name will
6924 * be correct: "foo.bar~"). Because a file can be accessed by
6925 * either its SFN or its LFN, "foo.bar" has effectively been
6926 * renamed to "foo.bar", which is not at all what was wanted. This
6927 * seems to happen only when renaming files with three-character
6928 * extensions by appending a suffix that does not include ".".
6929 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6930 *
6931 * There is another problem, which isn't really a bug but isn't right either:
6932 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6933 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6934 * service pack 6. Doesn't seem to happen on Windows 98.
6935 *
6936 * Like rename(), returns 0 upon success, non-zero upon failure.
6937 * Should probably set errno appropriately when errors occur.
6938 */
6939 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006940mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006941{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006942 WCHAR *p;
6943 int i;
6944 WCHAR szTempFile[_MAX_PATH + 1];
6945 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006946 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006947
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006948 // No need to play tricks unless the file name contains a "~" as the
6949 // seventh character.
6950 p = wold;
6951 for (i = 0; wold[i] != NUL; ++i)
6952 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6953 && wold[i + 1] != 0)
6954 p = wold + i + 1;
6955 if ((int)(wold + i - p) < 8 || p[6] != '~')
6956 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006957
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006958 // Get base path of new file name. Undocumented feature: If pszNewFile is
6959 // a directory, no error is returned and pszFilePart will be NULL.
6960 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006961 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006962 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006963
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006964 // Get (and create) a unique temporary file name in directory of new file
6965 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006966 return -2;
6967
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006968 // blow the temp file away
6969 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006970 return -3;
6971
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006972 // rename old file to the temp file
6973 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006974 return -4;
6975
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006976 // now create an empty file called pszOldFile; this prevents the operating
6977 // system using pszOldFile as an alias (SFN) if we're renaming within the
6978 // same directory. For example, we're editing a file called
6979 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6980 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
6981 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
6982 // cause all sorts of problems later in buf_write(). So, we create an
6983 // empty file called filena~1.txt and the system will have to find some
6984 // other SFN for filena~1.txt~, such as filena~2.txt
6985 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006986 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6987 return -5;
6988 if (!CloseHandle(hf))
6989 return -6;
6990
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006991 // rename the temp file to the new file
6992 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006993 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006994 // Renaming failed. Rename the file back to its old name, so that it
6995 // looks like nothing happened.
6996 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006997 return -7;
6998 }
6999
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007000 // Seems to be left around on Novell filesystems
7001 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007002
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007003 // finally, remove the empty old file
7004 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007005 return -8;
7006
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007007 return 0;
7008}
7009
7010
7011/*
7012 * Converts the filenames to UTF-16, then call mch_wrename().
7013 * Like rename(), returns 0 upon success, non-zero upon failure.
7014 */
7015 int
7016mch_rename(
7017 const char *pszOldFile,
7018 const char *pszNewFile)
7019{
7020 WCHAR *wold = NULL;
7021 WCHAR *wnew = NULL;
7022 int retval = -1;
7023
7024 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7025 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7026 if (wold != NULL && wnew != NULL)
7027 retval = mch_wrename(wold, wnew);
7028 vim_free(wold);
7029 vim_free(wnew);
7030 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007031}
7032
7033/*
7034 * Get the default shell for the current hardware platform
7035 */
7036 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007037default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007038{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007039 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007040}
7041
7042/*
7043 * mch_access() extends access() to do more detailed check on network drives.
7044 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7045 */
7046 int
7047mch_access(char *n, int p)
7048{
7049 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007050 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007051 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007052
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007053 wn = enc_to_utf16((char_u *)n, NULL);
7054 if (wn == NULL)
7055 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007056
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007057 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007058 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007059 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007060
7061 if (p & R_OK)
7062 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007063 // Read check is performed by seeing if we can do a find file on
7064 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007065 int i;
7066 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007067
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007068 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7069 TempNameW[i] = wn[i];
7070 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7071 TempNameW[i++] = '\\';
7072 TempNameW[i++] = '*';
7073 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007074
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007075 hFile = FindFirstFileW(TempNameW, &d);
7076 if (hFile == INVALID_HANDLE_VALUE)
7077 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007078 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007079 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007080 }
7081
7082 if (p & W_OK)
7083 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007084 // Trying to create a temporary file in the directory should catch
7085 // directories on read-only network shares. However, in
7086 // directories whose ACL allows writes but denies deletes will end
7087 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007088 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7089 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007090 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007091 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007092 }
7093 }
7094 else
7095 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007096 // Don't consider a file read-only if another process has opened it.
7097 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7098
Bram Moolenaar0f873732019-12-05 20:28:46 +01007099 // Trying to open the file for the required access does ACL, read-only
7100 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007101 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7102 | ((p & R_OK) ? GENERIC_READ : 0);
7103
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007104 hFile = CreateFileW(wn, access_mode, share_mode,
7105 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007106 if (hFile == INVALID_HANDLE_VALUE)
7107 goto getout;
7108 CloseHandle(hFile);
7109 }
7110
Bram Moolenaar0f873732019-12-05 20:28:46 +01007111 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007112getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007113 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007114 return retval;
7115}
7116
Bram Moolenaar071d4272004-06-13 20:20:40 +00007117/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007118 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007119 */
7120 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007121mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007122{
7123 WCHAR *wn;
7124 int f;
7125
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007126 wn = enc_to_utf16((char_u *)name, NULL);
7127 if (wn == NULL)
7128 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007129
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007130 f = _wopen(wn, flags, mode);
7131 vim_free(wn);
7132 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007133}
7134
7135/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007136 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007137 */
7138 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007139mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007140{
7141 WCHAR *wn, *wm;
7142 FILE *f = NULL;
7143
Bram Moolenaara12a1612019-01-24 16:39:02 +01007144#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007145 // Work around an annoying assertion in the Microsoft debug CRT
7146 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007147 char newMode = mode[strlen(mode) - 1];
7148 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007149
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007150 _get_fmode(&oldMode);
7151 if (newMode == 't')
7152 _set_fmode(_O_TEXT);
7153 else if (newMode == 'b')
7154 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007155#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007156 wn = enc_to_utf16((char_u *)name, NULL);
7157 wm = enc_to_utf16((char_u *)mode, NULL);
7158 if (wn != NULL && wm != NULL)
7159 f = _wfopen(wn, wm);
7160 vim_free(wn);
7161 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007162
Bram Moolenaara12a1612019-01-24 16:39:02 +01007163#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007164 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007165#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007166 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007167}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007168
Bram Moolenaar071d4272004-06-13 20:20:40 +00007169/*
7170 * SUB STREAM (aka info stream) handling:
7171 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007172 * NTFS can have sub streams for each file. The normal contents of a file is
7173 * stored in the main stream, and extra contents (author information, title and
7174 * so on) can be stored in a sub stream. After Windows 2000, the user can
7175 * access and store this information in sub streams via an explorer's property
7176 * menu item in the right click menu. This information in sub streams was lost
7177 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007178 *
7179 * Incomplete explanation:
7180 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7181 * More useful info and an example:
7182 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7183 */
7184
7185/*
7186 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7187 * and write to stream "substream" of file "to".
7188 * Errors are ignored.
7189 */
7190 static void
7191copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7192{
7193 HANDLE hTo;
7194 WCHAR *to_name;
7195
7196 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7197 wcscpy(to_name, to);
7198 wcscat(to_name, substream);
7199
7200 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7201 FILE_ATTRIBUTE_NORMAL, NULL);
7202 if (hTo != INVALID_HANDLE_VALUE)
7203 {
7204 long done;
7205 DWORD todo;
7206 DWORD readcnt, written;
7207 char buf[4096];
7208
Bram Moolenaar0f873732019-12-05 20:28:46 +01007209 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007210 for (done = 0; done < len; done += written)
7211 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007212 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007213 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7214 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007215 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7216 FALSE, FALSE, context)
7217 || readcnt != todo
7218 || !WriteFile(hTo, buf, todo, &written, NULL)
7219 || written != todo)
7220 break;
7221 }
7222 CloseHandle(hTo);
7223 }
7224
7225 free(to_name);
7226}
7227
7228/*
7229 * Copy info streams from file "from" to file "to".
7230 */
7231 static void
7232copy_infostreams(char_u *from, char_u *to)
7233{
7234 WCHAR *fromw;
7235 WCHAR *tow;
7236 HANDLE sh;
7237 WIN32_STREAM_ID sid;
7238 int headersize;
7239 WCHAR streamname[_MAX_PATH];
7240 DWORD readcount;
7241 void *context = NULL;
7242 DWORD lo, hi;
7243 int len;
7244
Bram Moolenaar0f873732019-12-05 20:28:46 +01007245 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007246 fromw = enc_to_utf16(from, NULL);
7247 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007248 if (fromw != NULL && tow != NULL)
7249 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007250 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007251 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7252 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7253 if (sh != INVALID_HANDLE_VALUE)
7254 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007255 // Use BackupRead() to find the info streams. Repeat until we
7256 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007257 for (;;)
7258 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007259 // Get the header to find the length of the stream name. If
7260 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007261 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007262 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007263 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7264 &readcount, FALSE, FALSE, &context)
7265 || readcount == 0)
7266 break;
7267
Bram Moolenaar0f873732019-12-05 20:28:46 +01007268 // We only deal with streams that have a name. The normal
7269 // file data appears to be without a name, even though docs
7270 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007271 if (sid.dwStreamNameSize > 0)
7272 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007273 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007274 if (!BackupRead(sh, (LPBYTE)streamname,
7275 sid.dwStreamNameSize,
7276 &readcount, FALSE, FALSE, &context))
7277 break;
7278
Bram Moolenaar0f873732019-12-05 20:28:46 +01007279 // Copy an info stream with a name ":anything:$DATA".
7280 // Skip "::$DATA", it has no stream name (examples suggest
7281 // it might be used for the normal file contents).
7282 // Note that BackupRead() counts bytes, but the name is in
7283 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007284 len = readcount / sizeof(WCHAR);
7285 streamname[len] = 0;
7286 if (len > 7 && wcsicmp(streamname + len - 6,
7287 L":$DATA") == 0)
7288 {
7289 streamname[len - 6] = 0;
7290 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007291 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007292 }
7293 }
7294
Bram Moolenaar0f873732019-12-05 20:28:46 +01007295 // Advance to the next stream. We might try seeking too far,
7296 // but BackupSeek() doesn't skip over stream borders, thus
7297 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007298 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007299 &lo, &hi, &context);
7300 }
7301
Bram Moolenaar0f873732019-12-05 20:28:46 +01007302 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007303 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7304
7305 CloseHandle(sh);
7306 }
7307 }
7308 vim_free(fromw);
7309 vim_free(tow);
7310}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007311
7312/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007313 * ntdll.dll definitions
7314 */
7315#define FileEaInformation 7
7316#ifndef STATUS_SUCCESS
7317# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7318#endif
7319
7320typedef struct _FILE_FULL_EA_INFORMATION_ {
7321 ULONG NextEntryOffset;
7322 UCHAR Flags;
7323 UCHAR EaNameLength;
7324 USHORT EaValueLength;
7325 CHAR EaName[1];
7326} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7327
7328typedef struct _FILE_EA_INFORMATION_ {
7329 ULONG EaSize;
7330} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7331
Paul Ollis65745772022-06-05 16:55:54 +01007332#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007333typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7334 PHANDLE FileHandle,
7335 ACCESS_MASK DesiredAccess,
7336 POBJECT_ATTRIBUTES ObjectAttributes,
7337 PIO_STATUS_BLOCK IoStatusBlock,
7338 ULONG ShareAccess,
7339 ULONG OpenOptions);
7340typedef NTSTATUS (NTAPI *PfnNtClose)(
7341 HANDLE Handle);
7342typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007343 HANDLE FileHandle,
7344 PIO_STATUS_BLOCK IoStatusBlock,
7345 PVOID Buffer,
7346 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007347typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7348 HANDLE FileHandle,
7349 PIO_STATUS_BLOCK IoStatusBlock,
7350 PVOID Buffer,
7351 ULONG Length,
7352 BOOLEAN ReturnSingleEntry,
7353 PVOID EaList,
7354 ULONG EaListLength,
7355 PULONG EaIndex,
7356 BOOLEAN RestartScan);
7357typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007358 HANDLE FileHandle,
7359 PIO_STATUS_BLOCK IoStatusBlock,
7360 PVOID FileInformation,
7361 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007362 FILE_INFORMATION_CLASS FileInformationClass);
7363typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7364 PUNICODE_STRING DestinationString,
7365 PCWSTR SourceString);
7366
7367PfnNtOpenFile pNtOpenFile = NULL;
7368PfnNtClose pNtClose = NULL;
7369PfnNtSetEaFile pNtSetEaFile = NULL;
7370PfnNtQueryEaFile pNtQueryEaFile = NULL;
7371PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7372PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01007373#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007374
7375/*
7376 * Load ntdll.dll functions.
7377 */
7378 static BOOL
7379load_ntdll(void)
7380{
7381 static int loaded = -1;
7382
7383 if (loaded == -1)
7384 {
7385 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7386 if (hNtdll != NULL)
7387 {
7388 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7389 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7390 pNtSetEaFile = (PfnNtSetEaFile)
7391 GetProcAddress(hNtdll, "NtSetEaFile");
7392 pNtQueryEaFile = (PfnNtQueryEaFile)
7393 GetProcAddress(hNtdll, "NtQueryEaFile");
7394 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7395 GetProcAddress(hNtdll, "NtQueryInformationFile");
7396 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7397 GetProcAddress(hNtdll, "RtlInitUnicodeString");
7398 }
7399 if (pNtOpenFile == NULL
7400 || pNtClose == NULL
7401 || pNtSetEaFile == NULL
7402 || pNtQueryEaFile == NULL
7403 || pNtQueryInformationFile == NULL
7404 || pRtlInitUnicodeString == NULL)
7405 loaded = FALSE;
7406 else
7407 loaded = TRUE;
7408 }
7409 return (BOOL) loaded;
7410}
7411
7412/*
7413 * Copy extended attributes (EA) from file "from" to file "to".
7414 */
7415 static void
7416copy_extattr(char_u *from, char_u *to)
7417{
7418 char_u *fromf = NULL;
7419 char_u *tof = NULL;
7420 WCHAR *fromw = NULL;
7421 WCHAR *tow = NULL;
7422 UNICODE_STRING u;
7423 HANDLE h;
7424 OBJECT_ATTRIBUTES oa;
7425 IO_STATUS_BLOCK iosb;
7426 FILE_EA_INFORMATION_ eainfo = {0};
7427 void *ea = NULL;
7428
7429 if (!load_ntdll())
7430 return;
7431
7432 // Convert the file names to the fully qualified object names.
7433 fromf = alloc(STRLEN(from) + 5);
7434 tof = alloc(STRLEN(to) + 5);
7435 if (fromf == NULL || tof == NULL)
7436 goto theend;
7437 STRCPY(fromf, "\\??\\");
7438 STRCAT(fromf, from);
7439 STRCPY(tof, "\\??\\");
7440 STRCAT(tof, to);
7441
7442 // Convert the names to wide characters.
7443 fromw = enc_to_utf16(fromf, NULL);
7444 tow = enc_to_utf16(tof, NULL);
7445 if (fromw == NULL || tow == NULL)
7446 goto theend;
7447
7448 // Get the EA.
7449 pRtlInitUnicodeString(&u, fromw);
7450 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7451 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7452 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7453 goto theend;
7454 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7455 FileEaInformation);
7456 if (eainfo.EaSize != 0)
7457 {
7458 ea = alloc(eainfo.EaSize);
7459 if (ea != NULL)
7460 {
7461 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7462 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7463 {
7464 vim_free(ea);
7465 ea = NULL;
7466 }
7467 }
7468 }
7469 pNtClose(h);
7470
7471 // Set the EA.
7472 if (ea != NULL)
7473 {
7474 pRtlInitUnicodeString(&u, tow);
7475 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7476 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7477 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7478 goto theend;
7479
7480 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
7481 pNtClose(h);
7482 }
7483
7484theend:
7485 vim_free(fromf);
7486 vim_free(tof);
7487 vim_free(fromw);
7488 vim_free(tow);
7489 vim_free(ea);
7490}
7491
7492/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007493 * Copy file attributes from file "from" to file "to".
7494 * For Windows NT and later we copy info streams.
7495 * Always returns zero, errors are ignored.
7496 */
7497 int
7498mch_copy_file_attribute(char_u *from, char_u *to)
7499{
Bram Moolenaar0f873732019-12-05 20:28:46 +01007500 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007501 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007502 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007503 return 0;
7504}
7505
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007506
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007507/*
K.Takatadc73b4b2021-06-08 18:32:36 +02007508 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007509 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007510static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007511static LPWSTR *ArglistW = NULL;
7512static int global_argc = 0;
7513static char **global_argv;
7514
Bram Moolenaar0f873732019-12-05 20:28:46 +01007515static int used_file_argc = 0; // last argument in global_argv[] used
7516 // for the argument list.
7517static int *used_file_indexes = NULL; // indexes in global_argv[] for
7518 // command line arguments added to
7519 // the argument list
7520static int used_file_count = 0; // nr of entries in used_file_indexes
7521static int used_file_literal = FALSE; // take file names literally
7522static int used_file_full_path = FALSE; // file name was full path
7523static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007524static int used_alist_count = 0;
7525
7526
7527/*
7528 * Get the command line arguments. Unicode version.
7529 * Returns argc. Zero when something fails.
7530 */
7531 int
7532get_cmd_argsW(char ***argvp)
7533{
7534 char **argv = NULL;
7535 int argc = 0;
7536 int i;
7537
Bram Moolenaar14993322014-09-09 12:25:33 +02007538 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007539 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7540 if (ArglistW != NULL)
7541 {
7542 argv = malloc((nArgsW + 1) * sizeof(char *));
7543 if (argv != NULL)
7544 {
7545 argc = nArgsW;
7546 argv[argc] = NULL;
7547 for (i = 0; i < argc; ++i)
7548 {
7549 int len;
7550
K.Takatadc73b4b2021-06-08 18:32:36 +02007551 // Convert each Unicode argument to UTF-8.
7552 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007553 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007554 (LPSTR *)&argv[i], &len, 0, 0);
7555 if (argv[i] == NULL)
7556 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007557 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007558 while (i > 0)
7559 free(argv[--i]);
7560 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007561 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007562 argc = 0;
7563 }
7564 }
7565 }
7566 }
7567
7568 global_argc = argc;
7569 global_argv = argv;
7570 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007571 {
7572 if (used_file_indexes != NULL)
7573 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007574 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007575 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007576
7577 if (argvp != NULL)
7578 *argvp = argv;
7579 return argc;
7580}
7581
7582 void
7583free_cmd_argsW(void)
7584{
7585 if (ArglistW != NULL)
7586 {
7587 GlobalFree(ArglistW);
7588 ArglistW = NULL;
7589 }
7590}
7591
7592/*
7593 * Remember "name" is an argument that was added to the argument list.
7594 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7595 * is called.
7596 */
7597 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007598used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007599{
7600 int i;
7601
7602 if (used_file_indexes == NULL)
7603 return;
7604 for (i = used_file_argc + 1; i < global_argc; ++i)
7605 if (STRCMP(global_argv[i], name) == 0)
7606 {
7607 used_file_argc = i;
7608 used_file_indexes[used_file_count++] = i;
7609 break;
7610 }
7611 used_file_literal = literal;
7612 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007613 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007614}
7615
7616/*
7617 * Remember the length of the argument list as it was. If it changes then we
7618 * leave it alone when 'encoding' is set.
7619 */
7620 void
7621set_alist_count(void)
7622{
7623 used_alist_count = GARGCOUNT;
7624}
7625
7626/*
7627 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02007628 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007629 * and convert them to 'encoding'.
7630 */
7631 void
7632fix_arg_enc(void)
7633{
7634 int i;
7635 int idx;
7636 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007637 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007638
Bram Moolenaar0f873732019-12-05 20:28:46 +01007639 // Safety checks:
7640 // - if argument count differs between the wide and non-wide argument
7641 // list, something must be wrong.
7642 // - the file name arguments must have been located.
7643 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007644 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007645 || ArglistW == NULL
7646 || used_file_indexes == NULL
7647 || used_file_count == 0
7648 || used_alist_count != GARGCOUNT)
7649 return;
7650
Bram Moolenaar0f873732019-12-05 20:28:46 +01007651 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007652 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007653 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007654 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00007655 for (i = 0; i < GARGCOUNT; ++i)
7656 fnum_list[i] = GARGLIST[i].ae_fnum;
7657
Bram Moolenaar0f873732019-12-05 20:28:46 +01007658 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007659 alist_clear(&global_alist);
7660 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007661 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007662
7663 for (i = 0; i < used_file_count; ++i)
7664 {
7665 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007666 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007667 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007668 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007669 int literal = used_file_literal;
7670
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007671#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01007672 // When using diff mode may need to concatenate file name to
7673 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007674 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7675 && !mch_isdir(alist_name(&GARGLIST[0])))
7676 {
7677 char_u *r;
7678
7679 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7680 if (r != NULL)
7681 {
7682 vim_free(str);
7683 str = r;
7684 }
7685 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007686#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01007687 // Re-use the old buffer by renaming it. When not using literal
7688 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00007689 if (used_file_literal)
7690 buf_set_name(fnum_list[i], str);
7691
Bram Moolenaar0f873732019-12-05 20:28:46 +01007692 // Check backtick literal. backtick literal is already expanded in
7693 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007694 if (literal == FALSE)
7695 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007696 size_t len = STRLEN(str);
7697
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007698 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7699 literal = TRUE;
7700 }
7701 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007702 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007703 }
7704
7705 if (!used_file_literal)
7706 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007707 // Now expand wildcards in the arguments.
7708 // Temporarily add '(' and ')' to 'isfname'. These are valid
7709 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00007710 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01007711 // Also, unset wildignore to not be influenced by this option.
7712 // The arguments specified in command-line should be kept even if
7713 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00007714 // Use :legacy so that it also works when in Vim9 script.
7715 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
7716 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007717 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00007718 do_cmdline_cmd(
7719 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
7720 do_cmdline_cmd(
7721 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007722 }
7723
Bram Moolenaar0f873732019-12-05 20:28:46 +01007724 // If wildcard expansion failed, we are editing the first file of the
7725 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007726 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7727 {
7728 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00007729 if (GARGCOUNT == 1 && used_file_full_path
7730 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
7731 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007732 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007733
7734 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007735}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007736
7737 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007738mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007739{
7740 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007741 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007742
Bram Moolenaar964b3742019-05-24 18:54:09 +02007743 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007744 if (envbuf == NULL)
7745 return -1;
7746
7747 sprintf((char *)envbuf, "%s=%s", var, value);
7748
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007749 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007750
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007751 vim_free(envbuf);
7752 if (p == NULL)
7753 return -1;
7754 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007755#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007756 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007757#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007758 // Unlike Un*x systems, we can free the string for _wputenv().
7759 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007760
7761 return 0;
7762}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007763
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007764/*
7765 * Support for 256 colors and 24-bit colors was added in Windows 10
7766 * version 1703 (Creators update).
7767 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007768#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7769
7770/*
7771 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02007772 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007773 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007774#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007775
7776/*
7777 * ConPTY differences between versions, need different logic.
7778 * version 1903 (May 2019 update).
7779 */
7780#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
7781
7782/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007783 * version 1909 (November 2019 update).
7784 */
7785#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
7786
7787/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007788 * Stay ahead of the next update, and when it's done, fix this.
7789 * version ? (2020 update, temporarily use the build number of insider preview)
7790 */
7791#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
7792
7793/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02007794 * Confirm until this version. Also the logic changes.
7795 * insider preview.
7796 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02007797#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007798
7799/*
7800 * Not stable now.
7801 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007802#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007803
7804 static void
7805vtp_flag_init(void)
7806{
7807 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007808#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007809 DWORD mode;
7810 HANDLE out;
7811
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007812# ifdef VIMDLL
7813 if (!gui.in_use)
7814# endif
7815 {
7816 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007817
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007818 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7819 GetConsoleMode(out, &mode);
7820 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7821 if (SetConsoleMode(out, mode) == 0)
7822 vtp_working = 0;
7823 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007824#endif
7825
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007826 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007827 conpty_working = 1;
7828 if (ver >= CONPTY_STABLE_BUILD)
7829 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007830
Bram Moolenaar57da6982019-09-13 22:30:11 +02007831 if (ver <= CONPTY_INSIDER_BUILD)
7832 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007833 if (ver <= CONPTY_1909_BUILD)
7834 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02007835 if (ver <= CONPTY_1903_BUILD)
7836 conpty_type = 2;
7837 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
7838 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007839
7840 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
7841 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007842}
7843
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007844#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007845
7846 static void
7847vtp_init(void)
7848{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007849 HMODULE hKerneldll;
7850 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007851# ifdef FEAT_TERMGUICOLORS
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01007852 COLORREF fg;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007853# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007854
Bram Moolenaar0f873732019-12-05 20:28:46 +01007855 // Use functions supported from Vista
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007856 hKerneldll = GetModuleHandle("kernel32.dll");
7857 if (hKerneldll != NULL)
7858 {
7859 pGetConsoleScreenBufferInfoEx =
7860 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7861 hKerneldll, "GetConsoleScreenBufferInfoEx");
7862 pSetConsoleScreenBufferInfoEx =
7863 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7864 hKerneldll, "SetConsoleScreenBufferInfoEx");
7865 if (pGetConsoleScreenBufferInfoEx != NULL
7866 && pSetConsoleScreenBufferInfoEx != NULL)
7867 has_csbiex = TRUE;
7868 }
7869
7870 csbi.cbSize = sizeof(csbi);
7871 if (has_csbiex)
7872 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007873 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7874 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
Bram Moolenaardf543822020-01-30 11:53:59 +01007875 store_console_bg_rgb = save_console_bg_rgb;
7876 store_console_fg_rgb = save_console_fg_rgb;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007877
7878# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007879 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007880 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007881 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007882# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007883
7884 set_console_color_rgb();
7885}
7886
7887 static void
7888vtp_exit(void)
7889{
Bram Moolenaardf543822020-01-30 11:53:59 +01007890 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007891}
7892
Bram Moolenaar06b7b582020-05-30 17:49:25 +02007893 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007894vtp_printf(
7895 char *format,
7896 ...)
7897{
7898 char_u buf[100];
7899 va_list list;
7900 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007901 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007902
7903 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007904 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007905 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007906 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007907 return (int)result;
7908}
7909
7910 static void
7911vtp_sgr_bulk(
7912 int arg)
7913{
7914 int args[1];
7915
7916 args[0] = arg;
7917 vtp_sgr_bulks(1, args);
7918}
7919
K.Takata6e1d31e2022-02-03 13:05:32 +00007920# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007921 if ((*p-- = "0123456789"[(n = x % 10)]) \
7922 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
7923 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
7924
K.Takata6e1d31e2022-02-03 13:05:32 +00007925# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007926 case x: \
7927 FAST256(newargs[x - 1]);
7928
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007929 static void
7930vtp_sgr_bulks(
7931 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007932 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007933{
K.Takata6e1d31e2022-02-03 13:05:32 +00007934# define MAXSGR 16
7935# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007936 char_u buf[SGRBUFSIZE];
7937 char_u *p;
7938 int in, out;
7939 int newargs[16];
7940 static int sgrfgr = -1, sgrfgg, sgrfgb;
7941 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007942
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007943 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007944 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007945 sgrfgr = sgrbgr = -1;
7946 vtp_printf("033[m");
7947 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007948 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007949
7950 in = out = 0;
7951 while (in < argc)
7952 {
7953 int s = args[in];
7954 int copylen = 1;
7955
7956 if (s == 38)
7957 {
7958 if (argc - in >= 5 && args[in + 1] == 2)
7959 {
7960 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
7961 && sgrfgb == args[in + 4])
7962 {
7963 in += 5;
7964 copylen = 0;
7965 }
7966 else
7967 {
7968 sgrfgr = args[in + 2];
7969 sgrfgg = args[in + 3];
7970 sgrfgb = args[in + 4];
7971 copylen = 5;
7972 }
7973 }
7974 else if (argc - in >= 3 && args[in + 1] == 5)
7975 {
7976 sgrfgr = -1;
7977 copylen = 3;
7978 }
7979 }
7980 else if (s == 48)
7981 {
7982 if (argc - in >= 5 && args[in + 1] == 2)
7983 {
7984 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
7985 && sgrbgb == args[in + 4])
7986 {
7987 in += 5;
7988 copylen = 0;
7989 }
7990 else
7991 {
7992 sgrbgr = args[in + 2];
7993 sgrbgg = args[in + 3];
7994 sgrbgb = args[in + 4];
7995 copylen = 5;
7996 }
7997 }
7998 else if (argc - in >= 3 && args[in + 1] == 5)
7999 {
8000 sgrbgr = -1;
8001 copylen = 3;
8002 }
8003 }
8004 else if (30 <= s && s <= 39)
8005 sgrfgr = -1;
8006 else if (90 <= s && s <= 97)
8007 sgrfgr = -1;
8008 else if (40 <= s && s <= 49)
8009 sgrbgr = -1;
8010 else if (100 <= s && s <= 107)
8011 sgrbgr = -1;
8012 else if (s == 0)
8013 sgrfgr = sgrbgr = -1;
8014
8015 while (copylen--)
8016 newargs[out++] = args[in++];
8017 }
8018
8019 p = &buf[sizeof(buf) - 1];
8020 *p-- = 'm';
8021
8022 switch (out)
8023 {
8024 int n, m;
8025 DWORD r;
8026
8027 FAST256CASE(16);
8028 *p-- = ';';
8029 FAST256CASE(15);
8030 *p-- = ';';
8031 FAST256CASE(14);
8032 *p-- = ';';
8033 FAST256CASE(13);
8034 *p-- = ';';
8035 FAST256CASE(12);
8036 *p-- = ';';
8037 FAST256CASE(11);
8038 *p-- = ';';
8039 FAST256CASE(10);
8040 *p-- = ';';
8041 FAST256CASE(9);
8042 *p-- = ';';
8043 FAST256CASE(8);
8044 *p-- = ';';
8045 FAST256CASE(7);
8046 *p-- = ';';
8047 FAST256CASE(6);
8048 *p-- = ';';
8049 FAST256CASE(5);
8050 *p-- = ';';
8051 FAST256CASE(4);
8052 *p-- = ';';
8053 FAST256CASE(3);
8054 *p-- = ';';
8055 FAST256CASE(2);
8056 *p-- = ';';
8057 FAST256CASE(1);
8058 *p-- = '[';
8059 *p = '\033';
8060 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8061 default:
8062 break;
8063 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008064}
8065
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008066 static void
8067wt_init(void)
8068{
8069 wt_working = (mch_getenv("WT_SESSION") != NULL);
8070}
8071
8072 int
8073use_wt(void)
8074{
8075 return USE_WT;
8076}
8077
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008078# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008079 static int
8080ctermtoxterm(
8081 int cterm)
8082{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008083 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008084
8085 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8086 return (((int)r << 16) | ((int)g << 8) | (int)b);
8087}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008088# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008089
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008090 static void
8091set_console_color_rgb(void)
8092{
8093# ifdef FEAT_TERMGUICOLORS
8094 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008095 guicolor_T fg, bg;
8096 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008097
8098 if (!USE_VTP)
8099 return;
8100
Bram Moolenaara050b942019-12-02 21:35:31 +01008101 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8102
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008103 if (USE_WT)
8104 {
8105 term_fg_rgb_color(fg);
8106 term_bg_rgb_color(bg);
8107 return;
8108 }
8109
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008110 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8111 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8112
8113 csbi.cbSize = sizeof(csbi);
8114 if (has_csbiex)
8115 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8116
8117 csbi.cbSize = sizeof(csbi);
8118 csbi.srWindow.Right += 1;
8119 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008120 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8121 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008122 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8123 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008124 if (has_csbiex)
8125 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8126# endif
8127}
8128
Bram Moolenaara050b942019-12-02 21:35:31 +01008129# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8130 void
8131get_default_console_color(
8132 int *cterm_fg,
8133 int *cterm_bg,
8134 guicolor_T *gui_fg,
8135 guicolor_T *gui_bg)
8136{
8137 int id;
8138 guicolor_T guifg = INVALCOLOR;
8139 guicolor_T guibg = INVALCOLOR;
8140 int ctermfg = 0;
8141 int ctermbg = 0;
8142
8143 id = syn_name2id((char_u *)"Normal");
8144 if (id > 0 && p_tgc)
8145 syn_id2colors(id, &guifg, &guibg);
8146 if (guifg == INVALCOLOR)
8147 {
8148 ctermfg = -1;
8149 if (id > 0)
8150 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8151 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
8152 : default_console_color_fg;
8153 cterm_normal_fg_gui_color = guifg;
8154 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8155 }
8156 if (guibg == INVALCOLOR)
8157 {
8158 ctermbg = -1;
8159 if (id > 0)
8160 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01008161 cterm_normal_bg_gui_color = guibg =
8162 ctermbg != -1 ? ctermtoxterm(ctermbg) : INVALCOLOR;
8163
8164 if (ctermbg < 0)
8165 ctermbg = 0;
Bram Moolenaara050b942019-12-02 21:35:31 +01008166 }
8167
8168 *cterm_fg = ctermfg;
8169 *cterm_bg = ctermbg;
8170 *gui_fg = guifg;
8171 *gui_bg = guibg;
8172}
8173# endif
8174
Bram Moolenaardf543822020-01-30 11:53:59 +01008175/*
8176 * Set the console colors to the original colors or the last set colors.
8177 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008178 static void
8179reset_console_color_rgb(void)
8180{
8181# ifdef FEAT_TERMGUICOLORS
8182 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8183
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008184 if (USE_WT)
8185 return;
8186
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008187 csbi.cbSize = sizeof(csbi);
8188 if (has_csbiex)
8189 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8190
8191 csbi.cbSize = sizeof(csbi);
8192 csbi.srWindow.Right += 1;
8193 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008194 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8195 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
8196 if (has_csbiex)
8197 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8198# endif
8199}
8200
8201/*
8202 * Set the console colors to the original colors.
8203 */
8204 static void
8205restore_console_color_rgb(void)
8206{
8207# ifdef FEAT_TERMGUICOLORS
8208 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8209
8210 csbi.cbSize = sizeof(csbi);
8211 if (has_csbiex)
8212 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8213
8214 csbi.cbSize = sizeof(csbi);
8215 csbi.srWindow.Right += 1;
8216 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008217 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8218 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008219 if (has_csbiex)
8220 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8221# endif
8222}
8223
8224 void
8225control_console_color_rgb(void)
8226{
8227 if (USE_VTP)
8228 set_console_color_rgb();
8229 else
8230 reset_console_color_rgb();
8231}
8232
8233 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008234use_vtp(void)
8235{
8236 return USE_VTP;
8237}
8238
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008239 int
8240is_term_win32(void)
8241{
8242 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8243}
8244
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008245 int
8246has_vtp_working(void)
8247{
8248 return vtp_working;
8249}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008250
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008251#endif
8252
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008253 int
8254has_conpty_working(void)
8255{
8256 return conpty_working;
8257}
8258
8259 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008260get_conpty_type(void)
8261{
8262 return conpty_type;
8263}
8264
8265 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008266is_conpty_stable(void)
8267{
8268 return conpty_stable;
8269}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008270
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008271 int
8272get_conpty_fix_type(void)
8273{
8274 return conpty_fix_type;
8275}
8276
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008277#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008278 void
8279resize_console_buf(void)
8280{
8281 CONSOLE_SCREEN_BUFFER_INFO csbi;
8282 COORD coord;
8283 SMALL_RECT newsize;
8284
8285 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8286 {
8287 coord.X = SRWIDTH(csbi.srWindow);
8288 coord.Y = SRHEIGHT(csbi.srWindow);
8289 SetConsoleScreenBufferSize(g_hConOut, coord);
8290
8291 newsize.Left = 0;
8292 newsize.Top = 0;
8293 newsize.Right = coord.X - 1;
8294 newsize.Bottom = coord.Y - 1;
8295 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8296
8297 SetConsoleScreenBufferSize(g_hConOut, coord);
8298 }
8299}
8300#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008301
8302 char *
8303GetWin32Error(void)
8304{
K.Takatad68b2fc2022-02-12 11:18:37 +00008305 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008306 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008307
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008308 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8309 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008310 if (oldmsg != NULL)
8311 LocalFree(oldmsg);
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008312 if (msg != NULL)
8313 {
8314 // remove trailing \r\n
8315 char *pcrlf = strstr(msg, "\r\n");
8316 if (pcrlf != NULL)
8317 *pcrlf = '\0';
K.Takatad68b2fc2022-02-12 11:18:37 +00008318 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008319 }
8320 return msg;
8321}
Paul Ollis65745772022-06-05 16:55:54 +01008322
8323#if defined(FEAT_RELTIME) || defined(PROTO)
8324static HANDLE timer_handle;
8325static int timer_active = FALSE;
8326
8327/*
8328 * Calls to start_timeout alternate the return value pointer between the two
8329 * entries in timeout_flags. If the previously active timeout is very close to
8330 * expiring when start_timeout() is called then a race condition means that the
8331 * set_flag() function may still be invoked after the previous timer is
8332 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8333 * timeouts.
8334 */
8335static int timeout_flags[2];
8336static int flag_idx = 0;
8337static int *timeout_flag = &timeout_flags[0];
8338
8339
8340 static void CALLBACK
8341set_flag(void *param, BOOLEAN unused2)
8342{
8343 int *timeout_flag = (int *)param;
8344
8345 *timeout_flag = TRUE;
8346}
8347
8348/*
8349 * Stop any active timeout.
8350 */
8351 void
8352stop_timeout(void)
8353{
8354 if (timer_active)
8355 {
8356 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
8357 timer_active = FALSE;
8358 if (!ret && GetLastError() != ERROR_IO_PENDING)
8359 {
8360 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
8361 }
8362 }
8363 *timeout_flag = FALSE;
8364}
8365
8366/*
8367 * Start the timeout timer.
8368 *
8369 * The period is defined in milliseconds.
8370 *
8371 * The return value is a pointer to a flag that is initialised to 0. If the
8372 * timeout expires, the flag is set to 1. This will only return pointers to
8373 * static memory; i.e. any pointer returned by this function may always be
8374 * safely dereferenced.
8375 *
8376 * This function is not expected to fail, but if it does it still returns a
8377 * valid flag pointer; the flag will remain stuck at zero.
8378 */
8379 const int *
8380start_timeout(long msec)
8381{
8382 UINT interval = (UINT)msec;
8383 BOOL ret;
8384
8385 timeout_flag = &timeout_flags[flag_idx];
8386
8387 stop_timeout();
8388 ret = CreateTimerQueueTimer(
8389 &timer_handle, NULL, set_flag, timeout_flag,
8390 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
8391 if (!ret)
8392 {
8393 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
8394 }
8395 else
8396 {
8397 flag_idx = (flag_idx + 1) % 2;
8398 timer_active = TRUE;
8399 *timeout_flag = FALSE;
8400 }
8401 return timeout_flag;
8402}
8403#endif