blob: ead50e186a9c47dae6147f7f1d0a225003c52348 [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 {
Christopher Plewright03193062022-11-22 12:58:27 +00002050 // use K_SPECIAL instead of CSI to make mappings work
2051 typeahead[typeaheadlen++] = K_SPECIAL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002052 typeahead[typeaheadlen++] = KS_MODIFIER;
2053 typeahead[typeaheadlen++] = modifiers;
2054 }
2055 typeahead[typeaheadlen++] = CSI;
2056 typeahead[typeaheadlen++] = KS_EXTRA;
2057 typeahead[typeaheadlen++] = scroll_dir;
2058 g_nMouseClick = -1;
2059 }
2060 else
2061 {
2062 typeahead[typeaheadlen++] = ESC + 128;
2063 typeahead[typeaheadlen++] = 'M';
2064 typeahead[typeaheadlen++] = g_nMouseClick;
2065 typeahead[typeaheadlen++] = g_xMouse + '!';
2066 typeahead[typeaheadlen++] = g_yMouse + '!';
2067 g_nMouseClick = -1;
2068 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002069 }
2070 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002071 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002072 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002073 int modifiers = 0;
2074
2075 c = tgetch(&modifiers, &ch2);
2076
2077 if (typebuf_changed(tb_change_cnt))
2078 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002079 // "buf" may be invalid now if a client put something in the
2080 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002081 typeaheadlen = 0;
2082 break;
2083 }
2084
2085 if (c == Ctrl_C && ctrl_c_interrupts)
2086 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002087# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002088 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002089# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002090 got_int = TRUE;
2091 }
2092
Bram Moolenaar071d4272004-06-13 20:20:40 +00002093 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002094 {
2095 int n = 1;
2096
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002097 if (ch2 == NUL)
2098 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002099 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002100 char_u *p;
2101 WCHAR ch[2];
2102
2103 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002104 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002105 {
2106 ch[1] = tgetch(&modifiers, &ch2);
2107 n++;
2108 }
2109 p = utf16_to_enc(ch, &n);
2110 if (p != NULL)
2111 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002112 for (i = 0, j = 0; i < n; i++)
2113 {
2114 typeahead[typeaheadlen + j++] = p[i];
2115# ifdef VIMDLL
2116 if (p[i] == CSI)
2117 {
2118 typeahead[typeaheadlen + j++] = KS_EXTRA;
2119 typeahead[typeaheadlen + j++] = KE_CSI;
2120 }
2121# endif
2122 }
2123 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002124 vim_free(p);
2125 }
2126 }
2127 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002128 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002129 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002130# ifdef VIMDLL
2131 if (c == CSI)
2132 {
2133 typeahead[typeaheadlen + 1] = KS_EXTRA;
2134 typeahead[typeaheadlen + 2] = KE_CSI;
2135 n = 3;
2136 }
2137# endif
2138 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002139 if (ch2 != NUL)
2140 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002141 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002142 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002143 switch (ch2)
2144 {
2145 case (WCHAR)'\324': // SHIFT+Insert
2146 case (WCHAR)'\325': // CTRL+Insert
2147 case (WCHAR)'\327': // SHIFT+Delete
2148 case (WCHAR)'\330': // CTRL+Delete
2149 typeahead[typeaheadlen + n] = (char_u)ch2;
2150 n++;
2151 break;
2152
2153 default:
2154 typeahead[typeaheadlen + n] = 3;
2155 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2156 n += 2;
2157 break;
2158 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002159 }
2160 else
2161 {
2162 typeahead[typeaheadlen + n] = 3;
2163 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2164 n += 2;
2165 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002166 }
2167
Bram Moolenaar0f873732019-12-05 20:28:46 +01002168 // Use the ALT key to set the 8th bit of the character
2169 // when it's one byte, the 8th bit isn't set yet and not
2170 // using a double-byte encoding (would become a lead
2171 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002172 if ((modifiers & MOD_MASK_ALT)
2173 && n == 1
2174 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002175 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002176 )
2177 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002178 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2179 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002180 modifiers &= ~MOD_MASK_ALT;
2181 }
2182
2183 if (modifiers != 0)
2184 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002185 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002186 mch_memmove(typeahead + typeaheadlen + 3,
2187 typeahead + typeaheadlen, n);
2188 typeahead[typeaheadlen++] = K_SPECIAL;
2189 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2190 typeahead[typeaheadlen++] = modifiers;
2191 }
2192
2193 typeaheadlen += n;
2194
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002195# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002196 if (fdDump)
2197 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002198# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002199 }
2200 }
2201 }
2202
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002203# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002204 if (fdDump)
2205 {
2206 fputs("]\n", fdDump);
2207 fflush(fdDump);
2208 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002209# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002210
Bram Moolenaar071d4272004-06-13 20:20:40 +00002211theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002212 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002213 len = 0;
2214 while (len < maxlen && typeaheadlen > 0)
2215 {
2216 buf[len++] = typeahead[0];
2217 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2218 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002219# ifdef FEAT_JOB_CHANNEL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002220 if (len > 0)
2221 {
2222 buf[len] = NUL;
2223 ch_log(NULL, "raw key input: \"%s\"", buf);
2224 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002225# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002226 return len;
2227
Bram Moolenaar0f873732019-12-05 20:28:46 +01002228#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002229 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002230#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002231}
2232
Bram Moolenaar82881492012-11-20 16:53:39 +01002233#ifndef PROTO
2234# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002235# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002236# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002237#endif
2238
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002239/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002240 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002241 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2242 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002243 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002244 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002245 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002246executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002247{
LemonBoy40fd7e62022-05-05 20:18:16 +01002248 int attrs = win32_getattrs((char_u *)name);
2249
2250 // The file doesn't exist or is a folder.
2251 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2252 return FALSE;
2253 // Check if the file is an AppExecLink, a special alias used by Windows
2254 // Store for its apps.
2255 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002256 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002257 char_u *res = resolve_appexeclink((char_u *)name);
2258 if (res == NULL)
2259 return FALSE;
2260 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002261 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002262 *path = res;
2263 else
2264 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002265 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002266 else if (path != NULL)
2267 *path = FullName_save((char_u *)name, FALSE);
2268 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002269}
2270
2271/*
2272 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2273 * If "use_path" is FALSE: Return TRUE if "name" exists.
2274 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2275 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2276 * the allocated memory.
2277 */
2278 static int
2279executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2280{
2281 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2282 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2283 // UTF-8.
2284 char_u buf[_MAX_PATH * 3];
2285 size_t len = STRLEN(name);
2286 size_t tmplen;
2287 char_u *p, *e, *e2;
2288 char_u *pathbuf = NULL;
2289 char_u *pathext = NULL;
2290 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002291 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002292 int noext = FALSE;
2293 int retval = FALSE;
2294
2295 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002296 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002297
2298 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002299 shname = gettail(p_sh);
2300 if (strstr((char *)shname, "sh") != NULL &&
2301 !(strstr((char *)shname, "powershell") != NULL
2302 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002303 noext = TRUE;
2304
2305 if (use_pathext)
2306 {
2307 pathext = mch_getenv("PATHEXT");
2308 if (pathext == NULL)
2309 pathext = (char_u *)".com;.exe;.bat;.cmd";
2310
2311 if (noext == FALSE)
2312 {
2313 /*
2314 * Loop over all extensions in $PATHEXT.
2315 * Check "name" ends with extension.
2316 */
2317 p = pathext;
2318 while (*p)
2319 {
2320 if (p[0] == ';'
2321 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2322 {
2323 // Skip empty or single ".".
2324 ++p;
2325 continue;
2326 }
2327 e = vim_strchr(p, ';');
2328 if (e == NULL)
2329 e = p + STRLEN(p);
2330 tmplen = e - p;
2331
2332 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2333 {
2334 noext = TRUE;
2335 break;
2336 }
2337
2338 p = e;
2339 }
2340 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002341 }
2342
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002343 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002344 if (pathext == NULL)
2345 pathext = (char_u *)".";
2346 else if (noext == TRUE)
2347 {
2348 if (pathextbuf == NULL)
2349 pathextbuf = alloc(STRLEN(pathext) + 3);
2350 if (pathextbuf == NULL)
2351 {
2352 retval = FALSE;
2353 goto theend;
2354 }
2355 STRCPY(pathextbuf, ".;");
2356 STRCAT(pathextbuf, pathext);
2357 pathext = pathextbuf;
2358 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002359
Bram Moolenaar95da1362020-05-30 18:37:55 +02002360 // Use $PATH when "use_path" is TRUE and "name" is basename.
2361 if (use_path && gettail((char_u *)name) == (char_u *)name)
2362 {
2363 p = mch_getenv("PATH");
2364 if (p != NULL)
2365 {
2366 pathbuf = alloc(STRLEN(p) + 3);
2367 if (pathbuf == NULL)
2368 {
2369 retval = FALSE;
2370 goto theend;
2371 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002372
2373 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2374 STRCPY(pathbuf, ".;");
2375 else
2376 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002377 STRCAT(pathbuf, p);
2378 }
2379 }
2380
2381 /*
2382 * Walk through all entries in $PATH to check if "name" exists there and
2383 * is an executable file.
2384 */
2385 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2386 while (*p)
2387 {
2388 if (*p == ';') // Skip empty entry
2389 {
2390 ++p;
2391 continue;
2392 }
2393 e = vim_strchr(p, ';');
2394 if (e == NULL)
2395 e = p + STRLEN(p);
2396
2397 if (e - p + len + 2 > sizeof(buf))
2398 {
2399 retval = FALSE;
2400 goto theend;
2401 }
2402 // A single "." that means current dir.
2403 if (e - p == 1 && *p == '.')
2404 STRCPY(buf, name);
2405 else
2406 {
2407 vim_strncpy(buf, p, e - p);
2408 add_pathsep(buf);
2409 STRCAT(buf, name);
2410 }
2411 tmplen = STRLEN(buf);
2412
2413 /*
2414 * Loop over all extensions in $PATHEXT.
2415 * Check "name" with extension added.
2416 */
2417 p = pathext;
2418 while (*p)
2419 {
2420 if (*p == ';')
2421 {
2422 // Skip empty entry
2423 ++p;
2424 continue;
2425 }
2426 e2 = vim_strchr(p, (int)';');
2427 if (e2 == NULL)
2428 e2 = p + STRLEN(p);
2429
2430 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2431 {
2432 // Not a single "." that means no extension is added.
2433 if (e2 - p + tmplen + 1 > sizeof(buf))
2434 {
2435 retval = FALSE;
2436 goto theend;
2437 }
2438 vim_strncpy(buf + tmplen, p, e2 - p);
2439 }
2440 if (executable_file((char *)buf, path))
2441 {
2442 retval = TRUE;
2443 goto theend;
2444 }
2445
2446 p = e2;
2447 }
2448
2449 p = e;
2450 }
2451
2452theend:
2453 free(pathextbuf);
2454 free(pathbuf);
2455 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002456}
2457
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002458#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2459 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002460/*
2461 * Bad parameter handler.
2462 *
2463 * Certain MS CRT functions will intentionally crash when passed invalid
2464 * parameters to highlight possible security holes. Setting this function as
2465 * the bad parameter handler will prevent the crash.
2466 *
2467 * In debug builds the parameters contain CRT information that might help track
2468 * down the source of a problem, but in non-debug builds the arguments are all
2469 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2470 * worth allowing these to make debugging of issues easier.
2471 */
2472 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002473bad_param_handler(const wchar_t *expression UNUSED,
2474 const wchar_t *function UNUSED,
2475 const wchar_t *file UNUSED,
2476 unsigned int line UNUSED,
2477 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002478{
2479}
2480
2481# define SET_INVALID_PARAM_HANDLER \
2482 ((void)_set_invalid_parameter_handler(bad_param_handler))
2483#else
2484# define SET_INVALID_PARAM_HANDLER
2485#endif
2486
Bram Moolenaar4f974752019-02-17 17:44:42 +01002487#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002488
2489/*
2490 * GUI version of mch_init().
2491 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002492 static void
2493mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002494{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002495# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002496 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002497# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002498
Bram Moolenaar0f873732019-12-05 20:28:46 +01002499 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002500 SET_INVALID_PARAM_HANDLER;
2501
Bram Moolenaar0f873732019-12-05 20:28:46 +01002502 // Let critical errors result in a failure, not in a dialog box. Required
2503 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002504 SetErrorMode(SEM_FAILCRITICALERRORS);
2505
Bram Moolenaar0f873732019-12-05 20:28:46 +01002506 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002507
Bram Moolenaar0f873732019-12-05 20:28:46 +01002508 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002509 Rows = 25;
2510 Columns = 80;
2511
Bram Moolenaar0f873732019-12-05 20:28:46 +01002512 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002513 {
2514 char_u vimrun_location[_MAX_PATH + 4];
2515
Bram Moolenaar0f873732019-12-05 20:28:46 +01002516 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002517 STRCPY(vimrun_location, exe_name);
2518 STRCPY(gettail(vimrun_location), "vimrun.exe");
2519 if (mch_getperm(vimrun_location) >= 0)
2520 {
2521 if (*skiptowhite(vimrun_location) != NUL)
2522 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002523 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002524 mch_memmove(vimrun_location + 1, vimrun_location,
2525 STRLEN(vimrun_location) + 1);
2526 *vimrun_location = '"';
2527 STRCPY(gettail(vimrun_location), "vimrun\" ");
2528 }
2529 else
2530 STRCPY(gettail(vimrun_location), "vimrun ");
2531
2532 vimrun_path = (char *)vim_strsave(vimrun_location);
2533 s_dont_use_vimrun = FALSE;
2534 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002535 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002536 s_dont_use_vimrun = FALSE;
2537
Bram Moolenaar0f873732019-12-05 20:28:46 +01002538 // Don't give the warning for a missing vimrun.exe right now, but only
2539 // when vimrun was supposed to be used. Don't bother people that do
2540 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002541 if (s_dont_use_vimrun)
2542 need_vimrun_warning = TRUE;
2543 }
2544
2545 /*
2546 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2547 * Otherwise the default "findstr /n" is used.
2548 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002549 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01002550 set_option_value_give_err((char_u *)"grepprg",
2551 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002552
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002553# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002554 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002555# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002556
2557 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002558}
2559
2560
Bram Moolenaar0f873732019-12-05 20:28:46 +01002561#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002562
2563#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002564
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002565# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2566# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002567
2568/*
2569 * ClearConsoleBuffer()
2570 * Description:
2571 * Clears the entire contents of the console screen buffer, using the
2572 * specified attribute.
2573 * Returns:
2574 * TRUE on success
2575 */
2576 static BOOL
2577ClearConsoleBuffer(WORD wAttribute)
2578{
2579 CONSOLE_SCREEN_BUFFER_INFO csbi;
2580 COORD coord;
2581 DWORD NumCells, dummy;
2582
2583 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2584 return FALSE;
2585
2586 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2587 coord.X = 0;
2588 coord.Y = 0;
2589 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2590 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002591 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002592 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2593 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002594 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002595
2596 return TRUE;
2597}
2598
2599/*
2600 * FitConsoleWindow()
2601 * Description:
2602 * Checks if the console window will fit within given buffer dimensions.
2603 * Also, if requested, will shrink the window to fit.
2604 * Returns:
2605 * TRUE on success
2606 */
2607 static BOOL
2608FitConsoleWindow(
2609 COORD dwBufferSize,
2610 BOOL WantAdjust)
2611{
2612 CONSOLE_SCREEN_BUFFER_INFO csbi;
2613 COORD dwWindowSize;
2614 BOOL NeedAdjust = FALSE;
2615
2616 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2617 {
2618 /*
2619 * A buffer resize will fail if the current console window does
2620 * not lie completely within that buffer. To avoid this, we might
2621 * have to move and possibly shrink the window.
2622 */
2623 if (csbi.srWindow.Right >= dwBufferSize.X)
2624 {
2625 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2626 if (dwWindowSize.X > dwBufferSize.X)
2627 dwWindowSize.X = dwBufferSize.X;
2628 csbi.srWindow.Right = dwBufferSize.X - 1;
2629 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2630 NeedAdjust = TRUE;
2631 }
2632 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2633 {
2634 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2635 if (dwWindowSize.Y > dwBufferSize.Y)
2636 dwWindowSize.Y = dwBufferSize.Y;
2637 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2638 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2639 NeedAdjust = TRUE;
2640 }
2641 if (NeedAdjust && WantAdjust)
2642 {
2643 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2644 return FALSE;
2645 }
2646 return TRUE;
2647 }
2648
2649 return FALSE;
2650}
2651
2652typedef struct ConsoleBufferStruct
2653{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002654 BOOL IsValid;
2655 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002656 PCHAR_INFO Buffer;
2657 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002658 PSMALL_RECT Regions;
2659 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002660} ConsoleBuffer;
2661
2662/*
2663 * SaveConsoleBuffer()
2664 * Description:
2665 * Saves important information about the console buffer, including the
2666 * actual buffer contents. The saved information is suitable for later
2667 * restoration by RestoreConsoleBuffer().
2668 * Returns:
2669 * TRUE if all information was saved; FALSE otherwise
2670 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2671 */
2672 static BOOL
2673SaveConsoleBuffer(
2674 ConsoleBuffer *cb)
2675{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002676 DWORD NumCells;
2677 COORD BufferCoord;
2678 SMALL_RECT ReadRegion;
2679 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002680 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002681
Bram Moolenaar071d4272004-06-13 20:20:40 +00002682 if (cb == NULL)
2683 return FALSE;
2684
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002685 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002686 {
2687 cb->IsValid = FALSE;
2688 return FALSE;
2689 }
2690 cb->IsValid = TRUE;
2691
Christopher Plewright1140b512022-11-12 18:46:05 +00002692 // VTP uses alternate screen buffer.
2693 // No need to save buffer contents for restoration.
2694 if (win11_or_later && vtp_working)
2695 return TRUE;
2696
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002697 /*
2698 * Allocate a buffer large enough to hold the entire console screen
2699 * buffer. If this ConsoleBuffer structure has already been initialized
2700 * with a buffer of the correct size, then just use that one.
2701 */
2702 if (!cb->IsValid || cb->Buffer == NULL ||
2703 cb->BufferSize.X != cb->Info.dwSize.X ||
2704 cb->BufferSize.Y != cb->Info.dwSize.Y)
2705 {
2706 cb->BufferSize.X = cb->Info.dwSize.X;
2707 cb->BufferSize.Y = cb->Info.dwSize.Y;
2708 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2709 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002710 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002711 if (cb->Buffer == NULL)
2712 return FALSE;
2713 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002714
2715 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002716 * We will now copy the console screen buffer into our buffer.
2717 * ReadConsoleOutput() seems to be limited as far as how much you
2718 * can read at a time. Empirically, this number seems to be about
2719 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2720 * in chunks until it is all copied. The chunks will all have the
2721 * same horizontal characteristics, so initialize them now. The
2722 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002723 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002724 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002725 ReadRegion.Left = 0;
2726 ReadRegion.Right = cb->Info.dwSize.X - 1;
2727 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002728
2729 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2730 if (cb->Regions == NULL || numregions != cb->NumRegions)
2731 {
2732 cb->NumRegions = numregions;
2733 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002734 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002735 if (cb->Regions == NULL)
2736 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002737 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002738 return FALSE;
2739 }
2740 }
2741
2742 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002743 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002744 /*
2745 * Read into position (0, Y) in our buffer.
2746 */
2747 BufferCoord.Y = Y;
2748 /*
2749 * Read the region whose top left corner is (0, Y) and whose bottom
2750 * right corner is (width - 1, Y + Y_incr - 1). This should define
2751 * a region of size width by Y_incr. Don't worry if this region is
2752 * too large for the remaining buffer; it will be cropped.
2753 */
2754 ReadRegion.Top = Y;
2755 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002756 if (!ReadConsoleOutputW(g_hConOut, // output handle
2757 cb->Buffer, // our buffer
2758 cb->BufferSize, // dimensions of our buffer
2759 BufferCoord, // offset in our buffer
2760 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002761 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002762 VIM_CLEAR(cb->Buffer);
2763 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002764 return FALSE;
2765 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002766 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002767 }
2768
2769 return TRUE;
2770}
2771
2772/*
2773 * RestoreConsoleBuffer()
2774 * Description:
2775 * Restores important information about the console buffer, including the
2776 * actual buffer contents, if desired. The information to restore is in
2777 * the same format used by SaveConsoleBuffer().
2778 * Returns:
2779 * TRUE on success
2780 */
2781 static BOOL
2782RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002783 ConsoleBuffer *cb,
2784 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002785{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002786 COORD BufferCoord;
2787 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002788 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002789
Christopher Plewright1140b512022-11-12 18:46:05 +00002790 // VTP uses alternate screen buffer.
2791 // No need to restore buffer contents.
2792 if (win11_or_later && vtp_working)
2793 return TRUE;
2794
Bram Moolenaar071d4272004-06-13 20:20:40 +00002795 if (cb == NULL || !cb->IsValid)
2796 return FALSE;
2797
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002798 /*
2799 * Before restoring the buffer contents, clear the current buffer, and
2800 * restore the cursor position and window information. Doing this now
2801 * prevents old buffer contents from "flashing" onto the screen.
2802 */
2803 if (RestoreScreen)
2804 ClearConsoleBuffer(cb->Info.wAttributes);
2805
2806 FitConsoleWindow(cb->Info.dwSize, TRUE);
2807 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2808 return FALSE;
2809 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2810 return FALSE;
2811
2812 if (!RestoreScreen)
2813 {
2814 /*
2815 * No need to restore the screen buffer contents, so we're done.
2816 */
2817 return TRUE;
2818 }
2819
2820 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2821 return FALSE;
2822 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2823 return FALSE;
2824
2825 /*
2826 * Restore the screen buffer contents.
2827 */
2828 if (cb->Buffer != NULL)
2829 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002830 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002831 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002832 BufferCoord.X = cb->Regions[i].Left;
2833 BufferCoord.Y = cb->Regions[i].Top;
2834 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01002835 if (!WriteConsoleOutputW(g_hConOut, // output handle
2836 cb->Buffer, // our buffer
2837 cb->BufferSize, // dimensions of our buffer
2838 BufferCoord, // offset in our buffer
2839 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02002840 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002841 }
2842 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002843
2844 return TRUE;
2845}
2846
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002847# define FEAT_RESTORE_ORIG_SCREEN
2848# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002849static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002850# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002851static ConsoleBuffer g_cbNonTermcap = { 0 };
2852static ConsoleBuffer g_cbTermcap = { 0 };
2853
Bram Moolenaar071d4272004-06-13 20:20:40 +00002854char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01002855HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00002856static HICON g_hOrigIconSmall = NULL;
2857static HICON g_hOrigIcon = NULL;
2858static HICON g_hVimIcon = NULL;
2859static BOOL g_fCanChangeIcon = FALSE;
2860
Bram Moolenaar071d4272004-06-13 20:20:40 +00002861/*
2862 * GetConsoleIcon()
2863 * Description:
2864 * Attempts to retrieve the small icon and/or the big icon currently in
2865 * use by a given window.
2866 * Returns:
2867 * TRUE on success
2868 */
2869 static BOOL
2870GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002871 HWND hWnd,
2872 HICON *phIconSmall,
2873 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002874{
2875 if (hWnd == NULL)
2876 return FALSE;
2877
2878 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002879 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2880 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002881 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002882 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2883 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002884 return TRUE;
2885}
2886
2887/*
2888 * SetConsoleIcon()
2889 * Description:
2890 * Attempts to change the small icon and/or the big icon currently in
2891 * use by a given window.
2892 * Returns:
2893 * TRUE on success
2894 */
2895 static BOOL
2896SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002897 HWND hWnd,
2898 HICON hIconSmall,
2899 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002900{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002901 if (hWnd == NULL)
2902 return FALSE;
2903
2904 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002905 SendMessage(hWnd, WM_SETICON,
2906 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002907 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002908 SendMessage(hWnd, WM_SETICON,
2909 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002910 return TRUE;
2911}
2912
2913/*
2914 * SaveConsoleTitleAndIcon()
2915 * Description:
2916 * Saves the current console window title in g_szOrigTitle, for later
2917 * restoration. Also, attempts to obtain a handle to the console window,
2918 * and use it to save the small and big icons currently in use by the
2919 * console window. This is not always possible on some versions of Windows;
2920 * nor is it possible when running Vim remotely using Telnet (since the
2921 * console window the user sees is owned by a remote process).
2922 */
2923 static void
2924SaveConsoleTitleAndIcon(void)
2925{
Bram Moolenaar0f873732019-12-05 20:28:46 +01002926 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002927 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2928 return;
2929
2930 /*
2931 * Obtain a handle to the console window using GetConsoleWindow() from
2932 * KERNEL32.DLL; we need to handle in order to change the window icon.
2933 * This function only exists on NT-based Windows, starting with Windows
2934 * 2000. On older operating systems, we can't change the window icon
2935 * anyway.
2936 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002937 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002938 if (g_hWnd == NULL)
2939 return;
2940
Bram Moolenaar0f873732019-12-05 20:28:46 +01002941 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002942 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2943 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2944 return;
2945
Bram Moolenaar0f873732019-12-05 20:28:46 +01002946 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01002947 if (
2948# ifdef FEAT_LIBCALL
2949 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
2950# endif
2951 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002952 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002953 if (g_hVimIcon != NULL)
2954 g_fCanChangeIcon = TRUE;
2955}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002956
2957static int g_fWindInitCalled = FALSE;
2958static int g_fTermcapMode = FALSE;
2959static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002960
2961/*
2962 * non-GUI version of mch_init().
2963 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002964 static void
2965mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002966{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002967# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002968 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002969# endif
2970# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002971 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002972# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002973
Bram Moolenaar0f873732019-12-05 20:28:46 +01002974 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002975 SET_INVALID_PARAM_HANDLER;
2976
Bram Moolenaar0f873732019-12-05 20:28:46 +01002977 // Let critical errors result in a failure, not in a dialog box. Required
2978 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002979 SetErrorMode(SEM_FAILCRITICALERRORS);
2980
Bram Moolenaar0f873732019-12-05 20:28:46 +01002981 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002982 out_flush();
2983
Bram Moolenaar0f873732019-12-05 20:28:46 +01002984 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00002985 if (read_cmd_fd == 0)
2986 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2987 else
2988 create_conin();
2989 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2990
Christopher Plewright38804d62022-11-09 23:55:52 +00002991 wt_init();
2992 vtp_flag_init();
2993 vtp_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002994# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01002995 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002996 SaveConsoleBuffer(&g_cbOrig);
2997 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002998# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01002999 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003000 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
3001 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003002# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003003 if (cterm_normal_fg_color == 0)
3004 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
3005 if (cterm_normal_bg_color == 0)
3006 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
3007
Bram Moolenaarbdace832019-03-02 10:13:42 +01003008 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02003009 g_color_index_fg = g_attrDefault & 0xf;
3010 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
3011
Bram Moolenaar0f873732019-12-05 20:28:46 +01003012 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00003013 update_tcap(g_attrCurrent);
3014
3015 GetConsoleCursorInfo(g_hConOut, &g_cci);
3016 GetConsoleMode(g_hConIn, &g_cmodein);
3017 GetConsoleMode(g_hConOut, &g_cmodeout);
3018
Bram Moolenaar071d4272004-06-13 20:20:40 +00003019 SaveConsoleTitleAndIcon();
3020 /*
3021 * Set both the small and big icons of the console window to Vim's icon.
3022 * Note that Vim presently only has one size of icon (32x32), but it
3023 * automatically gets scaled down to 16x16 when setting the small icon.
3024 */
3025 if (g_fCanChangeIcon)
3026 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003027
3028 ui_get_shellsize();
3029
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003030# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003031 fdDump = fopen("dump", "wt");
3032
3033 if (fdDump)
3034 {
3035 time_t t;
3036
3037 time(&t);
3038 fputs(ctime(&t), fdDump);
3039 fflush(fdDump);
3040 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003041# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003042
3043 g_fWindInitCalled = TRUE;
3044
Bram Moolenaar071d4272004-06-13 20:20:40 +00003045 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003046
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003047# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003048 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003049# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003050}
3051
3052/*
3053 * non-GUI version of mch_exit().
3054 * Shut down and exit with status `r'
3055 * Careful: mch_exit() may be called before mch_init()!
3056 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003057 static void
3058mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003059{
Bram Moolenaar955f1982017-02-05 15:10:51 +01003060 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003061
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003062 vtp_exit();
3063
Bram Moolenaar955f1982017-02-05 15:10:51 +01003064 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003065 if (g_fWindInitCalled)
3066 settmode(TMODE_COOK);
3067
Bram Moolenaar0f873732019-12-05 20:28:46 +01003068 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00003069
3070 if (g_fWindInitCalled)
3071 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02003072 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003073 /*
3074 * Restore both the small and big icons of the console window to
3075 * what they were at startup. Don't do this when the window is
3076 * closed, Vim would hang here.
3077 */
3078 if (g_fCanChangeIcon && !g_fForceExit)
3079 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003080
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003081# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003082 if (fdDump)
3083 {
3084 time_t t;
3085
3086 time(&t);
3087 fputs(ctime(&t), fdDump);
3088 fclose(fdDump);
3089 }
3090 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003091# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003092 }
3093
3094 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003095 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003096 SetConsoleMode(g_hConOut, g_cmodeout);
3097
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003098# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003099 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003100# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003101
3102 exit(r);
3103}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003104#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003105
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003106 void
3107mch_init(void)
3108{
3109#ifdef VIMDLL
3110 if (gui.starting)
3111 mch_init_g();
3112 else
3113 mch_init_c();
3114#elif defined(FEAT_GUI_MSWIN)
3115 mch_init_g();
3116#else
3117 mch_init_c();
3118#endif
3119}
3120
3121 void
3122mch_exit(int r)
3123{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003124#ifdef FEAT_NETBEANS_INTG
3125 netbeans_send_disconnect();
3126#endif
3127
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003128#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003129 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003130 mch_exit_g(r);
3131 else
3132 mch_exit_c(r);
3133#elif defined(FEAT_GUI_MSWIN)
3134 mch_exit_g(r);
3135#else
3136 mch_exit_c(r);
3137#endif
3138}
3139
Bram Moolenaar071d4272004-06-13 20:20:40 +00003140/*
3141 * Do we have an interactive window?
3142 */
3143 int
3144mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003145 int argc UNUSED,
3146 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003147{
3148 get_exe_name();
3149
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003150#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003151 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003152#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003153# ifdef VIMDLL
3154 if (gui.in_use)
3155 return OK;
3156# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003157 if (isatty(1))
3158 return OK;
3159 return FAIL;
3160#endif
3161}
3162
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003163/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003164 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003165 * When "len" is > 0, also expand short to long filenames.
3166 */
3167 void
3168fname_case(
3169 char_u *name,
3170 int len)
3171{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003172 int flen;
3173 WCHAR *p;
3174 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003175
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003176 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003177 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003178 return;
3179
3180 slash_adjust(name);
3181
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003182 p = enc_to_utf16(name, NULL);
3183 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003184 return;
3185
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003186 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003187 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003188 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003189
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003190 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003191 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003192 if (len > 0 || flen >= (int)STRLEN(q))
3193 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3194 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003195 }
3196 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003197 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003198}
3199
3200
3201/*
3202 * Insert user name in s[len].
3203 */
3204 int
3205mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003206 char_u *s,
3207 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003208{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003209 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003210 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003211
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003212 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003213 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003214 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003215
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003216 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003217 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003218 vim_strncpy(s, p, len - 1);
3219 vim_free(p);
3220 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003221 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003222 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003223 s[0] = NUL;
3224 return FAIL;
3225}
3226
3227
3228/*
3229 * Insert host name in s[len].
3230 */
3231 void
3232mch_get_host_name(
3233 char_u *s,
3234 int len)
3235{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003236 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003237 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003238
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003239 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003240 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003241 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003242
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003243 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003244 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003245 vim_strncpy(s, p, len - 1);
3246 vim_free(p);
3247 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003248 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003249 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003250}
3251
3252
3253/*
3254 * return process ID
3255 */
3256 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003257mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003258{
3259 return (long)GetCurrentProcessId();
3260}
3261
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003262/*
3263 * return TRUE if process "pid" is still running
3264 */
3265 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003266mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003267{
3268 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3269 DWORD status = 0;
3270 int ret = FALSE;
3271
3272 if (hProcess == NULL)
3273 return FALSE; // might not have access
3274 if (GetExitCodeProcess(hProcess, &status) )
3275 ret = status == STILL_ACTIVE;
3276 CloseHandle(hProcess);
3277 return ret;
3278}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003279
3280/*
3281 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3282 * Return OK for success, FAIL for failure.
3283 */
3284 int
3285mch_dirname(
3286 char_u *buf,
3287 int len)
3288{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003289 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003290
Bram Moolenaar071d4272004-06-13 20:20:40 +00003291 /*
3292 * Originally this was:
3293 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3294 * But the Win32s known bug list says that getcwd() doesn't work
3295 * so use the Win32 system call instead. <Negri>
3296 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003297 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003298 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003299 WCHAR wcbuf[_MAX_PATH + 1];
3300 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003301
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003302 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003303 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003304 p = utf16_to_enc(wcbuf, NULL);
3305 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003306 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003307 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003308 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003309 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003310 }
3311 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003312 if (p == NULL)
3313 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003314
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003315 if (p != NULL)
3316 {
3317 vim_strncpy(buf, p, len - 1);
3318 vim_free(p);
3319 return OK;
3320 }
3321 }
3322 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003323}
3324
3325/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003326 * Get file permissions for "name".
3327 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003328 */
3329 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003330mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003331{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003332 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003333 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003334
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003335 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003336 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003337}
3338
3339
3340/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003341 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003342 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003343 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003344 */
3345 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003346mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003347{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003348 long n;
3349 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003350
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003351 p = enc_to_utf16(name, NULL);
3352 if (p == NULL)
3353 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003354
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003355 n = _wchmod(p, perm);
3356 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003357 if (n == -1)
3358 return FAIL;
3359
3360 win32_set_archive(name);
3361
3362 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003363}
3364
3365/*
3366 * Set hidden flag for "name".
3367 */
3368 void
3369mch_hide(char_u *name)
3370{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003371 int attrs = win32_getattrs(name);
3372 if (attrs == -1)
3373 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003374
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003375 attrs |= FILE_ATTRIBUTE_HIDDEN;
3376 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003377}
3378
3379/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003380 * Return TRUE if file "name" exists and is hidden.
3381 */
3382 int
3383mch_ishidden(char_u *name)
3384{
3385 int f = win32_getattrs(name);
3386
3387 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003388 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003389
3390 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3391}
3392
3393/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003394 * return TRUE if "name" is a directory
3395 * return FALSE if "name" is not a directory or upon error
3396 */
3397 int
3398mch_isdir(char_u *name)
3399{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003400 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003401
3402 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003403 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003404
3405 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3406}
3407
3408/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003409 * return TRUE if "name" is a directory, NOT a symlink to a directory
3410 * return FALSE if "name" is not a directory
3411 * return FALSE for error
3412 */
3413 int
3414mch_isrealdir(char_u *name)
3415{
3416 return mch_isdir(name) && !mch_is_symbolic_link(name);
3417}
3418
3419/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003420 * Create directory "name".
3421 * Return 0 on success, -1 on error.
3422 */
3423 int
3424mch_mkdir(char_u *name)
3425{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003426 WCHAR *p;
3427 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003428
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003429 p = enc_to_utf16(name, NULL);
3430 if (p == NULL)
3431 return -1;
3432 retval = _wmkdir(p);
3433 vim_free(p);
3434 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003435}
3436
3437/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003438 * Delete directory "name".
3439 * Return 0 on success, -1 on error.
3440 */
3441 int
3442mch_rmdir(char_u *name)
3443{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003444 WCHAR *p;
3445 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003446
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003447 p = enc_to_utf16(name, NULL);
3448 if (p == NULL)
3449 return -1;
3450 retval = _wrmdir(p);
3451 vim_free(p);
3452 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003453}
3454
3455/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003456 * Return TRUE if file "fname" has more than one link.
3457 */
3458 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003459mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003460{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003461 BY_HANDLE_FILE_INFORMATION info;
3462
3463 return win32_fileinfo(fname, &info) == FILEINFO_OK
3464 && info.nNumberOfLinks > 1;
3465}
3466
3467/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003468 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003469 */
3470 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003471mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003472{
3473 HANDLE hFind;
3474 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003475 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003476 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003477 WIN32_FIND_DATAW findDataW;
3478
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003479 wn = enc_to_utf16(name, NULL);
3480 if (wn == NULL)
3481 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003482
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003483 hFind = FindFirstFileW(wn, &findDataW);
3484 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003485 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003486 {
3487 fileFlags = findDataW.dwFileAttributes;
3488 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003489 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003490 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003491
3492 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003493 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3494 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003495 res = TRUE;
3496
3497 return res;
3498}
3499
3500/*
3501 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3502 * link.
3503 */
3504 int
3505mch_is_linked(char_u *fname)
3506{
3507 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3508 return TRUE;
3509 return FALSE;
3510}
3511
3512/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003513 * Get the by-handle-file-information for "fname".
3514 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003515 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003516 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3517 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3518 */
3519 int
3520win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3521{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003522 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003523 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003524 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003525
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003526 wn = enc_to_utf16(fname, NULL);
3527 if (wn == NULL)
3528 return FILEINFO_ENC_FAIL;
3529
3530 hFile = CreateFileW(wn, // file name
3531 GENERIC_READ, // access mode
3532 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3533 NULL, // security descriptor
3534 OPEN_EXISTING, // creation disposition
3535 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3536 NULL); // handle to template file
3537 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003538
3539 if (hFile != INVALID_HANDLE_VALUE)
3540 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003541 if (GetFileInformationByHandle(hFile, info) != 0)
3542 res = FILEINFO_OK;
3543 else
3544 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003545 CloseHandle(hFile);
3546 }
3547
Bram Moolenaar03f48552006-02-28 23:52:23 +00003548 return res;
3549}
3550
3551/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003552 * get file attributes for `name'
3553 * -1 : error
3554 * else FILE_ATTRIBUTE_* defined in winnt.h
3555 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003556 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003557win32_getattrs(char_u *name)
3558{
3559 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003560 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003561
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003562 p = enc_to_utf16(name, NULL);
3563 if (p == NULL)
3564 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003565
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003566 attr = GetFileAttributesW(p);
3567 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003568
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003569 return attr;
3570}
3571
3572/*
3573 * set file attributes for `name' to `attrs'
3574 *
3575 * return -1 for failure, 0 otherwise
3576 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003577 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003578win32_setattrs(char_u *name, int attrs)
3579{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003580 int res;
3581 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003582
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003583 p = enc_to_utf16(name, NULL);
3584 if (p == NULL)
3585 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003586
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003587 res = SetFileAttributesW(p, attrs);
3588 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003589
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003590 return res ? 0 : -1;
3591}
3592
3593/*
3594 * Set archive flag for "name".
3595 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003596 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003597win32_set_archive(char_u *name)
3598{
3599 int attrs = win32_getattrs(name);
3600 if (attrs == -1)
3601 return -1;
3602
3603 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3604 return win32_setattrs(name, attrs);
3605}
3606
3607/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003608 * Return TRUE if file or directory "name" is writable (not readonly).
3609 * Strange semantics of Win32: a readonly directory is writable, but you can't
3610 * delete a file. Let's say this means it is writable.
3611 */
3612 int
3613mch_writable(char_u *name)
3614{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003615 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003616
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003617 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3618 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003619}
3620
Bram Moolenaar071d4272004-06-13 20:20:40 +00003621/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003622 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003623 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003624 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3625 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003626 */
3627 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01003628mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003629{
Bram Moolenaar95da1362020-05-30 18:37:55 +02003630 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003631}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003632
3633/*
3634 * Check what "name" is:
3635 * NODE_NORMAL: file or directory (or doesn't exist)
3636 * NODE_WRITABLE: writable device, socket, fifo, etc.
3637 * NODE_OTHER: non-writable things
3638 */
3639 int
3640mch_nodetype(char_u *name)
3641{
3642 HANDLE hFile;
3643 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003644 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003645
Bram Moolenaar0f873732019-12-05 20:28:46 +01003646 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3647 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3648 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00003649 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3650 return NODE_WRITABLE;
3651
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003652 wn = enc_to_utf16(name, NULL);
3653 if (wn == NULL)
3654 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003655
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003656 hFile = CreateFileW(wn, // file name
3657 GENERIC_WRITE, // access mode
3658 0, // share mode
3659 NULL, // security descriptor
3660 OPEN_EXISTING, // creation disposition
3661 0, // file attributes
3662 NULL); // handle to template file
3663 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003664 if (hFile == INVALID_HANDLE_VALUE)
3665 return NODE_NORMAL;
3666
3667 type = GetFileType(hFile);
3668 CloseHandle(hFile);
3669 if (type == FILE_TYPE_CHAR)
3670 return NODE_WRITABLE;
3671 if (type == FILE_TYPE_DISK)
3672 return NODE_NORMAL;
3673 return NODE_OTHER;
3674}
3675
3676#ifdef HAVE_ACL
3677struct my_acl
3678{
3679 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3680 PSID pSidOwner;
3681 PSID pSidGroup;
3682 PACL pDacl;
3683 PACL pSacl;
3684};
3685#endif
3686
3687/*
3688 * Return a pointer to the ACL of file "fname" in allocated memory.
3689 * Return NULL if the ACL is not available for whatever reason.
3690 */
3691 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003692mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003693{
3694#ifndef HAVE_ACL
3695 return (vim_acl_T)NULL;
3696#else
3697 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003698 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003699
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003700 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003701 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003702 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003703 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003704
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003705 wn = enc_to_utf16(fname, NULL);
3706 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003707 {
3708 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003709 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003710 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003711
3712 // Try to retrieve the entire security descriptor.
3713 err = GetNamedSecurityInfoW(
3714 wn, // Abstract filename
3715 SE_FILE_OBJECT, // File Object
3716 OWNER_SECURITY_INFORMATION |
3717 GROUP_SECURITY_INFORMATION |
3718 DACL_SECURITY_INFORMATION |
3719 SACL_SECURITY_INFORMATION,
3720 &p->pSidOwner, // Ownership information.
3721 &p->pSidGroup, // Group membership.
3722 &p->pDacl, // Discretionary information.
3723 &p->pSacl, // For auditing purposes.
3724 &p->pSecurityDescriptor);
3725 if (err == ERROR_ACCESS_DENIED ||
3726 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003727 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003728 // Retrieve only DACL.
3729 (void)GetNamedSecurityInfoW(
3730 wn,
3731 SE_FILE_OBJECT,
3732 DACL_SECURITY_INFORMATION,
3733 NULL,
3734 NULL,
3735 &p->pDacl,
3736 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003737 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003738 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003739 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003740 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003741 mch_free_acl((vim_acl_T)p);
3742 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003743 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003744 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003745 }
3746
3747 return (vim_acl_T)p;
3748#endif
3749}
3750
Bram Moolenaar27515922013-06-29 15:36:26 +02003751#ifdef HAVE_ACL
3752/*
3753 * Check if "acl" contains inherited ACE.
3754 */
3755 static BOOL
3756is_acl_inherited(PACL acl)
3757{
3758 DWORD i;
3759 ACL_SIZE_INFORMATION acl_info;
3760 PACCESS_ALLOWED_ACE ace;
3761
3762 acl_info.AceCount = 0;
3763 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3764 for (i = 0; i < acl_info.AceCount; i++)
3765 {
3766 GetAce(acl, i, (LPVOID *)&ace);
3767 if (ace->Header.AceFlags & INHERITED_ACE)
3768 return TRUE;
3769 }
3770 return FALSE;
3771}
3772#endif
3773
Bram Moolenaar071d4272004-06-13 20:20:40 +00003774/*
3775 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3776 * Errors are ignored.
3777 * This must only be called with "acl" equal to what mch_get_acl() returned.
3778 */
3779 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003780mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003781{
3782#ifdef HAVE_ACL
3783 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003784 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003785 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003786
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003787 if (p == NULL)
3788 return;
3789
3790 wn = enc_to_utf16(fname, NULL);
3791 if (wn == NULL)
3792 return;
3793
3794 // Set security flags
3795 if (p->pSidOwner)
3796 sec_info |= OWNER_SECURITY_INFORMATION;
3797 if (p->pSidGroup)
3798 sec_info |= GROUP_SECURITY_INFORMATION;
3799 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003800 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003801 sec_info |= DACL_SECURITY_INFORMATION;
3802 // Do not inherit its parent's DACL.
3803 // If the DACL is inherited, Cygwin permissions would be changed.
3804 if (!is_acl_inherited(p->pDacl))
3805 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003806 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003807 if (p->pSacl)
3808 sec_info |= SACL_SECURITY_INFORMATION;
3809
3810 (void)SetNamedSecurityInfoW(
3811 wn, // Abstract filename
3812 SE_FILE_OBJECT, // File Object
3813 sec_info,
3814 p->pSidOwner, // Ownership information.
3815 p->pSidGroup, // Group membership.
3816 p->pDacl, // Discretionary information.
3817 p->pSacl // For auditing purposes.
3818 );
3819 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003820#endif
3821}
3822
3823 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003824mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003825{
3826#ifdef HAVE_ACL
3827 struct my_acl *p = (struct my_acl *)acl;
3828
3829 if (p != NULL)
3830 {
3831 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3832 vim_free(p);
3833 }
3834#endif
3835}
3836
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003837#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003838
3839/*
3840 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3841 */
3842 static BOOL WINAPI
3843handler_routine(
3844 DWORD dwCtrlType)
3845{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003846 INPUT_RECORD ir;
3847 DWORD out;
3848
Bram Moolenaar071d4272004-06-13 20:20:40 +00003849 switch (dwCtrlType)
3850 {
3851 case CTRL_C_EVENT:
3852 if (ctrl_c_interrupts)
3853 g_fCtrlCPressed = TRUE;
3854 return TRUE;
3855
3856 case CTRL_BREAK_EVENT:
3857 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003858 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003859 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02003860 ir.EventType = KEY_EVENT;
3861 ir.Event.KeyEvent.bKeyDown = TRUE;
3862 ir.Event.KeyEvent.wRepeatCount = 1;
3863 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3864 ir.Event.KeyEvent.wVirtualScanCode = 0;
3865 ir.Event.KeyEvent.dwControlKeyState = 0;
3866 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3867 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003868 return TRUE;
3869
Bram Moolenaar0f873732019-12-05 20:28:46 +01003870 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00003871 case CTRL_CLOSE_EVENT:
3872 case CTRL_LOGOFF_EVENT:
3873 case CTRL_SHUTDOWN_EVENT:
3874 windgoto((int)Rows - 1, 0);
3875 g_fForceExit = TRUE;
3876
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003877 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003878 (dwCtrlType == CTRL_CLOSE_EVENT
3879 ? _("close")
3880 : dwCtrlType == CTRL_LOGOFF_EVENT
3881 ? _("logoff")
3882 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003883# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00003884 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003885# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003886
Bram Moolenaar0f873732019-12-05 20:28:46 +01003887 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00003888
Bram Moolenaar0f873732019-12-05 20:28:46 +01003889 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00003890
3891 default:
3892 return FALSE;
3893 }
3894}
3895
3896
3897/*
3898 * set the tty in (raw) ? "raw" : "cooked" mode
3899 */
3900 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02003901mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003902{
3903 DWORD cmodein;
3904 DWORD cmodeout;
3905 BOOL bEnableHandler;
3906
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003907# ifdef VIMDLL
3908 if (gui.in_use)
3909 return;
3910# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003911 GetConsoleMode(g_hConIn, &cmodein);
3912 GetConsoleMode(g_hConOut, &cmodeout);
3913 if (tmode == TMODE_RAW)
3914 {
3915 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3916 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003917 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003918 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003919 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003920 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
3921 }
3922 else
3923 {
3924 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
3925 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003926 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003927# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01003928 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
3929 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003930 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003931# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003932 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003933# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003934 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003935 bEnableHandler = TRUE;
3936 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01003937 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00003938 {
3939 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3940 ENABLE_ECHO_INPUT);
3941 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3942 bEnableHandler = FALSE;
3943 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003944 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003945 SetConsoleMode(g_hConOut, cmodeout);
3946 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3947
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003948# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003949 if (fdDump)
3950 {
3951 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3952 tmode == TMODE_RAW ? "raw" :
3953 tmode == TMODE_COOK ? "cooked" : "normal",
3954 cmodein, cmodeout);
3955 fflush(fdDump);
3956 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003957# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003958}
3959
3960
3961/*
3962 * Get the size of the current window in `Rows' and `Columns'
3963 * Return OK when size could be determined, FAIL otherwise.
3964 */
3965 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003966mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003967{
3968 CONSOLE_SCREEN_BUFFER_INFO csbi;
3969
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003970# ifdef VIMDLL
3971 if (gui.in_use)
3972 return OK;
3973# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003974 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3975 {
3976 /*
3977 * For some reason, we are trying to get the screen dimensions
3978 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3979 * variables are really intended to mean the size of Vim screen
3980 * while in termcap mode.
3981 */
3982 Rows = g_cbTermcap.Info.dwSize.Y;
3983 Columns = g_cbTermcap.Info.dwSize.X;
3984 }
3985 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3986 {
3987 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3988 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3989 }
3990 else
3991 {
3992 Rows = 25;
3993 Columns = 80;
3994 }
3995 return OK;
3996}
3997
3998/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003999 * Resize console buffer to 'COORD'
4000 */
4001 static void
4002ResizeConBuf(
4003 HANDLE hConsole,
4004 COORD coordScreen)
4005{
4006 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4007 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004008# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004009 if (fdDump)
4010 {
4011 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4012 GetLastError());
4013 fflush(fdDump);
4014 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004015# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004016 }
4017}
4018
4019/*
4020 * Resize console window size to 'srWindowRect'
4021 */
4022 static void
4023ResizeWindow(
4024 HANDLE hConsole,
4025 SMALL_RECT srWindowRect)
4026{
4027 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4028 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004029# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004030 if (fdDump)
4031 {
4032 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4033 GetLastError());
4034 fflush(fdDump);
4035 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004036# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004037 }
4038}
4039
4040/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004041 * Set a console window to `xSize' * `ySize'
4042 */
4043 static void
4044ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004045 HANDLE hConsole,
4046 int xSize,
4047 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004048{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004049 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
4050 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004051 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004052 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004053 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004054
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004055# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004056 if (fdDump)
4057 {
4058 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4059 fflush(fdDump);
4060 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004061# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004062
Bram Moolenaar0f873732019-12-05 20:28:46 +01004063 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00004064 coordScreen = GetLargestConsoleWindowSize(hConsole);
4065
Bram Moolenaar0f873732019-12-05 20:28:46 +01004066 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00004067 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4068 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4069 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4070
4071 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4072 {
4073 int sx, sy;
4074
4075 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4076 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4077 if (sy < ySize || sx < xSize)
4078 {
4079 /*
4080 * Increasing number of lines/columns, do buffer first.
4081 * Use the maximal size in x and y direction.
4082 */
4083 if (sy < ySize)
4084 coordScreen.Y = ySize;
4085 else
4086 coordScreen.Y = sy;
4087 if (sx < xSize)
4088 coordScreen.X = xSize;
4089 else
4090 coordScreen.X = sx;
4091 SetConsoleScreenBufferSize(hConsole, coordScreen);
4092 }
4093 }
4094
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004095 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004096 coordScreen.X = xSize;
4097 coordScreen.Y = ySize;
4098
Bram Moolenaar2551c032018-08-23 22:38:31 +02004099 // In the new console call API, only the first time in reverse order
4100 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004101 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004102 ResizeWindow(hConsole, srWindowRect);
4103 ResizeConBuf(hConsole, coordScreen);
4104 }
4105 else
4106 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004107 // Workaround for a Windows 10 bug
4108 cursor.X = srWindowRect.Left;
4109 cursor.Y = srWindowRect.Top;
4110 SetConsoleCursorPosition(hConsole, cursor);
4111
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004112 ResizeConBuf(hConsole, coordScreen);
4113 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004114 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004115 }
4116}
4117
4118
4119/*
4120 * Set the console window to `Rows' * `Columns'
4121 */
4122 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004123mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004124{
4125 COORD coordScreen;
4126
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004127# ifdef VIMDLL
4128 if (gui.in_use)
4129 return;
4130# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004131 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004132 if (suppress_winsize != 0)
4133 {
4134 suppress_winsize = 2;
4135 return;
4136 }
4137
4138 if (term_console)
4139 {
4140 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4141
Bram Moolenaar0f873732019-12-05 20:28:46 +01004142 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004143 if (Rows > coordScreen.Y)
4144 Rows = coordScreen.Y;
4145 if (Columns > coordScreen.X)
4146 Columns = coordScreen.X;
4147
4148 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4149 }
4150}
4151
4152/*
4153 * Rows and/or Columns has changed.
4154 */
4155 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004156mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004157{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004158# ifdef VIMDLL
4159 if (gui.in_use)
4160 return;
4161# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004162 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4163}
4164
4165
4166/*
4167 * Called when started up, to set the winsize that was delayed.
4168 */
4169 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004170mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004171{
4172 if (suppress_winsize == 2)
4173 {
4174 suppress_winsize = 0;
4175 mch_set_shellsize();
4176 shell_resized();
4177 }
4178 suppress_winsize = 0;
4179}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004180#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004181
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004182 static BOOL
4183vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004184 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004185 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004186 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004187 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004188 PROCESS_INFORMATION *pi,
4189 LPVOID *env,
4190 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004191{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004192 BOOL ret = FALSE;
4193 WCHAR *wcmd, *wcwd = NULL;
4194
4195 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4196 if (wcmd == NULL)
4197 return FALSE;
4198 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004199 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004200 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4201 if (wcwd == NULL)
4202 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004203 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004204
4205 ret = CreateProcessW(
4206 NULL, // Executable name
4207 wcmd, // Command to execute
4208 NULL, // Process security attributes
4209 NULL, // Thread security attributes
4210 inherit_handles, // Inherit handles
4211 flags, // Creation flags
4212 env, // Environment
4213 wcwd, // Current directory
4214 (LPSTARTUPINFOW)si, // Startup information
4215 pi); // Process information
4216theend:
4217 vim_free(wcmd);
4218 vim_free(wcwd);
4219 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004220}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004221
4222
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004223 static HINSTANCE
4224vim_shell_execute(
4225 char *cmd,
4226 INT n_show_cmd)
4227{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004228 HINSTANCE ret;
4229 WCHAR *wcmd;
4230
4231 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4232 if (wcmd == NULL)
4233 return (HINSTANCE) 0;
4234
4235 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4236 vim_free(wcmd);
4237 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004238}
4239
4240
Bram Moolenaar4f974752019-02-17 17:44:42 +01004241#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004242
4243/*
4244 * Specialised version of system() for Win32 GUI mode.
4245 * This version proceeds as follows:
4246 * 1. Create a console window for use by the subprocess
4247 * 2. Run the subprocess (it gets the allocated console by default)
4248 * 3. Wait for the subprocess to terminate and get its exit code
4249 * 4. Prompt the user to press a key to close the console window
4250 */
4251 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004252mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004253{
4254 STARTUPINFO si;
4255 PROCESS_INFORMATION pi;
4256 DWORD ret = 0;
4257 HWND hwnd = GetFocus();
4258
4259 si.cb = sizeof(si);
4260 si.lpReserved = NULL;
4261 si.lpDesktop = NULL;
4262 si.lpTitle = NULL;
4263 si.dwFlags = STARTF_USESHOWWINDOW;
4264 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004265 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004266 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004267 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004268 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004269 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004270 else
4271 si.wShowWindow = SW_SHOWNORMAL;
4272 si.cbReserved2 = 0;
4273 si.lpReserved2 = NULL;
4274
Bram Moolenaar0f873732019-12-05 20:28:46 +01004275 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004276 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004277 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4278 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004279
Bram Moolenaar0f873732019-12-05 20:28:46 +01004280 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004281 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004282# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004283 int delay = 1;
4284
Bram Moolenaar0f873732019-12-05 20:28:46 +01004285 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004286 for (;;)
4287 {
4288 MSG msg;
4289
K.Takatab7057bd2022-01-21 11:37:07 +00004290 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004291 {
4292 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004293 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004294 delay = 1;
4295 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004296 }
4297 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4298 break;
4299
Bram Moolenaar0f873732019-12-05 20:28:46 +01004300 // We start waiting for a very short time and then increase it, so
4301 // that we respond quickly when the process is quick, and don't
4302 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004303 if (delay < 50)
4304 delay += 10;
4305 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004306# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004307 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004308# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004309
Bram Moolenaar0f873732019-12-05 20:28:46 +01004310 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004311 GetExitCodeProcess(pi.hProcess, &ret);
4312 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004313
Bram Moolenaar0f873732019-12-05 20:28:46 +01004314 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004315 CloseHandle(pi.hThread);
4316 CloseHandle(pi.hProcess);
4317
Bram Moolenaar0f873732019-12-05 20:28:46 +01004318 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004319 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4320
4321 return ret;
4322}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004323
4324/*
4325 * Thread launched by the gui to send the current buffer data to the
4326 * process. This way avoid to hang up vim totally if the children
4327 * process take a long time to process the lines.
4328 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004329 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004330sub_process_writer(LPVOID param)
4331{
4332 HANDLE g_hChildStd_IN_Wr = param;
4333 linenr_T lnum = curbuf->b_op_start.lnum;
4334 DWORD len = 0;
4335 DWORD l;
4336 char_u *lp = ml_get(lnum);
4337 char_u *s;
4338 int written = 0;
4339
4340 for (;;)
4341 {
4342 l = (DWORD)STRLEN(lp + written);
4343 if (l == 0)
4344 len = 0;
4345 else if (lp[written] == NL)
4346 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004347 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004348 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4349 }
4350 else
4351 {
4352 s = vim_strchr(lp + written, NL);
4353 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4354 s == NULL ? l : (DWORD)(s - (lp + written)),
4355 &len, NULL);
4356 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004357 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004358 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004359 // Finished a line, add a NL, unless this line should not have
4360 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004361 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004362 || (!curbuf->b_p_bin
4363 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004364 || (lnum != curbuf->b_no_eol_lnum
4365 && (lnum != curbuf->b_ml.ml_line_count
4366 || curbuf->b_p_eol)))
4367 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004368 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4369 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004370 }
4371
4372 ++lnum;
4373 if (lnum > curbuf->b_op_end.lnum)
4374 break;
4375
4376 lp = ml_get(lnum);
4377 written = 0;
4378 }
4379 else if (len > 0)
4380 written += len;
4381 }
4382
Bram Moolenaar0f873732019-12-05 20:28:46 +01004383 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004384 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004385 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004386}
4387
4388
Bram Moolenaar0f873732019-12-05 20:28:46 +01004389# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004390
4391/*
4392 * This function read from the children's stdout and write the
4393 * data on screen or in the buffer accordingly.
4394 */
4395 static void
4396dump_pipe(int options,
4397 HANDLE g_hChildStd_OUT_Rd,
4398 garray_T *ga,
4399 char_u buffer[],
4400 DWORD *buffer_off)
4401{
4402 DWORD availableBytes = 0;
4403 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004404 int ret;
4405 DWORD len;
4406 DWORD toRead;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004407
Bram Moolenaar0f873732019-12-05 20:28:46 +01004408 // we query the pipe to see if there is any data to read
4409 // to avoid to perform a blocking read
4410 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4411 NULL, // optional buffer
4412 0, // buffer size
4413 NULL, // number of read bytes
4414 &availableBytes, // available bytes total
4415 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004416
Bram Moolenaar0f873732019-12-05 20:28:46 +01004417 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004418 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004419 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01004420 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004421 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004422 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004423
Bram Moolenaar0f873732019-12-05 20:28:46 +01004424 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004425 if (len == 0)
4426 break;
4427
4428 availableBytes -= len;
4429
4430 if (options & SHELL_READ)
4431 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004432 // Do NUL -> NL translation, append NL separated
4433 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004434 for (i = 0; i < len; ++i)
4435 {
4436 if (buffer[i] == NL)
4437 append_ga_line(ga);
4438 else if (buffer[i] == NUL)
4439 ga_append(ga, NL);
4440 else
4441 ga_append(ga, buffer[i]);
4442 }
4443 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004444 else if (has_mbyte)
4445 {
4446 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004447 int c;
4448 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004449
4450 len += *buffer_off;
4451 buffer[len] = NUL;
4452
Bram Moolenaar0f873732019-12-05 20:28:46 +01004453 // Check if the last character in buffer[] is
4454 // incomplete, keep these bytes for the next
4455 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004456 for (p = buffer; p < buffer + len; p += l)
4457 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004458 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004459 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004460 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004461 else if (MB_BYTE2LEN(*p) != l)
4462 break;
4463 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004464 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004465 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004466 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004467 if (len >= 12)
4468 ++p;
4469 else
4470 {
4471 *buffer_off = len;
4472 return;
4473 }
4474 }
4475 c = *p;
4476 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004477 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004478 if (p < buffer + len)
4479 {
4480 *p = c;
4481 *buffer_off = (DWORD)((buffer + len) - p);
4482 mch_memmove(buffer, p, *buffer_off);
4483 return;
4484 }
4485 *buffer_off = 0;
4486 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004487 else
4488 {
4489 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004490 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004491 }
4492
4493 windgoto(msg_row, msg_col);
4494 cursor_on();
4495 out_flush();
4496 }
4497}
4498
4499/*
4500 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4501 * for communication and doesn't open any new window.
4502 */
4503 static int
4504mch_system_piped(char *cmd, int options)
4505{
4506 STARTUPINFO si;
4507 PROCESS_INFORMATION pi;
4508 DWORD ret = 0;
4509
4510 HANDLE g_hChildStd_IN_Rd = NULL;
4511 HANDLE g_hChildStd_IN_Wr = NULL;
4512 HANDLE g_hChildStd_OUT_Rd = NULL;
4513 HANDLE g_hChildStd_OUT_Wr = NULL;
4514
Bram Moolenaar0f873732019-12-05 20:28:46 +01004515 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004516 DWORD len;
4517
Bram Moolenaar0f873732019-12-05 20:28:46 +01004518 // buffer used to receive keys
4519 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4520 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004521
4522 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004523 int noread_cnt = 0;
4524 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004525 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004526 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004527 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004528
4529 SECURITY_ATTRIBUTES saAttr;
4530
Bram Moolenaar0f873732019-12-05 20:28:46 +01004531 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004532 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4533 saAttr.bInheritHandle = TRUE;
4534 saAttr.lpSecurityDescriptor = NULL;
4535
4536 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004537 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004538 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004539 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004540 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004541 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004542 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004543 {
4544 CloseHandle(g_hChildStd_IN_Rd);
4545 CloseHandle(g_hChildStd_IN_Wr);
4546 CloseHandle(g_hChildStd_OUT_Rd);
4547 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004548 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004549 }
4550
4551 si.cb = sizeof(si);
4552 si.lpReserved = NULL;
4553 si.lpDesktop = NULL;
4554 si.lpTitle = NULL;
4555 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4556
Bram Moolenaar0f873732019-12-05 20:28:46 +01004557 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004558 si.hStdError = g_hChildStd_OUT_Wr;
4559 si.hStdOutput = g_hChildStd_OUT_Wr;
4560 si.hStdInput = g_hChildStd_IN_Rd;
4561 si.wShowWindow = SW_HIDE;
4562 si.cbReserved2 = 0;
4563 si.lpReserved2 = NULL;
4564
4565 if (options & SHELL_READ)
4566 ga_init2(&ga, 1, BUFLEN);
4567
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004568 if (cmd != NULL)
4569 {
4570 p = (char *)vim_strsave((char_u *)cmd);
4571 if (p != NULL)
4572 unescape_shellxquote((char_u *)p, p_sxe);
4573 else
4574 p = cmd;
4575 }
4576
Bram Moolenaar0f873732019-12-05 20:28:46 +01004577 // Now, run the command.
4578 // About "Inherit handles" being TRUE: this command can be litigious,
4579 // handle inheritance was deactivated for pending temp file, but, if we
4580 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004581 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4582 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004583
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004584 if (p != cmd)
4585 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004586
Bram Moolenaar0f873732019-12-05 20:28:46 +01004587 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004588 CloseHandle(g_hChildStd_IN_Rd);
4589 CloseHandle(g_hChildStd_OUT_Wr);
4590
4591 if (options & SHELL_WRITE)
4592 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004593 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004594 _beginthreadex(NULL, // security attributes
4595 0, // default stack size
4596 sub_process_writer, // function to be executed
4597 g_hChildStd_IN_Wr, // parameter
4598 0, // creation flag, start immediately
4599 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004600 CloseHandle(thread);
4601 g_hChildStd_IN_Wr = NULL;
4602 }
4603
Bram Moolenaar0f873732019-12-05 20:28:46 +01004604 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004605 for (;;)
4606 {
4607 MSG msg;
4608
K.Takatab7057bd2022-01-21 11:37:07 +00004609 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004610 {
4611 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004612 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004613 }
4614
Bram Moolenaar0f873732019-12-05 20:28:46 +01004615 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004616 if ((options & (SHELL_READ|SHELL_WRITE))
4617# ifdef FEAT_GUI
4618 || gui.in_use
4619# endif
4620 )
4621 {
4622 len = 0;
4623 if (!(options & SHELL_EXPAND)
4624 && ((options &
4625 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4626 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4627# ifdef FEAT_GUI
4628 || gui.in_use
4629# endif
4630 )
4631 && (ta_len > 0 || noread_cnt > 4))
4632 {
4633 if (ta_len == 0)
4634 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004635 // Get extra characters when we don't have any. Reset the
4636 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004637 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004638 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4639 }
4640 if (ta_len > 0 || len > 0)
4641 {
4642 /*
4643 * For pipes: Check for CTRL-C: send interrupt signal to
4644 * child. Check for CTRL-D: EOF, close pipe to child.
4645 */
4646 if (len == 1 && cmd != NULL)
4647 {
4648 if (ta_buf[ta_len] == Ctrl_C)
4649 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004650 // Learn what exit code is expected, for
4651 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004652 TerminateProcess(pi.hProcess, 9);
4653 }
4654 if (ta_buf[ta_len] == Ctrl_D)
4655 {
4656 CloseHandle(g_hChildStd_IN_Wr);
4657 g_hChildStd_IN_Wr = NULL;
4658 }
4659 }
4660
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01004661 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004662
4663 /*
4664 * For pipes: echo the typed characters. For a pty this
4665 * does not seem to work.
4666 */
4667 for (i = ta_len; i < ta_len + len; ++i)
4668 {
4669 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4670 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004671 else if (has_mbyte)
4672 {
4673 int l = (*mb_ptr2len)(ta_buf + i);
4674
4675 msg_outtrans_len(ta_buf + i, l);
4676 i += l - 1;
4677 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004678 else
4679 msg_outtrans_len(ta_buf + i, 1);
4680 }
4681 windgoto(msg_row, msg_col);
4682 out_flush();
4683
4684 ta_len += len;
4685
4686 /*
4687 * Write the characters to the child, unless EOF has been
4688 * typed for pipes. Write one character at a time, to
4689 * avoid losing too much typeahead. When writing buffer
4690 * lines, drop the typed characters (only check for
4691 * CTRL-C).
4692 */
4693 if (options & SHELL_WRITE)
4694 ta_len = 0;
4695 else if (g_hChildStd_IN_Wr != NULL)
4696 {
4697 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4698 1, &len, NULL);
4699 // if we are typing in, we want to keep things reactive
4700 delay = 1;
4701 if (len > 0)
4702 {
4703 ta_len -= len;
4704 mch_memmove(ta_buf, ta_buf + len, ta_len);
4705 }
4706 }
4707 }
4708 }
4709 }
4710
4711 if (ta_len)
4712 ui_inchar_undo(ta_buf, ta_len);
4713
4714 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4715 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004716 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004717 break;
4718 }
4719
4720 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004721 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004722
Bram Moolenaar0f873732019-12-05 20:28:46 +01004723 // We start waiting for a very short time and then increase it, so
4724 // that we respond quickly when the process is quick, and don't
4725 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004726 if (delay < 50)
4727 delay += 10;
4728 }
4729
Bram Moolenaar0f873732019-12-05 20:28:46 +01004730 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004731 CloseHandle(g_hChildStd_OUT_Rd);
4732 if (g_hChildStd_IN_Wr != NULL)
4733 CloseHandle(g_hChildStd_IN_Wr);
4734
4735 WaitForSingleObject(pi.hProcess, INFINITE);
4736
Bram Moolenaar0f873732019-12-05 20:28:46 +01004737 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004738 GetExitCodeProcess(pi.hProcess, &ret);
4739
4740 if (options & SHELL_READ)
4741 {
4742 if (ga.ga_len > 0)
4743 {
4744 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01004745 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004746 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4747 }
4748 else
4749 curbuf->b_no_eol_lnum = 0;
4750 ga_clear(&ga);
4751 }
4752
Bram Moolenaar0f873732019-12-05 20:28:46 +01004753 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004754 CloseHandle(pi.hThread);
4755 CloseHandle(pi.hProcess);
4756
4757 return ret;
4758}
4759
4760 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004761mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004762{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004763 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004764 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004765 return mch_system_piped(cmd, options);
4766 else
4767 return mch_system_classic(cmd, options);
4768}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004769#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004770
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004771#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004772 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02004773mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004774{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004775 int ret;
4776 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004777 char_u *buf;
4778 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004779
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004780 // If the command starts and ends with double quotes, enclose the command
4781 // in parentheses.
4782 len = STRLEN(cmd);
4783 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
4784 {
4785 len += 3;
4786 buf = alloc(len);
4787 if (buf == NULL)
4788 return -1;
4789 vim_snprintf((char *)buf, len, "(%s)", cmd);
4790 wcmd = enc_to_utf16(buf, NULL);
4791 free(buf);
4792 }
4793 else
4794 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4795
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004796 if (wcmd == NULL)
4797 return -1;
4798
4799 ret = _wsystem(wcmd);
4800 vim_free(wcmd);
4801 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004802}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004803
4804#endif
4805
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004806 static int
4807mch_system(char *cmd, int options)
4808{
4809#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004810 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004811 return mch_system_g(cmd, options);
4812 else
4813 return mch_system_c(cmd, options);
4814#elif defined(FEAT_GUI_MSWIN)
4815 return mch_system_g(cmd, options);
4816#else
4817 return mch_system_c(cmd, options);
4818#endif
4819}
4820
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004821#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4822/*
4823 * Use a terminal window to run a shell command in.
4824 */
4825 static int
4826mch_call_shell_terminal(
4827 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004828 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004829{
4830 jobopt_T opt;
4831 char_u *newcmd = NULL;
4832 typval_T argvar[2];
4833 long_u cmdlen;
4834 int retval = -1;
4835 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004836 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004837 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004838 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004839
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004840 if (cmd == NULL)
4841 cmdlen = STRLEN(p_sh) + 1;
4842 else
4843 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004844 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004845 if (newcmd == NULL)
4846 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004847 if (cmd == NULL)
4848 {
4849 STRCPY(newcmd, p_sh);
4850 ch_log(NULL, "starting terminal to run a shell");
4851 }
4852 else
4853 {
4854 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4855 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4856 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004857
4858 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004859
4860 argvar[0].v_type = VAR_STRING;
4861 argvar[0].vval.v_string = newcmd;
4862 argvar[1].v_type = VAR_UNKNOWN;
4863 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004864 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004865 {
4866 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004867 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004868 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004869
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004870 job = term_getjob(buf->b_term);
4871 ++job->jv_refcount;
4872
Bram Moolenaar0f873732019-12-05 20:28:46 +01004873 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004874 aucmd_prepbuf(&aco, buf);
4875
4876 clear_oparg(&oa);
4877 while (term_use_loop())
4878 {
4879 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4880 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004881 // If terminal_loop() returns OK we got a key that is handled
4882 // in Normal model. We don't do redrawing anyway.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004883 if (terminal_loop(TRUE) == OK)
4884 normal_cmd(&oa, TRUE);
4885 }
4886 else
4887 normal_cmd(&oa, TRUE);
4888 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004889 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004890 ch_log(NULL, "system command finished");
4891
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004892 job_unref(job);
4893
Bram Moolenaar0f873732019-12-05 20:28:46 +01004894 // restore curwin/curbuf and a few other things
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004895 aucmd_restbuf(&aco);
4896
4897 wait_return(TRUE);
4898 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4899
4900 vim_free(newcmd);
4901 return retval;
4902}
4903#endif
4904
Bram Moolenaar071d4272004-06-13 20:20:40 +00004905/*
4906 * Either execute a command by calling the shell or start a new shell
4907 */
4908 int
4909mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004910 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004911 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00004912{
4913 int x = 0;
4914 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004915 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004916
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01004917#ifdef FEAT_JOB_CHANNEL
4918 ch_log(NULL, "executing shell command: %s", cmd);
4919#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004920 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02004921 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004922 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004923 if (cmd == NULL)
4924 wcscat(szShellTitle, L" :sh");
4925 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004926 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004927 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004928
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004929 if (wn != NULL)
4930 {
4931 wcscat(szShellTitle, L" - !");
4932 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02004933 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004934 wcscat(szShellTitle, wn);
4935 SetConsoleTitleW(szShellTitle);
4936 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004937 }
4938 }
4939 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004940
4941 out_flush();
4942
4943#ifdef MCH_WRITE_DUMP
4944 if (fdDump)
4945 {
4946 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4947 fflush(fdDump);
4948 }
4949#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004950#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004951 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004952 if (
4953# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004954 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004955# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004956 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004957 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4958 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004959 char_u *cmdbase = cmd;
4960
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004961 if (cmdbase != NULL)
4962 // Skip a leading quote and (.
4963 while (*cmdbase == '"' || *cmdbase == '(')
4964 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004965
4966 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01004967 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
4968 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004969 {
4970 // Use a terminal window to run the command in.
4971 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004972 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004973 return x;
4974 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004975 }
4976#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004977
4978 /*
4979 * Catch all deadly signals while running the external command, because a
4980 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4981 */
4982 signal(SIGINT, SIG_IGN);
4983#if defined(__GNUC__) && !defined(__MINGW32__)
4984 signal(SIGKILL, SIG_IGN);
4985#else
4986 signal(SIGBREAK, SIG_IGN);
4987#endif
4988 signal(SIGILL, SIG_IGN);
4989 signal(SIGFPE, SIG_IGN);
4990 signal(SIGSEGV, SIG_IGN);
4991 signal(SIGTERM, SIG_IGN);
4992 signal(SIGABRT, SIG_IGN);
4993
4994 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004995 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00004996
4997 if (cmd == NULL)
4998 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004999 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005000 }
5001 else
5002 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005003 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005004 char_u *newcmd = NULL;
5005 char_u *cmdbase = cmd;
5006 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005007
Bram Moolenaar0f873732019-12-05 20:28:46 +01005008 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005009 if (*cmdbase == '"' )
5010 ++cmdbase;
5011 if (*cmdbase == '(')
5012 ++cmdbase;
5013
Bram Moolenaar1c465442017-03-12 20:10:05 +01005014 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005015 {
5016 STARTUPINFO si;
5017 PROCESS_INFORMATION pi;
5018 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005019 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005020 char_u *p;
5021
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005022 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005023 si.cb = sizeof(si);
5024 si.lpReserved = NULL;
5025 si.lpDesktop = NULL;
5026 si.lpTitle = NULL;
5027 si.dwFlags = 0;
5028 si.cbReserved2 = 0;
5029 si.lpReserved2 = NULL;
5030
5031 cmdbase = skipwhite(cmdbase + 5);
5032 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005033 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005034 {
5035 cmdbase = skipwhite(cmdbase + 4);
5036 si.dwFlags = STARTF_USESHOWWINDOW;
5037 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005038 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005039 }
5040 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005041 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005042 {
5043 cmdbase = skipwhite(cmdbase + 2);
5044 flags = CREATE_NO_WINDOW;
5045 si.dwFlags = STARTF_USESTDHANDLES;
5046 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005047 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005048 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005049 NULL, // Security att.
5050 OPEN_EXISTING, // Open flags
5051 FILE_ATTRIBUTE_NORMAL, // File att.
5052 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005053 si.hStdOutput = si.hStdInput;
5054 si.hStdError = si.hStdInput;
5055 }
5056
Bram Moolenaar0f873732019-12-05 20:28:46 +01005057 // Remove a trailing ", ) and )" if they have a match
5058 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005059 if (cmdbase > cmd)
5060 {
5061 p = cmdbase + STRLEN(cmdbase);
5062 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5063 *--p = NUL;
5064 if (p > cmdbase && p[-1] == ')'
5065 && (*cmd =='(' || cmd[1] == '('))
5066 *--p = NUL;
5067 }
5068
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005069 newcmd = cmdbase;
5070 unescape_shellxquote(cmdbase, p_sxe);
5071
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005072 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005073 * If creating new console, arguments are passed to the
5074 * 'cmd.exe' as-is. If it's not, arguments are not treated
5075 * correctly for current 'cmd.exe'. So unescape characters in
5076 * shellxescape except '|' for avoiding to be treated as
5077 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005078 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005079 if (flags != CREATE_NEW_CONSOLE)
5080 {
5081 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005082 char_u *cmd_shell = mch_getenv("COMSPEC");
5083
5084 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005085 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005086
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005087 subcmd = vim_strsave_escaped_ext(cmdbase,
5088 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005089 if (subcmd != NULL)
5090 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005091 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005092 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005093 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005094 if (newcmd != NULL)
5095 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005096 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005097 else
5098 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005099 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005100 }
5101 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005102
5103 /*
5104 * Now, start the command as a process, so that it doesn't
5105 * inherit our handles which causes unpleasant dangling swap
5106 * files if we exit before the spawned process
5107 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005108 if (vim_create_process((char *)newcmd, FALSE, flags,
5109 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005110 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005111 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5112 > (HINSTANCE)32)
5113 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005114 else
5115 {
5116 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005117#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005118# ifdef VIMDLL
5119 if (gui.in_use)
5120# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005121 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005122#endif
5123 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005124
5125 if (newcmd != cmdbase)
5126 vim_free(newcmd);
5127
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005128 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005129 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005130 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005131 CloseHandle(si.hStdInput);
5132 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005133 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005134 CloseHandle(pi.hThread);
5135 CloseHandle(pi.hProcess);
5136 }
5137 else
5138 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005139 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005140#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005141 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005142 (!s_dont_use_vimrun && p_stmp ?
5143 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5144 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005145#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005146 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005147
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005148 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005149 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005150 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005151#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005152 if (
5153# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005154 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005155# endif
5156 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005157 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005158 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5159 "External commands will not pause after completion.\n"
5160 "See :help win32-vimrun for more information.");
5161 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005162 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5163 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005164
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005165 if (wmsg != NULL && wtitle != NULL)
5166 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5167 vim_free(wmsg);
5168 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005169 need_vimrun_warning = FALSE;
5170 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005171 if (
5172# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005173 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005174# endif
5175 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005176 // Use vimrun to execute the command. It opens a console
5177 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005178 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005179 vimrun_path,
5180 (msg_silent != 0 || (options & SHELL_DOOUT))
5181 ? "-s " : "",
5182 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005183 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005184# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005185 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005186# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005187 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005188 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005189 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5190 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005191 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005192#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005193 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005194 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005195 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005196 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005197 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005198 }
5199 }
5200
5201 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005202 {
5203 // The shell may have messed with the mode, always set it.
5204 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005205 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005206 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005207
Bram Moolenaar0f873732019-12-05 20:28:46 +01005208 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005209 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005210#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005211 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005212 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005213#endif
5214 )
5215 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005216 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005217 msg_putchar('\n');
5218 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005219 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005220
5221 signal(SIGINT, SIG_DFL);
5222#if defined(__GNUC__) && !defined(__MINGW32__)
5223 signal(SIGKILL, SIG_DFL);
5224#else
5225 signal(SIGBREAK, SIG_DFL);
5226#endif
5227 signal(SIGILL, SIG_DFL);
5228 signal(SIGFPE, SIG_DFL);
5229 signal(SIGSEGV, SIG_DFL);
5230 signal(SIGTERM, SIG_DFL);
5231 signal(SIGABRT, SIG_DFL);
5232
5233 return x;
5234}
5235
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005236#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005237 static HANDLE
5238job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005239 char_u *fname,
5240 DWORD dwDesiredAccess,
5241 DWORD dwShareMode,
5242 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5243 DWORD dwCreationDisposition,
5244 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005245{
5246 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005247 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005248
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005249 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005250 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005251 return INVALID_HANDLE_VALUE;
5252
5253 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5254 lpSecurityAttributes, dwCreationDisposition,
5255 dwFlagsAndAttributes, NULL);
5256 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005257 return h;
5258}
5259
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005260/*
5261 * Turn the dictionary "env" into a NUL separated list that can be used as the
5262 * environment argument of vim_create_process().
5263 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005264 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005265win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005266{
5267 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005268 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005269 LPVOID base = GetEnvironmentStringsW();
5270
Bram Moolenaar0f873732019-12-05 20:28:46 +01005271 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005272 if (ga_grow(gap, 1) == FAIL)
5273 return;
5274
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005275 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005276 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005277 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005278 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005279 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005280 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005281 typval_T *item = &dict_lookup(hi)->di_tv;
5282 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005283 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005284 --todo;
5285 if (wkey != NULL && wval != NULL)
5286 {
5287 size_t n;
5288 size_t lkey = wcslen(wkey);
5289 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005290
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005291 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5292 continue;
5293 for (n = 0; n < lkey; n++)
5294 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5295 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5296 for (n = 0; n < lval; n++)
5297 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5298 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5299 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005300 vim_free(wkey);
5301 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005302 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005303 }
5304 }
5305
Bram Moolenaar355757a2020-02-10 22:06:32 +01005306 if (base)
5307 {
5308 WCHAR *p = (WCHAR*) base;
5309
5310 // for last \0
5311 if (ga_grow(gap, 1) == FAIL)
5312 return;
5313
5314 while (*p != 0 || *(p + 1) != 0)
5315 {
5316 if (ga_grow(gap, 1) == OK)
5317 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5318 p++;
5319 }
5320 FreeEnvironmentStrings(base);
5321 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5322 }
5323
Bram Moolenaar493359e2018-06-12 20:25:52 +02005324# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005325 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005326# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005327 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005328 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005329# endif
5330# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005331 char_u *version = get_vim_var_str(VV_VERSION);
5332 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005333# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005334 // size of "VIM_SERVERNAME=" and value,
5335 // plus "VIM_TERMINAL=" and value,
5336 // plus two terminating NULs
5337 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005338# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005339 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005340# endif
5341# ifdef FEAT_TERMINAL
5342 + 13 + version_len + 2
5343# endif
5344 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005345
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005346 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005347 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005348# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005349 for (n = 0; n < 15; n++)
5350 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5351 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005352 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005353 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5354 (WCHAR)servername[n];
5355 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005356# endif
5357# ifdef FEAT_TERMINAL
5358 if (is_terminal)
5359 {
5360 for (n = 0; n < 13; n++)
5361 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5362 (WCHAR)"VIM_TERMINAL="[n];
5363 for (n = 0; n < version_len; n++)
5364 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5365 (WCHAR)version[n];
5366 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5367 }
5368# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005369 }
5370 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005371# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005372}
5373
Bram Moolenaarb091f302019-01-19 14:37:00 +01005374/*
5375 * Create a pair of pipes.
5376 * Return TRUE for success, FALSE for failure.
5377 */
5378 static BOOL
5379create_pipe_pair(HANDLE handles[2])
5380{
5381 static LONG s;
5382 char name[64];
5383 SECURITY_ATTRIBUTES sa;
5384
5385 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5386 GetCurrentProcessId(),
5387 InterlockedIncrement(&s));
5388
5389 // Create named pipe. Max size of named pipe is 65535.
5390 handles[1] = CreateNamedPipe(
5391 name,
5392 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5393 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005394 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005395
5396 if (handles[1] == INVALID_HANDLE_VALUE)
5397 return FALSE;
5398
5399 sa.nLength = sizeof(sa);
5400 sa.bInheritHandle = TRUE;
5401 sa.lpSecurityDescriptor = NULL;
5402
5403 handles[0] = CreateFile(name,
5404 FILE_GENERIC_READ,
5405 FILE_SHARE_READ, &sa,
5406 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5407
5408 if (handles[0] == INVALID_HANDLE_VALUE)
5409 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005410 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005411 return FALSE;
5412 }
5413
5414 return TRUE;
5415}
5416
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005417 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005418mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005419{
5420 STARTUPINFO si;
5421 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005422 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005423 SECURITY_ATTRIBUTES saAttr;
5424 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005425 HANDLE ifd[2];
5426 HANDLE ofd[2];
5427 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005428 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005429
5430 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5431 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5432 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5433 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5434 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5435 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5436 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5437
5438 if (use_out_for_err && use_null_for_out)
5439 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005440
5441 ifd[0] = INVALID_HANDLE_VALUE;
5442 ifd[1] = INVALID_HANDLE_VALUE;
5443 ofd[0] = INVALID_HANDLE_VALUE;
5444 ofd[1] = INVALID_HANDLE_VALUE;
5445 efd[0] = INVALID_HANDLE_VALUE;
5446 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005447 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005448
Bram Moolenaar14207f42016-10-27 21:13:10 +02005449 jo = CreateJobObject(NULL, NULL);
5450 if (jo == NULL)
5451 {
5452 job->jv_status = JOB_FAILED;
5453 goto failed;
5454 }
5455
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005456 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005457 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005458
Bram Moolenaar76467df2016-02-12 19:30:26 +01005459 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005460 ZeroMemory(&si, sizeof(si));
5461 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005462 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005463 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005464
Bram Moolenaard8070362016-02-15 21:56:54 +01005465 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5466 saAttr.bInheritHandle = TRUE;
5467 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005468
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005469 if (use_file_for_in)
5470 {
5471 char_u *fname = options->jo_io_name[PART_IN];
5472
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005473 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5474 FILE_SHARE_READ | FILE_SHARE_WRITE,
5475 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5476 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005477 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005478 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005479 goto failed;
5480 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005481 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005482 else if (!use_null_for_in
5483 && (!create_pipe_pair(ifd)
5484 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005485 goto failed;
5486
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005487 if (use_file_for_out)
5488 {
5489 char_u *fname = options->jo_io_name[PART_OUT];
5490
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005491 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5492 FILE_SHARE_READ | FILE_SHARE_WRITE,
5493 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5494 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005495 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005496 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005497 goto failed;
5498 }
5499 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005500 else if (!use_null_for_out &&
5501 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005502 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005503 goto failed;
5504
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005505 if (use_file_for_err)
5506 {
5507 char_u *fname = options->jo_io_name[PART_ERR];
5508
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005509 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5510 FILE_SHARE_READ | FILE_SHARE_WRITE,
5511 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5512 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005513 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005514 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005515 goto failed;
5516 }
5517 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005518 else if (!use_out_for_err && !use_null_for_err &&
5519 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005520 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005521 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005522
Bram Moolenaard8070362016-02-15 21:56:54 +01005523 si.dwFlags |= STARTF_USESTDHANDLES;
5524 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005525 si.hStdOutput = ofd[1];
5526 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5527
5528 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5529 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005530 if (options->jo_set & JO_CHANNEL)
5531 {
5532 channel = options->jo_channel;
5533 if (channel != NULL)
5534 ++channel->ch_refcount;
5535 }
5536 else
5537 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005538 if (channel == NULL)
5539 goto failed;
5540 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005541
5542 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005543 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005544 CREATE_DEFAULT_ERROR_MODE |
5545 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005546 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005547 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005548 &si, &pi,
5549 ga.ga_data,
5550 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005551 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005552 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005553 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005554 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005555 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005556
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005557 ga_clear(&ga);
5558
Bram Moolenaar14207f42016-10-27 21:13:10 +02005559 if (!AssignProcessToJobObject(jo, pi.hProcess))
5560 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005561 // if failing, switch the way to terminate
5562 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005563 CloseHandle(jo);
5564 jo = NULL;
5565 }
5566 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005567 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005568 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005569 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005570 job->jv_status = JOB_STARTED;
5571
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005572 CloseHandle(ifd[0]);
5573 CloseHandle(ofd[1]);
5574 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005575 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005576
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005577 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005578 if (channel != NULL)
5579 {
5580 channel_set_pipes(channel,
5581 use_file_for_in || use_null_for_in
5582 ? INVALID_FD : (sock_T)ifd[1],
5583 use_file_for_out || use_null_for_out
5584 ? INVALID_FD : (sock_T)ofd[0],
5585 use_out_for_err || use_file_for_err || use_null_for_err
5586 ? INVALID_FD : (sock_T)efd[0]);
5587 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005588 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005589 return;
5590
5591failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005592 CloseHandle(ifd[0]);
5593 CloseHandle(ofd[0]);
5594 CloseHandle(efd[0]);
5595 CloseHandle(ifd[1]);
5596 CloseHandle(ofd[1]);
5597 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005598 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005599 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005600}
5601
5602 char *
5603mch_job_status(job_T *job)
5604{
5605 DWORD dwExitCode = 0;
5606
Bram Moolenaar76467df2016-02-12 19:30:26 +01005607 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5608 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005609 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005610 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005611 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005612 {
5613 ch_log(job->jv_channel, "Job ended");
5614 job->jv_status = JOB_ENDED;
5615 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005616 return "dead";
5617 }
5618 return "run";
5619}
5620
Bram Moolenaar97792de2016-10-15 18:36:49 +02005621 job_T *
5622mch_detect_ended_job(job_T *job_list)
5623{
5624 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5625 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5626 job_T *job = job_list;
5627
5628 while (job != NULL)
5629 {
5630 DWORD n;
5631 DWORD result;
5632
5633 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5634 && job != NULL; job = job->jv_next)
5635 {
5636 if (job->jv_status == JOB_STARTED)
5637 {
5638 jobHandles[n] = job->jv_proc_info.hProcess;
5639 jobArray[n] = job;
5640 ++n;
5641 }
5642 }
5643 if (n == 0)
5644 continue;
5645 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5646 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5647 {
5648 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5649
5650 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5651 return wait_job;
5652 }
5653 }
5654 return NULL;
5655}
5656
Bram Moolenaarfb630902016-10-29 14:55:00 +02005657 static BOOL
5658terminate_all(HANDLE process, int code)
5659{
5660 PROCESSENTRY32 pe;
5661 HANDLE h = INVALID_HANDLE_VALUE;
5662 DWORD pid = GetProcessId(process);
5663
5664 if (pid != 0)
5665 {
5666 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5667 if (h != INVALID_HANDLE_VALUE)
5668 {
5669 pe.dwSize = sizeof(PROCESSENTRY32);
5670 if (!Process32First(h, &pe))
5671 goto theend;
5672
5673 do
5674 {
5675 if (pe.th32ParentProcessID == pid)
5676 {
5677 HANDLE ph = OpenProcess(
5678 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5679 if (ph != NULL)
5680 {
5681 terminate_all(ph, code);
5682 CloseHandle(ph);
5683 }
5684 }
5685 } while (Process32Next(h, &pe));
5686
5687 CloseHandle(h);
5688 }
5689 }
5690
5691theend:
5692 return TerminateProcess(process, code);
5693}
5694
5695/*
5696 * Send a (deadly) signal to "job".
5697 * Return FAIL if it didn't work.
5698 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005699 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005700mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005701{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005702 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005703
Bram Moolenaar923d9262016-02-25 20:56:01 +01005704 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005705 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005706 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02005707 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005708 {
5709 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5710 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00005711 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005712 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01005713 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005714 }
5715
5716 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5717 return FAIL;
5718 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005719 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5720 job->jv_proc_info.dwProcessId)
5721 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005722 FreeConsole();
5723 return ret;
5724}
5725
5726/*
5727 * Clear the data related to "job".
5728 */
5729 void
5730mch_clear_job(job_T *job)
5731{
5732 if (job->jv_status != JOB_FAILED)
5733 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005734 if (job->jv_job_object != NULL)
5735 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005736 CloseHandle(job->jv_proc_info.hProcess);
5737 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005738}
5739#endif
5740
Bram Moolenaar071d4272004-06-13 20:20:40 +00005741
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005742#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005743
5744/*
5745 * Start termcap mode
5746 */
5747 static void
5748termcap_mode_start(void)
5749{
5750 DWORD cmodein;
5751
5752 if (g_fTermcapMode)
5753 return;
5754
Christopher Plewright1140b512022-11-12 18:46:05 +00005755 // VTP uses alternate screen buffer.
5756 // Switch to a new alternate screen buffer.
5757 if (win11_or_later && p_rs && vtp_working)
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005758 vtp_printf("\033[?1049h");
5759
Bram Moolenaar071d4272004-06-13 20:20:40 +00005760 SaveConsoleBuffer(&g_cbNonTermcap);
5761
5762 if (g_cbTermcap.IsValid)
5763 {
5764 /*
5765 * We've been in termcap mode before. Restore certain screen
5766 * characteristics, including the buffer size and the window
5767 * size. Since we will be redrawing the screen, we don't need
5768 * to restore the actual contents of the buffer.
5769 */
5770 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005771 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005772 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5773 Rows = g_cbTermcap.Info.dwSize.Y;
5774 Columns = g_cbTermcap.Info.dwSize.X;
5775 }
5776 else
5777 {
5778 /*
5779 * This is our first time entering termcap mode. Clear the console
5780 * screen buffer, and resize the buffer to match the current window
5781 * size. We will use this as the size of our editing environment.
5782 */
5783 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005784 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005785 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5786 }
5787
Bram Moolenaar071d4272004-06-13 20:20:40 +00005788 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005789
5790 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005791 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005792 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005793 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005794 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
5795 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005796 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005797 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005798 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005799 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5800 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005801 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005802 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005803
5804 redraw_later_clear();
5805 g_fTermcapMode = TRUE;
5806}
5807
5808
5809/*
5810 * End termcap mode
5811 */
5812 static void
5813termcap_mode_end(void)
5814{
5815 DWORD cmodein;
5816 ConsoleBuffer *cb;
5817 COORD coord;
5818 DWORD dwDummy;
5819
5820 if (!g_fTermcapMode)
5821 return;
5822
5823 SaveConsoleBuffer(&g_cbTermcap);
5824
5825 GetConsoleMode(g_hConIn, &cmodein);
5826 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005827 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5828 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005829
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005830# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005831 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005832# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005833 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005834# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005835 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01005836 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005837
Christopher Plewright1140b512022-11-12 18:46:05 +00005838 // VTP uses alternate screen buffer.
5839 // Switch back to main screen buffer.
5840 if (exiting && win11_or_later && p_rs && vtp_working)
5841 vtp_printf("\033[?1049l");
5842
5843 if (!USE_WT && (p_rs || exiting))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005844 {
5845 /*
5846 * Clear anything that happens to be on the current line.
5847 */
5848 coord.X = 0;
5849 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
Christopher Plewright1140b512022-11-12 18:46:05 +00005850 if (!vtp_working)
5851 FillConsoleOutputCharacter(g_hConOut, ' ',
5852 cb->Info.dwSize.X, coord, &dwDummy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005853 /*
5854 * The following is just for aesthetics. If we are exiting without
5855 * restoring the screen, then we want to have a prompt string
5856 * appear at the bottom line. However, the command interpreter
5857 * seems to always advance the cursor one line before displaying
5858 * the prompt string, which causes the screen to scroll. To
5859 * counter this, move the cursor up one line before exiting.
5860 */
5861 if (exiting && !p_rs)
5862 coord.Y--;
5863 /*
5864 * Position the cursor at the leftmost column of the desired row.
5865 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005866 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005867 }
Christopher Plewright1140b512022-11-12 18:46:05 +00005868 SetConsoleCursorInfo(g_hConOut, &g_cci);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005869 g_fTermcapMode = FALSE;
5870}
Christopher Plewright38804d62022-11-09 23:55:52 +00005871#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00005872
5873
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005874#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005875 void
5876mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005877 char_u *s UNUSED,
5878 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005879{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005880 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00005881}
5882
5883#else
5884
5885/*
5886 * clear `n' chars, starting from `coord'
5887 */
5888 static void
5889clear_chars(
5890 COORD coord,
5891 DWORD n)
5892{
Christopher Plewright38804d62022-11-09 23:55:52 +00005893 if (!vtp_working)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02005894 {
5895 DWORD dwDummy;
5896
5897 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5898 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
5899 &dwDummy);
5900 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005901 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005902 {
5903 set_console_color_rgb();
5904 gotoxy(coord.X + 1, coord.Y + 1);
5905 vtp_printf("\033[%dX", n);
5906 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005907}
5908
5909
5910/*
5911 * Clear the screen
5912 */
5913 static void
5914clear_screen(void)
5915{
5916 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005917
Christopher Plewright38804d62022-11-09 23:55:52 +00005918 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005919 clear_chars(g_coord, Rows * Columns);
5920 else
5921 {
5922 set_console_color_rgb();
5923 gotoxy(1, 1);
5924 vtp_printf("\033[2J");
5925 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005926}
5927
5928
5929/*
5930 * Clear to end of display
5931 */
5932 static void
5933clear_to_end_of_display(void)
5934{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005935 COORD save = g_coord;
5936
Christopher Plewright38804d62022-11-09 23:55:52 +00005937 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005938 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005939 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005940 else
5941 {
5942 set_console_color_rgb();
5943 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5944 vtp_printf("\033[0J");
5945
5946 gotoxy(save.X + 1, save.Y + 1);
5947 g_coord = save;
5948 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005949}
5950
5951
5952/*
5953 * Clear to end of line
5954 */
5955 static void
5956clear_to_end_of_line(void)
5957{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005958 COORD save = g_coord;
5959
Christopher Plewright38804d62022-11-09 23:55:52 +00005960 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005961 clear_chars(g_coord, Columns - g_coord.X);
5962 else
5963 {
5964 set_console_color_rgb();
5965 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5966 vtp_printf("\033[0K");
5967
5968 gotoxy(save.X + 1, save.Y + 1);
5969 g_coord = save;
5970 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005971}
5972
5973
5974/*
5975 * Scroll the scroll region up by `cLines' lines
5976 */
5977 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005978scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005979{
5980 COORD oldcoord = g_coord;
5981
5982 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5983 delete_lines(cLines);
5984
5985 g_coord = oldcoord;
5986}
5987
5988
5989/*
5990 * Set the scroll region
5991 */
5992 static void
5993set_scroll_region(
5994 unsigned left,
5995 unsigned top,
5996 unsigned right,
5997 unsigned bottom)
5998{
5999 if (left >= right
6000 || top >= bottom
6001 || right > (unsigned) Columns - 1
6002 || bottom > (unsigned) Rows - 1)
6003 return;
6004
6005 g_srScrollRegion.Left = left;
6006 g_srScrollRegion.Top = top;
6007 g_srScrollRegion.Right = right;
6008 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006009}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006010
Bram Moolenaar6982f422019-02-16 16:48:01 +01006011 static void
6012set_scroll_region_tb(
6013 unsigned top,
6014 unsigned bottom)
6015{
6016 if (top >= bottom || bottom > (unsigned)Rows - 1)
6017 return;
6018
6019 g_srScrollRegion.Top = top;
6020 g_srScrollRegion.Bottom = bottom;
6021}
6022
6023 static void
6024set_scroll_region_lr(
6025 unsigned left,
6026 unsigned right)
6027{
6028 if (left >= right || right > (unsigned)Columns - 1)
6029 return;
6030
6031 g_srScrollRegion.Left = left;
6032 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006033}
6034
6035
6036/*
6037 * Insert `cLines' lines at the current cursor position
6038 */
6039 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006040insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006041{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006042 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006043 COORD dest;
6044 CHAR_INFO fill;
6045
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006046 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6047
Bram Moolenaar6982f422019-02-16 16:48:01 +01006048 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006049 dest.Y = g_coord.Y + cLines;
6050
Bram Moolenaar6982f422019-02-16 16:48:01 +01006051 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006052 source.Top = g_coord.Y;
6053 source.Right = g_srScrollRegion.Right;
6054 source.Bottom = g_srScrollRegion.Bottom - cLines;
6055
Bram Moolenaar6982f422019-02-16 16:48:01 +01006056 clip.Left = g_srScrollRegion.Left;
6057 clip.Top = g_coord.Y;
6058 clip.Right = g_srScrollRegion.Right;
6059 clip.Bottom = g_srScrollRegion.Bottom;
6060
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006061 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006062 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006063# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006064 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006065# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006066 ))
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006067 fill.Attributes = g_attrCurrent;
6068 else
6069 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006070
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006071 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006072
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006073 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6074
Bram Moolenaar6982f422019-02-16 16:48:01 +01006075 // Here we have to deal with a win32 console flake: If the scroll
6076 // region looks like abc and we scroll c to a and fill with d we get
6077 // cbd... if we scroll block c one line at a time to a, we get cdd...
6078 // vim expects cdd consistently... So we have to deal with that
6079 // here... (this also occurs scrolling the same way in the other
6080 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006081
6082 if (source.Bottom < dest.Y)
6083 {
6084 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006085 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006086
Bram Moolenaar6982f422019-02-16 16:48:01 +01006087 coord.X = source.Left;
6088 for (i = clip.Top; i < dest.Y; ++i)
6089 {
6090 coord.Y = i;
6091 clear_chars(coord, source.Right - source.Left + 1);
6092 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006093 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006094
Christopher Plewright38804d62022-11-09 23:55:52 +00006095 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006096 {
6097 COORD coord;
6098 int i;
6099
6100 coord.X = source.Left;
6101 for (i = source.Top; i < dest.Y; ++i)
6102 {
6103 coord.Y = i;
6104 clear_chars(coord, source.Right - source.Left + 1);
6105 }
6106 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006107}
6108
6109
6110/*
6111 * Delete `cLines' lines at the current cursor position
6112 */
6113 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006114delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006115{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006116 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006117 COORD dest;
6118 CHAR_INFO fill;
6119 int nb;
6120
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006121 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6122
Bram Moolenaar6982f422019-02-16 16:48:01 +01006123 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006124 dest.Y = g_coord.Y;
6125
Bram Moolenaar6982f422019-02-16 16:48:01 +01006126 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006127 source.Top = g_coord.Y + cLines;
6128 source.Right = g_srScrollRegion.Right;
6129 source.Bottom = g_srScrollRegion.Bottom;
6130
Bram Moolenaar6982f422019-02-16 16:48:01 +01006131 clip.Left = g_srScrollRegion.Left;
6132 clip.Top = g_coord.Y;
6133 clip.Right = g_srScrollRegion.Right;
6134 clip.Bottom = g_srScrollRegion.Bottom;
6135
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006136 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006137 if (!vtp_working)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006138 fill.Attributes = g_attrCurrent;
6139 else
6140 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006141
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006142 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006143
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006144 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6145
Bram Moolenaar6982f422019-02-16 16:48:01 +01006146 // Here we have to deal with a win32 console flake; See insert_lines()
6147 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006148
6149 nb = dest.Y + (source.Bottom - source.Top) + 1;
6150
6151 if (nb < source.Top)
6152 {
6153 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006154 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006155
Bram Moolenaar6982f422019-02-16 16:48:01 +01006156 coord.X = source.Left;
6157 for (i = nb; i < clip.Bottom; ++i)
6158 {
6159 coord.Y = i;
6160 clear_chars(coord, source.Right - source.Left + 1);
6161 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006162 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006163
Christopher Plewright38804d62022-11-09 23:55:52 +00006164 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006165 {
6166 COORD coord;
6167 int i;
6168
6169 coord.X = source.Left;
6170 for (i = nb; i <= source.Bottom; ++i)
6171 {
6172 coord.Y = i;
6173 clear_chars(coord, source.Right - source.Left + 1);
6174 }
6175 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006176}
6177
6178
6179/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006180 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006181 */
6182 static void
6183gotoxy(
6184 unsigned x,
6185 unsigned y)
6186{
6187 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6188 return;
6189
Christopher Plewright38804d62022-11-09 23:55:52 +00006190 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006191# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006192 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006193# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006194 ))
Bram Moolenaar2313b612019-09-27 14:14:32 +02006195 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006196 // There are reports of double-width characters not displayed
6197 // correctly. This workaround should fix it, similar to how it's done
6198 // for VTP.
6199 g_coord.X = 0;
6200 SetConsoleCursorPosition(g_hConOut, g_coord);
6201
Bram Moolenaar2313b612019-09-27 14:14:32 +02006202 // external cursor coords are 1-based; internal are 0-based
6203 g_coord.X = x - 1;
6204 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006205 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006206 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006207 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006208 {
6209 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006210 // destruction. Insider build bug. Always enabled because it's cheap
6211 // and avoids mistakes with recognizing the build.
6212 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006213
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006214 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006215
6216 g_coord.X = x - 1;
6217 g_coord.Y = y - 1;
6218 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006219}
6220
6221
6222/*
6223 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006224 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006225 */
6226 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006227textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006228{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006229 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006230
6231 SetConsoleTextAttribute(g_hConOut, wAttr);
6232}
6233
6234
6235 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006236textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006237{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006238 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006239
Christopher Plewright38804d62022-11-09 23:55:52 +00006240 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006241 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6242 else
6243 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006244}
6245
6246
6247 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006248textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006249{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006250 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006251
Christopher Plewright38804d62022-11-09 23:55:52 +00006252 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006253 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6254 else
6255 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006256}
6257
6258
6259/*
6260 * restore the default text attribute (whatever we started with)
6261 */
6262 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006263normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006264{
Christopher Plewright38804d62022-11-09 23:55:52 +00006265 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006266 textattr(g_attrDefault);
6267 else
6268 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006269}
6270
6271
6272static WORD g_attrPreStandout = 0;
6273
6274/*
6275 * Make the text standout, by brightening it
6276 */
6277 static void
6278standout(void)
6279{
6280 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006281
Bram Moolenaar071d4272004-06-13 20:20:40 +00006282 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6283}
6284
6285
6286/*
6287 * Turn off standout mode
6288 */
6289 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006290standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006291{
6292 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006293 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006294
6295 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006296}
6297
6298
6299/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006300 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006301 */
6302 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006303mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006304{
6305 char_u *p;
6306 int n;
6307
6308 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6309 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006310 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006311# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006312 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006313# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006314 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006315 {
6316 p = T_ME + 2;
6317 n = getdigits(&p);
6318 if (*p == 'm' && n > 0)
6319 {
6320 cterm_normal_fg_color = (n & 0xf) + 1;
6321 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6322 }
6323 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006324# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006325 cterm_normal_fg_gui_color = INVALCOLOR;
6326 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006327# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006328}
6329
6330
6331/*
6332 * visual bell: flash the screen
6333 */
6334 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006335visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006336{
6337 COORD coordOrigin = {0, 0};
6338 WORD attrFlash = ~g_attrCurrent & 0xff;
6339
6340 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006341 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006342
6343 if (oldattrs == NULL)
6344 return;
6345 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6346 coordOrigin, &dwDummy);
6347 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6348 coordOrigin, &dwDummy);
6349
Bram Moolenaar0f873732019-12-05 20:28:46 +01006350 Sleep(15); // wait for 15 msec
Christopher Plewright38804d62022-11-09 23:55:52 +00006351 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006352 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006353 coordOrigin, &dwDummy);
6354 vim_free(oldattrs);
6355}
6356
6357
6358/*
6359 * Make the cursor visible or invisible
6360 */
6361 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006362cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006363{
6364 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006365
Christopher Plewright38804d62022-11-09 23:55:52 +00006366 if (vtp_working)
Bram Moolenaar2695de62020-04-17 21:13:01 +02006367 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6368
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006369# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006370 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006371# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006372}
6373
6374
6375/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006376 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006377 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006378 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006379 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006380write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006381 char_u *pchBuf,
6382 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006383{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006384 COORD coord = g_coord;
6385 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006386 DWORD n, cchwritten;
6387 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006388 static WCHAR *unicodebuf = NULL;
6389 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006390 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006391 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006392 static WCHAR *utf8spbuf = NULL;
6393 static int utf8splength;
6394 static DWORD utf8spcells;
6395 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006396
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006397 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006398 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006399 utf8usingbuf = &unicodebuf;
6400 do
6401 {
6402 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6403 unicodebuf, unibuflen);
6404 if (length && length <= unibuflen)
6405 break;
6406 vim_free(unicodebuf);
6407 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6408 unibuflen = unibuflen ? 0 : length;
6409 } while(1);
6410 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006411 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006412 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6413 {
6414 if (utf8usingbuf != &utf8spbuf)
6415 {
6416 if (utf8spbuf == NULL)
6417 {
6418 cells = mb_string2cells((char_u *)" ", 1);
6419 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6420 utf8spbuf = LALLOC_MULT(WCHAR, length);
6421 if (utf8spbuf != NULL)
6422 {
6423 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6424 utf8usingbuf = &utf8spbuf;
6425 utf8splength = length;
6426 utf8spcells = cells;
6427 }
6428 }
6429 else
6430 {
6431 utf8usingbuf = &utf8spbuf;
6432 length = utf8splength;
6433 cells = utf8spcells;
6434 }
6435 }
6436 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006437
Christopher Plewright38804d62022-11-09 23:55:52 +00006438 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006439# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006440 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006441# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006442 ))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006443 {
6444 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6445 coord, &written);
6446 // When writing fails or didn't write a single character, pretend one
6447 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006448 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006449 coord, &cchwritten) == 0
6450 || cchwritten == 0 || cchwritten == (DWORD)-1)
6451 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006452 }
6453 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006454 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006455 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006456 NULL) == 0 || cchwritten == 0)
6457 cchwritten = 1;
6458 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006459
K.Takata135e1522022-01-29 15:27:58 +00006460 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006461 {
6462 written = cbToWrite;
6463 g_coord.X += (SHORT)cells;
6464 }
6465 else
6466 {
6467 char_u *p = pchBuf;
6468 for (n = 0; n < cchwritten; n++)
6469 MB_CPTR_ADV(p);
6470 written = p - pchBuf;
6471 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006472 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006473
6474 while (g_coord.X > g_srScrollRegion.Right)
6475 {
6476 g_coord.X -= (SHORT) Columns;
6477 if (g_coord.Y < g_srScrollRegion.Bottom)
6478 g_coord.Y++;
6479 }
6480
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006481 // Cursor under VTP is always in the correct position, no need to reset.
Christopher Plewright38804d62022-11-09 23:55:52 +00006482 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006483# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006484 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006485# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006486 ))
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006487 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006488
6489 return written;
6490}
6491
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006492 static char_u *
6493get_seq(
6494 int *args,
6495 int *count,
6496 char_u *head)
6497{
6498 int argc;
6499 char_u *p;
6500
6501 if (head == NULL || *head != '\033')
6502 return NULL;
6503
6504 argc = 0;
6505 p = head;
6506 ++p;
6507 do
6508 {
6509 ++p;
6510 args[argc] = getdigits(&p);
6511 argc += (argc < 15) ? 1 : 0;
6512 } while (*p == ';');
6513 *count = argc;
6514
6515 return p;
6516}
6517
6518 static char_u *
6519get_sgr(
6520 int *args,
6521 int *count,
6522 char_u *head)
6523{
6524 char_u *p = get_seq(args, count, head);
6525
6526 return (p && *p == 'm') ? ++p : NULL;
6527}
6528
6529/*
6530 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6531 */
6532 static char_u *
6533sgrn2(
6534 char_u *head,
6535 int n)
6536{
6537 int argc;
6538 int args[16];
6539 char_u *p = get_sgr(args, &argc, head);
6540
6541 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6542}
6543
6544/*
6545 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6546 */
6547 static char_u *
6548sgrnc(
6549 char_u *head,
6550 int n)
6551{
6552 int argc;
6553 int args[16];
6554 char_u *p = get_sgr(args, &argc, head);
6555
6556 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6557 ? p : NULL;
6558}
6559
6560 static char_u *
6561skipblank(char_u *q)
6562{
6563 char_u *p = q;
6564
6565 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6566 ++p;
6567 return p;
6568}
6569
6570/*
6571 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6572 * NULL.
6573 */
6574 static char_u *
6575sgrn2c(
6576 char_u *head,
6577 int n)
6578{
6579 char_u *p = sgrn2(head, n);
6580
6581 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6582}
6583
6584/*
6585 * If there is only a newline between the sequence immediately following it,
6586 * a pointer to the character following the newline is returned.
6587 * Otherwise NULL.
6588 */
6589 static char_u *
6590sgrn2cn(
6591 char_u *head,
6592 int n)
6593{
6594 char_u *p = sgrn2(head, n);
6595
6596 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6597}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006598
6599/*
6600 * mch_write(): write the output buffer to the screen, translating ESC
6601 * sequences into calls to console output routines.
6602 */
6603 void
6604mch_write(
6605 char_u *s,
6606 int len)
6607{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006608 char_u *end = s + len;
6609
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006610# ifdef VIMDLL
6611 if (gui.in_use)
6612 return;
6613# endif
6614
Bram Moolenaar071d4272004-06-13 20:20:40 +00006615 if (!term_console)
6616 {
6617 write(1, s, (unsigned)len);
6618 return;
6619 }
6620
Bram Moolenaar0f873732019-12-05 20:28:46 +01006621 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00006622 while (len--)
6623 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006624 int prefix = -1;
6625 char_u ch;
6626
6627 // While processing a sequence, on rare occasions it seems that another
6628 // sequence may be inserted asynchronously.
6629 if (len < 0)
6630 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006631 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006632 return;
6633 }
6634
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006635 while (s + ++prefix < end)
6636 {
6637 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006638 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6639 && ch != '\a' && ch != '\033'))
6640 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006641 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006642
6643 if (p_wd)
6644 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006645 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006646 if (prefix != 0)
6647 prefix = 1;
6648 }
6649
6650 if (prefix != 0)
6651 {
6652 DWORD nWritten;
6653
6654 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006655# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006656 if (fdDump)
6657 {
6658 fputc('>', fdDump);
6659 fwrite(s, sizeof(char_u), nWritten, fdDump);
6660 fputs("<\n", fdDump);
6661 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006662# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006663 len -= (nWritten - 1);
6664 s += nWritten;
6665 }
6666 else if (s[0] == '\n')
6667 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006668 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00006669 if (g_coord.Y == g_srScrollRegion.Bottom)
6670 {
6671 scroll(1);
6672 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6673 }
6674 else
6675 {
6676 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6677 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006678# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006679 if (fdDump)
6680 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006681# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006682 s++;
6683 }
6684 else if (s[0] == '\r')
6685 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006686 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00006687 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006688# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006689 if (fdDump)
6690 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006691# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006692 s++;
6693 }
6694 else if (s[0] == '\b')
6695 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006696 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00006697 if (g_coord.X > g_srScrollRegion.Left)
6698 g_coord.X--;
6699 else if (g_coord.Y > g_srScrollRegion.Top)
6700 {
6701 g_coord.X = g_srScrollRegion.Right;
6702 g_coord.Y--;
6703 }
6704 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006705# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006706 if (fdDump)
6707 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006708# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006709 s++;
6710 }
6711 else if (s[0] == '\a')
6712 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006713 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00006714 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006715# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006716 if (fdDump)
6717 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006718# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006719 s++;
6720 }
6721 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6722 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006723# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006724 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006725# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006726 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006727 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006728 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006729
6730 switch (s[2])
6731 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006732 case '0': case '1': case '2': case '3': case '4':
6733 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006734 if (*(p = get_seq(args, &argc, s)) != 'm')
6735 goto notsgr;
6736
6737 p = s;
6738
6739 // Handling frequent optional sequences. Output to the screen
6740 // takes too long, so do not output as much as possible.
6741
6742 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
6743 // resetFG,FG,BG are omitted.
6744 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006745 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006746 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
6747 len = len + 1 - (int)(p - s);
6748 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006749 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006750 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006751
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006752 // If FG,BG,BG,FG of SGR are connected, the first FG can be
6753 // omitted.
6754 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
6755 p = sp;
6756
6757 // If FG,BG,FG,BG of SGR are connected, the first FG can be
6758 // omitted.
6759 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
6760 p = sp;
6761
6762 // If BG,BG of SGR are connected, the first BG can be omitted.
6763 if (sgrn2((sp = sgrn2(p, 48)), 48))
6764 p = sp;
6765
6766 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01006767 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006768 if (sgrn2((sp = sgrnc(p, 39)), 38))
6769 p = sp;
6770
6771 p = get_seq(args, &argc, p);
6772
6773notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006774 arg1 = args[0];
6775 arg2 = args[1];
6776 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006777 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006778 if (argc == 1 && args[0] == 0)
6779 normvideo();
6780 else if (argc == 1)
6781 {
Christopher Plewright38804d62022-11-09 23:55:52 +00006782 if (vtp_working
6783# ifdef FEAT_TERMGUICOLORS
6784 && (p_tgc || t_colors >= 256)
6785# endif
6786 )
6787 textcolor((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006788 else
Christopher Plewright38804d62022-11-09 23:55:52 +00006789 textattr((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006790 }
Christopher Plewright38804d62022-11-09 23:55:52 +00006791 else if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006792 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006793 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006794 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006795 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006796 gotoxy(arg2, arg1);
6797 }
6798 else if (argc == 2 && *p == 'r')
6799 {
6800 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6801 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006802 else if (argc == 2 && *p == 'R')
6803 {
6804 set_scroll_region_tb(arg1, arg2);
6805 }
6806 else if (argc == 2 && *p == 'V')
6807 {
6808 set_scroll_region_lr(arg1, arg2);
6809 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006810 else if (argc == 1 && *p == 'A')
6811 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006812 gotoxy(g_coord.X + 1,
6813 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6814 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006815 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006816 {
6817 textbackground((WORD) arg1);
6818 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006819 else if (argc == 1 && *p == 'C')
6820 {
6821 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6822 g_coord.Y + 1);
6823 }
6824 else if (argc == 1 && *p == 'f')
6825 {
6826 textcolor((WORD) arg1);
6827 }
6828 else if (argc == 1 && *p == 'H')
6829 {
6830 gotoxy(1, arg1);
6831 }
6832 else if (argc == 1 && *p == 'L')
6833 {
6834 insert_lines(arg1);
6835 }
6836 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006837 {
6838 delete_lines(arg1);
6839 }
6840
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006841 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006842 s = p + 1;
6843 break;
6844
Bram Moolenaar071d4272004-06-13 20:20:40 +00006845 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006846 gotoxy(g_coord.X + 1,
6847 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6848 goto got3;
6849
6850 case 'B':
6851 visual_bell();
6852 goto got3;
6853
6854 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006855 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6856 g_coord.Y + 1);
6857 goto got3;
6858
6859 case 'E':
6860 termcap_mode_end();
6861 goto got3;
6862
6863 case 'F':
6864 standout();
6865 goto got3;
6866
6867 case 'f':
6868 standend();
6869 goto got3;
6870
6871 case 'H':
6872 gotoxy(1, 1);
6873 goto got3;
6874
6875 case 'j':
6876 clear_to_end_of_display();
6877 goto got3;
6878
6879 case 'J':
6880 clear_screen();
6881 goto got3;
6882
6883 case 'K':
6884 clear_to_end_of_line();
6885 goto got3;
6886
6887 case 'L':
6888 insert_lines(1);
6889 goto got3;
6890
6891 case 'M':
6892 delete_lines(1);
6893 goto got3;
6894
6895 case 'S':
6896 termcap_mode_start();
6897 goto got3;
6898
6899 case 'V':
6900 cursor_visible(TRUE);
6901 goto got3;
6902
6903 case 'v':
6904 cursor_visible(FALSE);
6905 goto got3;
6906
6907 got3:
6908 s += 3;
6909 len -= 2;
6910 }
6911
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006912# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006913 if (fdDump)
6914 {
6915 fputs("ESC | ", fdDump);
6916 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6917 fputc('\n', fdDump);
6918 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006919# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006920 }
K.Takatadf5320c2022-09-01 13:20:16 +01006921 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
6922 {
6923 int l = 2;
6924
6925 if (isdigit(s[l]))
6926 l++;
6927 if (s[l] == ' ' && s[l + 1] == 'q')
6928 {
6929 // DECSCUSR (cursor style) sequences
Christopher Plewright38804d62022-11-09 23:55:52 +00006930 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01006931 vtp_printf("%.*s", l + 2, s); // Pass through
6932 s += l + 2;
6933 len -= l + 1;
6934 }
6935 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006936 else
6937 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006938 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00006939 DWORD nWritten;
6940
6941 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006942# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006943 if (fdDump)
6944 {
6945 fputc('>', fdDump);
6946 fwrite(s, sizeof(char_u), nWritten, fdDump);
6947 fputs("<\n", fdDump);
6948 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006949# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006950
6951 len -= (nWritten - 1);
6952 s += nWritten;
6953 }
6954 }
6955
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006956# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006957 if (fdDump)
6958 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006959# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006960}
6961
Bram Moolenaar0f873732019-12-05 20:28:46 +01006962#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006963
6964
6965/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006966 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006967 */
6968 void
6969mch_delay(
6970 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02006971 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006972{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006973#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006974 Sleep((int)msec); // never wait for input
6975#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006976# ifdef VIMDLL
6977 if (gui.in_use)
6978 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006979 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006980 return;
6981 }
6982# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02006983 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006984# ifdef FEAT_MZSCHEME
6985 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6986 {
6987 int towait = p_mzq;
6988
Bram Moolenaar0f873732019-12-05 20:28:46 +01006989 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006990 while (msec > 0)
6991 {
6992 mzvim_check_threads();
6993 if (msec < towait)
6994 towait = msec;
6995 Sleep(towait);
6996 msec -= towait;
6997 }
6998 }
6999 else
7000# endif
7001 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007002 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007003 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007004#endif
7005}
7006
7007
7008/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01007009 * This version of remove is not scared by a readonly (backup) file.
7010 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007011 * Return 0 for success, -1 for failure.
7012 */
7013 int
7014mch_remove(char_u *name)
7015{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007016 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007017 int n;
7018
Bram Moolenaar203258c2016-01-17 22:15:16 +01007019 /*
7020 * On Windows, deleting a directory's symbolic link is done by
7021 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
7022 */
7023 if (mch_isdir(name) && mch_is_symbolic_link(name))
7024 return mch_rmdir(name);
7025
Bram Moolenaar12b559e2013-06-12 22:41:37 +02007026 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
7027
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007028 wn = enc_to_utf16(name, NULL);
7029 if (wn == NULL)
7030 return -1;
7031
7032 n = DeleteFileW(wn) ? 0 : -1;
7033 vim_free(wn);
7034 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007035}
7036
7037
7038/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007039 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007040 */
7041 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007042mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007043{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007044#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7045# ifdef VIMDLL
7046 if (!gui.in_use)
7047# endif
7048 if (g_fCtrlCPressed || g_fCBrkPressed)
7049 {
7050 ctrl_break_was_pressed = g_fCBrkPressed;
7051 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7052 got_int = TRUE;
7053 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007054#endif
7055}
7056
Bram Moolenaar0f873732019-12-05 20:28:46 +01007057// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007058#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007059
7060/*
7061 * How much main memory in KiB that can be used by VIM.
7062 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007063 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007064mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007065{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007066 MEMORYSTATUSEX ms;
7067
Bram Moolenaar0f873732019-12-05 20:28:46 +01007068 // Need to use GlobalMemoryStatusEx() when there is more memory than
7069 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007070 ms.dwLength = sizeof(MEMORYSTATUSEX);
7071 GlobalMemoryStatusEx(&ms);
7072 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007073 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007074 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007075 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007076 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007077 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007078 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007079 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007080 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007081 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007082 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007083 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007084}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007085
Bram Moolenaar071d4272004-06-13 20:20:40 +00007086/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007087 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00007088 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
7089 * file whose short file name is "FOO.BAR" (its long file name will
7090 * be correct: "foo.bar~"). Because a file can be accessed by
7091 * either its SFN or its LFN, "foo.bar" has effectively been
7092 * renamed to "foo.bar", which is not at all what was wanted. This
7093 * seems to happen only when renaming files with three-character
7094 * extensions by appending a suffix that does not include ".".
7095 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
7096 *
7097 * There is another problem, which isn't really a bug but isn't right either:
7098 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
7099 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
7100 * service pack 6. Doesn't seem to happen on Windows 98.
7101 *
7102 * Like rename(), returns 0 upon success, non-zero upon failure.
7103 * Should probably set errno appropriately when errors occur.
7104 */
7105 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007106mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007107{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007108 WCHAR *p;
7109 int i;
7110 WCHAR szTempFile[_MAX_PATH + 1];
7111 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007112 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007113
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007114 // No need to play tricks unless the file name contains a "~" as the
7115 // seventh character.
7116 p = wold;
7117 for (i = 0; wold[i] != NUL; ++i)
7118 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
7119 && wold[i + 1] != 0)
7120 p = wold + i + 1;
7121 if ((int)(wold + i - p) < 8 || p[6] != '~')
7122 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007123
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007124 // Get base path of new file name. Undocumented feature: If pszNewFile is
7125 // a directory, no error is returned and pszFilePart will be NULL.
7126 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007127 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007128 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007129
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007130 // Get (and create) a unique temporary file name in directory of new file
7131 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007132 return -2;
7133
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007134 // blow the temp file away
7135 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007136 return -3;
7137
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007138 // rename old file to the temp file
7139 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007140 return -4;
7141
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007142 // now create an empty file called pszOldFile; this prevents the operating
7143 // system using pszOldFile as an alias (SFN) if we're renaming within the
7144 // same directory. For example, we're editing a file called
7145 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7146 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7147 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7148 // cause all sorts of problems later in buf_write(). So, we create an
7149 // empty file called filena~1.txt and the system will have to find some
7150 // other SFN for filena~1.txt~, such as filena~2.txt
7151 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007152 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7153 return -5;
7154 if (!CloseHandle(hf))
7155 return -6;
7156
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007157 // rename the temp file to the new file
7158 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007159 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007160 // Renaming failed. Rename the file back to its old name, so that it
7161 // looks like nothing happened.
7162 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007163 return -7;
7164 }
7165
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007166 // Seems to be left around on Novell filesystems
7167 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007168
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007169 // finally, remove the empty old file
7170 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007171 return -8;
7172
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007173 return 0;
7174}
7175
7176
7177/*
7178 * Converts the filenames to UTF-16, then call mch_wrename().
7179 * Like rename(), returns 0 upon success, non-zero upon failure.
7180 */
7181 int
7182mch_rename(
7183 const char *pszOldFile,
7184 const char *pszNewFile)
7185{
7186 WCHAR *wold = NULL;
7187 WCHAR *wnew = NULL;
7188 int retval = -1;
7189
7190 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7191 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7192 if (wold != NULL && wnew != NULL)
7193 retval = mch_wrename(wold, wnew);
7194 vim_free(wold);
7195 vim_free(wnew);
7196 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007197}
7198
7199/*
7200 * Get the default shell for the current hardware platform
7201 */
7202 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007203default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007204{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007205 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007206}
7207
7208/*
7209 * mch_access() extends access() to do more detailed check on network drives.
7210 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7211 */
7212 int
7213mch_access(char *n, int p)
7214{
7215 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007216 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007217 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007218
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007219 wn = enc_to_utf16((char_u *)n, NULL);
7220 if (wn == NULL)
7221 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007222
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007223 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007224 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007225 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007226
7227 if (p & R_OK)
7228 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007229 // Read check is performed by seeing if we can do a find file on
7230 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007231 int i;
7232 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007233
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007234 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7235 TempNameW[i] = wn[i];
7236 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7237 TempNameW[i++] = '\\';
7238 TempNameW[i++] = '*';
7239 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007240
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007241 hFile = FindFirstFileW(TempNameW, &d);
7242 if (hFile == INVALID_HANDLE_VALUE)
7243 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007244 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007245 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007246 }
7247
7248 if (p & W_OK)
7249 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007250 // Trying to create a temporary file in the directory should catch
7251 // directories on read-only network shares. However, in
7252 // directories whose ACL allows writes but denies deletes will end
7253 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007254 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7255 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007256 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007257 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007258 }
7259 }
7260 else
7261 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007262 // Don't consider a file read-only if another process has opened it.
7263 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7264
Bram Moolenaar0f873732019-12-05 20:28:46 +01007265 // Trying to open the file for the required access does ACL, read-only
7266 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007267 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7268 | ((p & R_OK) ? GENERIC_READ : 0);
7269
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007270 hFile = CreateFileW(wn, access_mode, share_mode,
7271 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007272 if (hFile == INVALID_HANDLE_VALUE)
7273 goto getout;
7274 CloseHandle(hFile);
7275 }
7276
Bram Moolenaar0f873732019-12-05 20:28:46 +01007277 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007278getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007279 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007280 return retval;
7281}
7282
Bram Moolenaar071d4272004-06-13 20:20:40 +00007283/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007284 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007285 */
7286 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007287mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007288{
7289 WCHAR *wn;
7290 int f;
7291
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007292 wn = enc_to_utf16((char_u *)name, NULL);
7293 if (wn == NULL)
7294 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007295
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007296 f = _wopen(wn, flags, mode);
7297 vim_free(wn);
7298 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007299}
7300
7301/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007302 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007303 */
7304 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007305mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007306{
7307 WCHAR *wn, *wm;
7308 FILE *f = NULL;
7309
Bram Moolenaara12a1612019-01-24 16:39:02 +01007310#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007311 // Work around an annoying assertion in the Microsoft debug CRT
7312 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007313 char newMode = mode[strlen(mode) - 1];
7314 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007315
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007316 _get_fmode(&oldMode);
7317 if (newMode == 't')
7318 _set_fmode(_O_TEXT);
7319 else if (newMode == 'b')
7320 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007321#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007322 wn = enc_to_utf16((char_u *)name, NULL);
7323 wm = enc_to_utf16((char_u *)mode, NULL);
7324 if (wn != NULL && wm != NULL)
7325 f = _wfopen(wn, wm);
7326 vim_free(wn);
7327 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007328
Bram Moolenaara12a1612019-01-24 16:39:02 +01007329#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007330 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007331#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007332 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007333}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007334
Bram Moolenaar071d4272004-06-13 20:20:40 +00007335/*
7336 * SUB STREAM (aka info stream) handling:
7337 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007338 * NTFS can have sub streams for each file. The normal contents of a file is
7339 * stored in the main stream, and extra contents (author information, title and
7340 * so on) can be stored in a sub stream. After Windows 2000, the user can
7341 * access and store this information in sub streams via an explorer's property
7342 * menu item in the right click menu. This information in sub streams was lost
7343 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007344 *
7345 * Incomplete explanation:
7346 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7347 * More useful info and an example:
7348 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7349 */
7350
7351/*
7352 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7353 * and write to stream "substream" of file "to".
7354 * Errors are ignored.
7355 */
7356 static void
7357copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7358{
7359 HANDLE hTo;
7360 WCHAR *to_name;
7361
7362 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7363 wcscpy(to_name, to);
7364 wcscat(to_name, substream);
7365
7366 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7367 FILE_ATTRIBUTE_NORMAL, NULL);
7368 if (hTo != INVALID_HANDLE_VALUE)
7369 {
7370 long done;
7371 DWORD todo;
7372 DWORD readcnt, written;
7373 char buf[4096];
7374
Bram Moolenaar0f873732019-12-05 20:28:46 +01007375 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007376 for (done = 0; done < len; done += written)
7377 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007378 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007379 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7380 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007381 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7382 FALSE, FALSE, context)
7383 || readcnt != todo
7384 || !WriteFile(hTo, buf, todo, &written, NULL)
7385 || written != todo)
7386 break;
7387 }
7388 CloseHandle(hTo);
7389 }
7390
7391 free(to_name);
7392}
7393
7394/*
7395 * Copy info streams from file "from" to file "to".
7396 */
7397 static void
7398copy_infostreams(char_u *from, char_u *to)
7399{
7400 WCHAR *fromw;
7401 WCHAR *tow;
7402 HANDLE sh;
7403 WIN32_STREAM_ID sid;
7404 int headersize;
7405 WCHAR streamname[_MAX_PATH];
7406 DWORD readcount;
7407 void *context = NULL;
7408 DWORD lo, hi;
7409 int len;
7410
Bram Moolenaar0f873732019-12-05 20:28:46 +01007411 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007412 fromw = enc_to_utf16(from, NULL);
7413 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007414 if (fromw != NULL && tow != NULL)
7415 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007416 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007417 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7418 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7419 if (sh != INVALID_HANDLE_VALUE)
7420 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007421 // Use BackupRead() to find the info streams. Repeat until we
7422 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007423 for (;;)
7424 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007425 // Get the header to find the length of the stream name. If
7426 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007427 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007428 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007429 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7430 &readcount, FALSE, FALSE, &context)
7431 || readcount == 0)
7432 break;
7433
Bram Moolenaar0f873732019-12-05 20:28:46 +01007434 // We only deal with streams that have a name. The normal
7435 // file data appears to be without a name, even though docs
7436 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007437 if (sid.dwStreamNameSize > 0)
7438 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007439 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007440 if (!BackupRead(sh, (LPBYTE)streamname,
7441 sid.dwStreamNameSize,
7442 &readcount, FALSE, FALSE, &context))
7443 break;
7444
Bram Moolenaar0f873732019-12-05 20:28:46 +01007445 // Copy an info stream with a name ":anything:$DATA".
7446 // Skip "::$DATA", it has no stream name (examples suggest
7447 // it might be used for the normal file contents).
7448 // Note that BackupRead() counts bytes, but the name is in
7449 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007450 len = readcount / sizeof(WCHAR);
7451 streamname[len] = 0;
7452 if (len > 7 && wcsicmp(streamname + len - 6,
7453 L":$DATA") == 0)
7454 {
7455 streamname[len - 6] = 0;
7456 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007457 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007458 }
7459 }
7460
Bram Moolenaar0f873732019-12-05 20:28:46 +01007461 // Advance to the next stream. We might try seeking too far,
7462 // but BackupSeek() doesn't skip over stream borders, thus
7463 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007464 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007465 &lo, &hi, &context);
7466 }
7467
Bram Moolenaar0f873732019-12-05 20:28:46 +01007468 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007469 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7470
7471 CloseHandle(sh);
7472 }
7473 }
7474 vim_free(fromw);
7475 vim_free(tow);
7476}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007477
7478/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007479 * ntdll.dll definitions
7480 */
7481#define FileEaInformation 7
7482#ifndef STATUS_SUCCESS
7483# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7484#endif
7485
7486typedef struct _FILE_FULL_EA_INFORMATION_ {
7487 ULONG NextEntryOffset;
7488 UCHAR Flags;
7489 UCHAR EaNameLength;
7490 USHORT EaValueLength;
7491 CHAR EaName[1];
7492} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7493
7494typedef struct _FILE_EA_INFORMATION_ {
7495 ULONG EaSize;
7496} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7497
Paul Ollis65745772022-06-05 16:55:54 +01007498#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007499typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7500 PHANDLE FileHandle,
7501 ACCESS_MASK DesiredAccess,
7502 POBJECT_ATTRIBUTES ObjectAttributes,
7503 PIO_STATUS_BLOCK IoStatusBlock,
7504 ULONG ShareAccess,
7505 ULONG OpenOptions);
7506typedef NTSTATUS (NTAPI *PfnNtClose)(
7507 HANDLE Handle);
7508typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007509 HANDLE FileHandle,
7510 PIO_STATUS_BLOCK IoStatusBlock,
7511 PVOID Buffer,
7512 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007513typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7514 HANDLE FileHandle,
7515 PIO_STATUS_BLOCK IoStatusBlock,
7516 PVOID Buffer,
7517 ULONG Length,
7518 BOOLEAN ReturnSingleEntry,
7519 PVOID EaList,
7520 ULONG EaListLength,
7521 PULONG EaIndex,
7522 BOOLEAN RestartScan);
7523typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007524 HANDLE FileHandle,
7525 PIO_STATUS_BLOCK IoStatusBlock,
7526 PVOID FileInformation,
7527 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007528 FILE_INFORMATION_CLASS FileInformationClass);
7529typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7530 PUNICODE_STRING DestinationString,
7531 PCWSTR SourceString);
7532
7533PfnNtOpenFile pNtOpenFile = NULL;
7534PfnNtClose pNtClose = NULL;
7535PfnNtSetEaFile pNtSetEaFile = NULL;
7536PfnNtQueryEaFile pNtQueryEaFile = NULL;
7537PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7538PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01007539#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007540
7541/*
7542 * Load ntdll.dll functions.
7543 */
7544 static BOOL
7545load_ntdll(void)
7546{
7547 static int loaded = -1;
7548
7549 if (loaded == -1)
7550 {
7551 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7552 if (hNtdll != NULL)
7553 {
7554 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7555 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7556 pNtSetEaFile = (PfnNtSetEaFile)
7557 GetProcAddress(hNtdll, "NtSetEaFile");
7558 pNtQueryEaFile = (PfnNtQueryEaFile)
7559 GetProcAddress(hNtdll, "NtQueryEaFile");
7560 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7561 GetProcAddress(hNtdll, "NtQueryInformationFile");
7562 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7563 GetProcAddress(hNtdll, "RtlInitUnicodeString");
7564 }
7565 if (pNtOpenFile == NULL
7566 || pNtClose == NULL
7567 || pNtSetEaFile == NULL
7568 || pNtQueryEaFile == NULL
7569 || pNtQueryInformationFile == NULL
7570 || pRtlInitUnicodeString == NULL)
7571 loaded = FALSE;
7572 else
7573 loaded = TRUE;
7574 }
7575 return (BOOL) loaded;
7576}
7577
7578/*
7579 * Copy extended attributes (EA) from file "from" to file "to".
7580 */
7581 static void
7582copy_extattr(char_u *from, char_u *to)
7583{
7584 char_u *fromf = NULL;
7585 char_u *tof = NULL;
7586 WCHAR *fromw = NULL;
7587 WCHAR *tow = NULL;
7588 UNICODE_STRING u;
7589 HANDLE h;
7590 OBJECT_ATTRIBUTES oa;
7591 IO_STATUS_BLOCK iosb;
7592 FILE_EA_INFORMATION_ eainfo = {0};
7593 void *ea = NULL;
7594
7595 if (!load_ntdll())
7596 return;
7597
7598 // Convert the file names to the fully qualified object names.
7599 fromf = alloc(STRLEN(from) + 5);
7600 tof = alloc(STRLEN(to) + 5);
7601 if (fromf == NULL || tof == NULL)
7602 goto theend;
7603 STRCPY(fromf, "\\??\\");
7604 STRCAT(fromf, from);
7605 STRCPY(tof, "\\??\\");
7606 STRCAT(tof, to);
7607
7608 // Convert the names to wide characters.
7609 fromw = enc_to_utf16(fromf, NULL);
7610 tow = enc_to_utf16(tof, NULL);
7611 if (fromw == NULL || tow == NULL)
7612 goto theend;
7613
7614 // Get the EA.
7615 pRtlInitUnicodeString(&u, fromw);
7616 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7617 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7618 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7619 goto theend;
7620 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7621 FileEaInformation);
7622 if (eainfo.EaSize != 0)
7623 {
7624 ea = alloc(eainfo.EaSize);
7625 if (ea != NULL)
7626 {
7627 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7628 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7629 {
7630 vim_free(ea);
7631 ea = NULL;
7632 }
7633 }
7634 }
7635 pNtClose(h);
7636
7637 // Set the EA.
7638 if (ea != NULL)
7639 {
7640 pRtlInitUnicodeString(&u, tow);
7641 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7642 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7643 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7644 goto theend;
7645
7646 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
7647 pNtClose(h);
7648 }
7649
7650theend:
7651 vim_free(fromf);
7652 vim_free(tof);
7653 vim_free(fromw);
7654 vim_free(tow);
7655 vim_free(ea);
7656}
7657
7658/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007659 * Copy file attributes from file "from" to file "to".
7660 * For Windows NT and later we copy info streams.
7661 * Always returns zero, errors are ignored.
7662 */
7663 int
7664mch_copy_file_attribute(char_u *from, char_u *to)
7665{
Bram Moolenaar0f873732019-12-05 20:28:46 +01007666 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007667 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007668 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007669 return 0;
7670}
7671
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007672
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007673/*
K.Takatadc73b4b2021-06-08 18:32:36 +02007674 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007675 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007676static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007677static LPWSTR *ArglistW = NULL;
7678static int global_argc = 0;
7679static char **global_argv;
7680
Bram Moolenaar0f873732019-12-05 20:28:46 +01007681static int used_file_argc = 0; // last argument in global_argv[] used
7682 // for the argument list.
7683static int *used_file_indexes = NULL; // indexes in global_argv[] for
7684 // command line arguments added to
7685 // the argument list
7686static int used_file_count = 0; // nr of entries in used_file_indexes
7687static int used_file_literal = FALSE; // take file names literally
7688static int used_file_full_path = FALSE; // file name was full path
7689static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007690static int used_alist_count = 0;
7691
7692
7693/*
7694 * Get the command line arguments. Unicode version.
7695 * Returns argc. Zero when something fails.
7696 */
7697 int
7698get_cmd_argsW(char ***argvp)
7699{
7700 char **argv = NULL;
7701 int argc = 0;
7702 int i;
7703
Bram Moolenaar14993322014-09-09 12:25:33 +02007704 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007705 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7706 if (ArglistW != NULL)
7707 {
7708 argv = malloc((nArgsW + 1) * sizeof(char *));
7709 if (argv != NULL)
7710 {
7711 argc = nArgsW;
7712 argv[argc] = NULL;
7713 for (i = 0; i < argc; ++i)
7714 {
7715 int len;
7716
K.Takatadc73b4b2021-06-08 18:32:36 +02007717 // Convert each Unicode argument to UTF-8.
7718 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007719 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007720 (LPSTR *)&argv[i], &len, 0, 0);
7721 if (argv[i] == NULL)
7722 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007723 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007724 while (i > 0)
7725 free(argv[--i]);
7726 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007727 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007728 argc = 0;
7729 }
7730 }
7731 }
7732 }
7733
7734 global_argc = argc;
7735 global_argv = argv;
7736 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007737 {
7738 if (used_file_indexes != NULL)
7739 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007740 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007741 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007742
7743 if (argvp != NULL)
7744 *argvp = argv;
7745 return argc;
7746}
7747
7748 void
7749free_cmd_argsW(void)
7750{
7751 if (ArglistW != NULL)
7752 {
7753 GlobalFree(ArglistW);
7754 ArglistW = NULL;
7755 }
7756}
7757
7758/*
7759 * Remember "name" is an argument that was added to the argument list.
7760 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7761 * is called.
7762 */
7763 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007764used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007765{
7766 int i;
7767
7768 if (used_file_indexes == NULL)
7769 return;
7770 for (i = used_file_argc + 1; i < global_argc; ++i)
7771 if (STRCMP(global_argv[i], name) == 0)
7772 {
7773 used_file_argc = i;
7774 used_file_indexes[used_file_count++] = i;
7775 break;
7776 }
7777 used_file_literal = literal;
7778 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007779 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007780}
7781
7782/*
7783 * Remember the length of the argument list as it was. If it changes then we
7784 * leave it alone when 'encoding' is set.
7785 */
7786 void
7787set_alist_count(void)
7788{
7789 used_alist_count = GARGCOUNT;
7790}
7791
7792/*
7793 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02007794 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007795 * and convert them to 'encoding'.
7796 */
7797 void
7798fix_arg_enc(void)
7799{
7800 int i;
7801 int idx;
7802 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007803 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007804
Bram Moolenaar0f873732019-12-05 20:28:46 +01007805 // Safety checks:
7806 // - if argument count differs between the wide and non-wide argument
7807 // list, something must be wrong.
7808 // - the file name arguments must have been located.
7809 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007810 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007811 || ArglistW == NULL
7812 || used_file_indexes == NULL
7813 || used_file_count == 0
7814 || used_alist_count != GARGCOUNT)
7815 return;
7816
Bram Moolenaar0f873732019-12-05 20:28:46 +01007817 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007818 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007819 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007820 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00007821 for (i = 0; i < GARGCOUNT; ++i)
7822 fnum_list[i] = GARGLIST[i].ae_fnum;
7823
Bram Moolenaar0f873732019-12-05 20:28:46 +01007824 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007825 alist_clear(&global_alist);
7826 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007827 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007828
7829 for (i = 0; i < used_file_count; ++i)
7830 {
7831 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007832 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007833 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007834 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007835 int literal = used_file_literal;
7836
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007837#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01007838 // When using diff mode may need to concatenate file name to
7839 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007840 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7841 && !mch_isdir(alist_name(&GARGLIST[0])))
7842 {
7843 char_u *r;
7844
7845 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7846 if (r != NULL)
7847 {
7848 vim_free(str);
7849 str = r;
7850 }
7851 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007852#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01007853 // Re-use the old buffer by renaming it. When not using literal
7854 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00007855 if (used_file_literal)
7856 buf_set_name(fnum_list[i], str);
7857
Bram Moolenaar0f873732019-12-05 20:28:46 +01007858 // Check backtick literal. backtick literal is already expanded in
7859 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007860 if (literal == FALSE)
7861 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007862 size_t len = STRLEN(str);
7863
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007864 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7865 literal = TRUE;
7866 }
7867 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007868 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007869 }
7870
7871 if (!used_file_literal)
7872 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007873 // Now expand wildcards in the arguments.
7874 // Temporarily add '(' and ')' to 'isfname'. These are valid
7875 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00007876 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01007877 // Also, unset wildignore to not be influenced by this option.
7878 // The arguments specified in command-line should be kept even if
7879 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00007880 // Use :legacy so that it also works when in Vim9 script.
7881 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
7882 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007883 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00007884 do_cmdline_cmd(
7885 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
7886 do_cmdline_cmd(
7887 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007888 }
7889
Bram Moolenaar0f873732019-12-05 20:28:46 +01007890 // If wildcard expansion failed, we are editing the first file of the
7891 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007892 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7893 {
7894 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00007895 if (GARGCOUNT == 1 && used_file_full_path
7896 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
7897 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007898 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007899
7900 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007901}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007902
7903 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007904mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007905{
7906 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007907 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007908
Bram Moolenaar964b3742019-05-24 18:54:09 +02007909 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007910 if (envbuf == NULL)
7911 return -1;
7912
7913 sprintf((char *)envbuf, "%s=%s", var, value);
7914
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007915 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007916
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007917 vim_free(envbuf);
7918 if (p == NULL)
7919 return -1;
7920 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007921#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007922 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007923#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007924 // Unlike Un*x systems, we can free the string for _wputenv().
7925 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007926
7927 return 0;
7928}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007929
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007930/*
7931 * Support for 256 colors and 24-bit colors was added in Windows 10
7932 * version 1703 (Creators update).
7933 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007934#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7935
7936/*
7937 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02007938 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007939 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007940#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007941
7942/*
7943 * ConPTY differences between versions, need different logic.
7944 * version 1903 (May 2019 update).
7945 */
7946#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
7947
7948/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007949 * version 1909 (November 2019 update).
7950 */
7951#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
7952
7953/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007954 * Stay ahead of the next update, and when it's done, fix this.
7955 * version ? (2020 update, temporarily use the build number of insider preview)
7956 */
7957#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
7958
7959/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02007960 * Confirm until this version. Also the logic changes.
7961 * insider preview.
7962 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02007963#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007964
7965/*
7966 * Not stable now.
7967 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007968#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Christopher Plewright1140b512022-11-12 18:46:05 +00007969// Notes:
7970// Win 10 22H2 Final is build 19045, it's conpty is widely used.
7971// Strangely, 19045 is newer but is a lower build number than the 2020 insider
7972// preview which had a build 19587. And, not sure how stable that was?
7973// Win Server 2022 (May 10, 2022) is build 20348, its conpty is widely used.
7974// Win 11 starts from build 22000, even though the major version says 10!
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007975
7976 static void
7977vtp_flag_init(void)
7978{
7979 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007980#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007981 DWORD mode;
7982 HANDLE out;
7983
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007984# ifdef VIMDLL
7985 if (!gui.in_use)
7986# endif
7987 {
7988 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007989
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007990 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7991 GetConsoleMode(out, &mode);
7992 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7993 if (SetConsoleMode(out, mode) == 0)
7994 vtp_working = 0;
7995 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007996#endif
7997
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007998 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007999 conpty_working = 1;
8000 if (ver >= CONPTY_STABLE_BUILD)
8001 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008002
Bram Moolenaar57da6982019-09-13 22:30:11 +02008003 if (ver <= CONPTY_INSIDER_BUILD)
8004 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008005 if (ver <= CONPTY_1909_BUILD)
8006 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02008007 if (ver <= CONPTY_1903_BUILD)
8008 conpty_type = 2;
8009 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
8010 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008011
8012 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
8013 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008014}
8015
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008016#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008017
8018 static void
8019vtp_init(void)
8020{
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008021# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00008022 if (!vtp_working)
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008023 {
Christopher Plewright38804d62022-11-09 23:55:52 +00008024 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8025 csbi.cbSize = sizeof(csbi);
8026 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8027 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
8028 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
8029 store_console_bg_rgb = save_console_bg_rgb;
8030 store_console_fg_rgb = save_console_fg_rgb;
8031
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008032 COLORREF bg;
8033 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
8034 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8035 default_console_color_bg = bg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008036
8037 COLORREF fg;
8038 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
8039 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8040 default_console_color_fg = fg;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008041 }
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008042# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008043
8044 set_console_color_rgb();
8045}
8046
8047 static void
8048vtp_exit(void)
8049{
Bram Moolenaardf543822020-01-30 11:53:59 +01008050 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008051}
8052
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008053 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008054vtp_printf(
8055 char *format,
8056 ...)
8057{
8058 char_u buf[100];
8059 va_list list;
8060 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008061 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008062
8063 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008064 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008065 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008066 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008067 return (int)result;
8068}
8069
8070 static void
8071vtp_sgr_bulk(
8072 int arg)
8073{
8074 int args[1];
8075
8076 args[0] = arg;
8077 vtp_sgr_bulks(1, args);
8078}
8079
K.Takata6e1d31e2022-02-03 13:05:32 +00008080# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008081 if ((*p-- = "0123456789"[(n = x % 10)]) \
8082 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8083 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8084
K.Takata6e1d31e2022-02-03 13:05:32 +00008085# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008086 case x: \
8087 FAST256(newargs[x - 1]);
8088
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008089 static void
8090vtp_sgr_bulks(
8091 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008092 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008093{
K.Takata6e1d31e2022-02-03 13:05:32 +00008094# define MAXSGR 16
8095# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008096 char_u buf[SGRBUFSIZE];
8097 char_u *p;
8098 int in, out;
8099 int newargs[16];
8100 static int sgrfgr = -1, sgrfgg, sgrfgb;
8101 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008102
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008103 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008104 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008105 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008106 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008107 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008108 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008109
8110 in = out = 0;
8111 while (in < argc)
8112 {
8113 int s = args[in];
8114 int copylen = 1;
8115
8116 if (s == 38)
8117 {
8118 if (argc - in >= 5 && args[in + 1] == 2)
8119 {
8120 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8121 && sgrfgb == args[in + 4])
8122 {
8123 in += 5;
8124 copylen = 0;
8125 }
8126 else
8127 {
8128 sgrfgr = args[in + 2];
8129 sgrfgg = args[in + 3];
8130 sgrfgb = args[in + 4];
8131 copylen = 5;
8132 }
8133 }
8134 else if (argc - in >= 3 && args[in + 1] == 5)
8135 {
8136 sgrfgr = -1;
8137 copylen = 3;
8138 }
8139 }
8140 else if (s == 48)
8141 {
8142 if (argc - in >= 5 && args[in + 1] == 2)
8143 {
8144 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8145 && sgrbgb == args[in + 4])
8146 {
8147 in += 5;
8148 copylen = 0;
8149 }
8150 else
8151 {
8152 sgrbgr = args[in + 2];
8153 sgrbgg = args[in + 3];
8154 sgrbgb = args[in + 4];
8155 copylen = 5;
8156 }
8157 }
8158 else if (argc - in >= 3 && args[in + 1] == 5)
8159 {
8160 sgrbgr = -1;
8161 copylen = 3;
8162 }
8163 }
8164 else if (30 <= s && s <= 39)
8165 sgrfgr = -1;
8166 else if (90 <= s && s <= 97)
8167 sgrfgr = -1;
8168 else if (40 <= s && s <= 49)
8169 sgrbgr = -1;
8170 else if (100 <= s && s <= 107)
8171 sgrbgr = -1;
8172 else if (s == 0)
8173 sgrfgr = sgrbgr = -1;
8174
8175 while (copylen--)
8176 newargs[out++] = args[in++];
8177 }
8178
8179 p = &buf[sizeof(buf) - 1];
8180 *p-- = 'm';
8181
8182 switch (out)
8183 {
8184 int n, m;
8185 DWORD r;
8186
8187 FAST256CASE(16);
8188 *p-- = ';';
8189 FAST256CASE(15);
8190 *p-- = ';';
8191 FAST256CASE(14);
8192 *p-- = ';';
8193 FAST256CASE(13);
8194 *p-- = ';';
8195 FAST256CASE(12);
8196 *p-- = ';';
8197 FAST256CASE(11);
8198 *p-- = ';';
8199 FAST256CASE(10);
8200 *p-- = ';';
8201 FAST256CASE(9);
8202 *p-- = ';';
8203 FAST256CASE(8);
8204 *p-- = ';';
8205 FAST256CASE(7);
8206 *p-- = ';';
8207 FAST256CASE(6);
8208 *p-- = ';';
8209 FAST256CASE(5);
8210 *p-- = ';';
8211 FAST256CASE(4);
8212 *p-- = ';';
8213 FAST256CASE(3);
8214 *p-- = ';';
8215 FAST256CASE(2);
8216 *p-- = ';';
8217 FAST256CASE(1);
8218 *p-- = '[';
8219 *p = '\033';
8220 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8221 default:
8222 break;
8223 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008224}
8225
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008226 static void
8227wt_init(void)
8228{
Christopher Plewright1140b512022-11-12 18:46:05 +00008229 wt_working = mch_getenv("WT_SESSION") != NULL;
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008230}
8231
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008232# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008233 static int
8234ctermtoxterm(
8235 int cterm)
8236{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008237 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008238
8239 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8240 return (((int)r << 16) | ((int)g << 8) | (int)b);
8241}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008242# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008243
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008244 static void
8245set_console_color_rgb(void)
8246{
8247# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008248 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008249 guicolor_T fg, bg;
8250 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008251
Christopher Plewright38804d62022-11-09 23:55:52 +00008252 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008253 return;
8254
Bram Moolenaara050b942019-12-02 21:35:31 +01008255 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8256
Christopher Plewright38804d62022-11-09 23:55:52 +00008257 if (p_tgc || t_colors >= 256)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008258 {
8259 term_fg_rgb_color(fg);
8260 term_bg_rgb_color(bg);
8261 return;
8262 }
8263
Christopher Plewright38804d62022-11-09 23:55:52 +00008264 if (!conpty_working)
8265 {
8266 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8267 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008268
Christopher Plewright38804d62022-11-09 23:55:52 +00008269 csbi.cbSize = sizeof(csbi);
8270 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008271
Christopher Plewright38804d62022-11-09 23:55:52 +00008272 csbi.cbSize = sizeof(csbi);
8273 csbi.srWindow.Right += 1;
8274 csbi.srWindow.Bottom += 1;
8275 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8276 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
8277 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8278 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
8279 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8280 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008281# endif
8282}
8283
Bram Moolenaara050b942019-12-02 21:35:31 +01008284# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8285 void
8286get_default_console_color(
8287 int *cterm_fg,
8288 int *cterm_bg,
8289 guicolor_T *gui_fg,
8290 guicolor_T *gui_bg)
8291{
8292 int id;
8293 guicolor_T guifg = INVALCOLOR;
8294 guicolor_T guibg = INVALCOLOR;
8295 int ctermfg = 0;
8296 int ctermbg = 0;
Christopher Plewright38804d62022-11-09 23:55:52 +00008297 int dummynull = 0;
Bram Moolenaara050b942019-12-02 21:35:31 +01008298
8299 id = syn_name2id((char_u *)"Normal");
8300 if (id > 0 && p_tgc)
8301 syn_id2colors(id, &guifg, &guibg);
8302 if (guifg == INVALCOLOR)
8303 {
8304 ctermfg = -1;
8305 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008306 syn_id2cterm_bg(id, &ctermfg, &dummynull);
8307 if (vtp_working)
8308 {
8309 cterm_normal_fg_gui_color = guifg =
8310 ctermfg != -1 ? ctermtoxterm(ctermfg) : INVALCOLOR;
8311 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8312 }
8313 else
8314 {
8315 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
Bram Moolenaara050b942019-12-02 21:35:31 +01008316 : default_console_color_fg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008317 cterm_normal_fg_gui_color = guifg;
8318 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8319 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008320 }
8321 if (guibg == INVALCOLOR)
8322 {
8323 ctermbg = -1;
8324 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008325 syn_id2cterm_bg(id, &dummynull, &ctermbg);
8326 if (vtp_working)
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008327 {
8328 cterm_normal_bg_gui_color = guibg =
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01008329 ctermbg != -1 ? ctermtoxterm(ctermbg) : INVALCOLOR;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008330 if (ctermbg < 0)
8331 ctermbg = 0;
8332 }
K.Takatae53a0d42022-09-05 21:45:11 +01008333 else
8334 {
8335 guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8336 : default_console_color_bg;
8337 cterm_normal_bg_gui_color = guibg;
8338 ctermbg = ctermbg < 0 ? 0 : ctermbg;
8339 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008340 }
8341
8342 *cterm_fg = ctermfg;
8343 *cterm_bg = ctermbg;
8344 *gui_fg = guifg;
8345 *gui_bg = guibg;
8346}
8347# endif
8348
Bram Moolenaardf543822020-01-30 11:53:59 +01008349/*
8350 * Set the console colors to the original colors or the last set colors.
8351 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008352 static void
8353reset_console_color_rgb(void)
8354{
8355# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008356
Christopher Plewright38804d62022-11-09 23:55:52 +00008357 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008358 return;
8359
Christopher Plewright38804d62022-11-09 23:55:52 +00008360 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8361
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008362 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008363 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008364
8365 csbi.cbSize = sizeof(csbi);
8366 csbi.srWindow.Right += 1;
8367 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008368 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8369 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008370 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008371# endif
8372}
8373
8374/*
8375 * Set the console colors to the original colors.
8376 */
8377 static void
8378restore_console_color_rgb(void)
8379{
8380# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00008381 if (vtp_working)
8382 return;
8383
K.Takata27b53be2022-09-18 12:25:49 +01008384 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008385
8386 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008387 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008388
8389 csbi.cbSize = sizeof(csbi);
8390 csbi.srWindow.Right += 1;
8391 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008392 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8393 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008394 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008395# endif
8396}
8397
8398 void
8399control_console_color_rgb(void)
8400{
Christopher Plewright38804d62022-11-09 23:55:52 +00008401 if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008402 set_console_color_rgb();
8403 else
8404 reset_console_color_rgb();
8405}
8406
8407 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008408use_vtp(void)
8409{
8410 return USE_VTP;
8411}
8412
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008413 int
8414is_term_win32(void)
8415{
8416 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8417}
8418
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008419 int
8420has_vtp_working(void)
8421{
8422 return vtp_working;
8423}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008424
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008425#endif
8426
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008427 int
8428has_conpty_working(void)
8429{
8430 return conpty_working;
8431}
8432
8433 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008434get_conpty_type(void)
8435{
8436 return conpty_type;
8437}
8438
8439 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008440is_conpty_stable(void)
8441{
8442 return conpty_stable;
8443}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008444
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008445 int
8446get_conpty_fix_type(void)
8447{
8448 return conpty_fix_type;
8449}
8450
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008451#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008452 void
8453resize_console_buf(void)
8454{
8455 CONSOLE_SCREEN_BUFFER_INFO csbi;
8456 COORD coord;
8457 SMALL_RECT newsize;
8458
8459 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8460 {
8461 coord.X = SRWIDTH(csbi.srWindow);
8462 coord.Y = SRHEIGHT(csbi.srWindow);
8463 SetConsoleScreenBufferSize(g_hConOut, coord);
8464
8465 newsize.Left = 0;
8466 newsize.Top = 0;
8467 newsize.Right = coord.X - 1;
8468 newsize.Bottom = coord.Y - 1;
8469 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8470
8471 SetConsoleScreenBufferSize(g_hConOut, coord);
8472 }
8473}
8474#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008475
8476 char *
8477GetWin32Error(void)
8478{
K.Takatad68b2fc2022-02-12 11:18:37 +00008479 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008480 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008481
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008482 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8483 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008484 if (oldmsg != NULL)
8485 LocalFree(oldmsg);
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008486 if (msg != NULL)
8487 {
8488 // remove trailing \r\n
8489 char *pcrlf = strstr(msg, "\r\n");
8490 if (pcrlf != NULL)
8491 *pcrlf = '\0';
K.Takatad68b2fc2022-02-12 11:18:37 +00008492 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008493 }
8494 return msg;
8495}
Paul Ollis65745772022-06-05 16:55:54 +01008496
8497#if defined(FEAT_RELTIME) || defined(PROTO)
8498static HANDLE timer_handle;
8499static int timer_active = FALSE;
8500
8501/*
8502 * Calls to start_timeout alternate the return value pointer between the two
8503 * entries in timeout_flags. If the previously active timeout is very close to
8504 * expiring when start_timeout() is called then a race condition means that the
8505 * set_flag() function may still be invoked after the previous timer is
8506 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8507 * timeouts.
8508 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008509static sig_atomic_t timeout_flags[2];
8510static int timeout_flag_idx = 0;
8511static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01008512
8513
8514 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01008515set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01008516{
8517 int *timeout_flag = (int *)param;
8518
8519 *timeout_flag = TRUE;
8520}
8521
8522/*
8523 * Stop any active timeout.
8524 */
8525 void
8526stop_timeout(void)
8527{
8528 if (timer_active)
8529 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01008530 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01008531 timer_active = FALSE;
8532 if (!ret && GetLastError() != ERROR_IO_PENDING)
8533 {
8534 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
8535 }
8536 }
8537 *timeout_flag = FALSE;
8538}
8539
8540/*
8541 * Start the timeout timer.
8542 *
8543 * The period is defined in milliseconds.
8544 *
8545 * The return value is a pointer to a flag that is initialised to 0. If the
8546 * timeout expires, the flag is set to 1. This will only return pointers to
8547 * static memory; i.e. any pointer returned by this function may always be
8548 * safely dereferenced.
8549 *
8550 * This function is not expected to fail, but if it does it still returns a
8551 * valid flag pointer; the flag will remain stuck at zero.
8552 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008553 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01008554start_timeout(long msec)
8555{
Paul Ollis65745772022-06-05 16:55:54 +01008556 BOOL ret;
8557
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008558 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01008559
8560 stop_timeout();
8561 ret = CreateTimerQueueTimer(
8562 &timer_handle, NULL, set_flag, timeout_flag,
8563 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
8564 if (!ret)
8565 {
8566 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
8567 }
8568 else
8569 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008570 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01008571 timer_active = TRUE;
8572 *timeout_flag = FALSE;
8573 }
8574 return timeout_flag;
8575}
8576#endif