blob: 36051f4852bcefb0c68aff67e6f2e2c6cab84a26 [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;
Christopher Plewright1140b512022-11-12 18:46:05 +0000205static void wt_init(void);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200206
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200207static int g_color_index_bg = 0;
208static int g_color_index_fg = 7;
209
210# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +0000211static guicolor_T save_console_bg_rgb;
212static guicolor_T save_console_fg_rgb;
213static guicolor_T store_console_bg_rgb;
214static guicolor_T store_console_fg_rgb;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +0100215static int default_console_color_bg = 0x000000; // black
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200216static int default_console_color_fg = 0xc0c0c0; // white
Christopher Plewright38804d62022-11-09 23:55:52 +0000217# define USE_VTP (vtp_working && is_term_win32())
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200218# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100219# else
220# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200221# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100222# endif
223
224static void set_console_color_rgb(void);
225static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100226static void restore_console_color_rgb(void);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100227#endif
228
Bram Moolenaar0f873732019-12-05 20:28:46 +0100229// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100230#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
231# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
232#endif
233
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200234#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100235static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000236#endif
237
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200238static char_u *exe_path = NULL;
239
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100240static BOOL win8_or_later = FALSE;
Christopher Plewright1140b512022-11-12 18:46:05 +0000241static BOOL win11_or_later = FALSE;
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100242
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100243/*
244 * Get version number including build number
245 */
246typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100247#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100248 (((major) << 24) | ((minor) << 16) | (build))
249
250 static DWORD
251get_build_number(void)
252{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100253 OSVERSIONINFOW osver;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100254 HMODULE hNtdll;
255 PfnRtlGetVersion pRtlGetVersion;
256 DWORD ver = MAKE_VER(0, 0, 0);
257
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100258 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100259 hNtdll = GetModuleHandle("ntdll.dll");
260 if (hNtdll != NULL)
261 {
262 pRtlGetVersion =
263 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
264 pRtlGetVersion(&osver);
265 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
266 min(osver.dwMinorVersion, 255),
267 min(osver.dwBuildNumber, 32767));
268 }
269 return ver;
270}
271
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200272#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200273 static BOOL
274is_ambiwidth_event(
275 INPUT_RECORD *ir)
276{
277 return ir->EventType == KEY_EVENT
278 && ir->Event.KeyEvent.bKeyDown
279 && ir->Event.KeyEvent.wRepeatCount == 1
280 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
281 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000282 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200283 && ir->Event.KeyEvent.dwControlKeyState == 2;
284}
285
286 static void
287make_ambiwidth_event(
288 INPUT_RECORD *down,
289 INPUT_RECORD *up)
290{
291 down->Event.KeyEvent.wVirtualKeyCode = 0;
292 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000293 down->Event.KeyEvent.uChar.UnicodeChar
294 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200295 down->Event.KeyEvent.dwControlKeyState = 0;
296}
297
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100298/*
299 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100300 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100301 */
302 static BOOL
303read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100304 HANDLE hInput,
305 INPUT_RECORD *lpBuffer,
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100306 int nLength,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100307 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100308{
309 enum
310 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100311 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100312 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100313 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100314 static DWORD s_dwIndex = 0;
315 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100316 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100317 int head;
318 int tail;
319 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200320 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100321
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200322 if (nLength == -2)
323 return (s_dwMax > 0) ? TRUE : FALSE;
324
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100325 if (!win8_or_later)
326 {
327 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200328 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
329 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100330 }
331
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100332 if (s_dwMax == 0)
333 {
Christopher Plewright38804d62022-11-09 23:55:52 +0000334 if (!vtp_working && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200335 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200336 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
337 if (dwEvents == 0 && nLength == -1)
338 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
339 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100340 s_dwIndex = 0;
341 s_dwMax = dwEvents;
342 if (dwEvents == 0)
343 {
344 *lpEvents = 0;
345 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100346 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100347
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200348 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
349 if (is_ambiwidth_event(&s_irCache[i]))
350 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
351
Bram Moolenaardd415a62014-02-05 14:02:27 +0100352 if (s_dwMax > 1)
353 {
354 head = 0;
355 tail = s_dwMax - 1;
356 while (head != tail)
357 {
358 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
359 && s_irCache[head + 1].EventType
360 == WINDOW_BUFFER_SIZE_EVENT)
361 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100362 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100363 for (i = head; i < tail; ++i)
364 s_irCache[i] = s_irCache[i + 1];
365 --tail;
366 continue;
367 }
368 head++;
369 }
370 s_dwMax = tail + 1;
371 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100372 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100373
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200374 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
375 {
376 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
377 {
378 s_irPseudo = s_irCache[s_dwIndex];
379 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
380 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
381 *lpBuffer = s_irPseudo;
382 *lpEvents = 1;
383 return TRUE;
384 }
385 }
386
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100387 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200388 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100389 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100390 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100391 return TRUE;
392}
393
394/*
395 * Version of PeekConsoleInput() that works with IME.
396 */
397 static BOOL
398peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100399 HANDLE hInput,
400 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200401 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100402 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100403{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100404 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100405}
406
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100407# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200408 static DWORD
409msg_wait_for_multiple_objects(
410 DWORD nCount,
411 LPHANDLE pHandles,
412 BOOL fWaitAll,
413 DWORD dwMilliseconds,
414 DWORD dwWakeMask)
415{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100416 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200417 return WAIT_OBJECT_0;
418 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
419 dwMilliseconds, dwWakeMask);
420}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100421# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200422
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100423# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200424 static DWORD
425wait_for_single_object(
426 HANDLE hHandle,
427 DWORD dwMilliseconds)
428{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100429 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200430 return WAIT_OBJECT_0;
431 return WaitForSingleObject(hHandle, dwMilliseconds);
432}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100433# endif
434#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200435
Bram Moolenaar071d4272004-06-13 20:20:40 +0000436 static void
437get_exe_name(void)
438{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100439 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
440 // as the maximum length that works (plus a NUL byte).
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100441#define MAX_ENV_PATH_LEN 8192
442 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200443 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000444
445 if (exe_name == NULL)
446 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100447 // store the name of the executable, may be used for $VIM
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100448 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000449 if (*temp != NUL)
450 exe_name = FullName_save((char_u *)temp, FALSE);
451 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000452
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200453 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000454 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200455 exe_path = vim_strnsave(exe_name, gettail_sep(exe_name) - exe_name);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200456 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000457 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100458 // Append our starting directory to $PATH, so that when doing
459 // "!xxd" it's found in our starting directory. Needed because
460 // SearchPath() also looks there.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200461 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100462 if (p == NULL
463 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200464 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100465 if (p == NULL || *p == NUL)
466 temp[0] = NUL;
467 else
468 {
469 STRCPY(temp, p);
470 STRCAT(temp, ";");
471 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200472 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100473 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200474 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000475 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000476 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000477}
478
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200479/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100480 * Unescape characters in "p" that appear in "escaped".
481 */
482 static void
483unescape_shellxquote(char_u *p, char_u *escaped)
484{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100485 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100486 int n;
487
488 while (*p != NUL)
489 {
490 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
491 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100492 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100493 p += n;
494 l -= n;
495 }
496}
497
498/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200499 * Load library "name".
500 */
501 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000502vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200503{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200504 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200505
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200506 // No need to load any library when registering OLE.
507 if (found_register_arg)
508 return dll;
509
Bram Moolenaar0f873732019-12-05 20:28:46 +0100510 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
511 // vimLoadLib() recursively, which causes a stack overflow.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200512 if (exe_path == NULL)
513 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200514 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200515 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200516 WCHAR old_dirw[MAXPATHL];
517
518 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
519 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100520 // Change directory to where the executable is, both to make
521 // sure we find a .dll there and to avoid looking for a .dll
522 // in the current directory.
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100523 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200524 dll = LoadLibrary(name);
525 SetCurrentDirectoryW(old_dirw);
526 return dll;
527 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200528 }
529 return dll;
530}
531
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200532#if defined(VIMDLL) || defined(PROTO)
533/*
534 * Check if the current executable file is for the GUI subsystem.
535 */
536 int
537mch_is_gui_executable(void)
538{
539 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
540 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
541 PIMAGE_NT_HEADERS pPE;
542
543 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
544 return FALSE;
545 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
546 if (pPE->Signature != IMAGE_NT_SIGNATURE)
547 return FALSE;
548 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
549 return TRUE;
550 return FALSE;
551}
552#endif
553
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000554#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
555 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100556/*
557 * Get related information about 'funcname' which is imported by 'hInst'.
558 * If 'info' is 0, return the function address.
559 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000560 * If 'info' is 2, hook the function with 'ptr', and return the original
561 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100562 */
563 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000564get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
565 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100566{
567 PBYTE pImage = (PBYTE)hInst;
568 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
569 PIMAGE_NT_HEADERS pPE;
570 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100571 PIMAGE_THUNK_DATA pIAT; // Import Address Table
572 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100573 PIMAGE_IMPORT_BY_NAME pImpName;
574
575 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
576 return NULL;
577 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
578 if (pPE->Signature != IMAGE_NT_SIGNATURE)
579 return NULL;
580 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
581 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
582 .VirtualAddress);
583 for (; pImpDesc->FirstThunk; ++pImpDesc)
584 {
585 if (!pImpDesc->OriginalFirstThunk)
586 continue;
587 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
588 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
589 for (; pIAT->u1.Function; ++pIAT, ++pINT)
590 {
591 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
592 continue;
593 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
594 + (UINT_PTR)(pINT->u1.AddressOfData));
595 if (strcmp((char *)pImpName->Name, funcname) == 0)
596 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000597 void *original;
598 DWORD old, new = PAGE_READWRITE;
599
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100600 switch (info)
601 {
602 case 0:
603 return (void *)pIAT->u1.Function;
604 case 1:
605 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000606 case 2:
607 original = (void *)pIAT->u1.Function;
608 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
609 new, &old);
610 pIAT->u1.Function = (UINT_PTR)ptr;
611 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
612 old, &new);
613 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100614 default:
615 return NULL;
616 }
617 }
618 }
619 }
620 return NULL;
621}
622
623/*
624 * Get the module handle which 'funcname' in 'hInst' is imported from.
625 */
626 HINSTANCE
627find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
628{
629 char *modulename;
630
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000631 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100632 if (modulename != NULL)
633 return GetModuleHandleA(modulename);
634 return NULL;
635}
636
637/*
638 * Get the address of 'funcname' which is imported by 'hInst' DLL.
639 */
640 void *
641get_dll_import_func(HINSTANCE hInst, const char *funcname)
642{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000643 return get_imported_func_info(hInst, funcname, 0, NULL);
644}
645
646/*
647 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
648 * and return the original function address.
649 */
650 void *
651hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
652{
653 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100654}
655#endif
656
Bram Moolenaar071d4272004-06-13 20:20:40 +0000657#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
658# ifndef GETTEXT_DLL
659# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200660# define GETTEXT_DLL_ALT1 "libintl-8.dll"
661# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000662# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100663// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000664static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200665static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000666static char *null_libintl_textdomain(const char *);
667static char *null_libintl_bindtextdomain(const char *, const char *);
668static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100669static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000670
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200671static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000672char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200673char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
674 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000675char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
676char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000677 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000678char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
679 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100680int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000681
682 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100683dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000684{
685 int i;
686 static struct
687 {
688 char *name;
689 FARPROC *ptr;
690 } libintl_entry[] =
691 {
692 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200693 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000694 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
695 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
696 {NULL, NULL}
697 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100698 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000699
Bram Moolenaar7554c542018-10-06 15:03:15 +0200700 // No need to initialize twice.
701 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000702 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200703 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100704 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100705# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100706 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200707 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100708# endif
709# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200710 if (!hLibintlDLL)
711 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100712# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100713 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000714 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200715 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000716 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200717 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000718 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200719 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000720 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200721 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000722 }
723 for (i = 0; libintl_entry[i].name != NULL
724 && libintl_entry[i].ptr != NULL; ++i)
725 {
K.Takata54119102022-02-03 13:33:03 +0000726 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000727 libintl_entry[i].name)) == NULL)
728 {
729 dyn_libintl_end();
730 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000731 {
732 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000733 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000734 verbose_leave();
735 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000736 return 0;
737 }
738 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000739
Bram Moolenaar0f873732019-12-05 20:28:46 +0100740 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100741 dyn_libintl_bind_textdomain_codeset = (char *(*)(const char *, const char *))
742 GetProcAddress(hLibintlDLL, "bind_textdomain_codeset");
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000743 if (dyn_libintl_bind_textdomain_codeset == NULL)
744 dyn_libintl_bind_textdomain_codeset =
745 null_libintl_bind_textdomain_codeset;
746
Bram Moolenaar0f873732019-12-05 20:28:46 +0100747 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100748 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
749 if (hmsvcrt != NULL)
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100750 dyn_libintl_wputenv = (int (*)(const wchar_t *))
751 GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100752 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
753 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100754
Bram Moolenaar071d4272004-06-13 20:20:40 +0000755 return 1;
756}
757
758 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100759dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000760{
761 if (hLibintlDLL)
762 FreeLibrary(hLibintlDLL);
763 hLibintlDLL = NULL;
764 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200765 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000766 dyn_libintl_textdomain = null_libintl_textdomain;
767 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000768 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100769 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000770}
771
772 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000773null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000774{
775 return (char*)msgid;
776}
777
778 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200779null_libintl_ngettext(
780 const char *msgid,
781 const char *msgid_plural,
782 unsigned long n)
783{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200784 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200785}
786
Bram Moolenaaree695f72016-08-03 22:08:45 +0200787 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100788null_libintl_bindtextdomain(
789 const char *domainname UNUSED,
790 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000791{
792 return NULL;
793}
794
795 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100796null_libintl_bind_textdomain_codeset(
797 const char *domainname UNUSED,
798 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000799{
800 return NULL;
801}
802
803 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100804null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000805{
806 return NULL;
807}
808
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200809 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100810null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100811{
812 return 0;
813}
814
Bram Moolenaar0f873732019-12-05 20:28:46 +0100815#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000816
Bram Moolenaar0f873732019-12-05 20:28:46 +0100817// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000818
819#ifndef VER_PLATFORM_WIN32_WINDOWS
820# define VER_PLATFORM_WIN32_WINDOWS 1
821#endif
822
Bram Moolenaar071d4272004-06-13 20:20:40 +0000823#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100824# ifndef PROTO
825# include <aclapi.h>
826# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200827# ifndef PROTECTED_DACL_SECURITY_INFORMATION
828# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
829# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000830#endif
831
Bram Moolenaar27515922013-06-29 15:36:26 +0200832#ifdef HAVE_ACL
833/*
834 * Enables or disables the specified privilege.
835 */
836 static BOOL
837win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
838{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100839 BOOL bResult;
840 LUID luid;
841 HANDLE hToken;
842 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200843
844 if (!OpenProcessToken(GetCurrentProcess(),
845 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
846 return FALSE;
847
848 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
849 {
850 CloseHandle(hToken);
851 return FALSE;
852 }
853
Bram Moolenaar45500912014-07-09 20:51:07 +0200854 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200855 tokenPrivileges.Privileges[0].Luid = luid;
856 tokenPrivileges.Privileges[0].Attributes = bEnable ?
857 SE_PRIVILEGE_ENABLED : 0;
858
859 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
860 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
861
862 CloseHandle(hToken);
863
864 return bResult && GetLastError() == ERROR_SUCCESS;
865}
866#endif
867
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100868#ifdef _MSC_VER
869// Suppress the deprecation warning for using GetVersionEx().
870// It is needed for implementing "windowsversion()".
871# pragma warning(push)
872# pragma warning(disable: 4996)
873#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000874/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200875 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000876 */
877 void
878PlatformId(void)
879{
880 static int done = FALSE;
881
882 if (!done)
883 {
884 OSVERSIONINFO ovi;
885
886 ovi.dwOSVersionInfoSize = sizeof(ovi);
887 GetVersionEx(&ovi);
888
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200889#ifdef FEAT_EVAL
Bram Moolenaar0c1e3742019-12-27 13:49:24 +0100890 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
891 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200892#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100893 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
894 || ovi.dwMajorVersion > 6)
895 win8_or_later = TRUE;
896
Christopher Plewright1140b512022-11-12 18:46:05 +0000897 if ((ovi.dwMajorVersion == 10 && ovi.dwBuildNumber >= 22000)
898 || ovi.dwMajorVersion > 10)
899 win11_or_later = TRUE;
900
Bram Moolenaar071d4272004-06-13 20:20:40 +0000901#ifdef HAVE_ACL
Bram Moolenaar0f873732019-12-05 20:28:46 +0100902 // Enable privilege for getting or setting SACLs.
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200903 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000904#endif
905 done = TRUE;
906 }
907}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100908#ifdef _MSC_VER
909# pragma warning(pop)
910#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000911
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200912#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000913
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100914# define SHIFT (SHIFT_PRESSED)
915# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
916# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
917# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000918
919
Bram Moolenaar0f873732019-12-05 20:28:46 +0100920// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
921// We map function keys to their ANSI terminal equivalents, as produced
922// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
923// ANSI key with a value >= '\300' is nonstandard, but provided anyway
924// so that the user can have access to all SHIFT-, CTRL-, and ALT-
925// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000926
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000927static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000928{
929 WORD wVirtKey;
930 BOOL fAnsiKey;
931 int chAlone;
932 int chShift;
933 int chCtrl;
934 int chAlt;
935} VirtKeyMap[] =
936{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200937// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000938 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
939
940 { VK_F1, TRUE, ';', 'T', '^', 'h', },
941 { VK_F2, TRUE, '<', 'U', '_', 'i', },
942 { VK_F3, TRUE, '=', 'V', '`', 'j', },
943 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
944 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
945 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
946 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
947 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
948 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
949 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200950 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
951 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000952
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200953 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
954 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
955 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
956 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
957 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
958 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
959 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
960 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
961 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
962 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100963 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000964
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200965 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000966
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100967# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200968 // Most people don't have F13-F20, but what the hell...
969 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
970 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
971 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
972 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
973 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
974 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
975 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
976 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100977# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200978 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
979 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
980 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
981 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000982
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200983 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
984 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
985 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
986 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
987 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
988 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
989 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
990 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
991 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
992 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100993 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000994};
995
996
Bram Moolenaar0f873732019-12-05 20:28:46 +0100997/*
998 * The return code indicates key code size.
999 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001000 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001001win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001002 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001003{
1004 UINT uMods = pker->dwControlKeyState;
1005 static int s_iIsDead = 0;
1006 static WORD awAnsiCode[2];
1007 static BYTE abKeystate[256];
1008
1009
1010 if (s_iIsDead == 2)
1011 {
K.Takata972db232022-02-04 10:45:38 +00001012 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001013 s_iIsDead = 0;
1014 return 1;
1015 }
1016
K.Takata972db232022-02-04 10:45:38 +00001017 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001018 return 1;
1019
Bram Moolenaara80faa82020-04-12 19:37:17 +02001020 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001021
Bram Moolenaar0f873732019-12-05 20:28:46 +01001022 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001023 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001024
1025 if (uMods & SHIFT_PRESSED)
1026 abKeystate[VK_SHIFT] = 0x80;
1027 if (uMods & CAPSLOCK_ON)
1028 abKeystate[VK_CAPITAL] = 1;
1029
1030 if ((uMods & ALT_GR) == ALT_GR)
1031 {
1032 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1033 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1034 }
1035
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001036 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1037 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001038
1039 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001040 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001041
1042 return s_iIsDead;
1043}
1044
Bram Moolenaar071d4272004-06-13 20:20:40 +00001045static BOOL g_fJustGotFocus = FALSE;
1046
1047/*
1048 * Decode a KEY_EVENT into one or two keystrokes
1049 */
1050 static BOOL
1051decode_key_event(
1052 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001053 WCHAR *pch,
1054 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001055 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001056 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001057{
1058 int i;
1059 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1060
1061 *pch = *pch2 = NUL;
1062 g_fJustGotFocus = FALSE;
1063
Bram Moolenaar0f873732019-12-05 20:28:46 +01001064 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001065 if (!pker->bKeyDown)
1066 return FALSE;
1067
Bram Moolenaar0f873732019-12-05 20:28:46 +01001068 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001069 switch (pker->wVirtualKeyCode)
1070 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001071 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001072 case VK_SHIFT:
1073 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001074 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001075 return FALSE;
1076
1077 default:
1078 break;
1079 }
1080
Bram Moolenaar0f873732019-12-05 20:28:46 +01001081 // special cases
K.Takata972db232022-02-04 10:45:38 +00001082 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0
1083 && pker->uChar.UnicodeChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001084 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001085 // Ctrl-6 is Ctrl-^
Bram Moolenaar071d4272004-06-13 20:20:40 +00001086 if (pker->wVirtualKeyCode == '6')
1087 {
1088 *pch = Ctrl_HAT;
1089 return TRUE;
1090 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001091 // Ctrl-2 is Ctrl-@
Bram Moolenaar071d4272004-06-13 20:20:40 +00001092 else if (pker->wVirtualKeyCode == '2')
1093 {
1094 *pch = NUL;
1095 return TRUE;
1096 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001097 // Ctrl-- is Ctrl-_
Bram Moolenaar071d4272004-06-13 20:20:40 +00001098 else if (pker->wVirtualKeyCode == 0xBD)
1099 {
1100 *pch = Ctrl__;
1101 return TRUE;
1102 }
1103 }
1104
Bram Moolenaar0f873732019-12-05 20:28:46 +01001105 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001106 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1107 {
1108 *pch = K_NUL;
1109 *pch2 = '\017';
1110 return TRUE;
1111 }
1112
K.Takataeeec2542021-06-02 13:28:16 +02001113 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001114 {
1115 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1116 {
1117 if (nModifs == 0)
1118 *pch = VirtKeyMap[i].chAlone;
1119 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1120 *pch = VirtKeyMap[i].chShift;
1121 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1122 *pch = VirtKeyMap[i].chCtrl;
1123 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1124 *pch = VirtKeyMap[i].chAlt;
1125
1126 if (*pch != 0)
1127 {
1128 if (VirtKeyMap[i].fAnsiKey)
1129 {
1130 *pch2 = *pch;
1131 *pch = K_NUL;
1132 }
1133
1134 return TRUE;
1135 }
1136 }
1137 }
1138
1139 i = win32_kbd_patch_key(pker);
1140
1141 if (i < 0)
1142 *pch = NUL;
1143 else
1144 {
K.Takata972db232022-02-04 10:45:38 +00001145 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001146
1147 if (pmodifiers != NULL)
1148 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001149 // Pass on the ALT key as a modifier, but only when not combined
1150 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001151 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1152 *pmodifiers |= MOD_MASK_ALT;
1153
Bram Moolenaar0f873732019-12-05 20:28:46 +01001154 // Pass on SHIFT only for special keys, because we don't know when
1155 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001156 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1157 *pmodifiers |= MOD_MASK_SHIFT;
1158
Bram Moolenaar0f873732019-12-05 20:28:46 +01001159 // Pass on CTRL only for non-special keys, because we don't know
1160 // when it's already included with the character. And not when
1161 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001162 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1163 && *pch >= 0x20 && *pch < 0x80)
1164 *pmodifiers |= MOD_MASK_CTRL;
1165 }
1166 }
1167
1168 return (*pch != NUL);
1169}
1170
Bram Moolenaar0f873732019-12-05 20:28:46 +01001171#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001172
1173
Bram Moolenaar071d4272004-06-13 20:20:40 +00001174/*
1175 * For the GUI the mouse handling is in gui_w32.c.
1176 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001177#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001178 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001179mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001180{
1181}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001182#else
Bram Moolenaar0f873732019-12-05 20:28:46 +01001183static int g_fMouseAvail = FALSE; // mouse present
1184static int g_fMouseActive = FALSE; // mouse enabled
1185static int g_nMouseClick = -1; // mouse status
1186static int g_xMouse; // mouse x coordinate
1187static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001188static DWORD g_cmodein = 0; // Original console input mode
1189static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001190
1191/*
1192 * Enable or disable mouse input
1193 */
1194 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001195mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001196{
1197 DWORD cmodein;
1198
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001199# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001200 if (gui.in_use)
1201 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001202# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001203 if (!g_fMouseAvail)
1204 return;
1205
1206 g_fMouseActive = on;
1207 GetConsoleMode(g_hConIn, &cmodein);
1208
1209 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001210 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001211 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001212 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1213 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001214 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001215 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001216 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001217 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1218 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001219
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001220 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001221}
1222
Bram Moolenaar157d8132018-03-06 17:09:20 +01001223
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001224# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001225/*
1226 * Called when 'balloonevalterm' changed.
1227 */
1228 void
1229mch_bevalterm_changed(void)
1230{
1231 mch_setmouse(g_fMouseActive);
1232}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001233# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001234
Christopher Plewright2a46f812022-10-16 19:47:45 +01001235/*
1236 * Win32 console mouse scroll event handler.
1237 * Loosely based on the _OnMouseWheel() function in gui_w32.c
1238 *
1239 * This encodes the mouse scroll direction and keyboard modifiers into
1240 * g_nMouseClick, and the mouse position into g_xMouse and g_yMouse
1241 *
1242 * The direction of the scroll is decoded from two fields of the win32 console
1243 * mouse event record;
1244 * 1. The axis - vertical or horizontal flag - from dwEventFlags, and
1245 * 2. The sign - positive or negative (aka delta flag) - from dwButtonState
1246 *
1247 * When scroll axis is HORIZONTAL
1248 * - If the high word of the dwButtonState member contains a positive
1249 * value, the wheel was rotated to the right.
1250 * - Otherwise, the wheel was rotated to the left.
1251 * When scroll axis is VERTICAL
1252 * - If the high word of the dwButtonState member contains a positive value,
1253 * the wheel was rotated forward, away from the user.
1254 * - Otherwise, the wheel was rotated backward, toward the user.
1255 */
1256 static void
1257decode_mouse_wheel(MOUSE_EVENT_RECORD *pmer)
1258{
Christopher Plewright2a46f812022-10-16 19:47:45 +01001259 int horizontal = (pmer->dwEventFlags == MOUSE_HWHEELED);
1260 int zDelta = pmer->dwButtonState;
1261
1262 g_xMouse = pmer->dwMousePosition.X;
1263 g_yMouse = pmer->dwMousePosition.Y;
1264
K.Takata161b6ac2022-11-14 15:31:07 +00001265# ifdef FEAT_PROP_POPUP
Christopher Plewright605d02a2022-10-19 11:54:46 +01001266 int lcol = g_xMouse;
1267 int lrow = g_yMouse;
Christopher Plewright38804d62022-11-09 23:55:52 +00001268 win_T *wp = mouse_find_win(&lrow, &lcol, FIND_POPUP);
Christopher Plewright2a46f812022-10-16 19:47:45 +01001269 if (wp != NULL && popup_is_popup(wp))
1270 {
1271 g_nMouseClick = -1;
1272 cmdarg_T cap;
1273 oparg_T oa;
1274 CLEAR_FIELD(cap);
1275 clear_oparg(&oa);
1276 cap.oap = &oa;
1277 if (horizontal)
1278 {
1279 cap.arg = zDelta < 0 ? MSCR_LEFT : MSCR_RIGHT;
1280 cap.cmdchar = zDelta < 0 ? K_MOUSELEFT : K_MOUSERIGHT;
1281 }
1282 else
1283 {
1284 cap.cmdchar = zDelta < 0 ? K_MOUSEUP : K_MOUSEDOWN;
1285 cap.arg = zDelta < 0 ? MSCR_UP : MSCR_DOWN;
1286 }
1287
1288 // Mouse hovers over popup window, scroll it if possible.
1289 mouse_row = wp->w_winrow;
1290 mouse_col = wp->w_wincol;
1291 nv_mousescroll(&cap);
1292 update_screen(0);
1293 setcursor();
1294 out_flush();
1295 return;
1296 }
K.Takata161b6ac2022-11-14 15:31:07 +00001297# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01001298 mouse_col = g_xMouse;
1299 mouse_row = g_yMouse;
1300
1301 char_u modifiers = 0;
1302 char_u direction = 0;
1303
1304 // Decode the direction into an event that Vim can process
1305 if (horizontal)
1306 direction = zDelta >= 0 ? KE_MOUSELEFT : KE_MOUSERIGHT;
1307 else
1308 direction = zDelta >= 0 ? KE_MOUSEDOWN : KE_MOUSEUP;
1309
dundargocc57b5bc2022-11-02 13:30:51 +00001310 // Decode the win32 console key modifiers into Vim mouse modifiers.
Christopher Plewright2a46f812022-10-16 19:47:45 +01001311 if (pmer->dwControlKeyState & SHIFT_PRESSED)
Christopher Plewright605d02a2022-10-19 11:54:46 +01001312 modifiers |= MOD_MASK_SHIFT; // MOUSE_SHIFT;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001313 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
Christopher Plewright605d02a2022-10-19 11:54:46 +01001314 modifiers |= MOD_MASK_CTRL; // MOUSE_CTRL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001315 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1316 modifiers |= MOD_MASK_ALT; // MOUSE_ALT;
1317
1318 // add (bitwise or) the scroll direction and the key modifier chars
1319 // together.
1320 g_nMouseClick = ((direction << 8) | modifiers);
1321
1322 return;
1323}
1324
Bram Moolenaar071d4272004-06-13 20:20:40 +00001325/*
1326 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1327 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1328 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1329 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1330 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1331 * and we return the mouse position in g_xMouse and g_yMouse.
1332 *
1333 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1334 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1335 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1336 *
1337 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1338 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1339 *
1340 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1341 * moves, even if it stays within the same character cell. We ignore
1342 * all MOUSE_MOVED messages if the position hasn't really changed, and
1343 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1344 * we're only interested in MOUSE_DRAG).
1345 *
1346 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1347 * 2-button mouses by pressing the left & right buttons simultaneously.
1348 * In practice, it's almost impossible to click both at the same time,
1349 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1350 * in such cases, if the user is clicking quickly.
1351 */
1352 static BOOL
1353decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001354 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001355{
1356 static int s_nOldButton = -1;
1357 static int s_nOldMouseClick = -1;
1358 static int s_xOldMouse = -1;
1359 static int s_yOldMouse = -1;
1360 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001361# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001362 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001363# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001364 static int s_cClicks = 1;
1365 static BOOL s_fReleased = TRUE;
1366 static DWORD s_dwLastClickTime = 0;
1367 static BOOL s_fNextIsMiddle = FALSE;
1368
Bram Moolenaar0f873732019-12-05 20:28:46 +01001369 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001370
1371 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1372 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1373 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1374 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1375
1376 int nButton;
1377
1378 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1379 cButtons = 2;
1380
1381 if (!g_fMouseAvail || !g_fMouseActive)
1382 {
1383 g_nMouseClick = -1;
1384 return FALSE;
1385 }
1386
Bram Moolenaar0f873732019-12-05 20:28:46 +01001387 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001388 if (g_fJustGotFocus)
1389 {
1390 g_fJustGotFocus = FALSE;
1391 return FALSE;
1392 }
1393
Christopher Plewright605d02a2022-10-19 11:54:46 +01001394 // If there is an unprocessed mouse click drop this one.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001395 if (g_nMouseClick != -1)
1396 return TRUE;
Christopher Plewright605d02a2022-10-19 11:54:46 +01001397
Christopher Plewright2a46f812022-10-16 19:47:45 +01001398 if (pmer->dwEventFlags == MOUSE_WHEELED
1399 || pmer->dwEventFlags == MOUSE_HWHEELED)
1400 {
1401 decode_mouse_wheel(pmer);
1402 return TRUE; // we now should have a mouse scroll in g_nMouseClick
1403 }
Christopher Plewright605d02a2022-10-19 11:54:46 +01001404
Bram Moolenaar071d4272004-06-13 20:20:40 +00001405 nButton = -1;
1406 g_xMouse = pmer->dwMousePosition.X;
1407 g_yMouse = pmer->dwMousePosition.Y;
1408
1409 if (pmer->dwEventFlags == MOUSE_MOVED)
1410 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001411 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1412 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001413 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1414 return FALSE;
1415 }
1416
Bram Moolenaar0f873732019-12-05 20:28:46 +01001417 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001418 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1419 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001420 nButton = MOUSE_RELEASE;
1421
Bram Moolenaar0f873732019-12-05 20:28:46 +01001422 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001423 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001424 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001425# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001426 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001427 if (p_bevalterm)
1428 nButton = MOUSE_DRAG;
1429 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001430# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001431 return FALSE;
1432 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001433
Bram Moolenaar071d4272004-06-13 20:20:40 +00001434 s_fReleased = TRUE;
1435 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001436 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001437 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001438 // on a 2-button mouse, hold down left and right buttons
1439 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001440
1441 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1442 {
1443 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1444
Bram Moolenaar0f873732019-12-05 20:28:46 +01001445 // if either left or right button only is pressed, see if the
1446 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001447 if (dwLR == LEFT || dwLR == RIGHT)
1448 {
1449 for (;;)
1450 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001451 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001452 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1453 != WAIT_OBJECT_0)
1454 break;
1455 else
1456 {
1457 DWORD cRecords = 0;
1458 INPUT_RECORD ir;
1459 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1460
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001461 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001462
1463 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1464 || !(pmer2->dwButtonState & LEFT_RIGHT))
1465 break;
1466 else
1467 {
1468 if (pmer2->dwEventFlags != MOUSE_MOVED)
1469 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001470 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001471
1472 return decode_mouse_event(pmer2);
1473 }
1474 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1475 s_yOldMouse == pmer2->dwMousePosition.Y)
1476 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001477 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001478 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001479
Bram Moolenaar0f873732019-12-05 20:28:46 +01001480 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001481 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001482
1483 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1484 break;
1485 }
1486 else
1487 break;
1488 }
1489 }
1490 }
1491 }
1492 }
1493
1494 if (s_fNextIsMiddle)
1495 {
1496 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1497 ? MOUSE_DRAG : MOUSE_MIDDLE;
1498 s_fNextIsMiddle = FALSE;
1499 }
1500 else if (cButtons == 2 &&
1501 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1502 {
1503 nButton = MOUSE_MIDDLE;
1504
1505 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1506 {
1507 s_fNextIsMiddle = TRUE;
1508 nButton = MOUSE_RELEASE;
1509 }
1510 }
1511 else if ((pmer->dwButtonState & LEFT) == LEFT)
1512 nButton = MOUSE_LEFT;
1513 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1514 nButton = MOUSE_MIDDLE;
1515 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1516 nButton = MOUSE_RIGHT;
1517
1518 if (! s_fReleased && ! s_fNextIsMiddle
1519 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1520 return FALSE;
1521
1522 s_fReleased = s_fNextIsMiddle;
1523 }
1524
1525 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1526 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001527 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001528 if (nButton != -1 && nButton != MOUSE_RELEASE)
1529 {
1530 DWORD dwCurrentTime = GetTickCount();
1531
1532 if (s_xOldMouse != g_xMouse
1533 || s_yOldMouse != g_yMouse
1534 || s_nOldButton != nButton
1535 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001536# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001537 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001538# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001539 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1540 {
1541 s_cClicks = 1;
1542 }
1543 else if (++s_cClicks > 4)
1544 {
1545 s_cClicks = 1;
1546 }
1547
1548 s_dwLastClickTime = dwCurrentTime;
1549 }
1550 }
1551 else if (pmer->dwEventFlags == MOUSE_MOVED)
1552 {
1553 if (nButton != -1 && nButton != MOUSE_RELEASE)
1554 nButton = MOUSE_DRAG;
1555
1556 s_cClicks = 1;
1557 }
1558
1559 if (nButton == -1)
1560 return FALSE;
1561
1562 if (nButton != MOUSE_RELEASE)
1563 s_nOldButton = nButton;
1564
1565 g_nMouseClick = nButton;
1566
1567 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1568 g_nMouseClick |= MOUSE_SHIFT;
1569 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1570 g_nMouseClick |= MOUSE_CTRL;
1571 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1572 g_nMouseClick |= MOUSE_ALT;
1573
1574 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1575 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1576
Bram Moolenaar0f873732019-12-05 20:28:46 +01001577 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001578 if (s_xOldMouse == g_xMouse
1579 && s_yOldMouse == g_yMouse
1580 && s_nOldMouseClick == g_nMouseClick)
1581 {
1582 g_nMouseClick = -1;
1583 return FALSE;
1584 }
1585
1586 s_xOldMouse = g_xMouse;
1587 s_yOldMouse = g_yMouse;
1588 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001589# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001590 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001591# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001592 s_nOldMouseClick = g_nMouseClick;
1593
1594 return TRUE;
1595}
1596
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001597#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001598
1599
1600#ifdef MCH_CURSOR_SHAPE
1601/*
1602 * Set the shape of the cursor.
1603 * 'thickness' can be from 1 (thin) to 99 (block)
1604 */
1605 static void
1606mch_set_cursor_shape(int thickness)
1607{
Christopher Plewright38804d62022-11-09 23:55:52 +00001608 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01001609 {
1610 if (*T_CSI == NUL)
1611 {
1612 // If 't_SI' is not set, use the default cursor styles.
1613 if (thickness < 50)
1614 vtp_printf("\033[3 q"); // underline
1615 else
1616 vtp_printf("\033[0 q"); // default
1617 }
1618 }
1619 else
1620 {
1621 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1622 ConsoleCursorInfo.dwSize = thickness;
1623 ConsoleCursorInfo.bVisible = s_cursor_visible;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001624
K.Takatadf5320c2022-09-01 13:20:16 +01001625 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1626 if (s_cursor_visible)
1627 SetConsoleCursorPosition(g_hConOut, g_coord);
1628 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001629}
1630
1631 void
1632mch_update_cursor(void)
1633{
1634 int idx;
1635 int thickness;
1636
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001637# ifdef VIMDLL
1638 if (gui.in_use)
1639 return;
1640# endif
1641
Bram Moolenaar071d4272004-06-13 20:20:40 +00001642 /*
1643 * How the cursor is drawn depends on the current mode.
1644 */
1645 idx = get_shape_idx(FALSE);
1646
1647 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001648 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00001649 else
1650 thickness = shape_table[idx].percentage;
1651 mch_set_cursor_shape(thickness);
1652}
1653#endif
1654
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001655#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001656/*
1657 * Handle FOCUS_EVENT.
1658 */
1659 static void
1660handle_focus_event(INPUT_RECORD ir)
1661{
1662 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1663 ui_focus_change((int)g_fJustGotFocus);
1664}
1665
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001666static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1667
Bram Moolenaar071d4272004-06-13 20:20:40 +00001668/*
1669 * Wait until console input from keyboard or mouse is available,
1670 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001671 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001672 * Return TRUE if something is available FALSE if not.
1673 */
1674 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001675WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001676{
1677 DWORD dwNow = 0, dwEndTime = 0;
1678 INPUT_RECORD ir;
1679 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001680 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001681# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001682 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001683# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001684
1685 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001686 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001687 dwEndTime = GetTickCount() + msec;
1688 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001689 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001690 dwEndTime = INFINITE;
1691
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001692 // We need to loop until the end of the time period, because
1693 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001694 for (;;)
1695 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001696 // Only process messages when waiting.
1697 if (msec != 0)
1698 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001699# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001700 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001701# endif
1702# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001703 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001704# endif
1705# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001706 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001707# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001708 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001709
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001710 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001711# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001712 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001713# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001714 )
1715 return TRUE;
1716
1717 if (msec > 0)
1718 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001719 // If the specified wait time has passed, return. Beware that
1720 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001721 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001722 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001723 break;
1724 }
1725 if (msec != 0)
1726 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001727 DWORD dwWaitTime = dwEndTime - dwNow;
1728
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001729 // Don't wait for more than 11 msec to avoid dropping characters,
1730 // check channel while waiting for input and handle a callback from
1731 // 'balloonexpr'.
1732 if (dwWaitTime > 11)
1733 dwWaitTime = 11;
1734
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001735# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001736 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001737 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001738# endif
1739# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001740 // When waiting very briefly don't trigger timers.
1741 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001742 {
1743 long due_time;
1744
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001745 // Trigger timers and then get the time in msec until the next
1746 // one is due. Wait up to that time.
1747 due_time = check_due_timer();
1748 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001749 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001750 // timer may have used feedkeys().
1751 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001752 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001753 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1754 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001755 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001756# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001757 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001758# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001759 // Wait for either an event on the console input or a
1760 // message in the client-server window.
1761 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1762 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001763# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001764 wait_for_single_object(g_hConIn, dwWaitTime)
1765 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001766# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001767 )
1768 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001769 }
1770
1771 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001772 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001773
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001774# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02001775 // May have to redraw if the cursor ends up in the wrong place.
1776 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01001777 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001778 {
1779 CONSOLE_SCREEN_BUFFER_INFO csbi;
1780
1781 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1782 {
1783 if (csbi.dwCursorPosition.Y != msg_row)
1784 {
matveyte08795e2021-05-07 15:00:17 +02001785 // The screen is now messed up, must redraw the command
1786 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01001787 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02001788 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001789 redrawcmd();
1790 }
1791 }
1792 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001793# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001794
1795 if (cRecords > 0)
1796 {
1797 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1798 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001799# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01001800 // Windows IME sends two '\n's with only one 'ENTER'. First:
1801 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00001802 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001803 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1804 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001805 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001806 continue;
1807 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001808# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001809 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1810 NULL, FALSE))
1811 return TRUE;
1812 }
1813
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001814 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001815
1816 if (ir.EventType == FOCUS_EVENT)
1817 handle_focus_event(ir);
1818 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001819 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001820 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1821
Bram Moolenaar36698e32019-12-11 22:57:40 +01001822 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001823 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001824 if (dwSize.X != Columns || dwSize.Y != Rows)
1825 {
1826 CONSOLE_SCREEN_BUFFER_INFO csbi;
1827 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01001828 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001829 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01001830 if (dwSize.X != Columns || dwSize.Y != Rows)
1831 {
1832 ResizeConBuf(g_hConOut, dwSize);
1833 shell_resized();
1834 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001835 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001836 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001837 else if (ir.EventType == MOUSE_EVENT
1838 && decode_mouse_event(&ir.Event.MouseEvent))
1839 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001840 }
1841 else if (msec == 0)
1842 break;
1843 }
1844
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001845# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01001846 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001847 if (input_available())
1848 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001849# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001850
Bram Moolenaar071d4272004-06-13 20:20:40 +00001851 return FALSE;
1852}
1853
Bram Moolenaar071d4272004-06-13 20:20:40 +00001854/*
1855 * return non-zero if a character is available
1856 */
1857 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001858mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001859{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001860# ifdef VIMDLL
1861 if (gui.in_use)
1862 return TRUE;
1863# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001864 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001865}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001866
1867# if defined(FEAT_TERMINAL) || defined(PROTO)
1868/*
1869 * Check for any pending input or messages.
1870 */
1871 int
1872mch_check_messages(void)
1873{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001874# ifdef VIMDLL
1875 if (gui.in_use)
1876 return TRUE;
1877# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001878 return WaitForChar(0L, TRUE);
1879}
1880# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001881
1882/*
1883 * Create the console input. Used when reading stdin doesn't work.
1884 */
1885 static void
1886create_conin(void)
1887{
1888 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1889 FILE_SHARE_READ|FILE_SHARE_WRITE,
1890 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001891 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001892 did_create_conin = TRUE;
1893}
1894
1895/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001896 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001897 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001898 static WCHAR
1899tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001900{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001901 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001902
1903 for (;;)
1904 {
1905 INPUT_RECORD ir;
1906 DWORD cRecords = 0;
1907
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001908# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001909 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001910 if (input_available())
1911 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001912 if (g_nMouseClick != -1)
1913 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001914# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001915 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001916 {
1917 if (did_create_conin)
1918 read_error_exit();
1919 create_conin();
1920 continue;
1921 }
1922
1923 if (ir.EventType == KEY_EVENT)
1924 {
1925 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1926 pmodifiers, TRUE))
1927 return ch;
1928 }
1929 else if (ir.EventType == FOCUS_EVENT)
1930 handle_focus_event(ir);
1931 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1932 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001933 else if (ir.EventType == MOUSE_EVENT)
1934 {
1935 if (decode_mouse_event(&ir.Event.MouseEvent))
1936 return 0;
1937 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001938 }
1939}
Bram Moolenaar0f873732019-12-05 20:28:46 +01001940#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001941
1942
1943/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001944 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001945 * Get one or more characters from the keyboard or the mouse.
1946 * If time == 0, do not wait for characters.
1947 * If time == n, wait a short time for characters.
1948 * If time == -1, wait forever for characters.
1949 * Returns the number of characters read into buf.
1950 */
1951 int
1952mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001953 char_u *buf UNUSED,
1954 int maxlen UNUSED,
1955 long time UNUSED,
1956 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001957{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001958#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001959
1960 int len;
1961 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001962# ifdef VIMDLL
1963// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
1964# define TYPEAHEADSPACE 6
1965# else
1966# define TYPEAHEADSPACE 0
1967# endif
1968# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001969 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001970 static int typeaheadlen = 0;
1971
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001972# ifdef VIMDLL
1973 if (gui.in_use)
1974 return 0;
1975# endif
1976
Bram Moolenaar0f873732019-12-05 20:28:46 +01001977 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001978 if (typeaheadlen > 0)
1979 goto theend;
1980
Bram Moolenaar071d4272004-06-13 20:20:40 +00001981 if (time >= 0)
1982 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001983 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00001984 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001985 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001986 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00001987 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001988 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00001989
Bram Moolenaar3918c952005-03-15 22:34:55 +00001990 /*
1991 * If there is no character available within 2 seconds (default)
1992 * write the autoscript file to disk. Or cause the CursorHold event
1993 * to be triggered.
1994 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001995 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001996 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001997 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001998 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001999 buf[0] = K_SPECIAL;
2000 buf[1] = KS_EXTRA;
2001 buf[2] = (int)KE_CURSORHOLD;
2002 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002003 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00002004 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002005 }
2006 }
2007
2008 /*
2009 * Try to read as many characters as there are, until the buffer is full.
2010 */
2011
Bram Moolenaar0f873732019-12-05 20:28:46 +01002012 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002013 g_fCBrkPressed = FALSE;
2014
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002015# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002016 if (fdDump)
2017 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002018# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002019
Bram Moolenaar0f873732019-12-05 20:28:46 +01002020 // Keep looping until there is something in the typeahead buffer and more
2021 // to get and still room in the buffer (up to two bytes for a char and
2022 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002023 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01002024 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002025 {
2026 if (typebuf_changed(tb_change_cnt))
2027 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002028 // "buf" may be invalid now if a client put something in the
2029 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002030 typeaheadlen = 0;
2031 break;
2032 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002033 if (g_nMouseClick != -1)
2034 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002035# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002036 if (fdDump)
2037 fprintf(fdDump, "{%02x @ %d, %d}",
2038 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002039# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01002040 char_u modifiers = ((char_u *)(&g_nMouseClick))[0];
2041 char_u scroll_dir = ((char_u *)(&g_nMouseClick))[1];
2042
2043 if (scroll_dir == KE_MOUSEDOWN
2044 || scroll_dir == KE_MOUSEUP
2045 || scroll_dir == KE_MOUSELEFT
2046 || scroll_dir == KE_MOUSERIGHT)
2047 {
2048 if (modifiers > 0)
2049 {
2050 typeahead[typeaheadlen++] = CSI;
2051 typeahead[typeaheadlen++] = KS_MODIFIER;
2052 typeahead[typeaheadlen++] = modifiers;
2053 }
2054 typeahead[typeaheadlen++] = CSI;
2055 typeahead[typeaheadlen++] = KS_EXTRA;
2056 typeahead[typeaheadlen++] = scroll_dir;
2057 g_nMouseClick = -1;
2058 }
2059 else
2060 {
2061 typeahead[typeaheadlen++] = ESC + 128;
2062 typeahead[typeaheadlen++] = 'M';
2063 typeahead[typeaheadlen++] = g_nMouseClick;
2064 typeahead[typeaheadlen++] = g_xMouse + '!';
2065 typeahead[typeaheadlen++] = g_yMouse + '!';
2066 g_nMouseClick = -1;
2067 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002068 }
2069 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002070 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002071 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002072 int modifiers = 0;
2073
2074 c = tgetch(&modifiers, &ch2);
2075
2076 if (typebuf_changed(tb_change_cnt))
2077 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002078 // "buf" may be invalid now if a client put something in the
2079 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002080 typeaheadlen = 0;
2081 break;
2082 }
2083
2084 if (c == Ctrl_C && ctrl_c_interrupts)
2085 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002086# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002087 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002088# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002089 got_int = TRUE;
2090 }
2091
Bram Moolenaar071d4272004-06-13 20:20:40 +00002092 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002093 {
2094 int n = 1;
2095
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002096 if (ch2 == NUL)
2097 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002098 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002099 char_u *p;
2100 WCHAR ch[2];
2101
2102 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002103 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002104 {
2105 ch[1] = tgetch(&modifiers, &ch2);
2106 n++;
2107 }
2108 p = utf16_to_enc(ch, &n);
2109 if (p != NULL)
2110 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002111 for (i = 0, j = 0; i < n; i++)
2112 {
2113 typeahead[typeaheadlen + j++] = p[i];
2114# ifdef VIMDLL
2115 if (p[i] == CSI)
2116 {
2117 typeahead[typeaheadlen + j++] = KS_EXTRA;
2118 typeahead[typeaheadlen + j++] = KE_CSI;
2119 }
2120# endif
2121 }
2122 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002123 vim_free(p);
2124 }
2125 }
2126 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002127 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002128 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002129# ifdef VIMDLL
2130 if (c == CSI)
2131 {
2132 typeahead[typeaheadlen + 1] = KS_EXTRA;
2133 typeahead[typeaheadlen + 2] = KE_CSI;
2134 n = 3;
2135 }
2136# endif
2137 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002138 if (ch2 != NUL)
2139 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002140 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002141 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002142 switch (ch2)
2143 {
2144 case (WCHAR)'\324': // SHIFT+Insert
2145 case (WCHAR)'\325': // CTRL+Insert
2146 case (WCHAR)'\327': // SHIFT+Delete
2147 case (WCHAR)'\330': // CTRL+Delete
2148 typeahead[typeaheadlen + n] = (char_u)ch2;
2149 n++;
2150 break;
2151
2152 default:
2153 typeahead[typeaheadlen + n] = 3;
2154 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2155 n += 2;
2156 break;
2157 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002158 }
2159 else
2160 {
2161 typeahead[typeaheadlen + n] = 3;
2162 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2163 n += 2;
2164 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002165 }
2166
Bram Moolenaar0f873732019-12-05 20:28:46 +01002167 // Use the ALT key to set the 8th bit of the character
2168 // when it's one byte, the 8th bit isn't set yet and not
2169 // using a double-byte encoding (would become a lead
2170 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002171 if ((modifiers & MOD_MASK_ALT)
2172 && n == 1
2173 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002174 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002175 )
2176 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002177 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2178 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002179 modifiers &= ~MOD_MASK_ALT;
2180 }
2181
2182 if (modifiers != 0)
2183 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002184 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002185 mch_memmove(typeahead + typeaheadlen + 3,
2186 typeahead + typeaheadlen, n);
2187 typeahead[typeaheadlen++] = K_SPECIAL;
2188 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2189 typeahead[typeaheadlen++] = modifiers;
2190 }
2191
2192 typeaheadlen += n;
2193
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002194# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002195 if (fdDump)
2196 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002197# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002198 }
2199 }
2200 }
2201
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002202# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002203 if (fdDump)
2204 {
2205 fputs("]\n", fdDump);
2206 fflush(fdDump);
2207 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002208# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002209
Bram Moolenaar071d4272004-06-13 20:20:40 +00002210theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002211 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002212 len = 0;
2213 while (len < maxlen && typeaheadlen > 0)
2214 {
2215 buf[len++] = typeahead[0];
2216 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2217 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002218# ifdef FEAT_JOB_CHANNEL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002219 if (len > 0)
2220 {
2221 buf[len] = NUL;
2222 ch_log(NULL, "raw key input: \"%s\"", buf);
2223 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002224# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002225 return len;
2226
Bram Moolenaar0f873732019-12-05 20:28:46 +01002227#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002228 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002229#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002230}
2231
Bram Moolenaar82881492012-11-20 16:53:39 +01002232#ifndef PROTO
2233# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002234# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002235# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002236#endif
2237
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002238/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002239 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002240 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2241 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002242 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002243 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002244 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002245executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002246{
LemonBoy40fd7e62022-05-05 20:18:16 +01002247 int attrs = win32_getattrs((char_u *)name);
2248
2249 // The file doesn't exist or is a folder.
2250 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2251 return FALSE;
2252 // Check if the file is an AppExecLink, a special alias used by Windows
2253 // Store for its apps.
2254 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002255 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002256 char_u *res = resolve_appexeclink((char_u *)name);
2257 if (res == NULL)
2258 return FALSE;
2259 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002260 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002261 *path = res;
2262 else
2263 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002264 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002265 else if (path != NULL)
2266 *path = FullName_save((char_u *)name, FALSE);
2267 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002268}
2269
2270/*
2271 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2272 * If "use_path" is FALSE: Return TRUE if "name" exists.
2273 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2274 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2275 * the allocated memory.
2276 */
2277 static int
2278executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2279{
2280 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2281 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2282 // UTF-8.
2283 char_u buf[_MAX_PATH * 3];
2284 size_t len = STRLEN(name);
2285 size_t tmplen;
2286 char_u *p, *e, *e2;
2287 char_u *pathbuf = NULL;
2288 char_u *pathext = NULL;
2289 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002290 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002291 int noext = FALSE;
2292 int retval = FALSE;
2293
2294 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002295 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002296
2297 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002298 shname = gettail(p_sh);
2299 if (strstr((char *)shname, "sh") != NULL &&
2300 !(strstr((char *)shname, "powershell") != NULL
2301 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002302 noext = TRUE;
2303
2304 if (use_pathext)
2305 {
2306 pathext = mch_getenv("PATHEXT");
2307 if (pathext == NULL)
2308 pathext = (char_u *)".com;.exe;.bat;.cmd";
2309
2310 if (noext == FALSE)
2311 {
2312 /*
2313 * Loop over all extensions in $PATHEXT.
2314 * Check "name" ends with extension.
2315 */
2316 p = pathext;
2317 while (*p)
2318 {
2319 if (p[0] == ';'
2320 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2321 {
2322 // Skip empty or single ".".
2323 ++p;
2324 continue;
2325 }
2326 e = vim_strchr(p, ';');
2327 if (e == NULL)
2328 e = p + STRLEN(p);
2329 tmplen = e - p;
2330
2331 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2332 {
2333 noext = TRUE;
2334 break;
2335 }
2336
2337 p = e;
2338 }
2339 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002340 }
2341
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002342 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002343 if (pathext == NULL)
2344 pathext = (char_u *)".";
2345 else if (noext == TRUE)
2346 {
2347 if (pathextbuf == NULL)
2348 pathextbuf = alloc(STRLEN(pathext) + 3);
2349 if (pathextbuf == NULL)
2350 {
2351 retval = FALSE;
2352 goto theend;
2353 }
2354 STRCPY(pathextbuf, ".;");
2355 STRCAT(pathextbuf, pathext);
2356 pathext = pathextbuf;
2357 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002358
Bram Moolenaar95da1362020-05-30 18:37:55 +02002359 // Use $PATH when "use_path" is TRUE and "name" is basename.
2360 if (use_path && gettail((char_u *)name) == (char_u *)name)
2361 {
2362 p = mch_getenv("PATH");
2363 if (p != NULL)
2364 {
2365 pathbuf = alloc(STRLEN(p) + 3);
2366 if (pathbuf == NULL)
2367 {
2368 retval = FALSE;
2369 goto theend;
2370 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002371
2372 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2373 STRCPY(pathbuf, ".;");
2374 else
2375 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002376 STRCAT(pathbuf, p);
2377 }
2378 }
2379
2380 /*
2381 * Walk through all entries in $PATH to check if "name" exists there and
2382 * is an executable file.
2383 */
2384 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2385 while (*p)
2386 {
2387 if (*p == ';') // Skip empty entry
2388 {
2389 ++p;
2390 continue;
2391 }
2392 e = vim_strchr(p, ';');
2393 if (e == NULL)
2394 e = p + STRLEN(p);
2395
2396 if (e - p + len + 2 > sizeof(buf))
2397 {
2398 retval = FALSE;
2399 goto theend;
2400 }
2401 // A single "." that means current dir.
2402 if (e - p == 1 && *p == '.')
2403 STRCPY(buf, name);
2404 else
2405 {
2406 vim_strncpy(buf, p, e - p);
2407 add_pathsep(buf);
2408 STRCAT(buf, name);
2409 }
2410 tmplen = STRLEN(buf);
2411
2412 /*
2413 * Loop over all extensions in $PATHEXT.
2414 * Check "name" with extension added.
2415 */
2416 p = pathext;
2417 while (*p)
2418 {
2419 if (*p == ';')
2420 {
2421 // Skip empty entry
2422 ++p;
2423 continue;
2424 }
2425 e2 = vim_strchr(p, (int)';');
2426 if (e2 == NULL)
2427 e2 = p + STRLEN(p);
2428
2429 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2430 {
2431 // Not a single "." that means no extension is added.
2432 if (e2 - p + tmplen + 1 > sizeof(buf))
2433 {
2434 retval = FALSE;
2435 goto theend;
2436 }
2437 vim_strncpy(buf + tmplen, p, e2 - p);
2438 }
2439 if (executable_file((char *)buf, path))
2440 {
2441 retval = TRUE;
2442 goto theend;
2443 }
2444
2445 p = e2;
2446 }
2447
2448 p = e;
2449 }
2450
2451theend:
2452 free(pathextbuf);
2453 free(pathbuf);
2454 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002455}
2456
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002457#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2458 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002459/*
2460 * Bad parameter handler.
2461 *
2462 * Certain MS CRT functions will intentionally crash when passed invalid
2463 * parameters to highlight possible security holes. Setting this function as
2464 * the bad parameter handler will prevent the crash.
2465 *
2466 * In debug builds the parameters contain CRT information that might help track
2467 * down the source of a problem, but in non-debug builds the arguments are all
2468 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2469 * worth allowing these to make debugging of issues easier.
2470 */
2471 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002472bad_param_handler(const wchar_t *expression UNUSED,
2473 const wchar_t *function UNUSED,
2474 const wchar_t *file UNUSED,
2475 unsigned int line UNUSED,
2476 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002477{
2478}
2479
2480# define SET_INVALID_PARAM_HANDLER \
2481 ((void)_set_invalid_parameter_handler(bad_param_handler))
2482#else
2483# define SET_INVALID_PARAM_HANDLER
2484#endif
2485
Bram Moolenaar4f974752019-02-17 17:44:42 +01002486#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002487
2488/*
2489 * GUI version of mch_init().
2490 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002491 static void
2492mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002494# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002495 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002496# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002497
Bram Moolenaar0f873732019-12-05 20:28:46 +01002498 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002499 SET_INVALID_PARAM_HANDLER;
2500
Bram Moolenaar0f873732019-12-05 20:28:46 +01002501 // Let critical errors result in a failure, not in a dialog box. Required
2502 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002503 SetErrorMode(SEM_FAILCRITICALERRORS);
2504
Bram Moolenaar0f873732019-12-05 20:28:46 +01002505 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002506
Bram Moolenaar0f873732019-12-05 20:28:46 +01002507 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002508 Rows = 25;
2509 Columns = 80;
2510
Bram Moolenaar0f873732019-12-05 20:28:46 +01002511 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002512 {
2513 char_u vimrun_location[_MAX_PATH + 4];
2514
Bram Moolenaar0f873732019-12-05 20:28:46 +01002515 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002516 STRCPY(vimrun_location, exe_name);
2517 STRCPY(gettail(vimrun_location), "vimrun.exe");
2518 if (mch_getperm(vimrun_location) >= 0)
2519 {
2520 if (*skiptowhite(vimrun_location) != NUL)
2521 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002522 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002523 mch_memmove(vimrun_location + 1, vimrun_location,
2524 STRLEN(vimrun_location) + 1);
2525 *vimrun_location = '"';
2526 STRCPY(gettail(vimrun_location), "vimrun\" ");
2527 }
2528 else
2529 STRCPY(gettail(vimrun_location), "vimrun ");
2530
2531 vimrun_path = (char *)vim_strsave(vimrun_location);
2532 s_dont_use_vimrun = FALSE;
2533 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002534 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002535 s_dont_use_vimrun = FALSE;
2536
Bram Moolenaar0f873732019-12-05 20:28:46 +01002537 // Don't give the warning for a missing vimrun.exe right now, but only
2538 // when vimrun was supposed to be used. Don't bother people that do
2539 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002540 if (s_dont_use_vimrun)
2541 need_vimrun_warning = TRUE;
2542 }
2543
2544 /*
2545 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2546 * Otherwise the default "findstr /n" is used.
2547 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002548 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01002549 set_option_value_give_err((char_u *)"grepprg",
2550 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002551
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002552# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002553 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002554# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002555
2556 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002557}
2558
2559
Bram Moolenaar0f873732019-12-05 20:28:46 +01002560#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002561
2562#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002563
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002564# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2565# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002566
2567/*
2568 * ClearConsoleBuffer()
2569 * Description:
2570 * Clears the entire contents of the console screen buffer, using the
2571 * specified attribute.
2572 * Returns:
2573 * TRUE on success
2574 */
2575 static BOOL
2576ClearConsoleBuffer(WORD wAttribute)
2577{
2578 CONSOLE_SCREEN_BUFFER_INFO csbi;
2579 COORD coord;
2580 DWORD NumCells, dummy;
2581
2582 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2583 return FALSE;
2584
2585 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2586 coord.X = 0;
2587 coord.Y = 0;
2588 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2589 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002590 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002591 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2592 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002593 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002594
2595 return TRUE;
2596}
2597
2598/*
2599 * FitConsoleWindow()
2600 * Description:
2601 * Checks if the console window will fit within given buffer dimensions.
2602 * Also, if requested, will shrink the window to fit.
2603 * Returns:
2604 * TRUE on success
2605 */
2606 static BOOL
2607FitConsoleWindow(
2608 COORD dwBufferSize,
2609 BOOL WantAdjust)
2610{
2611 CONSOLE_SCREEN_BUFFER_INFO csbi;
2612 COORD dwWindowSize;
2613 BOOL NeedAdjust = FALSE;
2614
2615 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2616 {
2617 /*
2618 * A buffer resize will fail if the current console window does
2619 * not lie completely within that buffer. To avoid this, we might
2620 * have to move and possibly shrink the window.
2621 */
2622 if (csbi.srWindow.Right >= dwBufferSize.X)
2623 {
2624 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2625 if (dwWindowSize.X > dwBufferSize.X)
2626 dwWindowSize.X = dwBufferSize.X;
2627 csbi.srWindow.Right = dwBufferSize.X - 1;
2628 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2629 NeedAdjust = TRUE;
2630 }
2631 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2632 {
2633 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2634 if (dwWindowSize.Y > dwBufferSize.Y)
2635 dwWindowSize.Y = dwBufferSize.Y;
2636 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2637 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2638 NeedAdjust = TRUE;
2639 }
2640 if (NeedAdjust && WantAdjust)
2641 {
2642 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2643 return FALSE;
2644 }
2645 return TRUE;
2646 }
2647
2648 return FALSE;
2649}
2650
2651typedef struct ConsoleBufferStruct
2652{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002653 BOOL IsValid;
2654 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002655 PCHAR_INFO Buffer;
2656 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002657 PSMALL_RECT Regions;
2658 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002659} ConsoleBuffer;
2660
2661/*
2662 * SaveConsoleBuffer()
2663 * Description:
2664 * Saves important information about the console buffer, including the
2665 * actual buffer contents. The saved information is suitable for later
2666 * restoration by RestoreConsoleBuffer().
2667 * Returns:
2668 * TRUE if all information was saved; FALSE otherwise
2669 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2670 */
2671 static BOOL
2672SaveConsoleBuffer(
2673 ConsoleBuffer *cb)
2674{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002675 DWORD NumCells;
2676 COORD BufferCoord;
2677 SMALL_RECT ReadRegion;
2678 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002679 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002680
Bram Moolenaar071d4272004-06-13 20:20:40 +00002681 if (cb == NULL)
2682 return FALSE;
2683
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002684 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002685 {
2686 cb->IsValid = FALSE;
2687 return FALSE;
2688 }
2689 cb->IsValid = TRUE;
2690
Christopher Plewright1140b512022-11-12 18:46:05 +00002691 // VTP uses alternate screen buffer.
2692 // No need to save buffer contents for restoration.
2693 if (win11_or_later && vtp_working)
2694 return TRUE;
2695
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002696 /*
2697 * Allocate a buffer large enough to hold the entire console screen
2698 * buffer. If this ConsoleBuffer structure has already been initialized
2699 * with a buffer of the correct size, then just use that one.
2700 */
2701 if (!cb->IsValid || cb->Buffer == NULL ||
2702 cb->BufferSize.X != cb->Info.dwSize.X ||
2703 cb->BufferSize.Y != cb->Info.dwSize.Y)
2704 {
2705 cb->BufferSize.X = cb->Info.dwSize.X;
2706 cb->BufferSize.Y = cb->Info.dwSize.Y;
2707 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2708 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002709 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002710 if (cb->Buffer == NULL)
2711 return FALSE;
2712 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002713
2714 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002715 * We will now copy the console screen buffer into our buffer.
2716 * ReadConsoleOutput() seems to be limited as far as how much you
2717 * can read at a time. Empirically, this number seems to be about
2718 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2719 * in chunks until it is all copied. The chunks will all have the
2720 * same horizontal characteristics, so initialize them now. The
2721 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002722 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002723 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002724 ReadRegion.Left = 0;
2725 ReadRegion.Right = cb->Info.dwSize.X - 1;
2726 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002727
2728 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2729 if (cb->Regions == NULL || numregions != cb->NumRegions)
2730 {
2731 cb->NumRegions = numregions;
2732 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002733 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002734 if (cb->Regions == NULL)
2735 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002736 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002737 return FALSE;
2738 }
2739 }
2740
2741 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002742 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002743 /*
2744 * Read into position (0, Y) in our buffer.
2745 */
2746 BufferCoord.Y = Y;
2747 /*
2748 * Read the region whose top left corner is (0, Y) and whose bottom
2749 * right corner is (width - 1, Y + Y_incr - 1). This should define
2750 * a region of size width by Y_incr. Don't worry if this region is
2751 * too large for the remaining buffer; it will be cropped.
2752 */
2753 ReadRegion.Top = Y;
2754 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002755 if (!ReadConsoleOutputW(g_hConOut, // output handle
2756 cb->Buffer, // our buffer
2757 cb->BufferSize, // dimensions of our buffer
2758 BufferCoord, // offset in our buffer
2759 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002760 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002761 VIM_CLEAR(cb->Buffer);
2762 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002763 return FALSE;
2764 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002765 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002766 }
2767
2768 return TRUE;
2769}
2770
2771/*
2772 * RestoreConsoleBuffer()
2773 * Description:
2774 * Restores important information about the console buffer, including the
2775 * actual buffer contents, if desired. The information to restore is in
2776 * the same format used by SaveConsoleBuffer().
2777 * Returns:
2778 * TRUE on success
2779 */
2780 static BOOL
2781RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002782 ConsoleBuffer *cb,
2783 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002784{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002785 COORD BufferCoord;
2786 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002787 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002788
Christopher Plewright1140b512022-11-12 18:46:05 +00002789 // VTP uses alternate screen buffer.
2790 // No need to restore buffer contents.
2791 if (win11_or_later && vtp_working)
2792 return TRUE;
2793
Bram Moolenaar071d4272004-06-13 20:20:40 +00002794 if (cb == NULL || !cb->IsValid)
2795 return FALSE;
2796
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002797 /*
2798 * Before restoring the buffer contents, clear the current buffer, and
2799 * restore the cursor position and window information. Doing this now
2800 * prevents old buffer contents from "flashing" onto the screen.
2801 */
2802 if (RestoreScreen)
2803 ClearConsoleBuffer(cb->Info.wAttributes);
2804
2805 FitConsoleWindow(cb->Info.dwSize, TRUE);
2806 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2807 return FALSE;
2808 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2809 return FALSE;
2810
2811 if (!RestoreScreen)
2812 {
2813 /*
2814 * No need to restore the screen buffer contents, so we're done.
2815 */
2816 return TRUE;
2817 }
2818
2819 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2820 return FALSE;
2821 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2822 return FALSE;
2823
2824 /*
2825 * Restore the screen buffer contents.
2826 */
2827 if (cb->Buffer != NULL)
2828 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002829 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002830 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002831 BufferCoord.X = cb->Regions[i].Left;
2832 BufferCoord.Y = cb->Regions[i].Top;
2833 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01002834 if (!WriteConsoleOutputW(g_hConOut, // output handle
2835 cb->Buffer, // our buffer
2836 cb->BufferSize, // dimensions of our buffer
2837 BufferCoord, // offset in our buffer
2838 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02002839 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002840 }
2841 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002842
2843 return TRUE;
2844}
2845
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002846# define FEAT_RESTORE_ORIG_SCREEN
2847# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002848static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002849# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002850static ConsoleBuffer g_cbNonTermcap = { 0 };
2851static ConsoleBuffer g_cbTermcap = { 0 };
2852
Bram Moolenaar071d4272004-06-13 20:20:40 +00002853char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01002854HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00002855static HICON g_hOrigIconSmall = NULL;
2856static HICON g_hOrigIcon = NULL;
2857static HICON g_hVimIcon = NULL;
2858static BOOL g_fCanChangeIcon = FALSE;
2859
Bram Moolenaar071d4272004-06-13 20:20:40 +00002860/*
2861 * GetConsoleIcon()
2862 * Description:
2863 * Attempts to retrieve the small icon and/or the big icon currently in
2864 * use by a given window.
2865 * Returns:
2866 * TRUE on success
2867 */
2868 static BOOL
2869GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002870 HWND hWnd,
2871 HICON *phIconSmall,
2872 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002873{
2874 if (hWnd == NULL)
2875 return FALSE;
2876
2877 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002878 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2879 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002880 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002881 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2882 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002883 return TRUE;
2884}
2885
2886/*
2887 * SetConsoleIcon()
2888 * Description:
2889 * Attempts to change the small icon and/or the big icon currently in
2890 * use by a given window.
2891 * Returns:
2892 * TRUE on success
2893 */
2894 static BOOL
2895SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002896 HWND hWnd,
2897 HICON hIconSmall,
2898 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002899{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002900 if (hWnd == NULL)
2901 return FALSE;
2902
2903 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002904 SendMessage(hWnd, WM_SETICON,
2905 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002906 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002907 SendMessage(hWnd, WM_SETICON,
2908 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002909 return TRUE;
2910}
2911
2912/*
2913 * SaveConsoleTitleAndIcon()
2914 * Description:
2915 * Saves the current console window title in g_szOrigTitle, for later
2916 * restoration. Also, attempts to obtain a handle to the console window,
2917 * and use it to save the small and big icons currently in use by the
2918 * console window. This is not always possible on some versions of Windows;
2919 * nor is it possible when running Vim remotely using Telnet (since the
2920 * console window the user sees is owned by a remote process).
2921 */
2922 static void
2923SaveConsoleTitleAndIcon(void)
2924{
Bram Moolenaar0f873732019-12-05 20:28:46 +01002925 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002926 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2927 return;
2928
2929 /*
2930 * Obtain a handle to the console window using GetConsoleWindow() from
2931 * KERNEL32.DLL; we need to handle in order to change the window icon.
2932 * This function only exists on NT-based Windows, starting with Windows
2933 * 2000. On older operating systems, we can't change the window icon
2934 * anyway.
2935 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002936 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002937 if (g_hWnd == NULL)
2938 return;
2939
Bram Moolenaar0f873732019-12-05 20:28:46 +01002940 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002941 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2942 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2943 return;
2944
Bram Moolenaar0f873732019-12-05 20:28:46 +01002945 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01002946 if (
2947# ifdef FEAT_LIBCALL
2948 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
2949# endif
2950 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002951 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002952 if (g_hVimIcon != NULL)
2953 g_fCanChangeIcon = TRUE;
2954}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002955
2956static int g_fWindInitCalled = FALSE;
2957static int g_fTermcapMode = FALSE;
2958static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002959
2960/*
2961 * non-GUI version of mch_init().
2962 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002963 static void
2964mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002965{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002966# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002967 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002968# endif
2969# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002970 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002971# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002972
Bram Moolenaar0f873732019-12-05 20:28:46 +01002973 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002974 SET_INVALID_PARAM_HANDLER;
2975
Bram Moolenaar0f873732019-12-05 20:28:46 +01002976 // Let critical errors result in a failure, not in a dialog box. Required
2977 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002978 SetErrorMode(SEM_FAILCRITICALERRORS);
2979
Bram Moolenaar0f873732019-12-05 20:28:46 +01002980 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002981 out_flush();
2982
Bram Moolenaar0f873732019-12-05 20:28:46 +01002983 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00002984 if (read_cmd_fd == 0)
2985 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2986 else
2987 create_conin();
2988 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2989
Christopher Plewright38804d62022-11-09 23:55:52 +00002990 wt_init();
2991 vtp_flag_init();
2992 vtp_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002993# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01002994 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002995 SaveConsoleBuffer(&g_cbOrig);
2996 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002997# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01002998 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002999 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
3000 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003001# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003002 if (cterm_normal_fg_color == 0)
3003 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
3004 if (cterm_normal_bg_color == 0)
3005 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
3006
Bram Moolenaarbdace832019-03-02 10:13:42 +01003007 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02003008 g_color_index_fg = g_attrDefault & 0xf;
3009 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
3010
Bram Moolenaar0f873732019-12-05 20:28:46 +01003011 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00003012 update_tcap(g_attrCurrent);
3013
3014 GetConsoleCursorInfo(g_hConOut, &g_cci);
3015 GetConsoleMode(g_hConIn, &g_cmodein);
3016 GetConsoleMode(g_hConOut, &g_cmodeout);
3017
Bram Moolenaar071d4272004-06-13 20:20:40 +00003018 SaveConsoleTitleAndIcon();
3019 /*
3020 * Set both the small and big icons of the console window to Vim's icon.
3021 * Note that Vim presently only has one size of icon (32x32), but it
3022 * automatically gets scaled down to 16x16 when setting the small icon.
3023 */
3024 if (g_fCanChangeIcon)
3025 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003026
3027 ui_get_shellsize();
3028
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003029# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003030 fdDump = fopen("dump", "wt");
3031
3032 if (fdDump)
3033 {
3034 time_t t;
3035
3036 time(&t);
3037 fputs(ctime(&t), fdDump);
3038 fflush(fdDump);
3039 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003040# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003041
3042 g_fWindInitCalled = TRUE;
3043
Bram Moolenaar071d4272004-06-13 20:20:40 +00003044 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003045
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003046# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003047 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003048# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003049}
3050
3051/*
3052 * non-GUI version of mch_exit().
3053 * Shut down and exit with status `r'
3054 * Careful: mch_exit() may be called before mch_init()!
3055 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003056 static void
3057mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003058{
Bram Moolenaar955f1982017-02-05 15:10:51 +01003059 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003060
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003061 vtp_exit();
3062
Bram Moolenaar955f1982017-02-05 15:10:51 +01003063 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003064 if (g_fWindInitCalled)
3065 settmode(TMODE_COOK);
3066
Bram Moolenaar0f873732019-12-05 20:28:46 +01003067 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00003068
3069 if (g_fWindInitCalled)
3070 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02003071 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003072 /*
3073 * Restore both the small and big icons of the console window to
3074 * what they were at startup. Don't do this when the window is
3075 * closed, Vim would hang here.
3076 */
3077 if (g_fCanChangeIcon && !g_fForceExit)
3078 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003079
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003080# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003081 if (fdDump)
3082 {
3083 time_t t;
3084
3085 time(&t);
3086 fputs(ctime(&t), fdDump);
3087 fclose(fdDump);
3088 }
3089 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003090# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003091 }
3092
3093 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003094 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003095 SetConsoleMode(g_hConOut, g_cmodeout);
3096
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003097# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003098 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003099# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003100
3101 exit(r);
3102}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003103#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003104
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003105 void
3106mch_init(void)
3107{
3108#ifdef VIMDLL
3109 if (gui.starting)
3110 mch_init_g();
3111 else
3112 mch_init_c();
3113#elif defined(FEAT_GUI_MSWIN)
3114 mch_init_g();
3115#else
3116 mch_init_c();
3117#endif
3118}
3119
3120 void
3121mch_exit(int r)
3122{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003123#ifdef FEAT_NETBEANS_INTG
3124 netbeans_send_disconnect();
3125#endif
3126
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003127#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003128 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003129 mch_exit_g(r);
3130 else
3131 mch_exit_c(r);
3132#elif defined(FEAT_GUI_MSWIN)
3133 mch_exit_g(r);
3134#else
3135 mch_exit_c(r);
3136#endif
3137}
3138
Bram Moolenaar071d4272004-06-13 20:20:40 +00003139/*
3140 * Do we have an interactive window?
3141 */
3142 int
3143mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003144 int argc UNUSED,
3145 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003146{
3147 get_exe_name();
3148
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003149#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003150 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003151#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003152# ifdef VIMDLL
3153 if (gui.in_use)
3154 return OK;
3155# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003156 if (isatty(1))
3157 return OK;
3158 return FAIL;
3159#endif
3160}
3161
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003162/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003163 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003164 * When "len" is > 0, also expand short to long filenames.
3165 */
3166 void
3167fname_case(
3168 char_u *name,
3169 int len)
3170{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003171 int flen;
3172 WCHAR *p;
3173 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003174
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003175 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003176 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003177 return;
3178
3179 slash_adjust(name);
3180
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003181 p = enc_to_utf16(name, NULL);
3182 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003183 return;
3184
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003185 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003186 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003187 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003188
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003189 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003190 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003191 if (len > 0 || flen >= (int)STRLEN(q))
3192 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3193 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003194 }
3195 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003196 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003197}
3198
3199
3200/*
3201 * Insert user name in s[len].
3202 */
3203 int
3204mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003205 char_u *s,
3206 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003207{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003208 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003209 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003210
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003211 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003212 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003213 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003214
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003215 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003216 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003217 vim_strncpy(s, p, len - 1);
3218 vim_free(p);
3219 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003220 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003221 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003222 s[0] = NUL;
3223 return FAIL;
3224}
3225
3226
3227/*
3228 * Insert host name in s[len].
3229 */
3230 void
3231mch_get_host_name(
3232 char_u *s,
3233 int len)
3234{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003235 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003236 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003237
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003238 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003239 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003240 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003241
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003242 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003243 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003244 vim_strncpy(s, p, len - 1);
3245 vim_free(p);
3246 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003247 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003248 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003249}
3250
3251
3252/*
3253 * return process ID
3254 */
3255 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003256mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003257{
3258 return (long)GetCurrentProcessId();
3259}
3260
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003261/*
3262 * return TRUE if process "pid" is still running
3263 */
3264 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003265mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003266{
3267 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3268 DWORD status = 0;
3269 int ret = FALSE;
3270
3271 if (hProcess == NULL)
3272 return FALSE; // might not have access
3273 if (GetExitCodeProcess(hProcess, &status) )
3274 ret = status == STILL_ACTIVE;
3275 CloseHandle(hProcess);
3276 return ret;
3277}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003278
3279/*
3280 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3281 * Return OK for success, FAIL for failure.
3282 */
3283 int
3284mch_dirname(
3285 char_u *buf,
3286 int len)
3287{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003288 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003289
Bram Moolenaar071d4272004-06-13 20:20:40 +00003290 /*
3291 * Originally this was:
3292 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3293 * But the Win32s known bug list says that getcwd() doesn't work
3294 * so use the Win32 system call instead. <Negri>
3295 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003296 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003297 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003298 WCHAR wcbuf[_MAX_PATH + 1];
3299 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003300
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003301 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003302 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003303 p = utf16_to_enc(wcbuf, NULL);
3304 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003305 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003306 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003307 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003308 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003309 }
3310 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003311 if (p == NULL)
3312 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003313
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003314 if (p != NULL)
3315 {
3316 vim_strncpy(buf, p, len - 1);
3317 vim_free(p);
3318 return OK;
3319 }
3320 }
3321 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003322}
3323
3324/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003325 * Get file permissions for "name".
3326 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003327 */
3328 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003329mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003330{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003331 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003332 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003333
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003334 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003335 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003336}
3337
3338
3339/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003340 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003341 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003342 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003343 */
3344 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003345mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003346{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003347 long n;
3348 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003349
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003350 p = enc_to_utf16(name, NULL);
3351 if (p == NULL)
3352 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003353
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003354 n = _wchmod(p, perm);
3355 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003356 if (n == -1)
3357 return FAIL;
3358
3359 win32_set_archive(name);
3360
3361 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003362}
3363
3364/*
3365 * Set hidden flag for "name".
3366 */
3367 void
3368mch_hide(char_u *name)
3369{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003370 int attrs = win32_getattrs(name);
3371 if (attrs == -1)
3372 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003373
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003374 attrs |= FILE_ATTRIBUTE_HIDDEN;
3375 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003376}
3377
3378/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003379 * Return TRUE if file "name" exists and is hidden.
3380 */
3381 int
3382mch_ishidden(char_u *name)
3383{
3384 int f = win32_getattrs(name);
3385
3386 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003387 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003388
3389 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3390}
3391
3392/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003393 * return TRUE if "name" is a directory
3394 * return FALSE if "name" is not a directory or upon error
3395 */
3396 int
3397mch_isdir(char_u *name)
3398{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003399 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003400
3401 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003402 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003403
3404 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3405}
3406
3407/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003408 * return TRUE if "name" is a directory, NOT a symlink to a directory
3409 * return FALSE if "name" is not a directory
3410 * return FALSE for error
3411 */
3412 int
3413mch_isrealdir(char_u *name)
3414{
3415 return mch_isdir(name) && !mch_is_symbolic_link(name);
3416}
3417
3418/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003419 * Create directory "name".
3420 * Return 0 on success, -1 on error.
3421 */
3422 int
3423mch_mkdir(char_u *name)
3424{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003425 WCHAR *p;
3426 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003427
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003428 p = enc_to_utf16(name, NULL);
3429 if (p == NULL)
3430 return -1;
3431 retval = _wmkdir(p);
3432 vim_free(p);
3433 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003434}
3435
3436/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003437 * Delete directory "name".
3438 * Return 0 on success, -1 on error.
3439 */
3440 int
3441mch_rmdir(char_u *name)
3442{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003443 WCHAR *p;
3444 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003445
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003446 p = enc_to_utf16(name, NULL);
3447 if (p == NULL)
3448 return -1;
3449 retval = _wrmdir(p);
3450 vim_free(p);
3451 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003452}
3453
3454/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003455 * Return TRUE if file "fname" has more than one link.
3456 */
3457 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003458mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003459{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003460 BY_HANDLE_FILE_INFORMATION info;
3461
3462 return win32_fileinfo(fname, &info) == FILEINFO_OK
3463 && info.nNumberOfLinks > 1;
3464}
3465
3466/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003467 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003468 */
3469 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003470mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003471{
3472 HANDLE hFind;
3473 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003474 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003475 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003476 WIN32_FIND_DATAW findDataW;
3477
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003478 wn = enc_to_utf16(name, NULL);
3479 if (wn == NULL)
3480 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003481
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003482 hFind = FindFirstFileW(wn, &findDataW);
3483 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003484 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003485 {
3486 fileFlags = findDataW.dwFileAttributes;
3487 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003488 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003489 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003490
3491 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003492 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3493 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003494 res = TRUE;
3495
3496 return res;
3497}
3498
3499/*
3500 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3501 * link.
3502 */
3503 int
3504mch_is_linked(char_u *fname)
3505{
3506 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3507 return TRUE;
3508 return FALSE;
3509}
3510
3511/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003512 * Get the by-handle-file-information for "fname".
3513 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003514 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003515 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3516 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3517 */
3518 int
3519win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3520{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003521 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003522 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003523 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003524
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003525 wn = enc_to_utf16(fname, NULL);
3526 if (wn == NULL)
3527 return FILEINFO_ENC_FAIL;
3528
3529 hFile = CreateFileW(wn, // file name
3530 GENERIC_READ, // access mode
3531 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3532 NULL, // security descriptor
3533 OPEN_EXISTING, // creation disposition
3534 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3535 NULL); // handle to template file
3536 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003537
3538 if (hFile != INVALID_HANDLE_VALUE)
3539 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003540 if (GetFileInformationByHandle(hFile, info) != 0)
3541 res = FILEINFO_OK;
3542 else
3543 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003544 CloseHandle(hFile);
3545 }
3546
Bram Moolenaar03f48552006-02-28 23:52:23 +00003547 return res;
3548}
3549
3550/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003551 * get file attributes for `name'
3552 * -1 : error
3553 * else FILE_ATTRIBUTE_* defined in winnt.h
3554 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003555 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003556win32_getattrs(char_u *name)
3557{
3558 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003559 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003560
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003561 p = enc_to_utf16(name, NULL);
3562 if (p == NULL)
3563 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003564
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003565 attr = GetFileAttributesW(p);
3566 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003567
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003568 return attr;
3569}
3570
3571/*
3572 * set file attributes for `name' to `attrs'
3573 *
3574 * return -1 for failure, 0 otherwise
3575 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003576 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003577win32_setattrs(char_u *name, int attrs)
3578{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003579 int res;
3580 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003581
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003582 p = enc_to_utf16(name, NULL);
3583 if (p == NULL)
3584 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003585
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003586 res = SetFileAttributesW(p, attrs);
3587 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003588
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003589 return res ? 0 : -1;
3590}
3591
3592/*
3593 * Set archive flag for "name".
3594 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003595 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003596win32_set_archive(char_u *name)
3597{
3598 int attrs = win32_getattrs(name);
3599 if (attrs == -1)
3600 return -1;
3601
3602 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3603 return win32_setattrs(name, attrs);
3604}
3605
3606/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003607 * Return TRUE if file or directory "name" is writable (not readonly).
3608 * Strange semantics of Win32: a readonly directory is writable, but you can't
3609 * delete a file. Let's say this means it is writable.
3610 */
3611 int
3612mch_writable(char_u *name)
3613{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003614 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003615
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003616 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3617 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003618}
3619
Bram Moolenaar071d4272004-06-13 20:20:40 +00003620/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003621 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003622 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003623 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3624 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003625 */
3626 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01003627mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003628{
Bram Moolenaar95da1362020-05-30 18:37:55 +02003629 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003630}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003631
3632/*
3633 * Check what "name" is:
3634 * NODE_NORMAL: file or directory (or doesn't exist)
3635 * NODE_WRITABLE: writable device, socket, fifo, etc.
3636 * NODE_OTHER: non-writable things
3637 */
3638 int
3639mch_nodetype(char_u *name)
3640{
3641 HANDLE hFile;
3642 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003643 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003644
Bram Moolenaar0f873732019-12-05 20:28:46 +01003645 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3646 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3647 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00003648 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3649 return NODE_WRITABLE;
3650
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003651 wn = enc_to_utf16(name, NULL);
3652 if (wn == NULL)
3653 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003654
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003655 hFile = CreateFileW(wn, // file name
3656 GENERIC_WRITE, // access mode
3657 0, // share mode
3658 NULL, // security descriptor
3659 OPEN_EXISTING, // creation disposition
3660 0, // file attributes
3661 NULL); // handle to template file
3662 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003663 if (hFile == INVALID_HANDLE_VALUE)
3664 return NODE_NORMAL;
3665
3666 type = GetFileType(hFile);
3667 CloseHandle(hFile);
3668 if (type == FILE_TYPE_CHAR)
3669 return NODE_WRITABLE;
3670 if (type == FILE_TYPE_DISK)
3671 return NODE_NORMAL;
3672 return NODE_OTHER;
3673}
3674
3675#ifdef HAVE_ACL
3676struct my_acl
3677{
3678 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3679 PSID pSidOwner;
3680 PSID pSidGroup;
3681 PACL pDacl;
3682 PACL pSacl;
3683};
3684#endif
3685
3686/*
3687 * Return a pointer to the ACL of file "fname" in allocated memory.
3688 * Return NULL if the ACL is not available for whatever reason.
3689 */
3690 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003691mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003692{
3693#ifndef HAVE_ACL
3694 return (vim_acl_T)NULL;
3695#else
3696 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003697 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003698
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003699 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003700 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003701 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003702 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003703
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003704 wn = enc_to_utf16(fname, NULL);
3705 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003706 {
3707 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003708 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003709 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003710
3711 // Try to retrieve the entire security descriptor.
3712 err = GetNamedSecurityInfoW(
3713 wn, // Abstract filename
3714 SE_FILE_OBJECT, // File Object
3715 OWNER_SECURITY_INFORMATION |
3716 GROUP_SECURITY_INFORMATION |
3717 DACL_SECURITY_INFORMATION |
3718 SACL_SECURITY_INFORMATION,
3719 &p->pSidOwner, // Ownership information.
3720 &p->pSidGroup, // Group membership.
3721 &p->pDacl, // Discretionary information.
3722 &p->pSacl, // For auditing purposes.
3723 &p->pSecurityDescriptor);
3724 if (err == ERROR_ACCESS_DENIED ||
3725 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003726 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003727 // Retrieve only DACL.
3728 (void)GetNamedSecurityInfoW(
3729 wn,
3730 SE_FILE_OBJECT,
3731 DACL_SECURITY_INFORMATION,
3732 NULL,
3733 NULL,
3734 &p->pDacl,
3735 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003736 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003737 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003738 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003739 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003740 mch_free_acl((vim_acl_T)p);
3741 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003742 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003743 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003744 }
3745
3746 return (vim_acl_T)p;
3747#endif
3748}
3749
Bram Moolenaar27515922013-06-29 15:36:26 +02003750#ifdef HAVE_ACL
3751/*
3752 * Check if "acl" contains inherited ACE.
3753 */
3754 static BOOL
3755is_acl_inherited(PACL acl)
3756{
3757 DWORD i;
3758 ACL_SIZE_INFORMATION acl_info;
3759 PACCESS_ALLOWED_ACE ace;
3760
3761 acl_info.AceCount = 0;
3762 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3763 for (i = 0; i < acl_info.AceCount; i++)
3764 {
3765 GetAce(acl, i, (LPVOID *)&ace);
3766 if (ace->Header.AceFlags & INHERITED_ACE)
3767 return TRUE;
3768 }
3769 return FALSE;
3770}
3771#endif
3772
Bram Moolenaar071d4272004-06-13 20:20:40 +00003773/*
3774 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3775 * Errors are ignored.
3776 * This must only be called with "acl" equal to what mch_get_acl() returned.
3777 */
3778 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003779mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003780{
3781#ifdef HAVE_ACL
3782 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003783 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003784 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003785
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003786 if (p == NULL)
3787 return;
3788
3789 wn = enc_to_utf16(fname, NULL);
3790 if (wn == NULL)
3791 return;
3792
3793 // Set security flags
3794 if (p->pSidOwner)
3795 sec_info |= OWNER_SECURITY_INFORMATION;
3796 if (p->pSidGroup)
3797 sec_info |= GROUP_SECURITY_INFORMATION;
3798 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003799 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003800 sec_info |= DACL_SECURITY_INFORMATION;
3801 // Do not inherit its parent's DACL.
3802 // If the DACL is inherited, Cygwin permissions would be changed.
3803 if (!is_acl_inherited(p->pDacl))
3804 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003805 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003806 if (p->pSacl)
3807 sec_info |= SACL_SECURITY_INFORMATION;
3808
3809 (void)SetNamedSecurityInfoW(
3810 wn, // Abstract filename
3811 SE_FILE_OBJECT, // File Object
3812 sec_info,
3813 p->pSidOwner, // Ownership information.
3814 p->pSidGroup, // Group membership.
3815 p->pDacl, // Discretionary information.
3816 p->pSacl // For auditing purposes.
3817 );
3818 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003819#endif
3820}
3821
3822 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003823mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003824{
3825#ifdef HAVE_ACL
3826 struct my_acl *p = (struct my_acl *)acl;
3827
3828 if (p != NULL)
3829 {
3830 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3831 vim_free(p);
3832 }
3833#endif
3834}
3835
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003836#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003837
3838/*
3839 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3840 */
3841 static BOOL WINAPI
3842handler_routine(
3843 DWORD dwCtrlType)
3844{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003845 INPUT_RECORD ir;
3846 DWORD out;
3847
Bram Moolenaar071d4272004-06-13 20:20:40 +00003848 switch (dwCtrlType)
3849 {
3850 case CTRL_C_EVENT:
3851 if (ctrl_c_interrupts)
3852 g_fCtrlCPressed = TRUE;
3853 return TRUE;
3854
3855 case CTRL_BREAK_EVENT:
3856 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003857 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003858 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02003859 ir.EventType = KEY_EVENT;
3860 ir.Event.KeyEvent.bKeyDown = TRUE;
3861 ir.Event.KeyEvent.wRepeatCount = 1;
3862 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3863 ir.Event.KeyEvent.wVirtualScanCode = 0;
3864 ir.Event.KeyEvent.dwControlKeyState = 0;
3865 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3866 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003867 return TRUE;
3868
Bram Moolenaar0f873732019-12-05 20:28:46 +01003869 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00003870 case CTRL_CLOSE_EVENT:
3871 case CTRL_LOGOFF_EVENT:
3872 case CTRL_SHUTDOWN_EVENT:
3873 windgoto((int)Rows - 1, 0);
3874 g_fForceExit = TRUE;
3875
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003876 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003877 (dwCtrlType == CTRL_CLOSE_EVENT
3878 ? _("close")
3879 : dwCtrlType == CTRL_LOGOFF_EVENT
3880 ? _("logoff")
3881 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003882# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00003883 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003884# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003885
Bram Moolenaar0f873732019-12-05 20:28:46 +01003886 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00003887
Bram Moolenaar0f873732019-12-05 20:28:46 +01003888 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00003889
3890 default:
3891 return FALSE;
3892 }
3893}
3894
3895
3896/*
3897 * set the tty in (raw) ? "raw" : "cooked" mode
3898 */
3899 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02003900mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003901{
3902 DWORD cmodein;
3903 DWORD cmodeout;
3904 BOOL bEnableHandler;
3905
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003906# ifdef VIMDLL
3907 if (gui.in_use)
3908 return;
3909# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003910 GetConsoleMode(g_hConIn, &cmodein);
3911 GetConsoleMode(g_hConOut, &cmodeout);
3912 if (tmode == TMODE_RAW)
3913 {
3914 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3915 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003916 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003917 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003918 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003919 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
3920 }
3921 else
3922 {
3923 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
3924 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003925 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003926# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01003927 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
3928 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003929 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003930# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003931 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003932# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003933 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003934 bEnableHandler = TRUE;
3935 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01003936 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00003937 {
3938 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3939 ENABLE_ECHO_INPUT);
3940 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3941 bEnableHandler = FALSE;
3942 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003943 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003944 SetConsoleMode(g_hConOut, cmodeout);
3945 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3946
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003947# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003948 if (fdDump)
3949 {
3950 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3951 tmode == TMODE_RAW ? "raw" :
3952 tmode == TMODE_COOK ? "cooked" : "normal",
3953 cmodein, cmodeout);
3954 fflush(fdDump);
3955 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003956# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003957}
3958
3959
3960/*
3961 * Get the size of the current window in `Rows' and `Columns'
3962 * Return OK when size could be determined, FAIL otherwise.
3963 */
3964 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003965mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003966{
3967 CONSOLE_SCREEN_BUFFER_INFO csbi;
3968
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003969# ifdef VIMDLL
3970 if (gui.in_use)
3971 return OK;
3972# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003973 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3974 {
3975 /*
3976 * For some reason, we are trying to get the screen dimensions
3977 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3978 * variables are really intended to mean the size of Vim screen
3979 * while in termcap mode.
3980 */
3981 Rows = g_cbTermcap.Info.dwSize.Y;
3982 Columns = g_cbTermcap.Info.dwSize.X;
3983 }
3984 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3985 {
3986 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3987 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3988 }
3989 else
3990 {
3991 Rows = 25;
3992 Columns = 80;
3993 }
3994 return OK;
3995}
3996
3997/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003998 * Resize console buffer to 'COORD'
3999 */
4000 static void
4001ResizeConBuf(
4002 HANDLE hConsole,
4003 COORD coordScreen)
4004{
4005 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4006 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004007# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004008 if (fdDump)
4009 {
4010 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4011 GetLastError());
4012 fflush(fdDump);
4013 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004014# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004015 }
4016}
4017
4018/*
4019 * Resize console window size to 'srWindowRect'
4020 */
4021 static void
4022ResizeWindow(
4023 HANDLE hConsole,
4024 SMALL_RECT srWindowRect)
4025{
4026 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4027 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004028# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004029 if (fdDump)
4030 {
4031 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4032 GetLastError());
4033 fflush(fdDump);
4034 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004035# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004036 }
4037}
4038
4039/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004040 * Set a console window to `xSize' * `ySize'
4041 */
4042 static void
4043ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004044 HANDLE hConsole,
4045 int xSize,
4046 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004047{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004048 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
4049 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004050 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004051 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004052 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004053
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004054# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004055 if (fdDump)
4056 {
4057 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4058 fflush(fdDump);
4059 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004060# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004061
Bram Moolenaar0f873732019-12-05 20:28:46 +01004062 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00004063 coordScreen = GetLargestConsoleWindowSize(hConsole);
4064
Bram Moolenaar0f873732019-12-05 20:28:46 +01004065 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00004066 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4067 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4068 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4069
4070 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4071 {
4072 int sx, sy;
4073
4074 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4075 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4076 if (sy < ySize || sx < xSize)
4077 {
4078 /*
4079 * Increasing number of lines/columns, do buffer first.
4080 * Use the maximal size in x and y direction.
4081 */
4082 if (sy < ySize)
4083 coordScreen.Y = ySize;
4084 else
4085 coordScreen.Y = sy;
4086 if (sx < xSize)
4087 coordScreen.X = xSize;
4088 else
4089 coordScreen.X = sx;
4090 SetConsoleScreenBufferSize(hConsole, coordScreen);
4091 }
4092 }
4093
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004094 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004095 coordScreen.X = xSize;
4096 coordScreen.Y = ySize;
4097
Bram Moolenaar2551c032018-08-23 22:38:31 +02004098 // In the new console call API, only the first time in reverse order
4099 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004100 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004101 ResizeWindow(hConsole, srWindowRect);
4102 ResizeConBuf(hConsole, coordScreen);
4103 }
4104 else
4105 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004106 // Workaround for a Windows 10 bug
4107 cursor.X = srWindowRect.Left;
4108 cursor.Y = srWindowRect.Top;
4109 SetConsoleCursorPosition(hConsole, cursor);
4110
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004111 ResizeConBuf(hConsole, coordScreen);
4112 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004113 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004114 }
4115}
4116
4117
4118/*
4119 * Set the console window to `Rows' * `Columns'
4120 */
4121 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004122mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004123{
4124 COORD coordScreen;
4125
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004126# ifdef VIMDLL
4127 if (gui.in_use)
4128 return;
4129# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004130 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004131 if (suppress_winsize != 0)
4132 {
4133 suppress_winsize = 2;
4134 return;
4135 }
4136
4137 if (term_console)
4138 {
4139 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4140
Bram Moolenaar0f873732019-12-05 20:28:46 +01004141 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004142 if (Rows > coordScreen.Y)
4143 Rows = coordScreen.Y;
4144 if (Columns > coordScreen.X)
4145 Columns = coordScreen.X;
4146
4147 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4148 }
4149}
4150
4151/*
4152 * Rows and/or Columns has changed.
4153 */
4154 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004155mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004156{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004157# ifdef VIMDLL
4158 if (gui.in_use)
4159 return;
4160# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004161 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4162}
4163
4164
4165/*
4166 * Called when started up, to set the winsize that was delayed.
4167 */
4168 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004169mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004170{
4171 if (suppress_winsize == 2)
4172 {
4173 suppress_winsize = 0;
4174 mch_set_shellsize();
4175 shell_resized();
4176 }
4177 suppress_winsize = 0;
4178}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004179#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004180
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004181 static BOOL
4182vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004183 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004184 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004185 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004186 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004187 PROCESS_INFORMATION *pi,
4188 LPVOID *env,
4189 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004190{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004191 BOOL ret = FALSE;
4192 WCHAR *wcmd, *wcwd = NULL;
4193
4194 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4195 if (wcmd == NULL)
4196 return FALSE;
4197 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004198 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004199 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4200 if (wcwd == NULL)
4201 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004202 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004203
4204 ret = CreateProcessW(
4205 NULL, // Executable name
4206 wcmd, // Command to execute
4207 NULL, // Process security attributes
4208 NULL, // Thread security attributes
4209 inherit_handles, // Inherit handles
4210 flags, // Creation flags
4211 env, // Environment
4212 wcwd, // Current directory
4213 (LPSTARTUPINFOW)si, // Startup information
4214 pi); // Process information
4215theend:
4216 vim_free(wcmd);
4217 vim_free(wcwd);
4218 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004219}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004220
4221
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004222 static HINSTANCE
4223vim_shell_execute(
4224 char *cmd,
4225 INT n_show_cmd)
4226{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004227 HINSTANCE ret;
4228 WCHAR *wcmd;
4229
4230 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4231 if (wcmd == NULL)
4232 return (HINSTANCE) 0;
4233
4234 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4235 vim_free(wcmd);
4236 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004237}
4238
4239
Bram Moolenaar4f974752019-02-17 17:44:42 +01004240#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004241
4242/*
4243 * Specialised version of system() for Win32 GUI mode.
4244 * This version proceeds as follows:
4245 * 1. Create a console window for use by the subprocess
4246 * 2. Run the subprocess (it gets the allocated console by default)
4247 * 3. Wait for the subprocess to terminate and get its exit code
4248 * 4. Prompt the user to press a key to close the console window
4249 */
4250 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004251mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004252{
4253 STARTUPINFO si;
4254 PROCESS_INFORMATION pi;
4255 DWORD ret = 0;
4256 HWND hwnd = GetFocus();
4257
4258 si.cb = sizeof(si);
4259 si.lpReserved = NULL;
4260 si.lpDesktop = NULL;
4261 si.lpTitle = NULL;
4262 si.dwFlags = STARTF_USESHOWWINDOW;
4263 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004264 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004265 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004266 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004267 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004268 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004269 else
4270 si.wShowWindow = SW_SHOWNORMAL;
4271 si.cbReserved2 = 0;
4272 si.lpReserved2 = NULL;
4273
Bram Moolenaar0f873732019-12-05 20:28:46 +01004274 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004275 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004276 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4277 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004278
Bram Moolenaar0f873732019-12-05 20:28:46 +01004279 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004280 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004281# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004282 int delay = 1;
4283
Bram Moolenaar0f873732019-12-05 20:28:46 +01004284 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004285 for (;;)
4286 {
4287 MSG msg;
4288
K.Takatab7057bd2022-01-21 11:37:07 +00004289 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004290 {
4291 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004292 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004293 delay = 1;
4294 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004295 }
4296 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4297 break;
4298
Bram Moolenaar0f873732019-12-05 20:28:46 +01004299 // We start waiting for a very short time and then increase it, so
4300 // that we respond quickly when the process is quick, and don't
4301 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004302 if (delay < 50)
4303 delay += 10;
4304 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004305# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004306 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004307# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004308
Bram Moolenaar0f873732019-12-05 20:28:46 +01004309 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004310 GetExitCodeProcess(pi.hProcess, &ret);
4311 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004312
Bram Moolenaar0f873732019-12-05 20:28:46 +01004313 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004314 CloseHandle(pi.hThread);
4315 CloseHandle(pi.hProcess);
4316
Bram Moolenaar0f873732019-12-05 20:28:46 +01004317 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004318 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4319
4320 return ret;
4321}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004322
4323/*
4324 * Thread launched by the gui to send the current buffer data to the
4325 * process. This way avoid to hang up vim totally if the children
4326 * process take a long time to process the lines.
4327 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004328 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004329sub_process_writer(LPVOID param)
4330{
4331 HANDLE g_hChildStd_IN_Wr = param;
4332 linenr_T lnum = curbuf->b_op_start.lnum;
4333 DWORD len = 0;
4334 DWORD l;
4335 char_u *lp = ml_get(lnum);
4336 char_u *s;
4337 int written = 0;
4338
4339 for (;;)
4340 {
4341 l = (DWORD)STRLEN(lp + written);
4342 if (l == 0)
4343 len = 0;
4344 else if (lp[written] == NL)
4345 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004346 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004347 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4348 }
4349 else
4350 {
4351 s = vim_strchr(lp + written, NL);
4352 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4353 s == NULL ? l : (DWORD)(s - (lp + written)),
4354 &len, NULL);
4355 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004356 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004357 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004358 // Finished a line, add a NL, unless this line should not have
4359 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004360 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004361 || (!curbuf->b_p_bin
4362 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004363 || (lnum != curbuf->b_no_eol_lnum
4364 && (lnum != curbuf->b_ml.ml_line_count
4365 || curbuf->b_p_eol)))
4366 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004367 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4368 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004369 }
4370
4371 ++lnum;
4372 if (lnum > curbuf->b_op_end.lnum)
4373 break;
4374
4375 lp = ml_get(lnum);
4376 written = 0;
4377 }
4378 else if (len > 0)
4379 written += len;
4380 }
4381
Bram Moolenaar0f873732019-12-05 20:28:46 +01004382 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004383 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004384 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004385}
4386
4387
Bram Moolenaar0f873732019-12-05 20:28:46 +01004388# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004389
4390/*
4391 * This function read from the children's stdout and write the
4392 * data on screen or in the buffer accordingly.
4393 */
4394 static void
4395dump_pipe(int options,
4396 HANDLE g_hChildStd_OUT_Rd,
4397 garray_T *ga,
4398 char_u buffer[],
4399 DWORD *buffer_off)
4400{
4401 DWORD availableBytes = 0;
4402 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004403 int ret;
4404 DWORD len;
4405 DWORD toRead;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004406
Bram Moolenaar0f873732019-12-05 20:28:46 +01004407 // we query the pipe to see if there is any data to read
4408 // to avoid to perform a blocking read
4409 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4410 NULL, // optional buffer
4411 0, // buffer size
4412 NULL, // number of read bytes
4413 &availableBytes, // available bytes total
4414 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004415
Bram Moolenaar0f873732019-12-05 20:28:46 +01004416 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004417 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004418 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01004419 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004420 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004421 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004422
Bram Moolenaar0f873732019-12-05 20:28:46 +01004423 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004424 if (len == 0)
4425 break;
4426
4427 availableBytes -= len;
4428
4429 if (options & SHELL_READ)
4430 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004431 // Do NUL -> NL translation, append NL separated
4432 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004433 for (i = 0; i < len; ++i)
4434 {
4435 if (buffer[i] == NL)
4436 append_ga_line(ga);
4437 else if (buffer[i] == NUL)
4438 ga_append(ga, NL);
4439 else
4440 ga_append(ga, buffer[i]);
4441 }
4442 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004443 else if (has_mbyte)
4444 {
4445 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004446 int c;
4447 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004448
4449 len += *buffer_off;
4450 buffer[len] = NUL;
4451
Bram Moolenaar0f873732019-12-05 20:28:46 +01004452 // Check if the last character in buffer[] is
4453 // incomplete, keep these bytes for the next
4454 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004455 for (p = buffer; p < buffer + len; p += l)
4456 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004457 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004458 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004459 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004460 else if (MB_BYTE2LEN(*p) != l)
4461 break;
4462 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004463 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004464 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004465 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004466 if (len >= 12)
4467 ++p;
4468 else
4469 {
4470 *buffer_off = len;
4471 return;
4472 }
4473 }
4474 c = *p;
4475 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004476 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004477 if (p < buffer + len)
4478 {
4479 *p = c;
4480 *buffer_off = (DWORD)((buffer + len) - p);
4481 mch_memmove(buffer, p, *buffer_off);
4482 return;
4483 }
4484 *buffer_off = 0;
4485 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004486 else
4487 {
4488 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004489 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004490 }
4491
4492 windgoto(msg_row, msg_col);
4493 cursor_on();
4494 out_flush();
4495 }
4496}
4497
4498/*
4499 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4500 * for communication and doesn't open any new window.
4501 */
4502 static int
4503mch_system_piped(char *cmd, int options)
4504{
4505 STARTUPINFO si;
4506 PROCESS_INFORMATION pi;
4507 DWORD ret = 0;
4508
4509 HANDLE g_hChildStd_IN_Rd = NULL;
4510 HANDLE g_hChildStd_IN_Wr = NULL;
4511 HANDLE g_hChildStd_OUT_Rd = NULL;
4512 HANDLE g_hChildStd_OUT_Wr = NULL;
4513
Bram Moolenaar0f873732019-12-05 20:28:46 +01004514 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004515 DWORD len;
4516
Bram Moolenaar0f873732019-12-05 20:28:46 +01004517 // buffer used to receive keys
4518 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4519 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004520
4521 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004522 int noread_cnt = 0;
4523 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004524 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004525 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004526 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004527
4528 SECURITY_ATTRIBUTES saAttr;
4529
Bram Moolenaar0f873732019-12-05 20:28:46 +01004530 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004531 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4532 saAttr.bInheritHandle = TRUE;
4533 saAttr.lpSecurityDescriptor = NULL;
4534
4535 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004536 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004537 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004538 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004539 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004540 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004541 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004542 {
4543 CloseHandle(g_hChildStd_IN_Rd);
4544 CloseHandle(g_hChildStd_IN_Wr);
4545 CloseHandle(g_hChildStd_OUT_Rd);
4546 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004547 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004548 }
4549
4550 si.cb = sizeof(si);
4551 si.lpReserved = NULL;
4552 si.lpDesktop = NULL;
4553 si.lpTitle = NULL;
4554 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4555
Bram Moolenaar0f873732019-12-05 20:28:46 +01004556 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004557 si.hStdError = g_hChildStd_OUT_Wr;
4558 si.hStdOutput = g_hChildStd_OUT_Wr;
4559 si.hStdInput = g_hChildStd_IN_Rd;
4560 si.wShowWindow = SW_HIDE;
4561 si.cbReserved2 = 0;
4562 si.lpReserved2 = NULL;
4563
4564 if (options & SHELL_READ)
4565 ga_init2(&ga, 1, BUFLEN);
4566
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004567 if (cmd != NULL)
4568 {
4569 p = (char *)vim_strsave((char_u *)cmd);
4570 if (p != NULL)
4571 unescape_shellxquote((char_u *)p, p_sxe);
4572 else
4573 p = cmd;
4574 }
4575
Bram Moolenaar0f873732019-12-05 20:28:46 +01004576 // Now, run the command.
4577 // About "Inherit handles" being TRUE: this command can be litigious,
4578 // handle inheritance was deactivated for pending temp file, but, if we
4579 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004580 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4581 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004582
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004583 if (p != cmd)
4584 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004585
Bram Moolenaar0f873732019-12-05 20:28:46 +01004586 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004587 CloseHandle(g_hChildStd_IN_Rd);
4588 CloseHandle(g_hChildStd_OUT_Wr);
4589
4590 if (options & SHELL_WRITE)
4591 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004592 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004593 _beginthreadex(NULL, // security attributes
4594 0, // default stack size
4595 sub_process_writer, // function to be executed
4596 g_hChildStd_IN_Wr, // parameter
4597 0, // creation flag, start immediately
4598 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004599 CloseHandle(thread);
4600 g_hChildStd_IN_Wr = NULL;
4601 }
4602
Bram Moolenaar0f873732019-12-05 20:28:46 +01004603 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004604 for (;;)
4605 {
4606 MSG msg;
4607
K.Takatab7057bd2022-01-21 11:37:07 +00004608 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004609 {
4610 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004611 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004612 }
4613
Bram Moolenaar0f873732019-12-05 20:28:46 +01004614 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004615 if ((options & (SHELL_READ|SHELL_WRITE))
4616# ifdef FEAT_GUI
4617 || gui.in_use
4618# endif
4619 )
4620 {
4621 len = 0;
4622 if (!(options & SHELL_EXPAND)
4623 && ((options &
4624 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4625 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4626# ifdef FEAT_GUI
4627 || gui.in_use
4628# endif
4629 )
4630 && (ta_len > 0 || noread_cnt > 4))
4631 {
4632 if (ta_len == 0)
4633 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004634 // Get extra characters when we don't have any. Reset the
4635 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004636 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004637 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4638 }
4639 if (ta_len > 0 || len > 0)
4640 {
4641 /*
4642 * For pipes: Check for CTRL-C: send interrupt signal to
4643 * child. Check for CTRL-D: EOF, close pipe to child.
4644 */
4645 if (len == 1 && cmd != NULL)
4646 {
4647 if (ta_buf[ta_len] == Ctrl_C)
4648 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004649 // Learn what exit code is expected, for
4650 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004651 TerminateProcess(pi.hProcess, 9);
4652 }
4653 if (ta_buf[ta_len] == Ctrl_D)
4654 {
4655 CloseHandle(g_hChildStd_IN_Wr);
4656 g_hChildStd_IN_Wr = NULL;
4657 }
4658 }
4659
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01004660 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004661
4662 /*
4663 * For pipes: echo the typed characters. For a pty this
4664 * does not seem to work.
4665 */
4666 for (i = ta_len; i < ta_len + len; ++i)
4667 {
4668 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4669 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004670 else if (has_mbyte)
4671 {
4672 int l = (*mb_ptr2len)(ta_buf + i);
4673
4674 msg_outtrans_len(ta_buf + i, l);
4675 i += l - 1;
4676 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004677 else
4678 msg_outtrans_len(ta_buf + i, 1);
4679 }
4680 windgoto(msg_row, msg_col);
4681 out_flush();
4682
4683 ta_len += len;
4684
4685 /*
4686 * Write the characters to the child, unless EOF has been
4687 * typed for pipes. Write one character at a time, to
4688 * avoid losing too much typeahead. When writing buffer
4689 * lines, drop the typed characters (only check for
4690 * CTRL-C).
4691 */
4692 if (options & SHELL_WRITE)
4693 ta_len = 0;
4694 else if (g_hChildStd_IN_Wr != NULL)
4695 {
4696 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4697 1, &len, NULL);
4698 // if we are typing in, we want to keep things reactive
4699 delay = 1;
4700 if (len > 0)
4701 {
4702 ta_len -= len;
4703 mch_memmove(ta_buf, ta_buf + len, ta_len);
4704 }
4705 }
4706 }
4707 }
4708 }
4709
4710 if (ta_len)
4711 ui_inchar_undo(ta_buf, ta_len);
4712
4713 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4714 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004715 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004716 break;
4717 }
4718
4719 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004720 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004721
Bram Moolenaar0f873732019-12-05 20:28:46 +01004722 // We start waiting for a very short time and then increase it, so
4723 // that we respond quickly when the process is quick, and don't
4724 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004725 if (delay < 50)
4726 delay += 10;
4727 }
4728
Bram Moolenaar0f873732019-12-05 20:28:46 +01004729 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004730 CloseHandle(g_hChildStd_OUT_Rd);
4731 if (g_hChildStd_IN_Wr != NULL)
4732 CloseHandle(g_hChildStd_IN_Wr);
4733
4734 WaitForSingleObject(pi.hProcess, INFINITE);
4735
Bram Moolenaar0f873732019-12-05 20:28:46 +01004736 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004737 GetExitCodeProcess(pi.hProcess, &ret);
4738
4739 if (options & SHELL_READ)
4740 {
4741 if (ga.ga_len > 0)
4742 {
4743 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01004744 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004745 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4746 }
4747 else
4748 curbuf->b_no_eol_lnum = 0;
4749 ga_clear(&ga);
4750 }
4751
Bram Moolenaar0f873732019-12-05 20:28:46 +01004752 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004753 CloseHandle(pi.hThread);
4754 CloseHandle(pi.hProcess);
4755
4756 return ret;
4757}
4758
4759 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004760mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004761{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004762 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004763 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004764 return mch_system_piped(cmd, options);
4765 else
4766 return mch_system_classic(cmd, options);
4767}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004768#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004769
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004770#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004771 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02004772mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004773{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004774 int ret;
4775 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004776 char_u *buf;
4777 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004778
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004779 // If the command starts and ends with double quotes, enclose the command
4780 // in parentheses.
4781 len = STRLEN(cmd);
4782 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
4783 {
4784 len += 3;
4785 buf = alloc(len);
4786 if (buf == NULL)
4787 return -1;
4788 vim_snprintf((char *)buf, len, "(%s)", cmd);
4789 wcmd = enc_to_utf16(buf, NULL);
4790 free(buf);
4791 }
4792 else
4793 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4794
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004795 if (wcmd == NULL)
4796 return -1;
4797
4798 ret = _wsystem(wcmd);
4799 vim_free(wcmd);
4800 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004801}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004802
4803#endif
4804
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004805 static int
4806mch_system(char *cmd, int options)
4807{
4808#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004809 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004810 return mch_system_g(cmd, options);
4811 else
4812 return mch_system_c(cmd, options);
4813#elif defined(FEAT_GUI_MSWIN)
4814 return mch_system_g(cmd, options);
4815#else
4816 return mch_system_c(cmd, options);
4817#endif
4818}
4819
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004820#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4821/*
4822 * Use a terminal window to run a shell command in.
4823 */
4824 static int
4825mch_call_shell_terminal(
4826 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004827 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004828{
4829 jobopt_T opt;
4830 char_u *newcmd = NULL;
4831 typval_T argvar[2];
4832 long_u cmdlen;
4833 int retval = -1;
4834 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004835 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004836 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004837 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004838
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004839 if (cmd == NULL)
4840 cmdlen = STRLEN(p_sh) + 1;
4841 else
4842 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004843 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004844 if (newcmd == NULL)
4845 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004846 if (cmd == NULL)
4847 {
4848 STRCPY(newcmd, p_sh);
4849 ch_log(NULL, "starting terminal to run a shell");
4850 }
4851 else
4852 {
4853 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4854 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4855 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004856
4857 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004858
4859 argvar[0].v_type = VAR_STRING;
4860 argvar[0].vval.v_string = newcmd;
4861 argvar[1].v_type = VAR_UNKNOWN;
4862 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004863 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004864 {
4865 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004866 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004867 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004868
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004869 job = term_getjob(buf->b_term);
4870 ++job->jv_refcount;
4871
Bram Moolenaar0f873732019-12-05 20:28:46 +01004872 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004873 aucmd_prepbuf(&aco, buf);
4874
4875 clear_oparg(&oa);
4876 while (term_use_loop())
4877 {
4878 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4879 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004880 // If terminal_loop() returns OK we got a key that is handled
4881 // in Normal model. We don't do redrawing anyway.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004882 if (terminal_loop(TRUE) == OK)
4883 normal_cmd(&oa, TRUE);
4884 }
4885 else
4886 normal_cmd(&oa, TRUE);
4887 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004888 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004889 ch_log(NULL, "system command finished");
4890
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004891 job_unref(job);
4892
Bram Moolenaar0f873732019-12-05 20:28:46 +01004893 // restore curwin/curbuf and a few other things
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004894 aucmd_restbuf(&aco);
4895
4896 wait_return(TRUE);
4897 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4898
4899 vim_free(newcmd);
4900 return retval;
4901}
4902#endif
4903
Bram Moolenaar071d4272004-06-13 20:20:40 +00004904/*
4905 * Either execute a command by calling the shell or start a new shell
4906 */
4907 int
4908mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004909 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004910 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00004911{
4912 int x = 0;
4913 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004914 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004915
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01004916#ifdef FEAT_JOB_CHANNEL
4917 ch_log(NULL, "executing shell command: %s", cmd);
4918#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004919 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02004920 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004921 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004922 if (cmd == NULL)
4923 wcscat(szShellTitle, L" :sh");
4924 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004925 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004926 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004927
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004928 if (wn != NULL)
4929 {
4930 wcscat(szShellTitle, L" - !");
4931 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02004932 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004933 wcscat(szShellTitle, wn);
4934 SetConsoleTitleW(szShellTitle);
4935 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004936 }
4937 }
4938 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004939
4940 out_flush();
4941
4942#ifdef MCH_WRITE_DUMP
4943 if (fdDump)
4944 {
4945 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4946 fflush(fdDump);
4947 }
4948#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004949#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004950 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004951 if (
4952# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004953 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004954# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004955 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004956 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4957 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004958 char_u *cmdbase = cmd;
4959
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004960 if (cmdbase != NULL)
4961 // Skip a leading quote and (.
4962 while (*cmdbase == '"' || *cmdbase == '(')
4963 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004964
4965 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01004966 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
4967 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004968 {
4969 // Use a terminal window to run the command in.
4970 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004971 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004972 return x;
4973 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004974 }
4975#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004976
4977 /*
4978 * Catch all deadly signals while running the external command, because a
4979 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4980 */
4981 signal(SIGINT, SIG_IGN);
4982#if defined(__GNUC__) && !defined(__MINGW32__)
4983 signal(SIGKILL, SIG_IGN);
4984#else
4985 signal(SIGBREAK, SIG_IGN);
4986#endif
4987 signal(SIGILL, SIG_IGN);
4988 signal(SIGFPE, SIG_IGN);
4989 signal(SIGSEGV, SIG_IGN);
4990 signal(SIGTERM, SIG_IGN);
4991 signal(SIGABRT, SIG_IGN);
4992
4993 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004994 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00004995
4996 if (cmd == NULL)
4997 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004998 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004999 }
5000 else
5001 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005002 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005003 char_u *newcmd = NULL;
5004 char_u *cmdbase = cmd;
5005 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005006
Bram Moolenaar0f873732019-12-05 20:28:46 +01005007 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005008 if (*cmdbase == '"' )
5009 ++cmdbase;
5010 if (*cmdbase == '(')
5011 ++cmdbase;
5012
Bram Moolenaar1c465442017-03-12 20:10:05 +01005013 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005014 {
5015 STARTUPINFO si;
5016 PROCESS_INFORMATION pi;
5017 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005018 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005019 char_u *p;
5020
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005021 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005022 si.cb = sizeof(si);
5023 si.lpReserved = NULL;
5024 si.lpDesktop = NULL;
5025 si.lpTitle = NULL;
5026 si.dwFlags = 0;
5027 si.cbReserved2 = 0;
5028 si.lpReserved2 = NULL;
5029
5030 cmdbase = skipwhite(cmdbase + 5);
5031 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005032 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005033 {
5034 cmdbase = skipwhite(cmdbase + 4);
5035 si.dwFlags = STARTF_USESHOWWINDOW;
5036 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005037 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005038 }
5039 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005040 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005041 {
5042 cmdbase = skipwhite(cmdbase + 2);
5043 flags = CREATE_NO_WINDOW;
5044 si.dwFlags = STARTF_USESTDHANDLES;
5045 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005046 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005047 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005048 NULL, // Security att.
5049 OPEN_EXISTING, // Open flags
5050 FILE_ATTRIBUTE_NORMAL, // File att.
5051 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005052 si.hStdOutput = si.hStdInput;
5053 si.hStdError = si.hStdInput;
5054 }
5055
Bram Moolenaar0f873732019-12-05 20:28:46 +01005056 // Remove a trailing ", ) and )" if they have a match
5057 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005058 if (cmdbase > cmd)
5059 {
5060 p = cmdbase + STRLEN(cmdbase);
5061 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5062 *--p = NUL;
5063 if (p > cmdbase && p[-1] == ')'
5064 && (*cmd =='(' || cmd[1] == '('))
5065 *--p = NUL;
5066 }
5067
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005068 newcmd = cmdbase;
5069 unescape_shellxquote(cmdbase, p_sxe);
5070
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005071 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005072 * If creating new console, arguments are passed to the
5073 * 'cmd.exe' as-is. If it's not, arguments are not treated
5074 * correctly for current 'cmd.exe'. So unescape characters in
5075 * shellxescape except '|' for avoiding to be treated as
5076 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005077 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005078 if (flags != CREATE_NEW_CONSOLE)
5079 {
5080 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005081 char_u *cmd_shell = mch_getenv("COMSPEC");
5082
5083 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005084 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005085
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005086 subcmd = vim_strsave_escaped_ext(cmdbase,
5087 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005088 if (subcmd != NULL)
5089 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005090 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005091 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005092 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005093 if (newcmd != NULL)
5094 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005095 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005096 else
5097 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005098 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005099 }
5100 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005101
5102 /*
5103 * Now, start the command as a process, so that it doesn't
5104 * inherit our handles which causes unpleasant dangling swap
5105 * files if we exit before the spawned process
5106 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005107 if (vim_create_process((char *)newcmd, FALSE, flags,
5108 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005109 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005110 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5111 > (HINSTANCE)32)
5112 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005113 else
5114 {
5115 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005116#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005117# ifdef VIMDLL
5118 if (gui.in_use)
5119# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005120 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005121#endif
5122 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005123
5124 if (newcmd != cmdbase)
5125 vim_free(newcmd);
5126
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005127 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005128 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005129 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005130 CloseHandle(si.hStdInput);
5131 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005132 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005133 CloseHandle(pi.hThread);
5134 CloseHandle(pi.hProcess);
5135 }
5136 else
5137 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005138 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005139#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005140 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005141 (!s_dont_use_vimrun && p_stmp ?
5142 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5143 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005144#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005145 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005146
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005147 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005148 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005149 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005150#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005151 if (
5152# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005153 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005154# endif
5155 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005156 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005157 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5158 "External commands will not pause after completion.\n"
5159 "See :help win32-vimrun for more information.");
5160 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005161 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5162 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005163
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005164 if (wmsg != NULL && wtitle != NULL)
5165 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5166 vim_free(wmsg);
5167 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005168 need_vimrun_warning = FALSE;
5169 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005170 if (
5171# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005172 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005173# endif
5174 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005175 // Use vimrun to execute the command. It opens a console
5176 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005177 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005178 vimrun_path,
5179 (msg_silent != 0 || (options & SHELL_DOOUT))
5180 ? "-s " : "",
5181 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005182 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005183# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005184 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005185# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005186 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005187 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005188 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5189 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005190 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005191#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005192 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005193 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005194 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005195 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005196 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005197 }
5198 }
5199
5200 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005201 {
5202 // The shell may have messed with the mode, always set it.
5203 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005204 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005205 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005206
Bram Moolenaar0f873732019-12-05 20:28:46 +01005207 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005208 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005209#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005210 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005211 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005212#endif
5213 )
5214 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005215 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005216 msg_putchar('\n');
5217 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005218 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005219
5220 signal(SIGINT, SIG_DFL);
5221#if defined(__GNUC__) && !defined(__MINGW32__)
5222 signal(SIGKILL, SIG_DFL);
5223#else
5224 signal(SIGBREAK, SIG_DFL);
5225#endif
5226 signal(SIGILL, SIG_DFL);
5227 signal(SIGFPE, SIG_DFL);
5228 signal(SIGSEGV, SIG_DFL);
5229 signal(SIGTERM, SIG_DFL);
5230 signal(SIGABRT, SIG_DFL);
5231
5232 return x;
5233}
5234
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005235#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005236 static HANDLE
5237job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005238 char_u *fname,
5239 DWORD dwDesiredAccess,
5240 DWORD dwShareMode,
5241 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5242 DWORD dwCreationDisposition,
5243 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005244{
5245 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005246 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005247
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005248 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005249 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005250 return INVALID_HANDLE_VALUE;
5251
5252 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5253 lpSecurityAttributes, dwCreationDisposition,
5254 dwFlagsAndAttributes, NULL);
5255 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005256 return h;
5257}
5258
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005259/*
5260 * Turn the dictionary "env" into a NUL separated list that can be used as the
5261 * environment argument of vim_create_process().
5262 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005263 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005264win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005265{
5266 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005267 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005268 LPVOID base = GetEnvironmentStringsW();
5269
Bram Moolenaar0f873732019-12-05 20:28:46 +01005270 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005271 if (ga_grow(gap, 1) == FAIL)
5272 return;
5273
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005274 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005275 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005276 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005277 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005278 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005279 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005280 typval_T *item = &dict_lookup(hi)->di_tv;
5281 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005282 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005283 --todo;
5284 if (wkey != NULL && wval != NULL)
5285 {
5286 size_t n;
5287 size_t lkey = wcslen(wkey);
5288 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005289
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005290 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5291 continue;
5292 for (n = 0; n < lkey; n++)
5293 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5294 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5295 for (n = 0; n < lval; n++)
5296 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5297 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5298 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005299 vim_free(wkey);
5300 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005301 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005302 }
5303 }
5304
Bram Moolenaar355757a2020-02-10 22:06:32 +01005305 if (base)
5306 {
5307 WCHAR *p = (WCHAR*) base;
5308
5309 // for last \0
5310 if (ga_grow(gap, 1) == FAIL)
5311 return;
5312
5313 while (*p != 0 || *(p + 1) != 0)
5314 {
5315 if (ga_grow(gap, 1) == OK)
5316 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5317 p++;
5318 }
5319 FreeEnvironmentStrings(base);
5320 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5321 }
5322
Bram Moolenaar493359e2018-06-12 20:25:52 +02005323# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005324 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005325# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005326 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005327 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005328# endif
5329# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005330 char_u *version = get_vim_var_str(VV_VERSION);
5331 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005332# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005333 // size of "VIM_SERVERNAME=" and value,
5334 // plus "VIM_TERMINAL=" and value,
5335 // plus two terminating NULs
5336 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005337# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005338 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005339# endif
5340# ifdef FEAT_TERMINAL
5341 + 13 + version_len + 2
5342# endif
5343 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005344
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005345 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005346 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005347# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005348 for (n = 0; n < 15; n++)
5349 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5350 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005351 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005352 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5353 (WCHAR)servername[n];
5354 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005355# endif
5356# ifdef FEAT_TERMINAL
5357 if (is_terminal)
5358 {
5359 for (n = 0; n < 13; n++)
5360 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5361 (WCHAR)"VIM_TERMINAL="[n];
5362 for (n = 0; n < version_len; n++)
5363 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5364 (WCHAR)version[n];
5365 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5366 }
5367# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005368 }
5369 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005370# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005371}
5372
Bram Moolenaarb091f302019-01-19 14:37:00 +01005373/*
5374 * Create a pair of pipes.
5375 * Return TRUE for success, FALSE for failure.
5376 */
5377 static BOOL
5378create_pipe_pair(HANDLE handles[2])
5379{
5380 static LONG s;
5381 char name[64];
5382 SECURITY_ATTRIBUTES sa;
5383
5384 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5385 GetCurrentProcessId(),
5386 InterlockedIncrement(&s));
5387
5388 // Create named pipe. Max size of named pipe is 65535.
5389 handles[1] = CreateNamedPipe(
5390 name,
5391 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5392 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005393 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005394
5395 if (handles[1] == INVALID_HANDLE_VALUE)
5396 return FALSE;
5397
5398 sa.nLength = sizeof(sa);
5399 sa.bInheritHandle = TRUE;
5400 sa.lpSecurityDescriptor = NULL;
5401
5402 handles[0] = CreateFile(name,
5403 FILE_GENERIC_READ,
5404 FILE_SHARE_READ, &sa,
5405 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5406
5407 if (handles[0] == INVALID_HANDLE_VALUE)
5408 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005409 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005410 return FALSE;
5411 }
5412
5413 return TRUE;
5414}
5415
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005416 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005417mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005418{
5419 STARTUPINFO si;
5420 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005421 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005422 SECURITY_ATTRIBUTES saAttr;
5423 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005424 HANDLE ifd[2];
5425 HANDLE ofd[2];
5426 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005427 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005428
5429 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5430 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5431 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5432 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5433 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5434 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5435 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5436
5437 if (use_out_for_err && use_null_for_out)
5438 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005439
5440 ifd[0] = INVALID_HANDLE_VALUE;
5441 ifd[1] = INVALID_HANDLE_VALUE;
5442 ofd[0] = INVALID_HANDLE_VALUE;
5443 ofd[1] = INVALID_HANDLE_VALUE;
5444 efd[0] = INVALID_HANDLE_VALUE;
5445 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005446 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005447
Bram Moolenaar14207f42016-10-27 21:13:10 +02005448 jo = CreateJobObject(NULL, NULL);
5449 if (jo == NULL)
5450 {
5451 job->jv_status = JOB_FAILED;
5452 goto failed;
5453 }
5454
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005455 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005456 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005457
Bram Moolenaar76467df2016-02-12 19:30:26 +01005458 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005459 ZeroMemory(&si, sizeof(si));
5460 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005461 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005462 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005463
Bram Moolenaard8070362016-02-15 21:56:54 +01005464 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5465 saAttr.bInheritHandle = TRUE;
5466 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005467
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005468 if (use_file_for_in)
5469 {
5470 char_u *fname = options->jo_io_name[PART_IN];
5471
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005472 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5473 FILE_SHARE_READ | FILE_SHARE_WRITE,
5474 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5475 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005476 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005477 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005478 goto failed;
5479 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005480 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005481 else if (!use_null_for_in
5482 && (!create_pipe_pair(ifd)
5483 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005484 goto failed;
5485
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005486 if (use_file_for_out)
5487 {
5488 char_u *fname = options->jo_io_name[PART_OUT];
5489
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005490 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5491 FILE_SHARE_READ | FILE_SHARE_WRITE,
5492 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5493 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005494 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005495 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005496 goto failed;
5497 }
5498 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005499 else if (!use_null_for_out &&
5500 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005501 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005502 goto failed;
5503
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005504 if (use_file_for_err)
5505 {
5506 char_u *fname = options->jo_io_name[PART_ERR];
5507
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005508 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5509 FILE_SHARE_READ | FILE_SHARE_WRITE,
5510 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5511 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005512 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005513 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005514 goto failed;
5515 }
5516 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005517 else if (!use_out_for_err && !use_null_for_err &&
5518 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005519 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005520 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005521
Bram Moolenaard8070362016-02-15 21:56:54 +01005522 si.dwFlags |= STARTF_USESTDHANDLES;
5523 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005524 si.hStdOutput = ofd[1];
5525 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5526
5527 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5528 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005529 if (options->jo_set & JO_CHANNEL)
5530 {
5531 channel = options->jo_channel;
5532 if (channel != NULL)
5533 ++channel->ch_refcount;
5534 }
5535 else
5536 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005537 if (channel == NULL)
5538 goto failed;
5539 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005540
5541 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005542 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005543 CREATE_DEFAULT_ERROR_MODE |
5544 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005545 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005546 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005547 &si, &pi,
5548 ga.ga_data,
5549 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005550 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005551 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005552 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005553 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005554 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005555
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005556 ga_clear(&ga);
5557
Bram Moolenaar14207f42016-10-27 21:13:10 +02005558 if (!AssignProcessToJobObject(jo, pi.hProcess))
5559 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005560 // if failing, switch the way to terminate
5561 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005562 CloseHandle(jo);
5563 jo = NULL;
5564 }
5565 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005566 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005567 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005568 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005569 job->jv_status = JOB_STARTED;
5570
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005571 CloseHandle(ifd[0]);
5572 CloseHandle(ofd[1]);
5573 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005574 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005575
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005576 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005577 if (channel != NULL)
5578 {
5579 channel_set_pipes(channel,
5580 use_file_for_in || use_null_for_in
5581 ? INVALID_FD : (sock_T)ifd[1],
5582 use_file_for_out || use_null_for_out
5583 ? INVALID_FD : (sock_T)ofd[0],
5584 use_out_for_err || use_file_for_err || use_null_for_err
5585 ? INVALID_FD : (sock_T)efd[0]);
5586 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005587 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005588 return;
5589
5590failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005591 CloseHandle(ifd[0]);
5592 CloseHandle(ofd[0]);
5593 CloseHandle(efd[0]);
5594 CloseHandle(ifd[1]);
5595 CloseHandle(ofd[1]);
5596 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005597 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005598 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005599}
5600
5601 char *
5602mch_job_status(job_T *job)
5603{
5604 DWORD dwExitCode = 0;
5605
Bram Moolenaar76467df2016-02-12 19:30:26 +01005606 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5607 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005608 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005609 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005610 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005611 {
5612 ch_log(job->jv_channel, "Job ended");
5613 job->jv_status = JOB_ENDED;
5614 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005615 return "dead";
5616 }
5617 return "run";
5618}
5619
Bram Moolenaar97792de2016-10-15 18:36:49 +02005620 job_T *
5621mch_detect_ended_job(job_T *job_list)
5622{
5623 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5624 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5625 job_T *job = job_list;
5626
5627 while (job != NULL)
5628 {
5629 DWORD n;
5630 DWORD result;
5631
5632 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5633 && job != NULL; job = job->jv_next)
5634 {
5635 if (job->jv_status == JOB_STARTED)
5636 {
5637 jobHandles[n] = job->jv_proc_info.hProcess;
5638 jobArray[n] = job;
5639 ++n;
5640 }
5641 }
5642 if (n == 0)
5643 continue;
5644 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5645 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5646 {
5647 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5648
5649 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5650 return wait_job;
5651 }
5652 }
5653 return NULL;
5654}
5655
Bram Moolenaarfb630902016-10-29 14:55:00 +02005656 static BOOL
5657terminate_all(HANDLE process, int code)
5658{
5659 PROCESSENTRY32 pe;
5660 HANDLE h = INVALID_HANDLE_VALUE;
5661 DWORD pid = GetProcessId(process);
5662
5663 if (pid != 0)
5664 {
5665 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5666 if (h != INVALID_HANDLE_VALUE)
5667 {
5668 pe.dwSize = sizeof(PROCESSENTRY32);
5669 if (!Process32First(h, &pe))
5670 goto theend;
5671
5672 do
5673 {
5674 if (pe.th32ParentProcessID == pid)
5675 {
5676 HANDLE ph = OpenProcess(
5677 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5678 if (ph != NULL)
5679 {
5680 terminate_all(ph, code);
5681 CloseHandle(ph);
5682 }
5683 }
5684 } while (Process32Next(h, &pe));
5685
5686 CloseHandle(h);
5687 }
5688 }
5689
5690theend:
5691 return TerminateProcess(process, code);
5692}
5693
5694/*
5695 * Send a (deadly) signal to "job".
5696 * Return FAIL if it didn't work.
5697 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005698 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005699mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005700{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005701 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005702
Bram Moolenaar923d9262016-02-25 20:56:01 +01005703 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005704 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005705 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02005706 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005707 {
5708 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5709 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00005710 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005711 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01005712 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005713 }
5714
5715 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5716 return FAIL;
5717 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005718 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5719 job->jv_proc_info.dwProcessId)
5720 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005721 FreeConsole();
5722 return ret;
5723}
5724
5725/*
5726 * Clear the data related to "job".
5727 */
5728 void
5729mch_clear_job(job_T *job)
5730{
5731 if (job->jv_status != JOB_FAILED)
5732 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005733 if (job->jv_job_object != NULL)
5734 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005735 CloseHandle(job->jv_proc_info.hProcess);
5736 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005737}
5738#endif
5739
Bram Moolenaar071d4272004-06-13 20:20:40 +00005740
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005741#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005742
5743/*
5744 * Start termcap mode
5745 */
5746 static void
5747termcap_mode_start(void)
5748{
5749 DWORD cmodein;
5750
5751 if (g_fTermcapMode)
5752 return;
5753
Christopher Plewright1140b512022-11-12 18:46:05 +00005754 // VTP uses alternate screen buffer.
5755 // Switch to a new alternate screen buffer.
5756 if (win11_or_later && p_rs && vtp_working)
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005757 vtp_printf("\033[?1049h");
5758
Bram Moolenaar071d4272004-06-13 20:20:40 +00005759 SaveConsoleBuffer(&g_cbNonTermcap);
5760
5761 if (g_cbTermcap.IsValid)
5762 {
5763 /*
5764 * We've been in termcap mode before. Restore certain screen
5765 * characteristics, including the buffer size and the window
5766 * size. Since we will be redrawing the screen, we don't need
5767 * to restore the actual contents of the buffer.
5768 */
5769 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005770 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005771 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5772 Rows = g_cbTermcap.Info.dwSize.Y;
5773 Columns = g_cbTermcap.Info.dwSize.X;
5774 }
5775 else
5776 {
5777 /*
5778 * This is our first time entering termcap mode. Clear the console
5779 * screen buffer, and resize the buffer to match the current window
5780 * size. We will use this as the size of our editing environment.
5781 */
5782 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005783 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005784 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5785 }
5786
Bram Moolenaar071d4272004-06-13 20:20:40 +00005787 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005788
5789 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005790 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005791 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005792 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005793 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
5794 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005795 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005796 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005797 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005798 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5799 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005800 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005801 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005802
5803 redraw_later_clear();
5804 g_fTermcapMode = TRUE;
5805}
5806
5807
5808/*
5809 * End termcap mode
5810 */
5811 static void
5812termcap_mode_end(void)
5813{
5814 DWORD cmodein;
5815 ConsoleBuffer *cb;
5816 COORD coord;
5817 DWORD dwDummy;
5818
5819 if (!g_fTermcapMode)
5820 return;
5821
5822 SaveConsoleBuffer(&g_cbTermcap);
5823
5824 GetConsoleMode(g_hConIn, &cmodein);
5825 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005826 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5827 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005828
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005829# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005830 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005831# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005832 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005833# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005834 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01005835 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005836
Christopher Plewright1140b512022-11-12 18:46:05 +00005837 // VTP uses alternate screen buffer.
5838 // Switch back to main screen buffer.
5839 if (exiting && win11_or_later && p_rs && vtp_working)
5840 vtp_printf("\033[?1049l");
5841
5842 if (!USE_WT && (p_rs || exiting))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005843 {
5844 /*
5845 * Clear anything that happens to be on the current line.
5846 */
5847 coord.X = 0;
5848 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
Christopher Plewright1140b512022-11-12 18:46:05 +00005849 if (!vtp_working)
5850 FillConsoleOutputCharacter(g_hConOut, ' ',
5851 cb->Info.dwSize.X, coord, &dwDummy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005852 /*
5853 * The following is just for aesthetics. If we are exiting without
5854 * restoring the screen, then we want to have a prompt string
5855 * appear at the bottom line. However, the command interpreter
5856 * seems to always advance the cursor one line before displaying
5857 * the prompt string, which causes the screen to scroll. To
5858 * counter this, move the cursor up one line before exiting.
5859 */
5860 if (exiting && !p_rs)
5861 coord.Y--;
5862 /*
5863 * Position the cursor at the leftmost column of the desired row.
5864 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005865 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005866 }
Christopher Plewright1140b512022-11-12 18:46:05 +00005867 SetConsoleCursorInfo(g_hConOut, &g_cci);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005868 g_fTermcapMode = FALSE;
5869}
Christopher Plewright38804d62022-11-09 23:55:52 +00005870#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00005871
5872
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005873#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005874 void
5875mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005876 char_u *s UNUSED,
5877 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005878{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005879 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00005880}
5881
5882#else
5883
5884/*
5885 * clear `n' chars, starting from `coord'
5886 */
5887 static void
5888clear_chars(
5889 COORD coord,
5890 DWORD n)
5891{
Christopher Plewright38804d62022-11-09 23:55:52 +00005892 if (!vtp_working)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02005893 {
5894 DWORD dwDummy;
5895
5896 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5897 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
5898 &dwDummy);
5899 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005900 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005901 {
5902 set_console_color_rgb();
5903 gotoxy(coord.X + 1, coord.Y + 1);
5904 vtp_printf("\033[%dX", n);
5905 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005906}
5907
5908
5909/*
5910 * Clear the screen
5911 */
5912 static void
5913clear_screen(void)
5914{
5915 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005916
Christopher Plewright38804d62022-11-09 23:55:52 +00005917 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005918 clear_chars(g_coord, Rows * Columns);
5919 else
5920 {
5921 set_console_color_rgb();
5922 gotoxy(1, 1);
5923 vtp_printf("\033[2J");
5924 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005925}
5926
5927
5928/*
5929 * Clear to end of display
5930 */
5931 static void
5932clear_to_end_of_display(void)
5933{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005934 COORD save = g_coord;
5935
Christopher Plewright38804d62022-11-09 23:55:52 +00005936 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005937 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005938 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005939 else
5940 {
5941 set_console_color_rgb();
5942 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5943 vtp_printf("\033[0J");
5944
5945 gotoxy(save.X + 1, save.Y + 1);
5946 g_coord = save;
5947 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005948}
5949
5950
5951/*
5952 * Clear to end of line
5953 */
5954 static void
5955clear_to_end_of_line(void)
5956{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005957 COORD save = g_coord;
5958
Christopher Plewright38804d62022-11-09 23:55:52 +00005959 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005960 clear_chars(g_coord, Columns - g_coord.X);
5961 else
5962 {
5963 set_console_color_rgb();
5964 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5965 vtp_printf("\033[0K");
5966
5967 gotoxy(save.X + 1, save.Y + 1);
5968 g_coord = save;
5969 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005970}
5971
5972
5973/*
5974 * Scroll the scroll region up by `cLines' lines
5975 */
5976 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005977scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005978{
5979 COORD oldcoord = g_coord;
5980
5981 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5982 delete_lines(cLines);
5983
5984 g_coord = oldcoord;
5985}
5986
5987
5988/*
5989 * Set the scroll region
5990 */
5991 static void
5992set_scroll_region(
5993 unsigned left,
5994 unsigned top,
5995 unsigned right,
5996 unsigned bottom)
5997{
5998 if (left >= right
5999 || top >= bottom
6000 || right > (unsigned) Columns - 1
6001 || bottom > (unsigned) Rows - 1)
6002 return;
6003
6004 g_srScrollRegion.Left = left;
6005 g_srScrollRegion.Top = top;
6006 g_srScrollRegion.Right = right;
6007 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006008}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006009
Bram Moolenaar6982f422019-02-16 16:48:01 +01006010 static void
6011set_scroll_region_tb(
6012 unsigned top,
6013 unsigned bottom)
6014{
6015 if (top >= bottom || bottom > (unsigned)Rows - 1)
6016 return;
6017
6018 g_srScrollRegion.Top = top;
6019 g_srScrollRegion.Bottom = bottom;
6020}
6021
6022 static void
6023set_scroll_region_lr(
6024 unsigned left,
6025 unsigned right)
6026{
6027 if (left >= right || right > (unsigned)Columns - 1)
6028 return;
6029
6030 g_srScrollRegion.Left = left;
6031 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006032}
6033
6034
6035/*
6036 * Insert `cLines' lines at the current cursor position
6037 */
6038 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006039insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006040{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006041 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006042 COORD dest;
6043 CHAR_INFO fill;
6044
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006045 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6046
Bram Moolenaar6982f422019-02-16 16:48:01 +01006047 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006048 dest.Y = g_coord.Y + cLines;
6049
Bram Moolenaar6982f422019-02-16 16:48:01 +01006050 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006051 source.Top = g_coord.Y;
6052 source.Right = g_srScrollRegion.Right;
6053 source.Bottom = g_srScrollRegion.Bottom - cLines;
6054
Bram Moolenaar6982f422019-02-16 16:48:01 +01006055 clip.Left = g_srScrollRegion.Left;
6056 clip.Top = g_coord.Y;
6057 clip.Right = g_srScrollRegion.Right;
6058 clip.Bottom = g_srScrollRegion.Bottom;
6059
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006060 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006061 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006062# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006063 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006064# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006065 ))
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006066 fill.Attributes = g_attrCurrent;
6067 else
6068 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006069
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006070 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006071
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006072 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6073
Bram Moolenaar6982f422019-02-16 16:48:01 +01006074 // Here we have to deal with a win32 console flake: If the scroll
6075 // region looks like abc and we scroll c to a and fill with d we get
6076 // cbd... if we scroll block c one line at a time to a, we get cdd...
6077 // vim expects cdd consistently... So we have to deal with that
6078 // here... (this also occurs scrolling the same way in the other
6079 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006080
6081 if (source.Bottom < dest.Y)
6082 {
6083 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006084 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006085
Bram Moolenaar6982f422019-02-16 16:48:01 +01006086 coord.X = source.Left;
6087 for (i = clip.Top; i < dest.Y; ++i)
6088 {
6089 coord.Y = i;
6090 clear_chars(coord, source.Right - source.Left + 1);
6091 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006092 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006093
Christopher Plewright38804d62022-11-09 23:55:52 +00006094 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006095 {
6096 COORD coord;
6097 int i;
6098
6099 coord.X = source.Left;
6100 for (i = source.Top; i < dest.Y; ++i)
6101 {
6102 coord.Y = i;
6103 clear_chars(coord, source.Right - source.Left + 1);
6104 }
6105 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006106}
6107
6108
6109/*
6110 * Delete `cLines' lines at the current cursor position
6111 */
6112 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006113delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006114{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006115 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006116 COORD dest;
6117 CHAR_INFO fill;
6118 int nb;
6119
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006120 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6121
Bram Moolenaar6982f422019-02-16 16:48:01 +01006122 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006123 dest.Y = g_coord.Y;
6124
Bram Moolenaar6982f422019-02-16 16:48:01 +01006125 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006126 source.Top = g_coord.Y + cLines;
6127 source.Right = g_srScrollRegion.Right;
6128 source.Bottom = g_srScrollRegion.Bottom;
6129
Bram Moolenaar6982f422019-02-16 16:48:01 +01006130 clip.Left = g_srScrollRegion.Left;
6131 clip.Top = g_coord.Y;
6132 clip.Right = g_srScrollRegion.Right;
6133 clip.Bottom = g_srScrollRegion.Bottom;
6134
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006135 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006136 if (!vtp_working)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006137 fill.Attributes = g_attrCurrent;
6138 else
6139 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006140
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006141 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006142
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006143 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6144
Bram Moolenaar6982f422019-02-16 16:48:01 +01006145 // Here we have to deal with a win32 console flake; See insert_lines()
6146 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006147
6148 nb = dest.Y + (source.Bottom - source.Top) + 1;
6149
6150 if (nb < source.Top)
6151 {
6152 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006153 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006154
Bram Moolenaar6982f422019-02-16 16:48:01 +01006155 coord.X = source.Left;
6156 for (i = nb; i < clip.Bottom; ++i)
6157 {
6158 coord.Y = i;
6159 clear_chars(coord, source.Right - source.Left + 1);
6160 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006161 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006162
Christopher Plewright38804d62022-11-09 23:55:52 +00006163 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006164 {
6165 COORD coord;
6166 int i;
6167
6168 coord.X = source.Left;
6169 for (i = nb; i <= source.Bottom; ++i)
6170 {
6171 coord.Y = i;
6172 clear_chars(coord, source.Right - source.Left + 1);
6173 }
6174 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006175}
6176
6177
6178/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006179 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006180 */
6181 static void
6182gotoxy(
6183 unsigned x,
6184 unsigned y)
6185{
6186 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6187 return;
6188
Christopher Plewright38804d62022-11-09 23:55:52 +00006189 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006190# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006191 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006192# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006193 ))
Bram Moolenaar2313b612019-09-27 14:14:32 +02006194 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006195 // There are reports of double-width characters not displayed
6196 // correctly. This workaround should fix it, similar to how it's done
6197 // for VTP.
6198 g_coord.X = 0;
6199 SetConsoleCursorPosition(g_hConOut, g_coord);
6200
Bram Moolenaar2313b612019-09-27 14:14:32 +02006201 // external cursor coords are 1-based; internal are 0-based
6202 g_coord.X = x - 1;
6203 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006204 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006205 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006206 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006207 {
6208 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006209 // destruction. Insider build bug. Always enabled because it's cheap
6210 // and avoids mistakes with recognizing the build.
6211 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006212
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006213 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006214
6215 g_coord.X = x - 1;
6216 g_coord.Y = y - 1;
6217 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006218}
6219
6220
6221/*
6222 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006223 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006224 */
6225 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006226textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006227{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006228 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006229
6230 SetConsoleTextAttribute(g_hConOut, wAttr);
6231}
6232
6233
6234 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006235textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006236{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006237 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006238
Christopher Plewright38804d62022-11-09 23:55:52 +00006239 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006240 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6241 else
6242 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006243}
6244
6245
6246 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006247textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006248{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006249 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006250
Christopher Plewright38804d62022-11-09 23:55:52 +00006251 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006252 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6253 else
6254 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006255}
6256
6257
6258/*
6259 * restore the default text attribute (whatever we started with)
6260 */
6261 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006262normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006263{
Christopher Plewright38804d62022-11-09 23:55:52 +00006264 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006265 textattr(g_attrDefault);
6266 else
6267 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006268}
6269
6270
6271static WORD g_attrPreStandout = 0;
6272
6273/*
6274 * Make the text standout, by brightening it
6275 */
6276 static void
6277standout(void)
6278{
6279 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006280
Bram Moolenaar071d4272004-06-13 20:20:40 +00006281 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6282}
6283
6284
6285/*
6286 * Turn off standout mode
6287 */
6288 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006289standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006290{
6291 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006292 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006293
6294 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006295}
6296
6297
6298/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006299 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006300 */
6301 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006302mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006303{
6304 char_u *p;
6305 int n;
6306
6307 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6308 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006309 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006310# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006311 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006312# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006313 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006314 {
6315 p = T_ME + 2;
6316 n = getdigits(&p);
6317 if (*p == 'm' && n > 0)
6318 {
6319 cterm_normal_fg_color = (n & 0xf) + 1;
6320 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6321 }
6322 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006323# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006324 cterm_normal_fg_gui_color = INVALCOLOR;
6325 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006326# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006327}
6328
6329
6330/*
6331 * visual bell: flash the screen
6332 */
6333 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006334visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006335{
6336 COORD coordOrigin = {0, 0};
6337 WORD attrFlash = ~g_attrCurrent & 0xff;
6338
6339 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006340 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006341
6342 if (oldattrs == NULL)
6343 return;
6344 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6345 coordOrigin, &dwDummy);
6346 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6347 coordOrigin, &dwDummy);
6348
Bram Moolenaar0f873732019-12-05 20:28:46 +01006349 Sleep(15); // wait for 15 msec
Christopher Plewright38804d62022-11-09 23:55:52 +00006350 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006351 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006352 coordOrigin, &dwDummy);
6353 vim_free(oldattrs);
6354}
6355
6356
6357/*
6358 * Make the cursor visible or invisible
6359 */
6360 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006361cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006362{
6363 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006364
Christopher Plewright38804d62022-11-09 23:55:52 +00006365 if (vtp_working)
Bram Moolenaar2695de62020-04-17 21:13:01 +02006366 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6367
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006368# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006369 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006370# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006371}
6372
6373
6374/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006375 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006376 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006377 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006378 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006379write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006380 char_u *pchBuf,
6381 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006382{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006383 COORD coord = g_coord;
6384 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006385 DWORD n, cchwritten;
6386 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006387 static WCHAR *unicodebuf = NULL;
6388 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006389 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006390 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006391 static WCHAR *utf8spbuf = NULL;
6392 static int utf8splength;
6393 static DWORD utf8spcells;
6394 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006395
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006396 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006397 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006398 utf8usingbuf = &unicodebuf;
6399 do
6400 {
6401 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6402 unicodebuf, unibuflen);
6403 if (length && length <= unibuflen)
6404 break;
6405 vim_free(unicodebuf);
6406 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6407 unibuflen = unibuflen ? 0 : length;
6408 } while(1);
6409 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006410 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006411 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6412 {
6413 if (utf8usingbuf != &utf8spbuf)
6414 {
6415 if (utf8spbuf == NULL)
6416 {
6417 cells = mb_string2cells((char_u *)" ", 1);
6418 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6419 utf8spbuf = LALLOC_MULT(WCHAR, length);
6420 if (utf8spbuf != NULL)
6421 {
6422 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6423 utf8usingbuf = &utf8spbuf;
6424 utf8splength = length;
6425 utf8spcells = cells;
6426 }
6427 }
6428 else
6429 {
6430 utf8usingbuf = &utf8spbuf;
6431 length = utf8splength;
6432 cells = utf8spcells;
6433 }
6434 }
6435 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006436
Christopher Plewright38804d62022-11-09 23:55:52 +00006437 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006438# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006439 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006440# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006441 ))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006442 {
6443 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6444 coord, &written);
6445 // When writing fails or didn't write a single character, pretend one
6446 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006447 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006448 coord, &cchwritten) == 0
6449 || cchwritten == 0 || cchwritten == (DWORD)-1)
6450 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006451 }
6452 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006453 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006454 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006455 NULL) == 0 || cchwritten == 0)
6456 cchwritten = 1;
6457 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006458
K.Takata135e1522022-01-29 15:27:58 +00006459 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006460 {
6461 written = cbToWrite;
6462 g_coord.X += (SHORT)cells;
6463 }
6464 else
6465 {
6466 char_u *p = pchBuf;
6467 for (n = 0; n < cchwritten; n++)
6468 MB_CPTR_ADV(p);
6469 written = p - pchBuf;
6470 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006471 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006472
6473 while (g_coord.X > g_srScrollRegion.Right)
6474 {
6475 g_coord.X -= (SHORT) Columns;
6476 if (g_coord.Y < g_srScrollRegion.Bottom)
6477 g_coord.Y++;
6478 }
6479
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006480 // Cursor under VTP is always in the correct position, no need to reset.
Christopher Plewright38804d62022-11-09 23:55:52 +00006481 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006482# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006483 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006484# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006485 ))
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006486 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006487
6488 return written;
6489}
6490
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006491 static char_u *
6492get_seq(
6493 int *args,
6494 int *count,
6495 char_u *head)
6496{
6497 int argc;
6498 char_u *p;
6499
6500 if (head == NULL || *head != '\033')
6501 return NULL;
6502
6503 argc = 0;
6504 p = head;
6505 ++p;
6506 do
6507 {
6508 ++p;
6509 args[argc] = getdigits(&p);
6510 argc += (argc < 15) ? 1 : 0;
6511 } while (*p == ';');
6512 *count = argc;
6513
6514 return p;
6515}
6516
6517 static char_u *
6518get_sgr(
6519 int *args,
6520 int *count,
6521 char_u *head)
6522{
6523 char_u *p = get_seq(args, count, head);
6524
6525 return (p && *p == 'm') ? ++p : NULL;
6526}
6527
6528/*
6529 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6530 */
6531 static char_u *
6532sgrn2(
6533 char_u *head,
6534 int n)
6535{
6536 int argc;
6537 int args[16];
6538 char_u *p = get_sgr(args, &argc, head);
6539
6540 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6541}
6542
6543/*
6544 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6545 */
6546 static char_u *
6547sgrnc(
6548 char_u *head,
6549 int n)
6550{
6551 int argc;
6552 int args[16];
6553 char_u *p = get_sgr(args, &argc, head);
6554
6555 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6556 ? p : NULL;
6557}
6558
6559 static char_u *
6560skipblank(char_u *q)
6561{
6562 char_u *p = q;
6563
6564 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6565 ++p;
6566 return p;
6567}
6568
6569/*
6570 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6571 * NULL.
6572 */
6573 static char_u *
6574sgrn2c(
6575 char_u *head,
6576 int n)
6577{
6578 char_u *p = sgrn2(head, n);
6579
6580 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6581}
6582
6583/*
6584 * If there is only a newline between the sequence immediately following it,
6585 * a pointer to the character following the newline is returned.
6586 * Otherwise NULL.
6587 */
6588 static char_u *
6589sgrn2cn(
6590 char_u *head,
6591 int n)
6592{
6593 char_u *p = sgrn2(head, n);
6594
6595 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6596}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006597
6598/*
6599 * mch_write(): write the output buffer to the screen, translating ESC
6600 * sequences into calls to console output routines.
6601 */
6602 void
6603mch_write(
6604 char_u *s,
6605 int len)
6606{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006607 char_u *end = s + len;
6608
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006609# ifdef VIMDLL
6610 if (gui.in_use)
6611 return;
6612# endif
6613
Bram Moolenaar071d4272004-06-13 20:20:40 +00006614 if (!term_console)
6615 {
6616 write(1, s, (unsigned)len);
6617 return;
6618 }
6619
Bram Moolenaar0f873732019-12-05 20:28:46 +01006620 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00006621 while (len--)
6622 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006623 int prefix = -1;
6624 char_u ch;
6625
6626 // While processing a sequence, on rare occasions it seems that another
6627 // sequence may be inserted asynchronously.
6628 if (len < 0)
6629 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006630 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006631 return;
6632 }
6633
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006634 while (s + ++prefix < end)
6635 {
6636 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006637 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6638 && ch != '\a' && ch != '\033'))
6639 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006640 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006641
6642 if (p_wd)
6643 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006644 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006645 if (prefix != 0)
6646 prefix = 1;
6647 }
6648
6649 if (prefix != 0)
6650 {
6651 DWORD nWritten;
6652
6653 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006654# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006655 if (fdDump)
6656 {
6657 fputc('>', fdDump);
6658 fwrite(s, sizeof(char_u), nWritten, fdDump);
6659 fputs("<\n", fdDump);
6660 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006661# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006662 len -= (nWritten - 1);
6663 s += nWritten;
6664 }
6665 else if (s[0] == '\n')
6666 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006667 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00006668 if (g_coord.Y == g_srScrollRegion.Bottom)
6669 {
6670 scroll(1);
6671 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6672 }
6673 else
6674 {
6675 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6676 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006677# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006678 if (fdDump)
6679 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006680# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006681 s++;
6682 }
6683 else if (s[0] == '\r')
6684 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006685 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00006686 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006687# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006688 if (fdDump)
6689 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006690# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006691 s++;
6692 }
6693 else if (s[0] == '\b')
6694 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006695 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00006696 if (g_coord.X > g_srScrollRegion.Left)
6697 g_coord.X--;
6698 else if (g_coord.Y > g_srScrollRegion.Top)
6699 {
6700 g_coord.X = g_srScrollRegion.Right;
6701 g_coord.Y--;
6702 }
6703 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006704# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006705 if (fdDump)
6706 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006707# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006708 s++;
6709 }
6710 else if (s[0] == '\a')
6711 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006712 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00006713 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006714# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006715 if (fdDump)
6716 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006717# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006718 s++;
6719 }
6720 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6721 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006722# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006723 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006724# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006725 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006726 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006727 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006728
6729 switch (s[2])
6730 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006731 case '0': case '1': case '2': case '3': case '4':
6732 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006733 if (*(p = get_seq(args, &argc, s)) != 'm')
6734 goto notsgr;
6735
6736 p = s;
6737
6738 // Handling frequent optional sequences. Output to the screen
6739 // takes too long, so do not output as much as possible.
6740
6741 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
6742 // resetFG,FG,BG are omitted.
6743 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006744 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006745 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
6746 len = len + 1 - (int)(p - s);
6747 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006748 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006749 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006750
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006751 // If FG,BG,BG,FG of SGR are connected, the first FG can be
6752 // omitted.
6753 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
6754 p = sp;
6755
6756 // If FG,BG,FG,BG of SGR are connected, the first FG can be
6757 // omitted.
6758 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
6759 p = sp;
6760
6761 // If BG,BG of SGR are connected, the first BG can be omitted.
6762 if (sgrn2((sp = sgrn2(p, 48)), 48))
6763 p = sp;
6764
6765 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01006766 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006767 if (sgrn2((sp = sgrnc(p, 39)), 38))
6768 p = sp;
6769
6770 p = get_seq(args, &argc, p);
6771
6772notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006773 arg1 = args[0];
6774 arg2 = args[1];
6775 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006776 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006777 if (argc == 1 && args[0] == 0)
6778 normvideo();
6779 else if (argc == 1)
6780 {
Christopher Plewright38804d62022-11-09 23:55:52 +00006781 if (vtp_working
6782# ifdef FEAT_TERMGUICOLORS
6783 && (p_tgc || t_colors >= 256)
6784# endif
6785 )
6786 textcolor((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006787 else
Christopher Plewright38804d62022-11-09 23:55:52 +00006788 textattr((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006789 }
Christopher Plewright38804d62022-11-09 23:55:52 +00006790 else if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006791 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006792 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006793 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006794 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006795 gotoxy(arg2, arg1);
6796 }
6797 else if (argc == 2 && *p == 'r')
6798 {
6799 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6800 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006801 else if (argc == 2 && *p == 'R')
6802 {
6803 set_scroll_region_tb(arg1, arg2);
6804 }
6805 else if (argc == 2 && *p == 'V')
6806 {
6807 set_scroll_region_lr(arg1, arg2);
6808 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006809 else if (argc == 1 && *p == 'A')
6810 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006811 gotoxy(g_coord.X + 1,
6812 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6813 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006814 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006815 {
6816 textbackground((WORD) arg1);
6817 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006818 else if (argc == 1 && *p == 'C')
6819 {
6820 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6821 g_coord.Y + 1);
6822 }
6823 else if (argc == 1 && *p == 'f')
6824 {
6825 textcolor((WORD) arg1);
6826 }
6827 else if (argc == 1 && *p == 'H')
6828 {
6829 gotoxy(1, arg1);
6830 }
6831 else if (argc == 1 && *p == 'L')
6832 {
6833 insert_lines(arg1);
6834 }
6835 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006836 {
6837 delete_lines(arg1);
6838 }
6839
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006840 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006841 s = p + 1;
6842 break;
6843
Bram Moolenaar071d4272004-06-13 20:20:40 +00006844 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006845 gotoxy(g_coord.X + 1,
6846 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6847 goto got3;
6848
6849 case 'B':
6850 visual_bell();
6851 goto got3;
6852
6853 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006854 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6855 g_coord.Y + 1);
6856 goto got3;
6857
6858 case 'E':
6859 termcap_mode_end();
6860 goto got3;
6861
6862 case 'F':
6863 standout();
6864 goto got3;
6865
6866 case 'f':
6867 standend();
6868 goto got3;
6869
6870 case 'H':
6871 gotoxy(1, 1);
6872 goto got3;
6873
6874 case 'j':
6875 clear_to_end_of_display();
6876 goto got3;
6877
6878 case 'J':
6879 clear_screen();
6880 goto got3;
6881
6882 case 'K':
6883 clear_to_end_of_line();
6884 goto got3;
6885
6886 case 'L':
6887 insert_lines(1);
6888 goto got3;
6889
6890 case 'M':
6891 delete_lines(1);
6892 goto got3;
6893
6894 case 'S':
6895 termcap_mode_start();
6896 goto got3;
6897
6898 case 'V':
6899 cursor_visible(TRUE);
6900 goto got3;
6901
6902 case 'v':
6903 cursor_visible(FALSE);
6904 goto got3;
6905
6906 got3:
6907 s += 3;
6908 len -= 2;
6909 }
6910
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006911# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006912 if (fdDump)
6913 {
6914 fputs("ESC | ", fdDump);
6915 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6916 fputc('\n', fdDump);
6917 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006918# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006919 }
K.Takatadf5320c2022-09-01 13:20:16 +01006920 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
6921 {
6922 int l = 2;
6923
6924 if (isdigit(s[l]))
6925 l++;
6926 if (s[l] == ' ' && s[l + 1] == 'q')
6927 {
6928 // DECSCUSR (cursor style) sequences
Christopher Plewright38804d62022-11-09 23:55:52 +00006929 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01006930 vtp_printf("%.*s", l + 2, s); // Pass through
6931 s += l + 2;
6932 len -= l + 1;
6933 }
6934 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006935 else
6936 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006937 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00006938 DWORD nWritten;
6939
6940 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006941# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006942 if (fdDump)
6943 {
6944 fputc('>', fdDump);
6945 fwrite(s, sizeof(char_u), nWritten, fdDump);
6946 fputs("<\n", fdDump);
6947 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006948# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006949
6950 len -= (nWritten - 1);
6951 s += nWritten;
6952 }
6953 }
6954
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006955# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006956 if (fdDump)
6957 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006958# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006959}
6960
Bram Moolenaar0f873732019-12-05 20:28:46 +01006961#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006962
6963
6964/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006965 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006966 */
6967 void
6968mch_delay(
6969 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02006970 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006971{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006972#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006973 Sleep((int)msec); // never wait for input
6974#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006975# ifdef VIMDLL
6976 if (gui.in_use)
6977 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006978 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006979 return;
6980 }
6981# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02006982 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006983# ifdef FEAT_MZSCHEME
6984 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6985 {
6986 int towait = p_mzq;
6987
Bram Moolenaar0f873732019-12-05 20:28:46 +01006988 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006989 while (msec > 0)
6990 {
6991 mzvim_check_threads();
6992 if (msec < towait)
6993 towait = msec;
6994 Sleep(towait);
6995 msec -= towait;
6996 }
6997 }
6998 else
6999# endif
7000 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007001 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007002 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007003#endif
7004}
7005
7006
7007/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01007008 * This version of remove is not scared by a readonly (backup) file.
7009 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007010 * Return 0 for success, -1 for failure.
7011 */
7012 int
7013mch_remove(char_u *name)
7014{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007015 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007016 int n;
7017
Bram Moolenaar203258c2016-01-17 22:15:16 +01007018 /*
7019 * On Windows, deleting a directory's symbolic link is done by
7020 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
7021 */
7022 if (mch_isdir(name) && mch_is_symbolic_link(name))
7023 return mch_rmdir(name);
7024
Bram Moolenaar12b559e2013-06-12 22:41:37 +02007025 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
7026
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007027 wn = enc_to_utf16(name, NULL);
7028 if (wn == NULL)
7029 return -1;
7030
7031 n = DeleteFileW(wn) ? 0 : -1;
7032 vim_free(wn);
7033 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007034}
7035
7036
7037/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007038 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007039 */
7040 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007041mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007042{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007043#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7044# ifdef VIMDLL
7045 if (!gui.in_use)
7046# endif
7047 if (g_fCtrlCPressed || g_fCBrkPressed)
7048 {
7049 ctrl_break_was_pressed = g_fCBrkPressed;
7050 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7051 got_int = TRUE;
7052 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007053#endif
7054}
7055
Bram Moolenaar0f873732019-12-05 20:28:46 +01007056// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007057#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007058
7059/*
7060 * How much main memory in KiB that can be used by VIM.
7061 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007062 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007063mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007064{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007065 MEMORYSTATUSEX ms;
7066
Bram Moolenaar0f873732019-12-05 20:28:46 +01007067 // Need to use GlobalMemoryStatusEx() when there is more memory than
7068 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007069 ms.dwLength = sizeof(MEMORYSTATUSEX);
7070 GlobalMemoryStatusEx(&ms);
7071 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007072 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007073 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007074 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007075 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007076 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007077 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007078 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007079 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007080 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007081 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007082 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007083}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007084
Bram Moolenaar071d4272004-06-13 20:20:40 +00007085/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007086 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00007087 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
7088 * file whose short file name is "FOO.BAR" (its long file name will
7089 * be correct: "foo.bar~"). Because a file can be accessed by
7090 * either its SFN or its LFN, "foo.bar" has effectively been
7091 * renamed to "foo.bar", which is not at all what was wanted. This
7092 * seems to happen only when renaming files with three-character
7093 * extensions by appending a suffix that does not include ".".
7094 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
7095 *
7096 * There is another problem, which isn't really a bug but isn't right either:
7097 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
7098 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
7099 * service pack 6. Doesn't seem to happen on Windows 98.
7100 *
7101 * Like rename(), returns 0 upon success, non-zero upon failure.
7102 * Should probably set errno appropriately when errors occur.
7103 */
7104 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007105mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007106{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007107 WCHAR *p;
7108 int i;
7109 WCHAR szTempFile[_MAX_PATH + 1];
7110 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007111 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007112
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007113 // No need to play tricks unless the file name contains a "~" as the
7114 // seventh character.
7115 p = wold;
7116 for (i = 0; wold[i] != NUL; ++i)
7117 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
7118 && wold[i + 1] != 0)
7119 p = wold + i + 1;
7120 if ((int)(wold + i - p) < 8 || p[6] != '~')
7121 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007122
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007123 // Get base path of new file name. Undocumented feature: If pszNewFile is
7124 // a directory, no error is returned and pszFilePart will be NULL.
7125 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007126 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007127 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007128
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007129 // Get (and create) a unique temporary file name in directory of new file
7130 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007131 return -2;
7132
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007133 // blow the temp file away
7134 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007135 return -3;
7136
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007137 // rename old file to the temp file
7138 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007139 return -4;
7140
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007141 // now create an empty file called pszOldFile; this prevents the operating
7142 // system using pszOldFile as an alias (SFN) if we're renaming within the
7143 // same directory. For example, we're editing a file called
7144 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7145 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7146 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7147 // cause all sorts of problems later in buf_write(). So, we create an
7148 // empty file called filena~1.txt and the system will have to find some
7149 // other SFN for filena~1.txt~, such as filena~2.txt
7150 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007151 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7152 return -5;
7153 if (!CloseHandle(hf))
7154 return -6;
7155
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007156 // rename the temp file to the new file
7157 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007158 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007159 // Renaming failed. Rename the file back to its old name, so that it
7160 // looks like nothing happened.
7161 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007162 return -7;
7163 }
7164
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007165 // Seems to be left around on Novell filesystems
7166 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007167
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007168 // finally, remove the empty old file
7169 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007170 return -8;
7171
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007172 return 0;
7173}
7174
7175
7176/*
7177 * Converts the filenames to UTF-16, then call mch_wrename().
7178 * Like rename(), returns 0 upon success, non-zero upon failure.
7179 */
7180 int
7181mch_rename(
7182 const char *pszOldFile,
7183 const char *pszNewFile)
7184{
7185 WCHAR *wold = NULL;
7186 WCHAR *wnew = NULL;
7187 int retval = -1;
7188
7189 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7190 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7191 if (wold != NULL && wnew != NULL)
7192 retval = mch_wrename(wold, wnew);
7193 vim_free(wold);
7194 vim_free(wnew);
7195 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007196}
7197
7198/*
7199 * Get the default shell for the current hardware platform
7200 */
7201 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007202default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007203{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007204 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007205}
7206
7207/*
7208 * mch_access() extends access() to do more detailed check on network drives.
7209 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7210 */
7211 int
7212mch_access(char *n, int p)
7213{
7214 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007215 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007216 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007217
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007218 wn = enc_to_utf16((char_u *)n, NULL);
7219 if (wn == NULL)
7220 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007221
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007222 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007223 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007224 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007225
7226 if (p & R_OK)
7227 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007228 // Read check is performed by seeing if we can do a find file on
7229 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007230 int i;
7231 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007232
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007233 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7234 TempNameW[i] = wn[i];
7235 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7236 TempNameW[i++] = '\\';
7237 TempNameW[i++] = '*';
7238 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007239
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007240 hFile = FindFirstFileW(TempNameW, &d);
7241 if (hFile == INVALID_HANDLE_VALUE)
7242 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007243 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007244 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007245 }
7246
7247 if (p & W_OK)
7248 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007249 // Trying to create a temporary file in the directory should catch
7250 // directories on read-only network shares. However, in
7251 // directories whose ACL allows writes but denies deletes will end
7252 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007253 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7254 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007255 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007256 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007257 }
7258 }
7259 else
7260 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007261 // Don't consider a file read-only if another process has opened it.
7262 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7263
Bram Moolenaar0f873732019-12-05 20:28:46 +01007264 // Trying to open the file for the required access does ACL, read-only
7265 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007266 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7267 | ((p & R_OK) ? GENERIC_READ : 0);
7268
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007269 hFile = CreateFileW(wn, access_mode, share_mode,
7270 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007271 if (hFile == INVALID_HANDLE_VALUE)
7272 goto getout;
7273 CloseHandle(hFile);
7274 }
7275
Bram Moolenaar0f873732019-12-05 20:28:46 +01007276 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007277getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007278 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007279 return retval;
7280}
7281
Bram Moolenaar071d4272004-06-13 20:20:40 +00007282/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007283 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007284 */
7285 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007286mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007287{
7288 WCHAR *wn;
7289 int f;
7290
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007291 wn = enc_to_utf16((char_u *)name, NULL);
7292 if (wn == NULL)
7293 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007294
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007295 f = _wopen(wn, flags, mode);
7296 vim_free(wn);
7297 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007298}
7299
7300/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007301 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007302 */
7303 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007304mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007305{
7306 WCHAR *wn, *wm;
7307 FILE *f = NULL;
7308
Bram Moolenaara12a1612019-01-24 16:39:02 +01007309#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007310 // Work around an annoying assertion in the Microsoft debug CRT
7311 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007312 char newMode = mode[strlen(mode) - 1];
7313 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007314
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007315 _get_fmode(&oldMode);
7316 if (newMode == 't')
7317 _set_fmode(_O_TEXT);
7318 else if (newMode == 'b')
7319 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007320#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007321 wn = enc_to_utf16((char_u *)name, NULL);
7322 wm = enc_to_utf16((char_u *)mode, NULL);
7323 if (wn != NULL && wm != NULL)
7324 f = _wfopen(wn, wm);
7325 vim_free(wn);
7326 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007327
Bram Moolenaara12a1612019-01-24 16:39:02 +01007328#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007329 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007330#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007331 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007332}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007333
Bram Moolenaar071d4272004-06-13 20:20:40 +00007334/*
7335 * SUB STREAM (aka info stream) handling:
7336 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007337 * NTFS can have sub streams for each file. The normal contents of a file is
7338 * stored in the main stream, and extra contents (author information, title and
7339 * so on) can be stored in a sub stream. After Windows 2000, the user can
7340 * access and store this information in sub streams via an explorer's property
7341 * menu item in the right click menu. This information in sub streams was lost
7342 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007343 *
7344 * Incomplete explanation:
7345 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7346 * More useful info and an example:
7347 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7348 */
7349
7350/*
7351 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7352 * and write to stream "substream" of file "to".
7353 * Errors are ignored.
7354 */
7355 static void
7356copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7357{
7358 HANDLE hTo;
7359 WCHAR *to_name;
7360
7361 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7362 wcscpy(to_name, to);
7363 wcscat(to_name, substream);
7364
7365 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7366 FILE_ATTRIBUTE_NORMAL, NULL);
7367 if (hTo != INVALID_HANDLE_VALUE)
7368 {
7369 long done;
7370 DWORD todo;
7371 DWORD readcnt, written;
7372 char buf[4096];
7373
Bram Moolenaar0f873732019-12-05 20:28:46 +01007374 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007375 for (done = 0; done < len; done += written)
7376 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007377 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007378 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7379 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007380 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7381 FALSE, FALSE, context)
7382 || readcnt != todo
7383 || !WriteFile(hTo, buf, todo, &written, NULL)
7384 || written != todo)
7385 break;
7386 }
7387 CloseHandle(hTo);
7388 }
7389
7390 free(to_name);
7391}
7392
7393/*
7394 * Copy info streams from file "from" to file "to".
7395 */
7396 static void
7397copy_infostreams(char_u *from, char_u *to)
7398{
7399 WCHAR *fromw;
7400 WCHAR *tow;
7401 HANDLE sh;
7402 WIN32_STREAM_ID sid;
7403 int headersize;
7404 WCHAR streamname[_MAX_PATH];
7405 DWORD readcount;
7406 void *context = NULL;
7407 DWORD lo, hi;
7408 int len;
7409
Bram Moolenaar0f873732019-12-05 20:28:46 +01007410 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007411 fromw = enc_to_utf16(from, NULL);
7412 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007413 if (fromw != NULL && tow != NULL)
7414 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007415 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007416 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7417 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7418 if (sh != INVALID_HANDLE_VALUE)
7419 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007420 // Use BackupRead() to find the info streams. Repeat until we
7421 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007422 for (;;)
7423 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007424 // Get the header to find the length of the stream name. If
7425 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007426 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007427 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007428 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7429 &readcount, FALSE, FALSE, &context)
7430 || readcount == 0)
7431 break;
7432
Bram Moolenaar0f873732019-12-05 20:28:46 +01007433 // We only deal with streams that have a name. The normal
7434 // file data appears to be without a name, even though docs
7435 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007436 if (sid.dwStreamNameSize > 0)
7437 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007438 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007439 if (!BackupRead(sh, (LPBYTE)streamname,
7440 sid.dwStreamNameSize,
7441 &readcount, FALSE, FALSE, &context))
7442 break;
7443
Bram Moolenaar0f873732019-12-05 20:28:46 +01007444 // Copy an info stream with a name ":anything:$DATA".
7445 // Skip "::$DATA", it has no stream name (examples suggest
7446 // it might be used for the normal file contents).
7447 // Note that BackupRead() counts bytes, but the name is in
7448 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007449 len = readcount / sizeof(WCHAR);
7450 streamname[len] = 0;
7451 if (len > 7 && wcsicmp(streamname + len - 6,
7452 L":$DATA") == 0)
7453 {
7454 streamname[len - 6] = 0;
7455 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007456 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007457 }
7458 }
7459
Bram Moolenaar0f873732019-12-05 20:28:46 +01007460 // Advance to the next stream. We might try seeking too far,
7461 // but BackupSeek() doesn't skip over stream borders, thus
7462 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007463 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007464 &lo, &hi, &context);
7465 }
7466
Bram Moolenaar0f873732019-12-05 20:28:46 +01007467 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007468 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7469
7470 CloseHandle(sh);
7471 }
7472 }
7473 vim_free(fromw);
7474 vim_free(tow);
7475}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007476
7477/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007478 * ntdll.dll definitions
7479 */
7480#define FileEaInformation 7
7481#ifndef STATUS_SUCCESS
7482# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7483#endif
7484
7485typedef struct _FILE_FULL_EA_INFORMATION_ {
7486 ULONG NextEntryOffset;
7487 UCHAR Flags;
7488 UCHAR EaNameLength;
7489 USHORT EaValueLength;
7490 CHAR EaName[1];
7491} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7492
7493typedef struct _FILE_EA_INFORMATION_ {
7494 ULONG EaSize;
7495} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7496
Paul Ollis65745772022-06-05 16:55:54 +01007497#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007498typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7499 PHANDLE FileHandle,
7500 ACCESS_MASK DesiredAccess,
7501 POBJECT_ATTRIBUTES ObjectAttributes,
7502 PIO_STATUS_BLOCK IoStatusBlock,
7503 ULONG ShareAccess,
7504 ULONG OpenOptions);
7505typedef NTSTATUS (NTAPI *PfnNtClose)(
7506 HANDLE Handle);
7507typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007508 HANDLE FileHandle,
7509 PIO_STATUS_BLOCK IoStatusBlock,
7510 PVOID Buffer,
7511 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007512typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7513 HANDLE FileHandle,
7514 PIO_STATUS_BLOCK IoStatusBlock,
7515 PVOID Buffer,
7516 ULONG Length,
7517 BOOLEAN ReturnSingleEntry,
7518 PVOID EaList,
7519 ULONG EaListLength,
7520 PULONG EaIndex,
7521 BOOLEAN RestartScan);
7522typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007523 HANDLE FileHandle,
7524 PIO_STATUS_BLOCK IoStatusBlock,
7525 PVOID FileInformation,
7526 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007527 FILE_INFORMATION_CLASS FileInformationClass);
7528typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7529 PUNICODE_STRING DestinationString,
7530 PCWSTR SourceString);
7531
7532PfnNtOpenFile pNtOpenFile = NULL;
7533PfnNtClose pNtClose = NULL;
7534PfnNtSetEaFile pNtSetEaFile = NULL;
7535PfnNtQueryEaFile pNtQueryEaFile = NULL;
7536PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7537PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01007538#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007539
7540/*
7541 * Load ntdll.dll functions.
7542 */
7543 static BOOL
7544load_ntdll(void)
7545{
7546 static int loaded = -1;
7547
7548 if (loaded == -1)
7549 {
7550 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7551 if (hNtdll != NULL)
7552 {
7553 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7554 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7555 pNtSetEaFile = (PfnNtSetEaFile)
7556 GetProcAddress(hNtdll, "NtSetEaFile");
7557 pNtQueryEaFile = (PfnNtQueryEaFile)
7558 GetProcAddress(hNtdll, "NtQueryEaFile");
7559 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7560 GetProcAddress(hNtdll, "NtQueryInformationFile");
7561 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7562 GetProcAddress(hNtdll, "RtlInitUnicodeString");
7563 }
7564 if (pNtOpenFile == NULL
7565 || pNtClose == NULL
7566 || pNtSetEaFile == NULL
7567 || pNtQueryEaFile == NULL
7568 || pNtQueryInformationFile == NULL
7569 || pRtlInitUnicodeString == NULL)
7570 loaded = FALSE;
7571 else
7572 loaded = TRUE;
7573 }
7574 return (BOOL) loaded;
7575}
7576
7577/*
7578 * Copy extended attributes (EA) from file "from" to file "to".
7579 */
7580 static void
7581copy_extattr(char_u *from, char_u *to)
7582{
7583 char_u *fromf = NULL;
7584 char_u *tof = NULL;
7585 WCHAR *fromw = NULL;
7586 WCHAR *tow = NULL;
7587 UNICODE_STRING u;
7588 HANDLE h;
7589 OBJECT_ATTRIBUTES oa;
7590 IO_STATUS_BLOCK iosb;
7591 FILE_EA_INFORMATION_ eainfo = {0};
7592 void *ea = NULL;
7593
7594 if (!load_ntdll())
7595 return;
7596
7597 // Convert the file names to the fully qualified object names.
7598 fromf = alloc(STRLEN(from) + 5);
7599 tof = alloc(STRLEN(to) + 5);
7600 if (fromf == NULL || tof == NULL)
7601 goto theend;
7602 STRCPY(fromf, "\\??\\");
7603 STRCAT(fromf, from);
7604 STRCPY(tof, "\\??\\");
7605 STRCAT(tof, to);
7606
7607 // Convert the names to wide characters.
7608 fromw = enc_to_utf16(fromf, NULL);
7609 tow = enc_to_utf16(tof, NULL);
7610 if (fromw == NULL || tow == NULL)
7611 goto theend;
7612
7613 // Get the EA.
7614 pRtlInitUnicodeString(&u, fromw);
7615 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7616 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7617 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7618 goto theend;
7619 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7620 FileEaInformation);
7621 if (eainfo.EaSize != 0)
7622 {
7623 ea = alloc(eainfo.EaSize);
7624 if (ea != NULL)
7625 {
7626 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7627 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7628 {
7629 vim_free(ea);
7630 ea = NULL;
7631 }
7632 }
7633 }
7634 pNtClose(h);
7635
7636 // Set the EA.
7637 if (ea != NULL)
7638 {
7639 pRtlInitUnicodeString(&u, tow);
7640 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7641 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7642 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7643 goto theend;
7644
7645 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
7646 pNtClose(h);
7647 }
7648
7649theend:
7650 vim_free(fromf);
7651 vim_free(tof);
7652 vim_free(fromw);
7653 vim_free(tow);
7654 vim_free(ea);
7655}
7656
7657/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007658 * Copy file attributes from file "from" to file "to".
7659 * For Windows NT and later we copy info streams.
7660 * Always returns zero, errors are ignored.
7661 */
7662 int
7663mch_copy_file_attribute(char_u *from, char_u *to)
7664{
Bram Moolenaar0f873732019-12-05 20:28:46 +01007665 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007666 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007667 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007668 return 0;
7669}
7670
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007671
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007672/*
K.Takatadc73b4b2021-06-08 18:32:36 +02007673 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007674 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007675static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007676static LPWSTR *ArglistW = NULL;
7677static int global_argc = 0;
7678static char **global_argv;
7679
Bram Moolenaar0f873732019-12-05 20:28:46 +01007680static int used_file_argc = 0; // last argument in global_argv[] used
7681 // for the argument list.
7682static int *used_file_indexes = NULL; // indexes in global_argv[] for
7683 // command line arguments added to
7684 // the argument list
7685static int used_file_count = 0; // nr of entries in used_file_indexes
7686static int used_file_literal = FALSE; // take file names literally
7687static int used_file_full_path = FALSE; // file name was full path
7688static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007689static int used_alist_count = 0;
7690
7691
7692/*
7693 * Get the command line arguments. Unicode version.
7694 * Returns argc. Zero when something fails.
7695 */
7696 int
7697get_cmd_argsW(char ***argvp)
7698{
7699 char **argv = NULL;
7700 int argc = 0;
7701 int i;
7702
Bram Moolenaar14993322014-09-09 12:25:33 +02007703 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007704 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7705 if (ArglistW != NULL)
7706 {
7707 argv = malloc((nArgsW + 1) * sizeof(char *));
7708 if (argv != NULL)
7709 {
7710 argc = nArgsW;
7711 argv[argc] = NULL;
7712 for (i = 0; i < argc; ++i)
7713 {
7714 int len;
7715
K.Takatadc73b4b2021-06-08 18:32:36 +02007716 // Convert each Unicode argument to UTF-8.
7717 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007718 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007719 (LPSTR *)&argv[i], &len, 0, 0);
7720 if (argv[i] == NULL)
7721 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007722 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007723 while (i > 0)
7724 free(argv[--i]);
7725 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007726 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007727 argc = 0;
7728 }
7729 }
7730 }
7731 }
7732
7733 global_argc = argc;
7734 global_argv = argv;
7735 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007736 {
7737 if (used_file_indexes != NULL)
7738 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007739 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007740 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007741
7742 if (argvp != NULL)
7743 *argvp = argv;
7744 return argc;
7745}
7746
7747 void
7748free_cmd_argsW(void)
7749{
7750 if (ArglistW != NULL)
7751 {
7752 GlobalFree(ArglistW);
7753 ArglistW = NULL;
7754 }
7755}
7756
7757/*
7758 * Remember "name" is an argument that was added to the argument list.
7759 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7760 * is called.
7761 */
7762 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007763used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007764{
7765 int i;
7766
7767 if (used_file_indexes == NULL)
7768 return;
7769 for (i = used_file_argc + 1; i < global_argc; ++i)
7770 if (STRCMP(global_argv[i], name) == 0)
7771 {
7772 used_file_argc = i;
7773 used_file_indexes[used_file_count++] = i;
7774 break;
7775 }
7776 used_file_literal = literal;
7777 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007778 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007779}
7780
7781/*
7782 * Remember the length of the argument list as it was. If it changes then we
7783 * leave it alone when 'encoding' is set.
7784 */
7785 void
7786set_alist_count(void)
7787{
7788 used_alist_count = GARGCOUNT;
7789}
7790
7791/*
7792 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02007793 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007794 * and convert them to 'encoding'.
7795 */
7796 void
7797fix_arg_enc(void)
7798{
7799 int i;
7800 int idx;
7801 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007802 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007803
Bram Moolenaar0f873732019-12-05 20:28:46 +01007804 // Safety checks:
7805 // - if argument count differs between the wide and non-wide argument
7806 // list, something must be wrong.
7807 // - the file name arguments must have been located.
7808 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007809 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007810 || ArglistW == NULL
7811 || used_file_indexes == NULL
7812 || used_file_count == 0
7813 || used_alist_count != GARGCOUNT)
7814 return;
7815
Bram Moolenaar0f873732019-12-05 20:28:46 +01007816 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007817 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007818 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007819 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00007820 for (i = 0; i < GARGCOUNT; ++i)
7821 fnum_list[i] = GARGLIST[i].ae_fnum;
7822
Bram Moolenaar0f873732019-12-05 20:28:46 +01007823 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007824 alist_clear(&global_alist);
7825 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007826 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007827
7828 for (i = 0; i < used_file_count; ++i)
7829 {
7830 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007831 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007832 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007833 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007834 int literal = used_file_literal;
7835
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007836#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01007837 // When using diff mode may need to concatenate file name to
7838 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007839 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7840 && !mch_isdir(alist_name(&GARGLIST[0])))
7841 {
7842 char_u *r;
7843
7844 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7845 if (r != NULL)
7846 {
7847 vim_free(str);
7848 str = r;
7849 }
7850 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007851#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01007852 // Re-use the old buffer by renaming it. When not using literal
7853 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00007854 if (used_file_literal)
7855 buf_set_name(fnum_list[i], str);
7856
Bram Moolenaar0f873732019-12-05 20:28:46 +01007857 // Check backtick literal. backtick literal is already expanded in
7858 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007859 if (literal == FALSE)
7860 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007861 size_t len = STRLEN(str);
7862
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007863 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7864 literal = TRUE;
7865 }
7866 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007867 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007868 }
7869
7870 if (!used_file_literal)
7871 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007872 // Now expand wildcards in the arguments.
7873 // Temporarily add '(' and ')' to 'isfname'. These are valid
7874 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00007875 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01007876 // Also, unset wildignore to not be influenced by this option.
7877 // The arguments specified in command-line should be kept even if
7878 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00007879 // Use :legacy so that it also works when in Vim9 script.
7880 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
7881 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007882 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00007883 do_cmdline_cmd(
7884 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
7885 do_cmdline_cmd(
7886 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007887 }
7888
Bram Moolenaar0f873732019-12-05 20:28:46 +01007889 // If wildcard expansion failed, we are editing the first file of the
7890 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007891 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7892 {
7893 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00007894 if (GARGCOUNT == 1 && used_file_full_path
7895 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
7896 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007897 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007898
7899 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007900}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007901
7902 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007903mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007904{
7905 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007906 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007907
Bram Moolenaar964b3742019-05-24 18:54:09 +02007908 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007909 if (envbuf == NULL)
7910 return -1;
7911
7912 sprintf((char *)envbuf, "%s=%s", var, value);
7913
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007914 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007915
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007916 vim_free(envbuf);
7917 if (p == NULL)
7918 return -1;
7919 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007920#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007921 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007922#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007923 // Unlike Un*x systems, we can free the string for _wputenv().
7924 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007925
7926 return 0;
7927}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007928
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007929/*
7930 * Support for 256 colors and 24-bit colors was added in Windows 10
7931 * version 1703 (Creators update).
7932 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007933#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7934
7935/*
7936 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02007937 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007938 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007939#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007940
7941/*
7942 * ConPTY differences between versions, need different logic.
7943 * version 1903 (May 2019 update).
7944 */
7945#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
7946
7947/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007948 * version 1909 (November 2019 update).
7949 */
7950#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
7951
7952/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007953 * Stay ahead of the next update, and when it's done, fix this.
7954 * version ? (2020 update, temporarily use the build number of insider preview)
7955 */
7956#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
7957
7958/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02007959 * Confirm until this version. Also the logic changes.
7960 * insider preview.
7961 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02007962#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007963
7964/*
7965 * Not stable now.
7966 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007967#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Christopher Plewright1140b512022-11-12 18:46:05 +00007968// Notes:
7969// Win 10 22H2 Final is build 19045, it's conpty is widely used.
7970// Strangely, 19045 is newer but is a lower build number than the 2020 insider
7971// preview which had a build 19587. And, not sure how stable that was?
7972// Win Server 2022 (May 10, 2022) is build 20348, its conpty is widely used.
7973// Win 11 starts from build 22000, even though the major version says 10!
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007974
7975 static void
7976vtp_flag_init(void)
7977{
7978 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007979#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007980 DWORD mode;
7981 HANDLE out;
7982
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007983# ifdef VIMDLL
7984 if (!gui.in_use)
7985# endif
7986 {
7987 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007988
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007989 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7990 GetConsoleMode(out, &mode);
7991 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7992 if (SetConsoleMode(out, mode) == 0)
7993 vtp_working = 0;
7994 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007995#endif
7996
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007997 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007998 conpty_working = 1;
7999 if (ver >= CONPTY_STABLE_BUILD)
8000 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008001
Bram Moolenaar57da6982019-09-13 22:30:11 +02008002 if (ver <= CONPTY_INSIDER_BUILD)
8003 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008004 if (ver <= CONPTY_1909_BUILD)
8005 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02008006 if (ver <= CONPTY_1903_BUILD)
8007 conpty_type = 2;
8008 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
8009 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008010
8011 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
8012 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008013}
8014
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008015#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008016
8017 static void
8018vtp_init(void)
8019{
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008020# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00008021 if (!vtp_working)
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008022 {
Christopher Plewright38804d62022-11-09 23:55:52 +00008023 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8024 csbi.cbSize = sizeof(csbi);
8025 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8026 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
8027 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
8028 store_console_bg_rgb = save_console_bg_rgb;
8029 store_console_fg_rgb = save_console_fg_rgb;
8030
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008031 COLORREF bg;
8032 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
8033 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8034 default_console_color_bg = bg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008035
8036 COLORREF fg;
8037 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
8038 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8039 default_console_color_fg = fg;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008040 }
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008041# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008042
8043 set_console_color_rgb();
8044}
8045
8046 static void
8047vtp_exit(void)
8048{
Bram Moolenaardf543822020-01-30 11:53:59 +01008049 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008050}
8051
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008052 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008053vtp_printf(
8054 char *format,
8055 ...)
8056{
8057 char_u buf[100];
8058 va_list list;
8059 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008060 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008061
8062 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008063 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008064 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008065 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008066 return (int)result;
8067}
8068
8069 static void
8070vtp_sgr_bulk(
8071 int arg)
8072{
8073 int args[1];
8074
8075 args[0] = arg;
8076 vtp_sgr_bulks(1, args);
8077}
8078
K.Takata6e1d31e2022-02-03 13:05:32 +00008079# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008080 if ((*p-- = "0123456789"[(n = x % 10)]) \
8081 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8082 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8083
K.Takata6e1d31e2022-02-03 13:05:32 +00008084# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008085 case x: \
8086 FAST256(newargs[x - 1]);
8087
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008088 static void
8089vtp_sgr_bulks(
8090 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008091 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008092{
K.Takata6e1d31e2022-02-03 13:05:32 +00008093# define MAXSGR 16
8094# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008095 char_u buf[SGRBUFSIZE];
8096 char_u *p;
8097 int in, out;
8098 int newargs[16];
8099 static int sgrfgr = -1, sgrfgg, sgrfgb;
8100 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008101
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008102 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008103 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008104 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008105 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008106 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008107 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008108
8109 in = out = 0;
8110 while (in < argc)
8111 {
8112 int s = args[in];
8113 int copylen = 1;
8114
8115 if (s == 38)
8116 {
8117 if (argc - in >= 5 && args[in + 1] == 2)
8118 {
8119 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8120 && sgrfgb == args[in + 4])
8121 {
8122 in += 5;
8123 copylen = 0;
8124 }
8125 else
8126 {
8127 sgrfgr = args[in + 2];
8128 sgrfgg = args[in + 3];
8129 sgrfgb = args[in + 4];
8130 copylen = 5;
8131 }
8132 }
8133 else if (argc - in >= 3 && args[in + 1] == 5)
8134 {
8135 sgrfgr = -1;
8136 copylen = 3;
8137 }
8138 }
8139 else if (s == 48)
8140 {
8141 if (argc - in >= 5 && args[in + 1] == 2)
8142 {
8143 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8144 && sgrbgb == args[in + 4])
8145 {
8146 in += 5;
8147 copylen = 0;
8148 }
8149 else
8150 {
8151 sgrbgr = args[in + 2];
8152 sgrbgg = args[in + 3];
8153 sgrbgb = args[in + 4];
8154 copylen = 5;
8155 }
8156 }
8157 else if (argc - in >= 3 && args[in + 1] == 5)
8158 {
8159 sgrbgr = -1;
8160 copylen = 3;
8161 }
8162 }
8163 else if (30 <= s && s <= 39)
8164 sgrfgr = -1;
8165 else if (90 <= s && s <= 97)
8166 sgrfgr = -1;
8167 else if (40 <= s && s <= 49)
8168 sgrbgr = -1;
8169 else if (100 <= s && s <= 107)
8170 sgrbgr = -1;
8171 else if (s == 0)
8172 sgrfgr = sgrbgr = -1;
8173
8174 while (copylen--)
8175 newargs[out++] = args[in++];
8176 }
8177
8178 p = &buf[sizeof(buf) - 1];
8179 *p-- = 'm';
8180
8181 switch (out)
8182 {
8183 int n, m;
8184 DWORD r;
8185
8186 FAST256CASE(16);
8187 *p-- = ';';
8188 FAST256CASE(15);
8189 *p-- = ';';
8190 FAST256CASE(14);
8191 *p-- = ';';
8192 FAST256CASE(13);
8193 *p-- = ';';
8194 FAST256CASE(12);
8195 *p-- = ';';
8196 FAST256CASE(11);
8197 *p-- = ';';
8198 FAST256CASE(10);
8199 *p-- = ';';
8200 FAST256CASE(9);
8201 *p-- = ';';
8202 FAST256CASE(8);
8203 *p-- = ';';
8204 FAST256CASE(7);
8205 *p-- = ';';
8206 FAST256CASE(6);
8207 *p-- = ';';
8208 FAST256CASE(5);
8209 *p-- = ';';
8210 FAST256CASE(4);
8211 *p-- = ';';
8212 FAST256CASE(3);
8213 *p-- = ';';
8214 FAST256CASE(2);
8215 *p-- = ';';
8216 FAST256CASE(1);
8217 *p-- = '[';
8218 *p = '\033';
8219 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8220 default:
8221 break;
8222 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008223}
8224
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008225 static void
8226wt_init(void)
8227{
Christopher Plewright1140b512022-11-12 18:46:05 +00008228 wt_working = mch_getenv("WT_SESSION") != NULL;
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008229}
8230
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008231# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008232 static int
8233ctermtoxterm(
8234 int cterm)
8235{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008236 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008237
8238 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8239 return (((int)r << 16) | ((int)g << 8) | (int)b);
8240}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008241# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008242
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008243 static void
8244set_console_color_rgb(void)
8245{
8246# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008247 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008248 guicolor_T fg, bg;
8249 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008250
Christopher Plewright38804d62022-11-09 23:55:52 +00008251 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008252 return;
8253
Bram Moolenaara050b942019-12-02 21:35:31 +01008254 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8255
Christopher Plewright38804d62022-11-09 23:55:52 +00008256 if (p_tgc || t_colors >= 256)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008257 {
8258 term_fg_rgb_color(fg);
8259 term_bg_rgb_color(bg);
8260 return;
8261 }
8262
Christopher Plewright38804d62022-11-09 23:55:52 +00008263 if (!conpty_working)
8264 {
8265 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8266 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008267
Christopher Plewright38804d62022-11-09 23:55:52 +00008268 csbi.cbSize = sizeof(csbi);
8269 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008270
Christopher Plewright38804d62022-11-09 23:55:52 +00008271 csbi.cbSize = sizeof(csbi);
8272 csbi.srWindow.Right += 1;
8273 csbi.srWindow.Bottom += 1;
8274 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8275 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
8276 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8277 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
8278 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8279 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008280# endif
8281}
8282
Bram Moolenaara050b942019-12-02 21:35:31 +01008283# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8284 void
8285get_default_console_color(
8286 int *cterm_fg,
8287 int *cterm_bg,
8288 guicolor_T *gui_fg,
8289 guicolor_T *gui_bg)
8290{
8291 int id;
8292 guicolor_T guifg = INVALCOLOR;
8293 guicolor_T guibg = INVALCOLOR;
8294 int ctermfg = 0;
8295 int ctermbg = 0;
Christopher Plewright38804d62022-11-09 23:55:52 +00008296 int dummynull = 0;
Bram Moolenaara050b942019-12-02 21:35:31 +01008297
8298 id = syn_name2id((char_u *)"Normal");
8299 if (id > 0 && p_tgc)
8300 syn_id2colors(id, &guifg, &guibg);
8301 if (guifg == INVALCOLOR)
8302 {
8303 ctermfg = -1;
8304 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008305 syn_id2cterm_bg(id, &ctermfg, &dummynull);
8306 if (vtp_working)
8307 {
8308 cterm_normal_fg_gui_color = guifg =
8309 ctermfg != -1 ? ctermtoxterm(ctermfg) : INVALCOLOR;
8310 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8311 }
8312 else
8313 {
8314 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
Bram Moolenaara050b942019-12-02 21:35:31 +01008315 : default_console_color_fg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008316 cterm_normal_fg_gui_color = guifg;
8317 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8318 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008319 }
8320 if (guibg == INVALCOLOR)
8321 {
8322 ctermbg = -1;
8323 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008324 syn_id2cterm_bg(id, &dummynull, &ctermbg);
8325 if (vtp_working)
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008326 {
8327 cterm_normal_bg_gui_color = guibg =
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01008328 ctermbg != -1 ? ctermtoxterm(ctermbg) : INVALCOLOR;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008329 if (ctermbg < 0)
8330 ctermbg = 0;
8331 }
K.Takatae53a0d42022-09-05 21:45:11 +01008332 else
8333 {
8334 guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8335 : default_console_color_bg;
8336 cterm_normal_bg_gui_color = guibg;
8337 ctermbg = ctermbg < 0 ? 0 : ctermbg;
8338 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008339 }
8340
8341 *cterm_fg = ctermfg;
8342 *cterm_bg = ctermbg;
8343 *gui_fg = guifg;
8344 *gui_bg = guibg;
8345}
8346# endif
8347
Bram Moolenaardf543822020-01-30 11:53:59 +01008348/*
8349 * Set the console colors to the original colors or the last set colors.
8350 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008351 static void
8352reset_console_color_rgb(void)
8353{
8354# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008355
Christopher Plewright38804d62022-11-09 23:55:52 +00008356 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008357 return;
8358
Christopher Plewright38804d62022-11-09 23:55:52 +00008359 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8360
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008361 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008362 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008363
8364 csbi.cbSize = sizeof(csbi);
8365 csbi.srWindow.Right += 1;
8366 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008367 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8368 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008369 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008370# endif
8371}
8372
8373/*
8374 * Set the console colors to the original colors.
8375 */
8376 static void
8377restore_console_color_rgb(void)
8378{
8379# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00008380 if (vtp_working)
8381 return;
8382
K.Takata27b53be2022-09-18 12:25:49 +01008383 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008384
8385 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008386 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008387
8388 csbi.cbSize = sizeof(csbi);
8389 csbi.srWindow.Right += 1;
8390 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008391 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8392 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008393 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008394# endif
8395}
8396
8397 void
8398control_console_color_rgb(void)
8399{
Christopher Plewright38804d62022-11-09 23:55:52 +00008400 if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008401 set_console_color_rgb();
8402 else
8403 reset_console_color_rgb();
8404}
8405
8406 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008407use_vtp(void)
8408{
8409 return USE_VTP;
8410}
8411
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008412 int
8413is_term_win32(void)
8414{
8415 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8416}
8417
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008418 int
8419has_vtp_working(void)
8420{
8421 return vtp_working;
8422}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008423
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008424#endif
8425
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008426 int
8427has_conpty_working(void)
8428{
8429 return conpty_working;
8430}
8431
8432 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008433get_conpty_type(void)
8434{
8435 return conpty_type;
8436}
8437
8438 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008439is_conpty_stable(void)
8440{
8441 return conpty_stable;
8442}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008443
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008444 int
8445get_conpty_fix_type(void)
8446{
8447 return conpty_fix_type;
8448}
8449
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008450#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008451 void
8452resize_console_buf(void)
8453{
8454 CONSOLE_SCREEN_BUFFER_INFO csbi;
8455 COORD coord;
8456 SMALL_RECT newsize;
8457
8458 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8459 {
8460 coord.X = SRWIDTH(csbi.srWindow);
8461 coord.Y = SRHEIGHT(csbi.srWindow);
8462 SetConsoleScreenBufferSize(g_hConOut, coord);
8463
8464 newsize.Left = 0;
8465 newsize.Top = 0;
8466 newsize.Right = coord.X - 1;
8467 newsize.Bottom = coord.Y - 1;
8468 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8469
8470 SetConsoleScreenBufferSize(g_hConOut, coord);
8471 }
8472}
8473#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008474
8475 char *
8476GetWin32Error(void)
8477{
K.Takatad68b2fc2022-02-12 11:18:37 +00008478 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008479 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008480
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008481 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8482 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008483 if (oldmsg != NULL)
8484 LocalFree(oldmsg);
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008485 if (msg != NULL)
8486 {
8487 // remove trailing \r\n
8488 char *pcrlf = strstr(msg, "\r\n");
8489 if (pcrlf != NULL)
8490 *pcrlf = '\0';
K.Takatad68b2fc2022-02-12 11:18:37 +00008491 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008492 }
8493 return msg;
8494}
Paul Ollis65745772022-06-05 16:55:54 +01008495
8496#if defined(FEAT_RELTIME) || defined(PROTO)
8497static HANDLE timer_handle;
8498static int timer_active = FALSE;
8499
8500/*
8501 * Calls to start_timeout alternate the return value pointer between the two
8502 * entries in timeout_flags. If the previously active timeout is very close to
8503 * expiring when start_timeout() is called then a race condition means that the
8504 * set_flag() function may still be invoked after the previous timer is
8505 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8506 * timeouts.
8507 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008508static sig_atomic_t timeout_flags[2];
8509static int timeout_flag_idx = 0;
8510static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01008511
8512
8513 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01008514set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01008515{
8516 int *timeout_flag = (int *)param;
8517
8518 *timeout_flag = TRUE;
8519}
8520
8521/*
8522 * Stop any active timeout.
8523 */
8524 void
8525stop_timeout(void)
8526{
8527 if (timer_active)
8528 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01008529 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01008530 timer_active = FALSE;
8531 if (!ret && GetLastError() != ERROR_IO_PENDING)
8532 {
8533 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
8534 }
8535 }
8536 *timeout_flag = FALSE;
8537}
8538
8539/*
8540 * Start the timeout timer.
8541 *
8542 * The period is defined in milliseconds.
8543 *
8544 * The return value is a pointer to a flag that is initialised to 0. If the
8545 * timeout expires, the flag is set to 1. This will only return pointers to
8546 * static memory; i.e. any pointer returned by this function may always be
8547 * safely dereferenced.
8548 *
8549 * This function is not expected to fail, but if it does it still returns a
8550 * valid flag pointer; the flag will remain stuck at zero.
8551 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008552 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01008553start_timeout(long msec)
8554{
Paul Ollis65745772022-06-05 16:55:54 +01008555 BOOL ret;
8556
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008557 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01008558
8559 stop_timeout();
8560 ret = CreateTimerQueueTimer(
8561 &timer_handle, NULL, set_flag, timeout_flag,
8562 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
8563 if (!ret)
8564 {
8565 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
8566 }
8567 else
8568 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008569 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01008570 timer_active = TRUE;
8571 *timeout_flag = FALSE;
8572 }
8573 return timeout_flag;
8574}
8575#endif