blob: 682fdf2bcf1b4e4ba099581387cd9b8cabcb12a0 [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
12 * Used for both the console version and the Win32 GUI. A lot of code is for
Bram Moolenaar4f974752019-02-17 17:44:42 +010013 * the console version only, so there is a lot of "#ifndef FEAT_GUI_MSWIN".
Bram Moolenaar071d4272004-06-13 20:20:40 +000014 *
15 * Win32 (Windows NT and Windows 95) system-dependent routines.
16 * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17 * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18 *
19 * George V. Reilly <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
Bram Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010032
Bram Moolenaar0f873732019-12-05 20:28:46 +010033// cproto fails on missing include files
Bram Moolenaar82881492012-11-20 16:53:39 +010034#ifndef PROTO
35# include <process.h>
Bram Moolenaare7bebc42021-02-01 20:50:37 +010036# include <winternl.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010037#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000038
39#undef chdir
40#ifdef __GNUC__
41# ifndef __MINGW32__
42# include <dirent.h>
43# endif
44#else
45# include <direct.h>
46#endif
47
Bram Moolenaar82881492012-11-20 16:53:39 +010048#ifndef PROTO
Bram Moolenaar651fca82021-11-29 20:39:38 +000049# if !defined(FEAT_GUI_MSWIN)
Bram Moolenaar82881492012-11-20 16:53:39 +010050# include <shellapi.h>
51# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000052#endif
53
Bram Moolenaarfb630902016-10-29 14:55:00 +020054#ifdef FEAT_JOB_CHANNEL
55# include <tlhelp32.h>
56#endif
57
Bram Moolenaar071d4272004-06-13 20:20:40 +000058#ifdef __MINGW32__
59# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
60# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
61# endif
62# ifndef RIGHTMOST_BUTTON_PRESSED
63# define RIGHTMOST_BUTTON_PRESSED 0x0002
64# endif
65# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
66# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
67# endif
68# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
69# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
70# endif
71# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
72# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
73# endif
74
75/*
76 * EventFlags
77 */
78# ifndef MOUSE_MOVED
79# define MOUSE_MOVED 0x0001
80# endif
81# ifndef DOUBLE_CLICK
82# define DOUBLE_CLICK 0x0002
83# endif
84#endif
85
Bram Moolenaar0f873732019-12-05 20:28:46 +010086// Record all output and all keyboard & mouse input
87// #define MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +000088
89#ifdef MCH_WRITE_DUMP
90FILE* fdDump = NULL;
91#endif
92
93/*
94 * When generating prototypes for Win32 on Unix, these lines make the syntax
95 * errors disappear. They do not need to be correct.
96 */
97#ifdef PROTO
Bram Moolenaar912bc4a2019-12-01 18:58:11 +010098# define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000099typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000100typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000101typedef int ACCESS_MASK;
102typedef int BOOL;
103typedef int COLORREF;
104typedef int CONSOLE_CURSOR_INFO;
105typedef int COORD;
106typedef int DWORD;
107typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100108typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000109typedef int HDC;
110typedef int HFONT;
111typedef int HICON;
112typedef int HINSTANCE;
113typedef int HWND;
114typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200115typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000116typedef int KEY_EVENT_RECORD;
117typedef int LOGFONT;
118typedef int LPBOOL;
119typedef int LPCTSTR;
120typedef int LPDWORD;
121typedef int LPSTR;
122typedef int LPTSTR;
123typedef int LPVOID;
124typedef int MOUSE_EVENT_RECORD;
125typedef int PACL;
126typedef int PDWORD;
127typedef int PHANDLE;
128typedef int PRINTDLG;
129typedef int PSECURITY_DESCRIPTOR;
130typedef int PSID;
131typedef int SECURITY_INFORMATION;
132typedef int SHORT;
133typedef int SMALL_RECT;
134typedef int TEXTMETRIC;
135typedef int TOKEN_INFORMATION_CLASS;
136typedef int TRUSTEE;
137typedef int WORD;
138typedef int WCHAR;
139typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100140typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200141typedef int SE_OBJECT_TYPE;
142typedef int PSNSECINFO;
143typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100144typedef int STARTUPINFO;
145typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200146typedef int LPSECURITY_ATTRIBUTES;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100147# define __stdcall // empty
Bram Moolenaar071d4272004-06-13 20:20:40 +0000148#endif
149
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200150#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100151// Win32 Console handles for input and output
Bram Moolenaar071d4272004-06-13 20:20:40 +0000152static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
153static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
154
Bram Moolenaar0f873732019-12-05 20:28:46 +0100155// Win32 Screen buffer,coordinate,console I/O information
Bram Moolenaar071d4272004-06-13 20:20:40 +0000156static SMALL_RECT g_srScrollRegion;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100157static COORD g_coord; // 0-based, but external coords are 1-based
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158
Bram Moolenaar0f873732019-12-05 20:28:46 +0100159// The attribute of the screen when the editor was started
160static WORD g_attrDefault = 7; // lightgray text on black background
Bram Moolenaar071d4272004-06-13 20:20:40 +0000161static WORD g_attrCurrent;
162
Bram Moolenaar0f873732019-12-05 20:28:46 +0100163static int g_fCBrkPressed = FALSE; // set by ctrl-break interrupt
164static int g_fCtrlCPressed = FALSE; // set when ctrl-C or ctrl-break detected
165static int g_fForceExit = FALSE; // set when forcefully exiting
Bram Moolenaar071d4272004-06-13 20:20:40 +0000166
Bram Moolenaar071d4272004-06-13 20:20:40 +0000167static void scroll(unsigned cLines);
168static void set_scroll_region(unsigned left, unsigned top,
169 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100170static void set_scroll_region_tb(unsigned top, unsigned bottom);
171static void set_scroll_region_lr(unsigned left, unsigned right);
172static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000173static void delete_lines(unsigned cLines);
174static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000175static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000176static int s_cursor_visible = TRUE;
177static int did_create_conin = FALSE;
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200178#endif
179#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000180static int s_dont_use_vimrun = TRUE;
181static int need_vimrun_warning = FALSE;
182static char *vimrun_path = "vimrun ";
183#endif
184
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200185static int win32_getattrs(char_u *name);
186static int win32_setattrs(char_u *name, int attrs);
187static int win32_set_archive(char_u *name);
188
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100189static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200190static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100191static int conpty_stable = 0;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +0200192static int conpty_fix_type = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100193static void vtp_flag_init();
194
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200195#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100196static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100197static void vtp_init();
198static void vtp_exit();
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100199static void vtp_sgr_bulk(int arg);
200static void vtp_sgr_bulks(int argc, int *argv);
201
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200202static int wt_working = 0;
203static void wt_init();
204
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100205static guicolor_T save_console_bg_rgb;
206static guicolor_T save_console_fg_rgb;
Bram Moolenaardf543822020-01-30 11:53:59 +0100207static guicolor_T store_console_bg_rgb;
208static guicolor_T store_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100209
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200210static int g_color_index_bg = 0;
211static int g_color_index_fg = 7;
212
213# ifdef FEAT_TERMGUICOLORS
214static int default_console_color_bg = 0x000000; // black
215static int default_console_color_fg = 0xc0c0c0; // white
216# endif
217
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100218# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200219# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200220# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100221# else
222# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200223# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100224# endif
225
226static void set_console_color_rgb(void);
227static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100228static void restore_console_color_rgb(void);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100229#endif
230
Bram Moolenaar0f873732019-12-05 20:28:46 +0100231// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100232#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
233# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
234#endif
235
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200236#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100237static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000238#endif
239
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200240static char_u *exe_path = NULL;
241
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100242static BOOL win8_or_later = FALSE;
243
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200244#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100245// Dynamic loading for portability
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100246typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
247{
248 ULONG cbSize;
249 COORD dwSize;
250 COORD dwCursorPosition;
251 WORD wAttributes;
252 SMALL_RECT srWindow;
253 COORD dwMaximumWindowSize;
254 WORD wPopupAttributes;
255 BOOL bFullscreenSupported;
256 COLORREF ColorTable[16];
257} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
258typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
259static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
260typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
261static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
262static BOOL has_csbiex = FALSE;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100263#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100264
265/*
266 * Get version number including build number
267 */
268typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100269#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100270 (((major) << 24) | ((minor) << 16) | (build))
271
272 static DWORD
273get_build_number(void)
274{
275 OSVERSIONINFOW osver = {sizeof(OSVERSIONINFOW)};
276 HMODULE hNtdll;
277 PfnRtlGetVersion pRtlGetVersion;
278 DWORD ver = MAKE_VER(0, 0, 0);
279
280 hNtdll = GetModuleHandle("ntdll.dll");
281 if (hNtdll != NULL)
282 {
283 pRtlGetVersion =
284 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
285 pRtlGetVersion(&osver);
286 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
287 min(osver.dwMinorVersion, 255),
288 min(osver.dwBuildNumber, 32767));
289 }
290 return ver;
291}
292
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200293#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200294 static BOOL
295is_ambiwidth_event(
296 INPUT_RECORD *ir)
297{
298 return ir->EventType == KEY_EVENT
299 && ir->Event.KeyEvent.bKeyDown
300 && ir->Event.KeyEvent.wRepeatCount == 1
301 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
302 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000303 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200304 && ir->Event.KeyEvent.dwControlKeyState == 2;
305}
306
307 static void
308make_ambiwidth_event(
309 INPUT_RECORD *down,
310 INPUT_RECORD *up)
311{
312 down->Event.KeyEvent.wVirtualKeyCode = 0;
313 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000314 down->Event.KeyEvent.uChar.UnicodeChar
315 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200316 down->Event.KeyEvent.dwControlKeyState = 0;
317}
318
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100319/*
320 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100321 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100322 */
323 static BOOL
324read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100325 HANDLE hInput,
326 INPUT_RECORD *lpBuffer,
327 DWORD nLength,
328 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100329{
330 enum
331 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100332 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100333 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100334 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100335 static DWORD s_dwIndex = 0;
336 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100337 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100338 int head;
339 int tail;
340 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200341 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100342
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200343 if (nLength == -2)
344 return (s_dwMax > 0) ? TRUE : FALSE;
345
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100346 if (!win8_or_later)
347 {
348 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200349 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
350 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100351 }
352
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100353 if (s_dwMax == 0)
354 {
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200355 if (!USE_WT && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200356 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200357 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
358 if (dwEvents == 0 && nLength == -1)
359 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
360 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100361 s_dwIndex = 0;
362 s_dwMax = dwEvents;
363 if (dwEvents == 0)
364 {
365 *lpEvents = 0;
366 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100367 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100368
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200369 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
370 if (is_ambiwidth_event(&s_irCache[i]))
371 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
372
Bram Moolenaardd415a62014-02-05 14:02:27 +0100373 if (s_dwMax > 1)
374 {
375 head = 0;
376 tail = s_dwMax - 1;
377 while (head != tail)
378 {
379 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
380 && s_irCache[head + 1].EventType
381 == WINDOW_BUFFER_SIZE_EVENT)
382 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100383 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100384 for (i = head; i < tail; ++i)
385 s_irCache[i] = s_irCache[i + 1];
386 --tail;
387 continue;
388 }
389 head++;
390 }
391 s_dwMax = tail + 1;
392 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100393 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100394
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200395 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
396 {
397 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
398 {
399 s_irPseudo = s_irCache[s_dwIndex];
400 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
401 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
402 *lpBuffer = s_irPseudo;
403 *lpEvents = 1;
404 return TRUE;
405 }
406 }
407
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100408 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200409 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100410 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100411 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100412 return TRUE;
413}
414
415/*
416 * Version of PeekConsoleInput() that works with IME.
417 */
418 static BOOL
419peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100420 HANDLE hInput,
421 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200422 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100423 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100424{
K.Takata135e1522022-01-29 15:27:58 +0000425 return read_console_input(hInput, lpBuffer, (DWORD)-1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100426}
427
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100428# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200429 static DWORD
430msg_wait_for_multiple_objects(
431 DWORD nCount,
432 LPHANDLE pHandles,
433 BOOL fWaitAll,
434 DWORD dwMilliseconds,
435 DWORD dwWakeMask)
436{
K.Takata135e1522022-01-29 15:27:58 +0000437 if (read_console_input(NULL, NULL, (DWORD)-2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200438 return WAIT_OBJECT_0;
439 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
440 dwMilliseconds, dwWakeMask);
441}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100442# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200443
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100444# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200445 static DWORD
446wait_for_single_object(
447 HANDLE hHandle,
448 DWORD dwMilliseconds)
449{
K.Takata54119102022-02-03 13:33:03 +0000450 if (read_console_input(NULL, NULL, (DWORD)-2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200451 return WAIT_OBJECT_0;
452 return WaitForSingleObject(hHandle, dwMilliseconds);
453}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100454# endif
455#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200456
Bram Moolenaar071d4272004-06-13 20:20:40 +0000457 static void
458get_exe_name(void)
459{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100460 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
461 // as the maximum length that works (plus a NUL byte).
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100462#define MAX_ENV_PATH_LEN 8192
463 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200464 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000465
466 if (exe_name == NULL)
467 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100468 // store the name of the executable, may be used for $VIM
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100469 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000470 if (*temp != NUL)
471 exe_name = FullName_save((char_u *)temp, FALSE);
472 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000473
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200474 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000475 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200476 exe_path = vim_strnsave(exe_name, gettail_sep(exe_name) - exe_name);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200477 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000478 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100479 // Append our starting directory to $PATH, so that when doing
480 // "!xxd" it's found in our starting directory. Needed because
481 // SearchPath() also looks there.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200482 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100483 if (p == NULL
484 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200485 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100486 if (p == NULL || *p == NUL)
487 temp[0] = NUL;
488 else
489 {
490 STRCPY(temp, p);
491 STRCAT(temp, ";");
492 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200493 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100494 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200495 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000496 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000497 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000498}
499
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200500/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100501 * Unescape characters in "p" that appear in "escaped".
502 */
503 static void
504unescape_shellxquote(char_u *p, char_u *escaped)
505{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100506 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100507 int n;
508
509 while (*p != NUL)
510 {
511 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
512 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100513 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100514 p += n;
515 l -= n;
516 }
517}
518
519/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200520 * Load library "name".
521 */
522 HINSTANCE
523vimLoadLib(char *name)
524{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200525 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200526
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200527 // No need to load any library when registering OLE.
528 if (found_register_arg)
529 return dll;
530
Bram Moolenaar0f873732019-12-05 20:28:46 +0100531 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
532 // vimLoadLib() recursively, which causes a stack overflow.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200533 if (exe_path == NULL)
534 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200535 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200536 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200537 WCHAR old_dirw[MAXPATHL];
538
539 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
540 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100541 // Change directory to where the executable is, both to make
542 // sure we find a .dll there and to avoid looking for a .dll
543 // in the current directory.
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100544 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200545 dll = LoadLibrary(name);
546 SetCurrentDirectoryW(old_dirw);
547 return dll;
548 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200549 }
550 return dll;
551}
552
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200553#if defined(VIMDLL) || defined(PROTO)
554/*
555 * Check if the current executable file is for the GUI subsystem.
556 */
557 int
558mch_is_gui_executable(void)
559{
560 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
561 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
562 PIMAGE_NT_HEADERS pPE;
563
564 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
565 return FALSE;
566 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
567 if (pPE->Signature != IMAGE_NT_SIGNATURE)
568 return FALSE;
569 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
570 return TRUE;
571 return FALSE;
572}
573#endif
574
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000575#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
576 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100577/*
578 * Get related information about 'funcname' which is imported by 'hInst'.
579 * If 'info' is 0, return the function address.
580 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000581 * If 'info' is 2, hook the function with 'ptr', and return the original
582 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100583 */
584 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000585get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
586 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100587{
588 PBYTE pImage = (PBYTE)hInst;
589 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
590 PIMAGE_NT_HEADERS pPE;
591 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100592 PIMAGE_THUNK_DATA pIAT; // Import Address Table
593 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100594 PIMAGE_IMPORT_BY_NAME pImpName;
595
596 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
597 return NULL;
598 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
599 if (pPE->Signature != IMAGE_NT_SIGNATURE)
600 return NULL;
601 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
602 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
603 .VirtualAddress);
604 for (; pImpDesc->FirstThunk; ++pImpDesc)
605 {
606 if (!pImpDesc->OriginalFirstThunk)
607 continue;
608 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
609 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
610 for (; pIAT->u1.Function; ++pIAT, ++pINT)
611 {
612 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
613 continue;
614 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
615 + (UINT_PTR)(pINT->u1.AddressOfData));
616 if (strcmp((char *)pImpName->Name, funcname) == 0)
617 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000618 void *original;
619 DWORD old, new = PAGE_READWRITE;
620
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100621 switch (info)
622 {
623 case 0:
624 return (void *)pIAT->u1.Function;
625 case 1:
626 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000627 case 2:
628 original = (void *)pIAT->u1.Function;
629 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
630 new, &old);
631 pIAT->u1.Function = (UINT_PTR)ptr;
632 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
633 old, &new);
634 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100635 default:
636 return NULL;
637 }
638 }
639 }
640 }
641 return NULL;
642}
643
644/*
645 * Get the module handle which 'funcname' in 'hInst' is imported from.
646 */
647 HINSTANCE
648find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
649{
650 char *modulename;
651
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000652 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100653 if (modulename != NULL)
654 return GetModuleHandleA(modulename);
655 return NULL;
656}
657
658/*
659 * Get the address of 'funcname' which is imported by 'hInst' DLL.
660 */
661 void *
662get_dll_import_func(HINSTANCE hInst, const char *funcname)
663{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000664 return get_imported_func_info(hInst, funcname, 0, NULL);
665}
666
667/*
668 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
669 * and return the original function address.
670 */
671 void *
672hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
673{
674 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100675}
676#endif
677
Bram Moolenaar071d4272004-06-13 20:20:40 +0000678#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
679# ifndef GETTEXT_DLL
680# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200681# define GETTEXT_DLL_ALT1 "libintl-8.dll"
682# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000683# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100684// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000685static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200686static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000687static char *null_libintl_textdomain(const char *);
688static char *null_libintl_bindtextdomain(const char *, const char *);
689static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100690static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000691
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200692static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000693char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200694char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
695 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000696char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
697char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000698 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000699char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
700 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100701int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000702
703 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100704dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000705{
706 int i;
707 static struct
708 {
709 char *name;
710 FARPROC *ptr;
711 } libintl_entry[] =
712 {
713 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200714 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000715 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
716 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
717 {NULL, NULL}
718 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100719 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000720
Bram Moolenaar7554c542018-10-06 15:03:15 +0200721 // No need to initialize twice.
722 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000723 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200724 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100725 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100726# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100727 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200728 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100729# endif
730# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200731 if (!hLibintlDLL)
732 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100733# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100734 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000735 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200736 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000737 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200738 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000739 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200740 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000741 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200742 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000743 }
744 for (i = 0; libintl_entry[i].name != NULL
745 && libintl_entry[i].ptr != NULL; ++i)
746 {
K.Takata54119102022-02-03 13:33:03 +0000747 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000748 libintl_entry[i].name)) == NULL)
749 {
750 dyn_libintl_end();
751 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000752 {
753 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000754 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000755 verbose_leave();
756 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000757 return 0;
758 }
759 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000760
Bram Moolenaar0f873732019-12-05 20:28:46 +0100761 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000762 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000763 "bind_textdomain_codeset");
764 if (dyn_libintl_bind_textdomain_codeset == NULL)
765 dyn_libintl_bind_textdomain_codeset =
766 null_libintl_bind_textdomain_codeset;
767
Bram Moolenaar0f873732019-12-05 20:28:46 +0100768 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100769 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
770 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100771 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100772 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
773 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100774
Bram Moolenaar071d4272004-06-13 20:20:40 +0000775 return 1;
776}
777
778 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100779dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000780{
781 if (hLibintlDLL)
782 FreeLibrary(hLibintlDLL);
783 hLibintlDLL = NULL;
784 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200785 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000786 dyn_libintl_textdomain = null_libintl_textdomain;
787 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000788 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100789 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000790}
791
792 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000793null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000794{
795 return (char*)msgid;
796}
797
798 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200799null_libintl_ngettext(
800 const char *msgid,
801 const char *msgid_plural,
802 unsigned long n)
803{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200804 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200805}
806
Bram Moolenaaree695f72016-08-03 22:08:45 +0200807 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100808null_libintl_bindtextdomain(
809 const char *domainname UNUSED,
810 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000811{
812 return NULL;
813}
814
815 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100816null_libintl_bind_textdomain_codeset(
817 const char *domainname UNUSED,
818 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000819{
820 return NULL;
821}
822
823 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100824null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000825{
826 return NULL;
827}
828
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200829 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100830null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100831{
832 return 0;
833}
834
Bram Moolenaar0f873732019-12-05 20:28:46 +0100835#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000836
Bram Moolenaar0f873732019-12-05 20:28:46 +0100837// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000838
839#ifndef VER_PLATFORM_WIN32_WINDOWS
840# define VER_PLATFORM_WIN32_WINDOWS 1
841#endif
842
Bram Moolenaar071d4272004-06-13 20:20:40 +0000843#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100844# ifndef PROTO
845# include <aclapi.h>
846# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200847# ifndef PROTECTED_DACL_SECURITY_INFORMATION
848# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
849# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000850#endif
851
Bram Moolenaar27515922013-06-29 15:36:26 +0200852#ifdef HAVE_ACL
853/*
854 * Enables or disables the specified privilege.
855 */
856 static BOOL
857win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
858{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100859 BOOL bResult;
860 LUID luid;
861 HANDLE hToken;
862 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200863
864 if (!OpenProcessToken(GetCurrentProcess(),
865 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
866 return FALSE;
867
868 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
869 {
870 CloseHandle(hToken);
871 return FALSE;
872 }
873
Bram Moolenaar45500912014-07-09 20:51:07 +0200874 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200875 tokenPrivileges.Privileges[0].Luid = luid;
876 tokenPrivileges.Privileges[0].Attributes = bEnable ?
877 SE_PRIVILEGE_ENABLED : 0;
878
879 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
880 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
881
882 CloseHandle(hToken);
883
884 return bResult && GetLastError() == ERROR_SUCCESS;
885}
886#endif
887
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100888#ifdef _MSC_VER
889// Suppress the deprecation warning for using GetVersionEx().
890// It is needed for implementing "windowsversion()".
891# pragma warning(push)
892# pragma warning(disable: 4996)
893#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000894/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200895 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000896 */
897 void
898PlatformId(void)
899{
900 static int done = FALSE;
901
902 if (!done)
903 {
904 OSVERSIONINFO ovi;
905
906 ovi.dwOSVersionInfoSize = sizeof(ovi);
907 GetVersionEx(&ovi);
908
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200909#ifdef FEAT_EVAL
Bram Moolenaar0c1e3742019-12-27 13:49:24 +0100910 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
911 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200912#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100913 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
914 || ovi.dwMajorVersion > 6)
915 win8_or_later = TRUE;
916
Bram Moolenaar071d4272004-06-13 20:20:40 +0000917#ifdef HAVE_ACL
Bram Moolenaar0f873732019-12-05 20:28:46 +0100918 // Enable privilege for getting or setting SACLs.
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200919 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000920#endif
921 done = TRUE;
922 }
923}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100924#ifdef _MSC_VER
925# pragma warning(pop)
926#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000927
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200928#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000929
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100930# define SHIFT (SHIFT_PRESSED)
931# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
932# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
933# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000934
935
Bram Moolenaar0f873732019-12-05 20:28:46 +0100936// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
937// We map function keys to their ANSI terminal equivalents, as produced
938// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
939// ANSI key with a value >= '\300' is nonstandard, but provided anyway
940// so that the user can have access to all SHIFT-, CTRL-, and ALT-
941// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000942
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000943static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000944{
945 WORD wVirtKey;
946 BOOL fAnsiKey;
947 int chAlone;
948 int chShift;
949 int chCtrl;
950 int chAlt;
951} VirtKeyMap[] =
952{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200953// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000954 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
955
956 { VK_F1, TRUE, ';', 'T', '^', 'h', },
957 { VK_F2, TRUE, '<', 'U', '_', 'i', },
958 { VK_F3, TRUE, '=', 'V', '`', 'j', },
959 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
960 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
961 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
962 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
963 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
964 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
965 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200966 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
967 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000968
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200969 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
970 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
971 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
972 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
973 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
974 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
975 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
976 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
977 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
978 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100979 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000980
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200981 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000982
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100983# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200984 // Most people don't have F13-F20, but what the hell...
985 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
986 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
987 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
988 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
989 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
990 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
991 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
992 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100993# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200994 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
995 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
996 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
997 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000998
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200999 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
1000 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
1001 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
1002 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
1003 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
1004 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
1005 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
1006 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
1007 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
1008 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001009 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001010};
1011
1012
Bram Moolenaar0f873732019-12-05 20:28:46 +01001013/*
1014 * The return code indicates key code size.
1015 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001016 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001017win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001018 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001019{
1020 UINT uMods = pker->dwControlKeyState;
1021 static int s_iIsDead = 0;
1022 static WORD awAnsiCode[2];
1023 static BYTE abKeystate[256];
1024
1025
1026 if (s_iIsDead == 2)
1027 {
K.Takata972db232022-02-04 10:45:38 +00001028 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001029 s_iIsDead = 0;
1030 return 1;
1031 }
1032
K.Takata972db232022-02-04 10:45:38 +00001033 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001034 return 1;
1035
Bram Moolenaara80faa82020-04-12 19:37:17 +02001036 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001037
Bram Moolenaar0f873732019-12-05 20:28:46 +01001038 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001039 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001040
1041 if (uMods & SHIFT_PRESSED)
1042 abKeystate[VK_SHIFT] = 0x80;
1043 if (uMods & CAPSLOCK_ON)
1044 abKeystate[VK_CAPITAL] = 1;
1045
1046 if ((uMods & ALT_GR) == ALT_GR)
1047 {
1048 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1049 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1050 }
1051
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001052 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1053 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001054
1055 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001056 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001057
1058 return s_iIsDead;
1059}
1060
Bram Moolenaar071d4272004-06-13 20:20:40 +00001061static BOOL g_fJustGotFocus = FALSE;
1062
1063/*
1064 * Decode a KEY_EVENT into one or two keystrokes
1065 */
1066 static BOOL
1067decode_key_event(
1068 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001069 WCHAR *pch,
1070 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001071 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001072 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001073{
1074 int i;
1075 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1076
1077 *pch = *pch2 = NUL;
1078 g_fJustGotFocus = FALSE;
1079
Bram Moolenaar0f873732019-12-05 20:28:46 +01001080 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001081 if (!pker->bKeyDown)
1082 return FALSE;
1083
Bram Moolenaar0f873732019-12-05 20:28:46 +01001084 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001085 switch (pker->wVirtualKeyCode)
1086 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001087 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001088 case VK_SHIFT:
1089 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001090 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001091 return FALSE;
1092
1093 default:
1094 break;
1095 }
1096
Bram Moolenaar0f873732019-12-05 20:28:46 +01001097 // special cases
K.Takata972db232022-02-04 10:45:38 +00001098 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0
1099 && pker->uChar.UnicodeChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001100 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001101 // Ctrl-6 is Ctrl-^
Bram Moolenaar071d4272004-06-13 20:20:40 +00001102 if (pker->wVirtualKeyCode == '6')
1103 {
1104 *pch = Ctrl_HAT;
1105 return TRUE;
1106 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001107 // Ctrl-2 is Ctrl-@
Bram Moolenaar071d4272004-06-13 20:20:40 +00001108 else if (pker->wVirtualKeyCode == '2')
1109 {
1110 *pch = NUL;
1111 return TRUE;
1112 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001113 // Ctrl-- is Ctrl-_
Bram Moolenaar071d4272004-06-13 20:20:40 +00001114 else if (pker->wVirtualKeyCode == 0xBD)
1115 {
1116 *pch = Ctrl__;
1117 return TRUE;
1118 }
1119 }
1120
Bram Moolenaar0f873732019-12-05 20:28:46 +01001121 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001122 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1123 {
1124 *pch = K_NUL;
1125 *pch2 = '\017';
1126 return TRUE;
1127 }
1128
K.Takataeeec2542021-06-02 13:28:16 +02001129 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001130 {
1131 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1132 {
1133 if (nModifs == 0)
1134 *pch = VirtKeyMap[i].chAlone;
1135 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1136 *pch = VirtKeyMap[i].chShift;
1137 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1138 *pch = VirtKeyMap[i].chCtrl;
1139 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1140 *pch = VirtKeyMap[i].chAlt;
1141
1142 if (*pch != 0)
1143 {
1144 if (VirtKeyMap[i].fAnsiKey)
1145 {
1146 *pch2 = *pch;
1147 *pch = K_NUL;
1148 }
1149
1150 return TRUE;
1151 }
1152 }
1153 }
1154
1155 i = win32_kbd_patch_key(pker);
1156
1157 if (i < 0)
1158 *pch = NUL;
1159 else
1160 {
K.Takata972db232022-02-04 10:45:38 +00001161 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001162
1163 if (pmodifiers != NULL)
1164 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001165 // Pass on the ALT key as a modifier, but only when not combined
1166 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001167 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1168 *pmodifiers |= MOD_MASK_ALT;
1169
Bram Moolenaar0f873732019-12-05 20:28:46 +01001170 // Pass on SHIFT only for special keys, because we don't know when
1171 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001172 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1173 *pmodifiers |= MOD_MASK_SHIFT;
1174
Bram Moolenaar0f873732019-12-05 20:28:46 +01001175 // Pass on CTRL only for non-special keys, because we don't know
1176 // when it's already included with the character. And not when
1177 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001178 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1179 && *pch >= 0x20 && *pch < 0x80)
1180 *pmodifiers |= MOD_MASK_CTRL;
1181 }
1182 }
1183
1184 return (*pch != NUL);
1185}
1186
Bram Moolenaar0f873732019-12-05 20:28:46 +01001187#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001188
1189
Bram Moolenaar071d4272004-06-13 20:20:40 +00001190/*
1191 * For the GUI the mouse handling is in gui_w32.c.
1192 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001193#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001194 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001195mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001196{
1197}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001198#else
Bram Moolenaar0f873732019-12-05 20:28:46 +01001199static int g_fMouseAvail = FALSE; // mouse present
1200static int g_fMouseActive = FALSE; // mouse enabled
1201static int g_nMouseClick = -1; // mouse status
1202static int g_xMouse; // mouse x coordinate
1203static int g_yMouse; // mouse y coordinate
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001204static DWORD g_cmodein = 0; // Original console input mode
1205static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001206
1207/*
1208 * Enable or disable mouse input
1209 */
1210 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001211mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001212{
1213 DWORD cmodein;
1214
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001215# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001216 if (gui.in_use)
1217 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001218# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001219 if (!g_fMouseAvail)
1220 return;
1221
1222 g_fMouseActive = on;
1223 GetConsoleMode(g_hConIn, &cmodein);
1224
1225 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001226 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001227 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001228 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1229 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001230 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001231 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001232 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001233 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1234 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001235
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001236 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001237}
1238
Bram Moolenaar157d8132018-03-06 17:09:20 +01001239
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001240# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001241/*
1242 * Called when 'balloonevalterm' changed.
1243 */
1244 void
1245mch_bevalterm_changed(void)
1246{
1247 mch_setmouse(g_fMouseActive);
1248}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001249# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001250
Bram Moolenaar071d4272004-06-13 20:20:40 +00001251/*
1252 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1253 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1254 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1255 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1256 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1257 * and we return the mouse position in g_xMouse and g_yMouse.
1258 *
1259 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1260 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1261 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1262 *
1263 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1264 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1265 *
1266 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1267 * moves, even if it stays within the same character cell. We ignore
1268 * all MOUSE_MOVED messages if the position hasn't really changed, and
1269 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1270 * we're only interested in MOUSE_DRAG).
1271 *
1272 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1273 * 2-button mouses by pressing the left & right buttons simultaneously.
1274 * In practice, it's almost impossible to click both at the same time,
1275 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1276 * in such cases, if the user is clicking quickly.
1277 */
1278 static BOOL
1279decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001280 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001281{
1282 static int s_nOldButton = -1;
1283 static int s_nOldMouseClick = -1;
1284 static int s_xOldMouse = -1;
1285 static int s_yOldMouse = -1;
1286 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001287# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001288 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001289# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001290 static int s_cClicks = 1;
1291 static BOOL s_fReleased = TRUE;
1292 static DWORD s_dwLastClickTime = 0;
1293 static BOOL s_fNextIsMiddle = FALSE;
1294
Bram Moolenaar0f873732019-12-05 20:28:46 +01001295 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001296
1297 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1298 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1299 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1300 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1301
1302 int nButton;
1303
1304 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1305 cButtons = 2;
1306
1307 if (!g_fMouseAvail || !g_fMouseActive)
1308 {
1309 g_nMouseClick = -1;
1310 return FALSE;
1311 }
1312
Bram Moolenaar0f873732019-12-05 20:28:46 +01001313 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001314 if (g_fJustGotFocus)
1315 {
1316 g_fJustGotFocus = FALSE;
1317 return FALSE;
1318 }
1319
Bram Moolenaar0f873732019-12-05 20:28:46 +01001320 // unprocessed mouse click?
Bram Moolenaar071d4272004-06-13 20:20:40 +00001321 if (g_nMouseClick != -1)
1322 return TRUE;
1323
1324 nButton = -1;
1325 g_xMouse = pmer->dwMousePosition.X;
1326 g_yMouse = pmer->dwMousePosition.Y;
1327
1328 if (pmer->dwEventFlags == MOUSE_MOVED)
1329 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001330 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1331 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001332 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1333 return FALSE;
1334 }
1335
Bram Moolenaar0f873732019-12-05 20:28:46 +01001336 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001337 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1338 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001339 nButton = MOUSE_RELEASE;
1340
Bram Moolenaar0f873732019-12-05 20:28:46 +01001341 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001342 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001343 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001344# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001345 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001346 if (p_bevalterm)
1347 nButton = MOUSE_DRAG;
1348 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001349# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001350 return FALSE;
1351 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001352
Bram Moolenaar071d4272004-06-13 20:20:40 +00001353 s_fReleased = TRUE;
1354 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001355 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001356 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001357 // on a 2-button mouse, hold down left and right buttons
1358 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001359
1360 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1361 {
1362 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1363
Bram Moolenaar0f873732019-12-05 20:28:46 +01001364 // if either left or right button only is pressed, see if the
1365 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001366 if (dwLR == LEFT || dwLR == RIGHT)
1367 {
1368 for (;;)
1369 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001370 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001371 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1372 != WAIT_OBJECT_0)
1373 break;
1374 else
1375 {
1376 DWORD cRecords = 0;
1377 INPUT_RECORD ir;
1378 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1379
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001380 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001381
1382 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1383 || !(pmer2->dwButtonState & LEFT_RIGHT))
1384 break;
1385 else
1386 {
1387 if (pmer2->dwEventFlags != MOUSE_MOVED)
1388 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001389 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001390
1391 return decode_mouse_event(pmer2);
1392 }
1393 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1394 s_yOldMouse == pmer2->dwMousePosition.Y)
1395 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001396 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001397 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001398
Bram Moolenaar0f873732019-12-05 20:28:46 +01001399 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001400 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001401
1402 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1403 break;
1404 }
1405 else
1406 break;
1407 }
1408 }
1409 }
1410 }
1411 }
1412
1413 if (s_fNextIsMiddle)
1414 {
1415 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1416 ? MOUSE_DRAG : MOUSE_MIDDLE;
1417 s_fNextIsMiddle = FALSE;
1418 }
1419 else if (cButtons == 2 &&
1420 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1421 {
1422 nButton = MOUSE_MIDDLE;
1423
1424 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1425 {
1426 s_fNextIsMiddle = TRUE;
1427 nButton = MOUSE_RELEASE;
1428 }
1429 }
1430 else if ((pmer->dwButtonState & LEFT) == LEFT)
1431 nButton = MOUSE_LEFT;
1432 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1433 nButton = MOUSE_MIDDLE;
1434 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1435 nButton = MOUSE_RIGHT;
1436
1437 if (! s_fReleased && ! s_fNextIsMiddle
1438 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1439 return FALSE;
1440
1441 s_fReleased = s_fNextIsMiddle;
1442 }
1443
1444 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1445 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001446 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001447 if (nButton != -1 && nButton != MOUSE_RELEASE)
1448 {
1449 DWORD dwCurrentTime = GetTickCount();
1450
1451 if (s_xOldMouse != g_xMouse
1452 || s_yOldMouse != g_yMouse
1453 || s_nOldButton != nButton
1454 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001455# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001456 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001457# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001458 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1459 {
1460 s_cClicks = 1;
1461 }
1462 else if (++s_cClicks > 4)
1463 {
1464 s_cClicks = 1;
1465 }
1466
1467 s_dwLastClickTime = dwCurrentTime;
1468 }
1469 }
1470 else if (pmer->dwEventFlags == MOUSE_MOVED)
1471 {
1472 if (nButton != -1 && nButton != MOUSE_RELEASE)
1473 nButton = MOUSE_DRAG;
1474
1475 s_cClicks = 1;
1476 }
1477
1478 if (nButton == -1)
1479 return FALSE;
1480
1481 if (nButton != MOUSE_RELEASE)
1482 s_nOldButton = nButton;
1483
1484 g_nMouseClick = nButton;
1485
1486 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1487 g_nMouseClick |= MOUSE_SHIFT;
1488 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1489 g_nMouseClick |= MOUSE_CTRL;
1490 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1491 g_nMouseClick |= MOUSE_ALT;
1492
1493 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1494 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1495
Bram Moolenaar0f873732019-12-05 20:28:46 +01001496 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001497 if (s_xOldMouse == g_xMouse
1498 && s_yOldMouse == g_yMouse
1499 && s_nOldMouseClick == g_nMouseClick)
1500 {
1501 g_nMouseClick = -1;
1502 return FALSE;
1503 }
1504
1505 s_xOldMouse = g_xMouse;
1506 s_yOldMouse = g_yMouse;
1507 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001508# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001509 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001510# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001511 s_nOldMouseClick = g_nMouseClick;
1512
1513 return TRUE;
1514}
1515
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001516#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001517
1518
1519#ifdef MCH_CURSOR_SHAPE
1520/*
1521 * Set the shape of the cursor.
1522 * 'thickness' can be from 1 (thin) to 99 (block)
1523 */
1524 static void
1525mch_set_cursor_shape(int thickness)
1526{
1527 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1528 ConsoleCursorInfo.dwSize = thickness;
1529 ConsoleCursorInfo.bVisible = s_cursor_visible;
1530
1531 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1532 if (s_cursor_visible)
1533 SetConsoleCursorPosition(g_hConOut, g_coord);
1534}
1535
1536 void
1537mch_update_cursor(void)
1538{
1539 int idx;
1540 int thickness;
1541
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001542# ifdef VIMDLL
1543 if (gui.in_use)
1544 return;
1545# endif
1546
Bram Moolenaar071d4272004-06-13 20:20:40 +00001547 /*
1548 * How the cursor is drawn depends on the current mode.
1549 */
1550 idx = get_shape_idx(FALSE);
1551
1552 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001553 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00001554 else
1555 thickness = shape_table[idx].percentage;
1556 mch_set_cursor_shape(thickness);
1557}
1558#endif
1559
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001560#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001561/*
1562 * Handle FOCUS_EVENT.
1563 */
1564 static void
1565handle_focus_event(INPUT_RECORD ir)
1566{
1567 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1568 ui_focus_change((int)g_fJustGotFocus);
1569}
1570
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001571static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1572
Bram Moolenaar071d4272004-06-13 20:20:40 +00001573/*
1574 * Wait until console input from keyboard or mouse is available,
1575 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001576 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001577 * Return TRUE if something is available FALSE if not.
1578 */
1579 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001580WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001581{
1582 DWORD dwNow = 0, dwEndTime = 0;
1583 INPUT_RECORD ir;
1584 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001585 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001586# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001587 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001588# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001589
1590 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001591 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001592 dwEndTime = GetTickCount() + msec;
1593 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001594 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001595 dwEndTime = INFINITE;
1596
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001597 // We need to loop until the end of the time period, because
1598 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001599 for (;;)
1600 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001601 // Only process messages when waiting.
1602 if (msec != 0)
1603 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001604# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001605 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001606# endif
1607# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001608 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001609# endif
1610# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001611 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001612# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001613 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001614
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001615 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001616# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001617 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001618# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001619 )
1620 return TRUE;
1621
1622 if (msec > 0)
1623 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001624 // If the specified wait time has passed, return. Beware that
1625 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001626 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001627 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001628 break;
1629 }
1630 if (msec != 0)
1631 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001632 DWORD dwWaitTime = dwEndTime - dwNow;
1633
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001634 // Don't wait for more than 11 msec to avoid dropping characters,
1635 // check channel while waiting for input and handle a callback from
1636 // 'balloonexpr'.
1637 if (dwWaitTime > 11)
1638 dwWaitTime = 11;
1639
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001640# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001641 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001642 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001643# endif
1644# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001645 // When waiting very briefly don't trigger timers.
1646 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001647 {
1648 long due_time;
1649
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001650 // Trigger timers and then get the time in msec until the next
1651 // one is due. Wait up to that time.
1652 due_time = check_due_timer();
1653 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001654 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001655 // timer may have used feedkeys().
1656 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001657 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001658 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1659 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001660 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001661# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001662 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001663# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001664 // Wait for either an event on the console input or a
1665 // message in the client-server window.
1666 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1667 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001668# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001669 wait_for_single_object(g_hConIn, dwWaitTime)
1670 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001671# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001672 )
1673 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001674 }
1675
1676 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001677 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001678
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001679# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02001680 // May have to redraw if the cursor ends up in the wrong place.
1681 // Only when not peeking.
1682 if (State & CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001683 {
1684 CONSOLE_SCREEN_BUFFER_INFO csbi;
1685
1686 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1687 {
1688 if (csbi.dwCursorPosition.Y != msg_row)
1689 {
matveyte08795e2021-05-07 15:00:17 +02001690 // The screen is now messed up, must redraw the command
1691 // line and later all the windows.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001692 redraw_all_later(CLEAR);
matveyte08795e2021-05-07 15:00:17 +02001693 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001694 redrawcmd();
1695 }
1696 }
1697 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001698# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001699
1700 if (cRecords > 0)
1701 {
1702 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1703 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001704# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01001705 // Windows IME sends two '\n's with only one 'ENTER'. First:
1706 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00001707 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001708 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1709 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001710 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001711 continue;
1712 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001713# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001714 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1715 NULL, FALSE))
1716 return TRUE;
1717 }
1718
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001719 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001720
1721 if (ir.EventType == FOCUS_EVENT)
1722 handle_focus_event(ir);
1723 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001724 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001725 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1726
Bram Moolenaar36698e32019-12-11 22:57:40 +01001727 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001728 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001729 if (dwSize.X != Columns || dwSize.Y != Rows)
1730 {
1731 CONSOLE_SCREEN_BUFFER_INFO csbi;
1732 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01001733 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001734 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01001735 if (dwSize.X != Columns || dwSize.Y != Rows)
1736 {
1737 ResizeConBuf(g_hConOut, dwSize);
1738 shell_resized();
1739 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001740 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001741 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001742 else if (ir.EventType == MOUSE_EVENT
1743 && decode_mouse_event(&ir.Event.MouseEvent))
1744 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001745 }
1746 else if (msec == 0)
1747 break;
1748 }
1749
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001750# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01001751 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001752 if (input_available())
1753 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001754# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001755
Bram Moolenaar071d4272004-06-13 20:20:40 +00001756 return FALSE;
1757}
1758
Bram Moolenaar071d4272004-06-13 20:20:40 +00001759/*
1760 * return non-zero if a character is available
1761 */
1762 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001763mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001764{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001765# ifdef VIMDLL
1766 if (gui.in_use)
1767 return TRUE;
1768# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001769 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001770}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001771
1772# if defined(FEAT_TERMINAL) || defined(PROTO)
1773/*
1774 * Check for any pending input or messages.
1775 */
1776 int
1777mch_check_messages(void)
1778{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001779# ifdef VIMDLL
1780 if (gui.in_use)
1781 return TRUE;
1782# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001783 return WaitForChar(0L, TRUE);
1784}
1785# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001786
1787/*
1788 * Create the console input. Used when reading stdin doesn't work.
1789 */
1790 static void
1791create_conin(void)
1792{
1793 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1794 FILE_SHARE_READ|FILE_SHARE_WRITE,
1795 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001796 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001797 did_create_conin = TRUE;
1798}
1799
1800/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001801 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001802 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001803 static WCHAR
1804tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001805{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001806 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001807
1808 for (;;)
1809 {
1810 INPUT_RECORD ir;
1811 DWORD cRecords = 0;
1812
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001813# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001814 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001815 if (input_available())
1816 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001817 if (g_nMouseClick != -1)
1818 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001819# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001820 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001821 {
1822 if (did_create_conin)
1823 read_error_exit();
1824 create_conin();
1825 continue;
1826 }
1827
1828 if (ir.EventType == KEY_EVENT)
1829 {
1830 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1831 pmodifiers, TRUE))
1832 return ch;
1833 }
1834 else if (ir.EventType == FOCUS_EVENT)
1835 handle_focus_event(ir);
1836 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1837 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001838 else if (ir.EventType == MOUSE_EVENT)
1839 {
1840 if (decode_mouse_event(&ir.Event.MouseEvent))
1841 return 0;
1842 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001843 }
1844}
Bram Moolenaar0f873732019-12-05 20:28:46 +01001845#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001846
1847
1848/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001849 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001850 * Get one or more characters from the keyboard or the mouse.
1851 * If time == 0, do not wait for characters.
1852 * If time == n, wait a short time for characters.
1853 * If time == -1, wait forever for characters.
1854 * Returns the number of characters read into buf.
1855 */
1856 int
1857mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001858 char_u *buf UNUSED,
1859 int maxlen UNUSED,
1860 long time UNUSED,
1861 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001862{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001863#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001864
1865 int len;
1866 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001867# ifdef VIMDLL
1868// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
1869# define TYPEAHEADSPACE 6
1870# else
1871# define TYPEAHEADSPACE 0
1872# endif
1873# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001874 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001875 static int typeaheadlen = 0;
1876
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001877# ifdef VIMDLL
1878 if (gui.in_use)
1879 return 0;
1880# endif
1881
Bram Moolenaar0f873732019-12-05 20:28:46 +01001882 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001883 if (typeaheadlen > 0)
1884 goto theend;
1885
Bram Moolenaar071d4272004-06-13 20:20:40 +00001886 if (time >= 0)
1887 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001888 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00001889 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001890 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001891 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00001892 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001893 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00001894
Bram Moolenaar3918c952005-03-15 22:34:55 +00001895 /*
1896 * If there is no character available within 2 seconds (default)
1897 * write the autoscript file to disk. Or cause the CursorHold event
1898 * to be triggered.
1899 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001900 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001901 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001902 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001903 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001904 buf[0] = K_SPECIAL;
1905 buf[1] = KS_EXTRA;
1906 buf[2] = (int)KE_CURSORHOLD;
1907 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001908 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001909 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001910 }
1911 }
1912
1913 /*
1914 * Try to read as many characters as there are, until the buffer is full.
1915 */
1916
Bram Moolenaar0f873732019-12-05 20:28:46 +01001917 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001918 g_fCBrkPressed = FALSE;
1919
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001920# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001921 if (fdDump)
1922 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001923# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001924
Bram Moolenaar0f873732019-12-05 20:28:46 +01001925 // Keep looping until there is something in the typeahead buffer and more
1926 // to get and still room in the buffer (up to two bytes for a char and
1927 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001928 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001929 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001930 {
1931 if (typebuf_changed(tb_change_cnt))
1932 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001933 // "buf" may be invalid now if a client put something in the
1934 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001935 typeaheadlen = 0;
1936 break;
1937 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001938 if (g_nMouseClick != -1)
1939 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001940# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001941 if (fdDump)
1942 fprintf(fdDump, "{%02x @ %d, %d}",
1943 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001944# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001945 typeahead[typeaheadlen++] = ESC + 128;
1946 typeahead[typeaheadlen++] = 'M';
1947 typeahead[typeaheadlen++] = g_nMouseClick;
1948 typeahead[typeaheadlen++] = g_xMouse + '!';
1949 typeahead[typeaheadlen++] = g_yMouse + '!';
1950 g_nMouseClick = -1;
1951 }
1952 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001953 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001954 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001955 int modifiers = 0;
1956
1957 c = tgetch(&modifiers, &ch2);
1958
1959 if (typebuf_changed(tb_change_cnt))
1960 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001961 // "buf" may be invalid now if a client put something in the
1962 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001963 typeaheadlen = 0;
1964 break;
1965 }
1966
1967 if (c == Ctrl_C && ctrl_c_interrupts)
1968 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001969# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001970 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001971# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001972 got_int = TRUE;
1973 }
1974
Bram Moolenaar071d4272004-06-13 20:20:40 +00001975 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001976 {
1977 int n = 1;
1978
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001979 if (ch2 == NUL)
1980 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001981 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001982 char_u *p;
1983 WCHAR ch[2];
1984
1985 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01001986 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001987 {
1988 ch[1] = tgetch(&modifiers, &ch2);
1989 n++;
1990 }
1991 p = utf16_to_enc(ch, &n);
1992 if (p != NULL)
1993 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001994 for (i = 0, j = 0; i < n; i++)
1995 {
1996 typeahead[typeaheadlen + j++] = p[i];
1997# ifdef VIMDLL
1998 if (p[i] == CSI)
1999 {
2000 typeahead[typeaheadlen + j++] = KS_EXTRA;
2001 typeahead[typeaheadlen + j++] = KE_CSI;
2002 }
2003# endif
2004 }
2005 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002006 vim_free(p);
2007 }
2008 }
2009 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002010 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002011 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002012# ifdef VIMDLL
2013 if (c == CSI)
2014 {
2015 typeahead[typeaheadlen + 1] = KS_EXTRA;
2016 typeahead[typeaheadlen + 2] = KE_CSI;
2017 n = 3;
2018 }
2019# endif
2020 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002021 if (ch2 != NUL)
2022 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002023 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002024 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002025 switch (ch2)
2026 {
2027 case (WCHAR)'\324': // SHIFT+Insert
2028 case (WCHAR)'\325': // CTRL+Insert
2029 case (WCHAR)'\327': // SHIFT+Delete
2030 case (WCHAR)'\330': // CTRL+Delete
2031 typeahead[typeaheadlen + n] = (char_u)ch2;
2032 n++;
2033 break;
2034
2035 default:
2036 typeahead[typeaheadlen + n] = 3;
2037 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2038 n += 2;
2039 break;
2040 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002041 }
2042 else
2043 {
2044 typeahead[typeaheadlen + n] = 3;
2045 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2046 n += 2;
2047 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002048 }
2049
Bram Moolenaar0f873732019-12-05 20:28:46 +01002050 // Use the ALT key to set the 8th bit of the character
2051 // when it's one byte, the 8th bit isn't set yet and not
2052 // using a double-byte encoding (would become a lead
2053 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002054 if ((modifiers & MOD_MASK_ALT)
2055 && n == 1
2056 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002058 )
2059 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002060 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2061 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002062 modifiers &= ~MOD_MASK_ALT;
2063 }
2064
2065 if (modifiers != 0)
2066 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002067 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002068 mch_memmove(typeahead + typeaheadlen + 3,
2069 typeahead + typeaheadlen, n);
2070 typeahead[typeaheadlen++] = K_SPECIAL;
2071 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2072 typeahead[typeaheadlen++] = modifiers;
2073 }
2074
2075 typeaheadlen += n;
2076
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002077# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002078 if (fdDump)
2079 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002080# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002081 }
2082 }
2083 }
2084
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002085# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002086 if (fdDump)
2087 {
2088 fputs("]\n", fdDump);
2089 fflush(fdDump);
2090 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002091# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002092
Bram Moolenaar071d4272004-06-13 20:20:40 +00002093theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002094 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002095 len = 0;
2096 while (len < maxlen && typeaheadlen > 0)
2097 {
2098 buf[len++] = typeahead[0];
2099 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2100 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002101# ifdef FEAT_JOB_CHANNEL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002102 if (len > 0)
2103 {
2104 buf[len] = NUL;
2105 ch_log(NULL, "raw key input: \"%s\"", buf);
2106 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002107# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002108 return len;
2109
Bram Moolenaar0f873732019-12-05 20:28:46 +01002110#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002111 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002112#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002113}
2114
Bram Moolenaar82881492012-11-20 16:53:39 +01002115#ifndef PROTO
2116# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002117# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002118# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002119#endif
2120
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002121/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002122 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002123 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2124 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002125 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002126 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002127 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002128executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002129{
Bram Moolenaar95da1362020-05-30 18:37:55 +02002130 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01002131 {
Bram Moolenaar95da1362020-05-30 18:37:55 +02002132 if (path != NULL)
2133 *path = FullName_save((char_u *)name, FALSE);
2134 return TRUE;
2135 }
2136 return FALSE;
2137}
2138
2139/*
2140 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2141 * If "use_path" is FALSE: Return TRUE if "name" exists.
2142 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2143 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2144 * the allocated memory.
2145 */
2146 static int
2147executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2148{
2149 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2150 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2151 // UTF-8.
2152 char_u buf[_MAX_PATH * 3];
2153 size_t len = STRLEN(name);
2154 size_t tmplen;
2155 char_u *p, *e, *e2;
2156 char_u *pathbuf = NULL;
2157 char_u *pathext = NULL;
2158 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002159 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002160 int noext = FALSE;
2161 int retval = FALSE;
2162
2163 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002164 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002165
2166 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002167 shname = gettail(p_sh);
2168 if (strstr((char *)shname, "sh") != NULL &&
2169 !(strstr((char *)shname, "powershell") != NULL
2170 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002171 noext = TRUE;
2172
2173 if (use_pathext)
2174 {
2175 pathext = mch_getenv("PATHEXT");
2176 if (pathext == NULL)
2177 pathext = (char_u *)".com;.exe;.bat;.cmd";
2178
2179 if (noext == FALSE)
2180 {
2181 /*
2182 * Loop over all extensions in $PATHEXT.
2183 * Check "name" ends with extension.
2184 */
2185 p = pathext;
2186 while (*p)
2187 {
2188 if (p[0] == ';'
2189 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2190 {
2191 // Skip empty or single ".".
2192 ++p;
2193 continue;
2194 }
2195 e = vim_strchr(p, ';');
2196 if (e == NULL)
2197 e = p + STRLEN(p);
2198 tmplen = e - p;
2199
2200 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2201 {
2202 noext = TRUE;
2203 break;
2204 }
2205
2206 p = e;
2207 }
2208 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002209 }
2210
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002211 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002212 if (pathext == NULL)
2213 pathext = (char_u *)".";
2214 else if (noext == TRUE)
2215 {
2216 if (pathextbuf == NULL)
2217 pathextbuf = alloc(STRLEN(pathext) + 3);
2218 if (pathextbuf == NULL)
2219 {
2220 retval = FALSE;
2221 goto theend;
2222 }
2223 STRCPY(pathextbuf, ".;");
2224 STRCAT(pathextbuf, pathext);
2225 pathext = pathextbuf;
2226 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002227
Bram Moolenaar95da1362020-05-30 18:37:55 +02002228 // Use $PATH when "use_path" is TRUE and "name" is basename.
2229 if (use_path && gettail((char_u *)name) == (char_u *)name)
2230 {
2231 p = mch_getenv("PATH");
2232 if (p != NULL)
2233 {
2234 pathbuf = alloc(STRLEN(p) + 3);
2235 if (pathbuf == NULL)
2236 {
2237 retval = FALSE;
2238 goto theend;
2239 }
2240 STRCPY(pathbuf, ".;");
2241 STRCAT(pathbuf, p);
2242 }
2243 }
2244
2245 /*
2246 * Walk through all entries in $PATH to check if "name" exists there and
2247 * is an executable file.
2248 */
2249 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2250 while (*p)
2251 {
2252 if (*p == ';') // Skip empty entry
2253 {
2254 ++p;
2255 continue;
2256 }
2257 e = vim_strchr(p, ';');
2258 if (e == NULL)
2259 e = p + STRLEN(p);
2260
2261 if (e - p + len + 2 > sizeof(buf))
2262 {
2263 retval = FALSE;
2264 goto theend;
2265 }
2266 // A single "." that means current dir.
2267 if (e - p == 1 && *p == '.')
2268 STRCPY(buf, name);
2269 else
2270 {
2271 vim_strncpy(buf, p, e - p);
2272 add_pathsep(buf);
2273 STRCAT(buf, name);
2274 }
2275 tmplen = STRLEN(buf);
2276
2277 /*
2278 * Loop over all extensions in $PATHEXT.
2279 * Check "name" with extension added.
2280 */
2281 p = pathext;
2282 while (*p)
2283 {
2284 if (*p == ';')
2285 {
2286 // Skip empty entry
2287 ++p;
2288 continue;
2289 }
2290 e2 = vim_strchr(p, (int)';');
2291 if (e2 == NULL)
2292 e2 = p + STRLEN(p);
2293
2294 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2295 {
2296 // Not a single "." that means no extension is added.
2297 if (e2 - p + tmplen + 1 > sizeof(buf))
2298 {
2299 retval = FALSE;
2300 goto theend;
2301 }
2302 vim_strncpy(buf + tmplen, p, e2 - p);
2303 }
2304 if (executable_file((char *)buf, path))
2305 {
2306 retval = TRUE;
2307 goto theend;
2308 }
2309
2310 p = e2;
2311 }
2312
2313 p = e;
2314 }
2315
2316theend:
2317 free(pathextbuf);
2318 free(pathbuf);
2319 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002320}
2321
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002322#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2323 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002324/*
2325 * Bad parameter handler.
2326 *
2327 * Certain MS CRT functions will intentionally crash when passed invalid
2328 * parameters to highlight possible security holes. Setting this function as
2329 * the bad parameter handler will prevent the crash.
2330 *
2331 * In debug builds the parameters contain CRT information that might help track
2332 * down the source of a problem, but in non-debug builds the arguments are all
2333 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2334 * worth allowing these to make debugging of issues easier.
2335 */
2336 static void
2337bad_param_handler(const wchar_t *expression,
2338 const wchar_t *function,
2339 const wchar_t *file,
2340 unsigned int line,
2341 uintptr_t pReserved)
2342{
2343}
2344
2345# define SET_INVALID_PARAM_HANDLER \
2346 ((void)_set_invalid_parameter_handler(bad_param_handler))
2347#else
2348# define SET_INVALID_PARAM_HANDLER
2349#endif
2350
Bram Moolenaar4f974752019-02-17 17:44:42 +01002351#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002352
2353/*
2354 * GUI version of mch_init().
2355 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002356 static void
2357mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002358{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002359# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002360 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002361# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002362
Bram Moolenaar0f873732019-12-05 20:28:46 +01002363 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002364 SET_INVALID_PARAM_HANDLER;
2365
Bram Moolenaar0f873732019-12-05 20:28:46 +01002366 // Let critical errors result in a failure, not in a dialog box. Required
2367 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002368 SetErrorMode(SEM_FAILCRITICALERRORS);
2369
Bram Moolenaar0f873732019-12-05 20:28:46 +01002370 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002371
Bram Moolenaar0f873732019-12-05 20:28:46 +01002372 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002373 Rows = 25;
2374 Columns = 80;
2375
Bram Moolenaar0f873732019-12-05 20:28:46 +01002376 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002377 {
2378 char_u vimrun_location[_MAX_PATH + 4];
2379
Bram Moolenaar0f873732019-12-05 20:28:46 +01002380 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002381 STRCPY(vimrun_location, exe_name);
2382 STRCPY(gettail(vimrun_location), "vimrun.exe");
2383 if (mch_getperm(vimrun_location) >= 0)
2384 {
2385 if (*skiptowhite(vimrun_location) != NUL)
2386 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002387 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002388 mch_memmove(vimrun_location + 1, vimrun_location,
2389 STRLEN(vimrun_location) + 1);
2390 *vimrun_location = '"';
2391 STRCPY(gettail(vimrun_location), "vimrun\" ");
2392 }
2393 else
2394 STRCPY(gettail(vimrun_location), "vimrun ");
2395
2396 vimrun_path = (char *)vim_strsave(vimrun_location);
2397 s_dont_use_vimrun = FALSE;
2398 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002399 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002400 s_dont_use_vimrun = FALSE;
2401
Bram Moolenaar0f873732019-12-05 20:28:46 +01002402 // Don't give the warning for a missing vimrun.exe right now, but only
2403 // when vimrun was supposed to be used. Don't bother people that do
2404 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002405 if (s_dont_use_vimrun)
2406 need_vimrun_warning = TRUE;
2407 }
2408
2409 /*
2410 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2411 * Otherwise the default "findstr /n" is used.
2412 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002413 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002414 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2415
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002416# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002417 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002418# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002419
2420 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002421}
2422
2423
Bram Moolenaar0f873732019-12-05 20:28:46 +01002424#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002425
2426#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002427
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002428# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2429# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002430
2431/*
2432 * ClearConsoleBuffer()
2433 * Description:
2434 * Clears the entire contents of the console screen buffer, using the
2435 * specified attribute.
2436 * Returns:
2437 * TRUE on success
2438 */
2439 static BOOL
2440ClearConsoleBuffer(WORD wAttribute)
2441{
2442 CONSOLE_SCREEN_BUFFER_INFO csbi;
2443 COORD coord;
2444 DWORD NumCells, dummy;
2445
2446 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2447 return FALSE;
2448
2449 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2450 coord.X = 0;
2451 coord.Y = 0;
2452 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2453 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002454 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002455 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2456 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002457 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002458
2459 return TRUE;
2460}
2461
2462/*
2463 * FitConsoleWindow()
2464 * Description:
2465 * Checks if the console window will fit within given buffer dimensions.
2466 * Also, if requested, will shrink the window to fit.
2467 * Returns:
2468 * TRUE on success
2469 */
2470 static BOOL
2471FitConsoleWindow(
2472 COORD dwBufferSize,
2473 BOOL WantAdjust)
2474{
2475 CONSOLE_SCREEN_BUFFER_INFO csbi;
2476 COORD dwWindowSize;
2477 BOOL NeedAdjust = FALSE;
2478
2479 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2480 {
2481 /*
2482 * A buffer resize will fail if the current console window does
2483 * not lie completely within that buffer. To avoid this, we might
2484 * have to move and possibly shrink the window.
2485 */
2486 if (csbi.srWindow.Right >= dwBufferSize.X)
2487 {
2488 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2489 if (dwWindowSize.X > dwBufferSize.X)
2490 dwWindowSize.X = dwBufferSize.X;
2491 csbi.srWindow.Right = dwBufferSize.X - 1;
2492 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2493 NeedAdjust = TRUE;
2494 }
2495 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2496 {
2497 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2498 if (dwWindowSize.Y > dwBufferSize.Y)
2499 dwWindowSize.Y = dwBufferSize.Y;
2500 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2501 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2502 NeedAdjust = TRUE;
2503 }
2504 if (NeedAdjust && WantAdjust)
2505 {
2506 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2507 return FALSE;
2508 }
2509 return TRUE;
2510 }
2511
2512 return FALSE;
2513}
2514
2515typedef struct ConsoleBufferStruct
2516{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002517 BOOL IsValid;
2518 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002519 PCHAR_INFO Buffer;
2520 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002521 PSMALL_RECT Regions;
2522 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002523} ConsoleBuffer;
2524
2525/*
2526 * SaveConsoleBuffer()
2527 * Description:
2528 * Saves important information about the console buffer, including the
2529 * actual buffer contents. The saved information is suitable for later
2530 * restoration by RestoreConsoleBuffer().
2531 * Returns:
2532 * TRUE if all information was saved; FALSE otherwise
2533 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2534 */
2535 static BOOL
2536SaveConsoleBuffer(
2537 ConsoleBuffer *cb)
2538{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002539 DWORD NumCells;
2540 COORD BufferCoord;
2541 SMALL_RECT ReadRegion;
2542 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002543 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002544
Bram Moolenaar071d4272004-06-13 20:20:40 +00002545 if (cb == NULL)
2546 return FALSE;
2547
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002548 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002549 {
2550 cb->IsValid = FALSE;
2551 return FALSE;
2552 }
2553 cb->IsValid = TRUE;
2554
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002555 /*
2556 * Allocate a buffer large enough to hold the entire console screen
2557 * buffer. If this ConsoleBuffer structure has already been initialized
2558 * with a buffer of the correct size, then just use that one.
2559 */
2560 if (!cb->IsValid || cb->Buffer == NULL ||
2561 cb->BufferSize.X != cb->Info.dwSize.X ||
2562 cb->BufferSize.Y != cb->Info.dwSize.Y)
2563 {
2564 cb->BufferSize.X = cb->Info.dwSize.X;
2565 cb->BufferSize.Y = cb->Info.dwSize.Y;
2566 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2567 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002568 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002569 if (cb->Buffer == NULL)
2570 return FALSE;
2571 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002572
2573 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002574 * We will now copy the console screen buffer into our buffer.
2575 * ReadConsoleOutput() seems to be limited as far as how much you
2576 * can read at a time. Empirically, this number seems to be about
2577 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2578 * in chunks until it is all copied. The chunks will all have the
2579 * same horizontal characteristics, so initialize them now. The
2580 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002581 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002582 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002583 ReadRegion.Left = 0;
2584 ReadRegion.Right = cb->Info.dwSize.X - 1;
2585 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002586
2587 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2588 if (cb->Regions == NULL || numregions != cb->NumRegions)
2589 {
2590 cb->NumRegions = numregions;
2591 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002592 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002593 if (cb->Regions == NULL)
2594 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002595 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002596 return FALSE;
2597 }
2598 }
2599
2600 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002601 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002602 /*
2603 * Read into position (0, Y) in our buffer.
2604 */
2605 BufferCoord.Y = Y;
2606 /*
2607 * Read the region whose top left corner is (0, Y) and whose bottom
2608 * right corner is (width - 1, Y + Y_incr - 1). This should define
2609 * a region of size width by Y_incr. Don't worry if this region is
2610 * too large for the remaining buffer; it will be cropped.
2611 */
2612 ReadRegion.Top = Y;
2613 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002614 if (!ReadConsoleOutputW(g_hConOut, // output handle
2615 cb->Buffer, // our buffer
2616 cb->BufferSize, // dimensions of our buffer
2617 BufferCoord, // offset in our buffer
2618 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002619 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002620 VIM_CLEAR(cb->Buffer);
2621 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002622 return FALSE;
2623 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002624 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002625 }
2626
2627 return TRUE;
2628}
2629
2630/*
2631 * RestoreConsoleBuffer()
2632 * Description:
2633 * Restores important information about the console buffer, including the
2634 * actual buffer contents, if desired. The information to restore is in
2635 * the same format used by SaveConsoleBuffer().
2636 * Returns:
2637 * TRUE on success
2638 */
2639 static BOOL
2640RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002641 ConsoleBuffer *cb,
2642 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002643{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002644 COORD BufferCoord;
2645 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002646 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002647
2648 if (cb == NULL || !cb->IsValid)
2649 return FALSE;
2650
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002651 /*
2652 * Before restoring the buffer contents, clear the current buffer, and
2653 * restore the cursor position and window information. Doing this now
2654 * prevents old buffer contents from "flashing" onto the screen.
2655 */
2656 if (RestoreScreen)
2657 ClearConsoleBuffer(cb->Info.wAttributes);
2658
2659 FitConsoleWindow(cb->Info.dwSize, TRUE);
2660 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2661 return FALSE;
2662 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2663 return FALSE;
2664
2665 if (!RestoreScreen)
2666 {
2667 /*
2668 * No need to restore the screen buffer contents, so we're done.
2669 */
2670 return TRUE;
2671 }
2672
2673 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2674 return FALSE;
2675 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2676 return FALSE;
2677
2678 /*
2679 * Restore the screen buffer contents.
2680 */
2681 if (cb->Buffer != NULL)
2682 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002683 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002684 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002685 BufferCoord.X = cb->Regions[i].Left;
2686 BufferCoord.Y = cb->Regions[i].Top;
2687 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01002688 if (!WriteConsoleOutputW(g_hConOut, // output handle
2689 cb->Buffer, // our buffer
2690 cb->BufferSize, // dimensions of our buffer
2691 BufferCoord, // offset in our buffer
2692 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02002693 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002694 }
2695 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002696
2697 return TRUE;
2698}
2699
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002700# define FEAT_RESTORE_ORIG_SCREEN
2701# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002702static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002703# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002704static ConsoleBuffer g_cbNonTermcap = { 0 };
2705static ConsoleBuffer g_cbTermcap = { 0 };
2706
Bram Moolenaar071d4272004-06-13 20:20:40 +00002707char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01002708HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00002709static HICON g_hOrigIconSmall = NULL;
2710static HICON g_hOrigIcon = NULL;
2711static HICON g_hVimIcon = NULL;
2712static BOOL g_fCanChangeIcon = FALSE;
2713
Bram Moolenaar071d4272004-06-13 20:20:40 +00002714/*
2715 * GetConsoleIcon()
2716 * Description:
2717 * Attempts to retrieve the small icon and/or the big icon currently in
2718 * use by a given window.
2719 * Returns:
2720 * TRUE on success
2721 */
2722 static BOOL
2723GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002724 HWND hWnd,
2725 HICON *phIconSmall,
2726 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002727{
2728 if (hWnd == NULL)
2729 return FALSE;
2730
2731 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002732 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2733 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002734 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002735 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2736 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002737 return TRUE;
2738}
2739
2740/*
2741 * SetConsoleIcon()
2742 * Description:
2743 * Attempts to change the small icon and/or the big icon currently in
2744 * use by a given window.
2745 * Returns:
2746 * TRUE on success
2747 */
2748 static BOOL
2749SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002750 HWND hWnd,
2751 HICON hIconSmall,
2752 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002753{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002754 if (hWnd == NULL)
2755 return FALSE;
2756
2757 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002758 SendMessage(hWnd, WM_SETICON,
2759 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002760 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002761 SendMessage(hWnd, WM_SETICON,
2762 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002763 return TRUE;
2764}
2765
2766/*
2767 * SaveConsoleTitleAndIcon()
2768 * Description:
2769 * Saves the current console window title in g_szOrigTitle, for later
2770 * restoration. Also, attempts to obtain a handle to the console window,
2771 * and use it to save the small and big icons currently in use by the
2772 * console window. This is not always possible on some versions of Windows;
2773 * nor is it possible when running Vim remotely using Telnet (since the
2774 * console window the user sees is owned by a remote process).
2775 */
2776 static void
2777SaveConsoleTitleAndIcon(void)
2778{
Bram Moolenaar0f873732019-12-05 20:28:46 +01002779 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002780 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2781 return;
2782
2783 /*
2784 * Obtain a handle to the console window using GetConsoleWindow() from
2785 * KERNEL32.DLL; we need to handle in order to change the window icon.
2786 * This function only exists on NT-based Windows, starting with Windows
2787 * 2000. On older operating systems, we can't change the window icon
2788 * anyway.
2789 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002790 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002791 if (g_hWnd == NULL)
2792 return;
2793
Bram Moolenaar0f873732019-12-05 20:28:46 +01002794 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002795 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2796 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2797 return;
2798
Bram Moolenaar0f873732019-12-05 20:28:46 +01002799 // Extract the first icon contained in the Vim executable.
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002800 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002801 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002802 if (g_hVimIcon != NULL)
2803 g_fCanChangeIcon = TRUE;
2804}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002805
2806static int g_fWindInitCalled = FALSE;
2807static int g_fTermcapMode = FALSE;
2808static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002809
2810/*
2811 * non-GUI version of mch_init().
2812 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002813 static void
2814mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002815{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002816# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002817 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002818# endif
2819# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002820 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002821# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002822
Bram Moolenaar0f873732019-12-05 20:28:46 +01002823 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002824 SET_INVALID_PARAM_HANDLER;
2825
Bram Moolenaar0f873732019-12-05 20:28:46 +01002826 // Let critical errors result in a failure, not in a dialog box. Required
2827 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002828 SetErrorMode(SEM_FAILCRITICALERRORS);
2829
Bram Moolenaar0f873732019-12-05 20:28:46 +01002830 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002831 out_flush();
2832
Bram Moolenaar0f873732019-12-05 20:28:46 +01002833 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00002834 if (read_cmd_fd == 0)
2835 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2836 else
2837 create_conin();
2838 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2839
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002840# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01002841 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002842 SaveConsoleBuffer(&g_cbOrig);
2843 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002844# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01002845 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002846 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2847 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002848# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002849 if (cterm_normal_fg_color == 0)
2850 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2851 if (cterm_normal_bg_color == 0)
2852 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2853
Bram Moolenaarbdace832019-03-02 10:13:42 +01002854 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002855 g_color_index_fg = g_attrDefault & 0xf;
2856 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2857
Bram Moolenaar0f873732019-12-05 20:28:46 +01002858 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00002859 update_tcap(g_attrCurrent);
2860
2861 GetConsoleCursorInfo(g_hConOut, &g_cci);
2862 GetConsoleMode(g_hConIn, &g_cmodein);
2863 GetConsoleMode(g_hConOut, &g_cmodeout);
2864
Bram Moolenaar071d4272004-06-13 20:20:40 +00002865 SaveConsoleTitleAndIcon();
2866 /*
2867 * Set both the small and big icons of the console window to Vim's icon.
2868 * Note that Vim presently only has one size of icon (32x32), but it
2869 * automatically gets scaled down to 16x16 when setting the small icon.
2870 */
2871 if (g_fCanChangeIcon)
2872 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002873
2874 ui_get_shellsize();
2875
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002876# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002877 fdDump = fopen("dump", "wt");
2878
2879 if (fdDump)
2880 {
2881 time_t t;
2882
2883 time(&t);
2884 fputs(ctime(&t), fdDump);
2885 fflush(fdDump);
2886 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002887# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002888
2889 g_fWindInitCalled = TRUE;
2890
Bram Moolenaar071d4272004-06-13 20:20:40 +00002891 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002892
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002893# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002894 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002895# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002896
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02002897 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002898 vtp_init();
Bram Moolenaar06b7b582020-05-30 17:49:25 +02002899 wt_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002900}
2901
2902/*
2903 * non-GUI version of mch_exit().
2904 * Shut down and exit with status `r'
2905 * Careful: mch_exit() may be called before mch_init()!
2906 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002907 static void
2908mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002909{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002910 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002911
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002912 vtp_exit();
2913
Bram Moolenaar955f1982017-02-05 15:10:51 +01002914 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002915 if (g_fWindInitCalled)
2916 settmode(TMODE_COOK);
2917
Bram Moolenaar0f873732019-12-05 20:28:46 +01002918 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00002919
2920 if (g_fWindInitCalled)
2921 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02002922 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002923 /*
2924 * Restore both the small and big icons of the console window to
2925 * what they were at startup. Don't do this when the window is
2926 * closed, Vim would hang here.
2927 */
2928 if (g_fCanChangeIcon && !g_fForceExit)
2929 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002930
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002931# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002932 if (fdDump)
2933 {
2934 time_t t;
2935
2936 time(&t);
2937 fputs(ctime(&t), fdDump);
2938 fclose(fdDump);
2939 }
2940 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002941# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002942 }
2943
2944 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02002945 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002946 SetConsoleMode(g_hConOut, g_cmodeout);
2947
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002948# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00002949 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002950# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002951
2952 exit(r);
2953}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002954#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002955
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002956 void
2957mch_init(void)
2958{
2959#ifdef VIMDLL
2960 if (gui.starting)
2961 mch_init_g();
2962 else
2963 mch_init_c();
2964#elif defined(FEAT_GUI_MSWIN)
2965 mch_init_g();
2966#else
2967 mch_init_c();
2968#endif
2969}
2970
2971 void
2972mch_exit(int r)
2973{
Bram Moolenaar173d8412020-04-19 14:02:26 +02002974#ifdef FEAT_NETBEANS_INTG
2975 netbeans_send_disconnect();
2976#endif
2977
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002978#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02002979 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002980 mch_exit_g(r);
2981 else
2982 mch_exit_c(r);
2983#elif defined(FEAT_GUI_MSWIN)
2984 mch_exit_g(r);
2985#else
2986 mch_exit_c(r);
2987#endif
2988}
2989
Bram Moolenaar071d4272004-06-13 20:20:40 +00002990/*
2991 * Do we have an interactive window?
2992 */
2993 int
2994mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002995 int argc UNUSED,
2996 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002997{
2998 get_exe_name();
2999
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003000#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003001 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003002#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003003# ifdef VIMDLL
3004 if (gui.in_use)
3005 return OK;
3006# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003007 if (isatty(1))
3008 return OK;
3009 return FAIL;
3010#endif
3011}
3012
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003013/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003014 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003015 * When "len" is > 0, also expand short to long filenames.
3016 */
3017 void
3018fname_case(
3019 char_u *name,
3020 int len)
3021{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003022 int flen;
3023 WCHAR *p;
3024 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003026 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003027 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003028 return;
3029
3030 slash_adjust(name);
3031
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003032 p = enc_to_utf16(name, NULL);
3033 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003034 return;
3035
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003036 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003037 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003038 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003039
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003040 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003041 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003042 if (len > 0 || flen >= (int)STRLEN(q))
3043 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3044 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003045 }
3046 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003047 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048}
3049
3050
3051/*
3052 * Insert user name in s[len].
3053 */
3054 int
3055mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003056 char_u *s,
3057 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003058{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003059 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003060 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003061
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003062 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003063 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003064 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003065
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003066 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003067 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003068 vim_strncpy(s, p, len - 1);
3069 vim_free(p);
3070 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003071 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003072 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003073 s[0] = NUL;
3074 return FAIL;
3075}
3076
3077
3078/*
3079 * Insert host name in s[len].
3080 */
3081 void
3082mch_get_host_name(
3083 char_u *s,
3084 int len)
3085{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003086 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003087 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003088
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003089 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003090 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003091 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003092
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003093 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003094 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003095 vim_strncpy(s, p, len - 1);
3096 vim_free(p);
3097 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003098 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003099 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003100}
3101
3102
3103/*
3104 * return process ID
3105 */
3106 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003107mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003108{
3109 return (long)GetCurrentProcessId();
3110}
3111
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003112/*
3113 * return TRUE if process "pid" is still running
3114 */
3115 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003116mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003117{
3118 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3119 DWORD status = 0;
3120 int ret = FALSE;
3121
3122 if (hProcess == NULL)
3123 return FALSE; // might not have access
3124 if (GetExitCodeProcess(hProcess, &status) )
3125 ret = status == STILL_ACTIVE;
3126 CloseHandle(hProcess);
3127 return ret;
3128}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003129
3130/*
3131 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3132 * Return OK for success, FAIL for failure.
3133 */
3134 int
3135mch_dirname(
3136 char_u *buf,
3137 int len)
3138{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003139 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003140
Bram Moolenaar071d4272004-06-13 20:20:40 +00003141 /*
3142 * Originally this was:
3143 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3144 * But the Win32s known bug list says that getcwd() doesn't work
3145 * so use the Win32 system call instead. <Negri>
3146 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003147 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003148 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003149 WCHAR wcbuf[_MAX_PATH + 1];
3150 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003151
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003152 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003153 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003154 p = utf16_to_enc(wcbuf, NULL);
3155 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003156 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003157 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003158 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003159 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003160 }
3161 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003162 if (p == NULL)
3163 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003164
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003165 if (p != NULL)
3166 {
3167 vim_strncpy(buf, p, len - 1);
3168 vim_free(p);
3169 return OK;
3170 }
3171 }
3172 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003173}
3174
3175/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003176 * Get file permissions for "name".
3177 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003178 */
3179 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003180mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003181{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003182 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003183 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003184
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003185 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003186 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003187}
3188
3189
3190/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003191 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003192 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003193 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003194 */
3195 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003196mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003197{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003198 long n;
3199 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003200
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003201 p = enc_to_utf16(name, NULL);
3202 if (p == NULL)
3203 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003204
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003205 n = _wchmod(p, perm);
3206 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003207 if (n == -1)
3208 return FAIL;
3209
3210 win32_set_archive(name);
3211
3212 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003213}
3214
3215/*
3216 * Set hidden flag for "name".
3217 */
3218 void
3219mch_hide(char_u *name)
3220{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003221 int attrs = win32_getattrs(name);
3222 if (attrs == -1)
3223 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003224
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003225 attrs |= FILE_ATTRIBUTE_HIDDEN;
3226 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003227}
3228
3229/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003230 * Return TRUE if file "name" exists and is hidden.
3231 */
3232 int
3233mch_ishidden(char_u *name)
3234{
3235 int f = win32_getattrs(name);
3236
3237 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003238 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003239
3240 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3241}
3242
3243/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003244 * return TRUE if "name" is a directory
3245 * return FALSE if "name" is not a directory or upon error
3246 */
3247 int
3248mch_isdir(char_u *name)
3249{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003250 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003251
3252 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003253 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003254
3255 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3256}
3257
3258/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003259 * return TRUE if "name" is a directory, NOT a symlink to a directory
3260 * return FALSE if "name" is not a directory
3261 * return FALSE for error
3262 */
3263 int
3264mch_isrealdir(char_u *name)
3265{
3266 return mch_isdir(name) && !mch_is_symbolic_link(name);
3267}
3268
3269/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003270 * Create directory "name".
3271 * Return 0 on success, -1 on error.
3272 */
3273 int
3274mch_mkdir(char_u *name)
3275{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003276 WCHAR *p;
3277 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003278
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003279 p = enc_to_utf16(name, NULL);
3280 if (p == NULL)
3281 return -1;
3282 retval = _wmkdir(p);
3283 vim_free(p);
3284 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003285}
3286
3287/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003288 * Delete directory "name".
3289 * Return 0 on success, -1 on error.
3290 */
3291 int
3292mch_rmdir(char_u *name)
3293{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003294 WCHAR *p;
3295 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003296
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003297 p = enc_to_utf16(name, NULL);
3298 if (p == NULL)
3299 return -1;
3300 retval = _wrmdir(p);
3301 vim_free(p);
3302 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003303}
3304
3305/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003306 * Return TRUE if file "fname" has more than one link.
3307 */
3308 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003309mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003310{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003311 BY_HANDLE_FILE_INFORMATION info;
3312
3313 return win32_fileinfo(fname, &info) == FILEINFO_OK
3314 && info.nNumberOfLinks > 1;
3315}
3316
3317/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003318 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003319 */
3320 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003321mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003322{
3323 HANDLE hFind;
3324 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003325 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003326 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003327 WIN32_FIND_DATAW findDataW;
3328
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003329 wn = enc_to_utf16(name, NULL);
3330 if (wn == NULL)
3331 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003332
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003333 hFind = FindFirstFileW(wn, &findDataW);
3334 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003335 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003336 {
3337 fileFlags = findDataW.dwFileAttributes;
3338 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003339 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003340 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003341
3342 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003343 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3344 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003345 res = TRUE;
3346
3347 return res;
3348}
3349
3350/*
3351 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3352 * link.
3353 */
3354 int
3355mch_is_linked(char_u *fname)
3356{
3357 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3358 return TRUE;
3359 return FALSE;
3360}
3361
3362/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003363 * Get the by-handle-file-information for "fname".
3364 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003365 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003366 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3367 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3368 */
3369 int
3370win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3371{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003372 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003373 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003374 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003375
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003376 wn = enc_to_utf16(fname, NULL);
3377 if (wn == NULL)
3378 return FILEINFO_ENC_FAIL;
3379
3380 hFile = CreateFileW(wn, // file name
3381 GENERIC_READ, // access mode
3382 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3383 NULL, // security descriptor
3384 OPEN_EXISTING, // creation disposition
3385 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3386 NULL); // handle to template file
3387 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003388
3389 if (hFile != INVALID_HANDLE_VALUE)
3390 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003391 if (GetFileInformationByHandle(hFile, info) != 0)
3392 res = FILEINFO_OK;
3393 else
3394 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003395 CloseHandle(hFile);
3396 }
3397
Bram Moolenaar03f48552006-02-28 23:52:23 +00003398 return res;
3399}
3400
3401/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003402 * get file attributes for `name'
3403 * -1 : error
3404 * else FILE_ATTRIBUTE_* defined in winnt.h
3405 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003406 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003407win32_getattrs(char_u *name)
3408{
3409 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003410 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003411
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003412 p = enc_to_utf16(name, NULL);
3413 if (p == NULL)
3414 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003415
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003416 attr = GetFileAttributesW(p);
3417 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003418
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003419 return attr;
3420}
3421
3422/*
3423 * set file attributes for `name' to `attrs'
3424 *
3425 * return -1 for failure, 0 otherwise
3426 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003427 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003428win32_setattrs(char_u *name, int attrs)
3429{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003430 int res;
3431 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003432
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003433 p = enc_to_utf16(name, NULL);
3434 if (p == NULL)
3435 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003436
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003437 res = SetFileAttributesW(p, attrs);
3438 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003439
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003440 return res ? 0 : -1;
3441}
3442
3443/*
3444 * Set archive flag for "name".
3445 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003446 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003447win32_set_archive(char_u *name)
3448{
3449 int attrs = win32_getattrs(name);
3450 if (attrs == -1)
3451 return -1;
3452
3453 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3454 return win32_setattrs(name, attrs);
3455}
3456
3457/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003458 * Return TRUE if file or directory "name" is writable (not readonly).
3459 * Strange semantics of Win32: a readonly directory is writable, but you can't
3460 * delete a file. Let's say this means it is writable.
3461 */
3462 int
3463mch_writable(char_u *name)
3464{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003465 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003466
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003467 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3468 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003469}
3470
Bram Moolenaar071d4272004-06-13 20:20:40 +00003471/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003472 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003473 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003474 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3475 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003476 */
3477 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003478mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003479{
Bram Moolenaar95da1362020-05-30 18:37:55 +02003480 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003481}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003482
3483/*
3484 * Check what "name" is:
3485 * NODE_NORMAL: file or directory (or doesn't exist)
3486 * NODE_WRITABLE: writable device, socket, fifo, etc.
3487 * NODE_OTHER: non-writable things
3488 */
3489 int
3490mch_nodetype(char_u *name)
3491{
3492 HANDLE hFile;
3493 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003494 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003495
Bram Moolenaar0f873732019-12-05 20:28:46 +01003496 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3497 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3498 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00003499 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3500 return NODE_WRITABLE;
3501
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003502 wn = enc_to_utf16(name, NULL);
3503 if (wn == NULL)
3504 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003505
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003506 hFile = CreateFileW(wn, // file name
3507 GENERIC_WRITE, // access mode
3508 0, // share mode
3509 NULL, // security descriptor
3510 OPEN_EXISTING, // creation disposition
3511 0, // file attributes
3512 NULL); // handle to template file
3513 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003514 if (hFile == INVALID_HANDLE_VALUE)
3515 return NODE_NORMAL;
3516
3517 type = GetFileType(hFile);
3518 CloseHandle(hFile);
3519 if (type == FILE_TYPE_CHAR)
3520 return NODE_WRITABLE;
3521 if (type == FILE_TYPE_DISK)
3522 return NODE_NORMAL;
3523 return NODE_OTHER;
3524}
3525
3526#ifdef HAVE_ACL
3527struct my_acl
3528{
3529 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3530 PSID pSidOwner;
3531 PSID pSidGroup;
3532 PACL pDacl;
3533 PACL pSacl;
3534};
3535#endif
3536
3537/*
3538 * Return a pointer to the ACL of file "fname" in allocated memory.
3539 * Return NULL if the ACL is not available for whatever reason.
3540 */
3541 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003542mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003543{
3544#ifndef HAVE_ACL
3545 return (vim_acl_T)NULL;
3546#else
3547 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003548 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003549
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003550 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003551 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003552 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003553 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003554
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003555 wn = enc_to_utf16(fname, NULL);
3556 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003557 {
3558 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003559 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003560 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003561
3562 // Try to retrieve the entire security descriptor.
3563 err = GetNamedSecurityInfoW(
3564 wn, // Abstract filename
3565 SE_FILE_OBJECT, // File Object
3566 OWNER_SECURITY_INFORMATION |
3567 GROUP_SECURITY_INFORMATION |
3568 DACL_SECURITY_INFORMATION |
3569 SACL_SECURITY_INFORMATION,
3570 &p->pSidOwner, // Ownership information.
3571 &p->pSidGroup, // Group membership.
3572 &p->pDacl, // Discretionary information.
3573 &p->pSacl, // For auditing purposes.
3574 &p->pSecurityDescriptor);
3575 if (err == ERROR_ACCESS_DENIED ||
3576 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003577 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003578 // Retrieve only DACL.
3579 (void)GetNamedSecurityInfoW(
3580 wn,
3581 SE_FILE_OBJECT,
3582 DACL_SECURITY_INFORMATION,
3583 NULL,
3584 NULL,
3585 &p->pDacl,
3586 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003587 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003588 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003589 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003590 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003591 mch_free_acl((vim_acl_T)p);
3592 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003593 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003594 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003595 }
3596
3597 return (vim_acl_T)p;
3598#endif
3599}
3600
Bram Moolenaar27515922013-06-29 15:36:26 +02003601#ifdef HAVE_ACL
3602/*
3603 * Check if "acl" contains inherited ACE.
3604 */
3605 static BOOL
3606is_acl_inherited(PACL acl)
3607{
3608 DWORD i;
3609 ACL_SIZE_INFORMATION acl_info;
3610 PACCESS_ALLOWED_ACE ace;
3611
3612 acl_info.AceCount = 0;
3613 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3614 for (i = 0; i < acl_info.AceCount; i++)
3615 {
3616 GetAce(acl, i, (LPVOID *)&ace);
3617 if (ace->Header.AceFlags & INHERITED_ACE)
3618 return TRUE;
3619 }
3620 return FALSE;
3621}
3622#endif
3623
Bram Moolenaar071d4272004-06-13 20:20:40 +00003624/*
3625 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3626 * Errors are ignored.
3627 * This must only be called with "acl" equal to what mch_get_acl() returned.
3628 */
3629 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003630mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003631{
3632#ifdef HAVE_ACL
3633 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003634 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003635 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003636
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003637 if (p == NULL)
3638 return;
3639
3640 wn = enc_to_utf16(fname, NULL);
3641 if (wn == NULL)
3642 return;
3643
3644 // Set security flags
3645 if (p->pSidOwner)
3646 sec_info |= OWNER_SECURITY_INFORMATION;
3647 if (p->pSidGroup)
3648 sec_info |= GROUP_SECURITY_INFORMATION;
3649 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003650 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003651 sec_info |= DACL_SECURITY_INFORMATION;
3652 // Do not inherit its parent's DACL.
3653 // If the DACL is inherited, Cygwin permissions would be changed.
3654 if (!is_acl_inherited(p->pDacl))
3655 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003656 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003657 if (p->pSacl)
3658 sec_info |= SACL_SECURITY_INFORMATION;
3659
3660 (void)SetNamedSecurityInfoW(
3661 wn, // Abstract filename
3662 SE_FILE_OBJECT, // File Object
3663 sec_info,
3664 p->pSidOwner, // Ownership information.
3665 p->pSidGroup, // Group membership.
3666 p->pDacl, // Discretionary information.
3667 p->pSacl // For auditing purposes.
3668 );
3669 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003670#endif
3671}
3672
3673 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003674mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003675{
3676#ifdef HAVE_ACL
3677 struct my_acl *p = (struct my_acl *)acl;
3678
3679 if (p != NULL)
3680 {
3681 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3682 vim_free(p);
3683 }
3684#endif
3685}
3686
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003687#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003688
3689/*
3690 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3691 */
3692 static BOOL WINAPI
3693handler_routine(
3694 DWORD dwCtrlType)
3695{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003696 INPUT_RECORD ir;
3697 DWORD out;
3698
Bram Moolenaar071d4272004-06-13 20:20:40 +00003699 switch (dwCtrlType)
3700 {
3701 case CTRL_C_EVENT:
3702 if (ctrl_c_interrupts)
3703 g_fCtrlCPressed = TRUE;
3704 return TRUE;
3705
3706 case CTRL_BREAK_EVENT:
3707 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003708 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003709 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02003710 ir.EventType = KEY_EVENT;
3711 ir.Event.KeyEvent.bKeyDown = TRUE;
3712 ir.Event.KeyEvent.wRepeatCount = 1;
3713 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3714 ir.Event.KeyEvent.wVirtualScanCode = 0;
3715 ir.Event.KeyEvent.dwControlKeyState = 0;
3716 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3717 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003718 return TRUE;
3719
Bram Moolenaar0f873732019-12-05 20:28:46 +01003720 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00003721 case CTRL_CLOSE_EVENT:
3722 case CTRL_LOGOFF_EVENT:
3723 case CTRL_SHUTDOWN_EVENT:
3724 windgoto((int)Rows - 1, 0);
3725 g_fForceExit = TRUE;
3726
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003727 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003728 (dwCtrlType == CTRL_CLOSE_EVENT
3729 ? _("close")
3730 : dwCtrlType == CTRL_LOGOFF_EVENT
3731 ? _("logoff")
3732 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003733# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00003734 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003735# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003736
Bram Moolenaar0f873732019-12-05 20:28:46 +01003737 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00003738
Bram Moolenaar0f873732019-12-05 20:28:46 +01003739 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00003740
3741 default:
3742 return FALSE;
3743 }
3744}
3745
3746
3747/*
3748 * set the tty in (raw) ? "raw" : "cooked" mode
3749 */
3750 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02003751mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003752{
3753 DWORD cmodein;
3754 DWORD cmodeout;
3755 BOOL bEnableHandler;
3756
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003757# ifdef VIMDLL
3758 if (gui.in_use)
3759 return;
3760# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003761 GetConsoleMode(g_hConIn, &cmodein);
3762 GetConsoleMode(g_hConOut, &cmodeout);
3763 if (tmode == TMODE_RAW)
3764 {
3765 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3766 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003767 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003768 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003769 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003770 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
3771 }
3772 else
3773 {
3774 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
3775 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003776 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003777# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01003778 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
3779 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003780 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003781# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003782 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003783# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003784 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003785 bEnableHandler = TRUE;
3786 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01003787 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00003788 {
3789 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3790 ENABLE_ECHO_INPUT);
3791 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3792 bEnableHandler = FALSE;
3793 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003794 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003795 SetConsoleMode(g_hConOut, cmodeout);
3796 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3797
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003798# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003799 if (fdDump)
3800 {
3801 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3802 tmode == TMODE_RAW ? "raw" :
3803 tmode == TMODE_COOK ? "cooked" : "normal",
3804 cmodein, cmodeout);
3805 fflush(fdDump);
3806 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003807# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003808}
3809
3810
3811/*
3812 * Get the size of the current window in `Rows' and `Columns'
3813 * Return OK when size could be determined, FAIL otherwise.
3814 */
3815 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003816mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003817{
3818 CONSOLE_SCREEN_BUFFER_INFO csbi;
3819
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003820# ifdef VIMDLL
3821 if (gui.in_use)
3822 return OK;
3823# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003824 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3825 {
3826 /*
3827 * For some reason, we are trying to get the screen dimensions
3828 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3829 * variables are really intended to mean the size of Vim screen
3830 * while in termcap mode.
3831 */
3832 Rows = g_cbTermcap.Info.dwSize.Y;
3833 Columns = g_cbTermcap.Info.dwSize.X;
3834 }
3835 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3836 {
3837 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3838 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3839 }
3840 else
3841 {
3842 Rows = 25;
3843 Columns = 80;
3844 }
3845 return OK;
3846}
3847
3848/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003849 * Resize console buffer to 'COORD'
3850 */
3851 static void
3852ResizeConBuf(
3853 HANDLE hConsole,
3854 COORD coordScreen)
3855{
3856 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3857 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003858# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003859 if (fdDump)
3860 {
3861 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3862 GetLastError());
3863 fflush(fdDump);
3864 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003865# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003866 }
3867}
3868
3869/*
3870 * Resize console window size to 'srWindowRect'
3871 */
3872 static void
3873ResizeWindow(
3874 HANDLE hConsole,
3875 SMALL_RECT srWindowRect)
3876{
3877 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
3878 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003879# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003880 if (fdDump)
3881 {
3882 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3883 GetLastError());
3884 fflush(fdDump);
3885 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003886# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003887 }
3888}
3889
3890/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003891 * Set a console window to `xSize' * `ySize'
3892 */
3893 static void
3894ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003895 HANDLE hConsole,
3896 int xSize,
3897 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003898{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003899 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
3900 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003901 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003902 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02003903 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003904
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003905# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003906 if (fdDump)
3907 {
3908 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3909 fflush(fdDump);
3910 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003911# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003912
Bram Moolenaar0f873732019-12-05 20:28:46 +01003913 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00003914 coordScreen = GetLargestConsoleWindowSize(hConsole);
3915
Bram Moolenaar0f873732019-12-05 20:28:46 +01003916 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00003917 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3918 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3919 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3920
3921 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3922 {
3923 int sx, sy;
3924
3925 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3926 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3927 if (sy < ySize || sx < xSize)
3928 {
3929 /*
3930 * Increasing number of lines/columns, do buffer first.
3931 * Use the maximal size in x and y direction.
3932 */
3933 if (sy < ySize)
3934 coordScreen.Y = ySize;
3935 else
3936 coordScreen.Y = sy;
3937 if (sx < xSize)
3938 coordScreen.X = xSize;
3939 else
3940 coordScreen.X = sx;
3941 SetConsoleScreenBufferSize(hConsole, coordScreen);
3942 }
3943 }
3944
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003945 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003946 coordScreen.X = xSize;
3947 coordScreen.Y = ySize;
3948
Bram Moolenaar2551c032018-08-23 22:38:31 +02003949 // In the new console call API, only the first time in reverse order
3950 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003951 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003952 ResizeWindow(hConsole, srWindowRect);
3953 ResizeConBuf(hConsole, coordScreen);
3954 }
3955 else
3956 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003957 // Workaround for a Windows 10 bug
3958 cursor.X = srWindowRect.Left;
3959 cursor.Y = srWindowRect.Top;
3960 SetConsoleCursorPosition(hConsole, cursor);
3961
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003962 ResizeConBuf(hConsole, coordScreen);
3963 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02003964 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003965 }
3966}
3967
3968
3969/*
3970 * Set the console window to `Rows' * `Columns'
3971 */
3972 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003973mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003974{
3975 COORD coordScreen;
3976
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003977# ifdef VIMDLL
3978 if (gui.in_use)
3979 return;
3980# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01003981 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00003982 if (suppress_winsize != 0)
3983 {
3984 suppress_winsize = 2;
3985 return;
3986 }
3987
3988 if (term_console)
3989 {
3990 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3991
Bram Moolenaar0f873732019-12-05 20:28:46 +01003992 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00003993 if (Rows > coordScreen.Y)
3994 Rows = coordScreen.Y;
3995 if (Columns > coordScreen.X)
3996 Columns = coordScreen.X;
3997
3998 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3999 }
4000}
4001
4002/*
4003 * Rows and/or Columns has changed.
4004 */
4005 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004006mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004007{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004008# ifdef VIMDLL
4009 if (gui.in_use)
4010 return;
4011# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004012 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4013}
4014
4015
4016/*
4017 * Called when started up, to set the winsize that was delayed.
4018 */
4019 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004020mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004021{
4022 if (suppress_winsize == 2)
4023 {
4024 suppress_winsize = 0;
4025 mch_set_shellsize();
4026 shell_resized();
4027 }
4028 suppress_winsize = 0;
4029}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004030#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004031
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004032 static BOOL
4033vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004034 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004035 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004036 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004037 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004038 PROCESS_INFORMATION *pi,
4039 LPVOID *env,
4040 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004041{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004042 BOOL ret = FALSE;
4043 WCHAR *wcmd, *wcwd = NULL;
4044
4045 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4046 if (wcmd == NULL)
4047 return FALSE;
4048 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004049 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004050 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4051 if (wcwd == NULL)
4052 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004053 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004054
4055 ret = CreateProcessW(
4056 NULL, // Executable name
4057 wcmd, // Command to execute
4058 NULL, // Process security attributes
4059 NULL, // Thread security attributes
4060 inherit_handles, // Inherit handles
4061 flags, // Creation flags
4062 env, // Environment
4063 wcwd, // Current directory
4064 (LPSTARTUPINFOW)si, // Startup information
4065 pi); // Process information
4066theend:
4067 vim_free(wcmd);
4068 vim_free(wcwd);
4069 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004070}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004071
4072
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004073 static HINSTANCE
4074vim_shell_execute(
4075 char *cmd,
4076 INT n_show_cmd)
4077{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004078 HINSTANCE ret;
4079 WCHAR *wcmd;
4080
4081 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4082 if (wcmd == NULL)
4083 return (HINSTANCE) 0;
4084
4085 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4086 vim_free(wcmd);
4087 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004088}
4089
4090
Bram Moolenaar4f974752019-02-17 17:44:42 +01004091#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004092
4093/*
4094 * Specialised version of system() for Win32 GUI mode.
4095 * This version proceeds as follows:
4096 * 1. Create a console window for use by the subprocess
4097 * 2. Run the subprocess (it gets the allocated console by default)
4098 * 3. Wait for the subprocess to terminate and get its exit code
4099 * 4. Prompt the user to press a key to close the console window
4100 */
4101 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004102mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004103{
4104 STARTUPINFO si;
4105 PROCESS_INFORMATION pi;
4106 DWORD ret = 0;
4107 HWND hwnd = GetFocus();
4108
4109 si.cb = sizeof(si);
4110 si.lpReserved = NULL;
4111 si.lpDesktop = NULL;
4112 si.lpTitle = NULL;
4113 si.dwFlags = STARTF_USESHOWWINDOW;
4114 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004115 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004116 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004117 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004118 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004119 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004120 else
4121 si.wShowWindow = SW_SHOWNORMAL;
4122 si.cbReserved2 = 0;
4123 si.lpReserved2 = NULL;
4124
Bram Moolenaar0f873732019-12-05 20:28:46 +01004125 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004126 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004127 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4128 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004129
Bram Moolenaar0f873732019-12-05 20:28:46 +01004130 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004131 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004132# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004133 int delay = 1;
4134
Bram Moolenaar0f873732019-12-05 20:28:46 +01004135 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004136 for (;;)
4137 {
4138 MSG msg;
4139
K.Takatab7057bd2022-01-21 11:37:07 +00004140 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004141 {
4142 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004143 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004144 delay = 1;
4145 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004146 }
4147 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4148 break;
4149
Bram Moolenaar0f873732019-12-05 20:28:46 +01004150 // We start waiting for a very short time and then increase it, so
4151 // that we respond quickly when the process is quick, and don't
4152 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004153 if (delay < 50)
4154 delay += 10;
4155 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004156# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004157 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004158# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004159
Bram Moolenaar0f873732019-12-05 20:28:46 +01004160 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004161 GetExitCodeProcess(pi.hProcess, &ret);
4162 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004163
Bram Moolenaar0f873732019-12-05 20:28:46 +01004164 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004165 CloseHandle(pi.hThread);
4166 CloseHandle(pi.hProcess);
4167
Bram Moolenaar0f873732019-12-05 20:28:46 +01004168 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004169 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4170
4171 return ret;
4172}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004173
4174/*
4175 * Thread launched by the gui to send the current buffer data to the
4176 * process. This way avoid to hang up vim totally if the children
4177 * process take a long time to process the lines.
4178 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004179 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004180sub_process_writer(LPVOID param)
4181{
4182 HANDLE g_hChildStd_IN_Wr = param;
4183 linenr_T lnum = curbuf->b_op_start.lnum;
4184 DWORD len = 0;
4185 DWORD l;
4186 char_u *lp = ml_get(lnum);
4187 char_u *s;
4188 int written = 0;
4189
4190 for (;;)
4191 {
4192 l = (DWORD)STRLEN(lp + written);
4193 if (l == 0)
4194 len = 0;
4195 else if (lp[written] == NL)
4196 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004197 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004198 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4199 }
4200 else
4201 {
4202 s = vim_strchr(lp + written, NL);
4203 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4204 s == NULL ? l : (DWORD)(s - (lp + written)),
4205 &len, NULL);
4206 }
4207 if (len == (int)l)
4208 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004209 // Finished a line, add a NL, unless this line should not have
4210 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004211 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004212 || (!curbuf->b_p_bin
4213 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004214 || (lnum != curbuf->b_no_eol_lnum
4215 && (lnum != curbuf->b_ml.ml_line_count
4216 || curbuf->b_p_eol)))
4217 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004218 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4219 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004220 }
4221
4222 ++lnum;
4223 if (lnum > curbuf->b_op_end.lnum)
4224 break;
4225
4226 lp = ml_get(lnum);
4227 written = 0;
4228 }
4229 else if (len > 0)
4230 written += len;
4231 }
4232
Bram Moolenaar0f873732019-12-05 20:28:46 +01004233 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004234 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004235 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004236}
4237
4238
Bram Moolenaar0f873732019-12-05 20:28:46 +01004239# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004240
4241/*
4242 * This function read from the children's stdout and write the
4243 * data on screen or in the buffer accordingly.
4244 */
4245 static void
4246dump_pipe(int options,
4247 HANDLE g_hChildStd_OUT_Rd,
4248 garray_T *ga,
4249 char_u buffer[],
4250 DWORD *buffer_off)
4251{
4252 DWORD availableBytes = 0;
4253 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004254 int ret;
4255 DWORD len;
4256 DWORD toRead;
4257 int repeatCount;
4258
Bram Moolenaar0f873732019-12-05 20:28:46 +01004259 // we query the pipe to see if there is any data to read
4260 // to avoid to perform a blocking read
4261 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4262 NULL, // optional buffer
4263 0, // buffer size
4264 NULL, // number of read bytes
4265 &availableBytes, // available bytes total
4266 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004267
4268 repeatCount = 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004269 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004270 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004271 {
4272 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004273 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004274 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004275 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004276
Bram Moolenaar0f873732019-12-05 20:28:46 +01004277 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004278 if (len == 0)
4279 break;
4280
4281 availableBytes -= len;
4282
4283 if (options & SHELL_READ)
4284 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004285 // Do NUL -> NL translation, append NL separated
4286 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004287 for (i = 0; i < len; ++i)
4288 {
4289 if (buffer[i] == NL)
4290 append_ga_line(ga);
4291 else if (buffer[i] == NUL)
4292 ga_append(ga, NL);
4293 else
4294 ga_append(ga, buffer[i]);
4295 }
4296 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004297 else if (has_mbyte)
4298 {
4299 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004300 int c;
4301 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004302
4303 len += *buffer_off;
4304 buffer[len] = NUL;
4305
Bram Moolenaar0f873732019-12-05 20:28:46 +01004306 // Check if the last character in buffer[] is
4307 // incomplete, keep these bytes for the next
4308 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004309 for (p = buffer; p < buffer + len; p += l)
4310 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004311 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004312 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004313 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004314 else if (MB_BYTE2LEN(*p) != l)
4315 break;
4316 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004317 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004318 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004319 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004320 if (len >= 12)
4321 ++p;
4322 else
4323 {
4324 *buffer_off = len;
4325 return;
4326 }
4327 }
4328 c = *p;
4329 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004330 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004331 if (p < buffer + len)
4332 {
4333 *p = c;
4334 *buffer_off = (DWORD)((buffer + len) - p);
4335 mch_memmove(buffer, p, *buffer_off);
4336 return;
4337 }
4338 *buffer_off = 0;
4339 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004340 else
4341 {
4342 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004343 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004344 }
4345
4346 windgoto(msg_row, msg_col);
4347 cursor_on();
4348 out_flush();
4349 }
4350}
4351
4352/*
4353 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4354 * for communication and doesn't open any new window.
4355 */
4356 static int
4357mch_system_piped(char *cmd, int options)
4358{
4359 STARTUPINFO si;
4360 PROCESS_INFORMATION pi;
4361 DWORD ret = 0;
4362
4363 HANDLE g_hChildStd_IN_Rd = NULL;
4364 HANDLE g_hChildStd_IN_Wr = NULL;
4365 HANDLE g_hChildStd_OUT_Rd = NULL;
4366 HANDLE g_hChildStd_OUT_Wr = NULL;
4367
Bram Moolenaar0f873732019-12-05 20:28:46 +01004368 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004369 DWORD len;
4370
Bram Moolenaar0f873732019-12-05 20:28:46 +01004371 // buffer used to receive keys
4372 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4373 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004374
4375 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004376 int noread_cnt = 0;
4377 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004378 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004379 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004380 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004381
4382 SECURITY_ATTRIBUTES saAttr;
4383
Bram Moolenaar0f873732019-12-05 20:28:46 +01004384 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004385 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4386 saAttr.bInheritHandle = TRUE;
4387 saAttr.lpSecurityDescriptor = NULL;
4388
4389 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004390 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004391 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004392 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004393 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004394 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004395 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004396 {
4397 CloseHandle(g_hChildStd_IN_Rd);
4398 CloseHandle(g_hChildStd_IN_Wr);
4399 CloseHandle(g_hChildStd_OUT_Rd);
4400 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004401 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004402 }
4403
4404 si.cb = sizeof(si);
4405 si.lpReserved = NULL;
4406 si.lpDesktop = NULL;
4407 si.lpTitle = NULL;
4408 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4409
Bram Moolenaar0f873732019-12-05 20:28:46 +01004410 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004411 si.hStdError = g_hChildStd_OUT_Wr;
4412 si.hStdOutput = g_hChildStd_OUT_Wr;
4413 si.hStdInput = g_hChildStd_IN_Rd;
4414 si.wShowWindow = SW_HIDE;
4415 si.cbReserved2 = 0;
4416 si.lpReserved2 = NULL;
4417
4418 if (options & SHELL_READ)
4419 ga_init2(&ga, 1, BUFLEN);
4420
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004421 if (cmd != NULL)
4422 {
4423 p = (char *)vim_strsave((char_u *)cmd);
4424 if (p != NULL)
4425 unescape_shellxquote((char_u *)p, p_sxe);
4426 else
4427 p = cmd;
4428 }
4429
Bram Moolenaar0f873732019-12-05 20:28:46 +01004430 // Now, run the command.
4431 // About "Inherit handles" being TRUE: this command can be litigious,
4432 // handle inheritance was deactivated for pending temp file, but, if we
4433 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004434 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4435 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004436
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004437 if (p != cmd)
4438 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004439
Bram Moolenaar0f873732019-12-05 20:28:46 +01004440 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004441 CloseHandle(g_hChildStd_IN_Rd);
4442 CloseHandle(g_hChildStd_OUT_Wr);
4443
4444 if (options & SHELL_WRITE)
4445 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004446 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004447 _beginthreadex(NULL, // security attributes
4448 0, // default stack size
4449 sub_process_writer, // function to be executed
4450 g_hChildStd_IN_Wr, // parameter
4451 0, // creation flag, start immediately
4452 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004453 CloseHandle(thread);
4454 g_hChildStd_IN_Wr = NULL;
4455 }
4456
Bram Moolenaar0f873732019-12-05 20:28:46 +01004457 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004458 for (;;)
4459 {
4460 MSG msg;
4461
K.Takatab7057bd2022-01-21 11:37:07 +00004462 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004463 {
4464 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004465 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004466 }
4467
Bram Moolenaar0f873732019-12-05 20:28:46 +01004468 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004469 if ((options & (SHELL_READ|SHELL_WRITE))
4470# ifdef FEAT_GUI
4471 || gui.in_use
4472# endif
4473 )
4474 {
4475 len = 0;
4476 if (!(options & SHELL_EXPAND)
4477 && ((options &
4478 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4479 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4480# ifdef FEAT_GUI
4481 || gui.in_use
4482# endif
4483 )
4484 && (ta_len > 0 || noread_cnt > 4))
4485 {
4486 if (ta_len == 0)
4487 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004488 // Get extra characters when we don't have any. Reset the
4489 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004490 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004491 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4492 }
4493 if (ta_len > 0 || len > 0)
4494 {
4495 /*
4496 * For pipes: Check for CTRL-C: send interrupt signal to
4497 * child. Check for CTRL-D: EOF, close pipe to child.
4498 */
4499 if (len == 1 && cmd != NULL)
4500 {
4501 if (ta_buf[ta_len] == Ctrl_C)
4502 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004503 // Learn what exit code is expected, for
4504 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004505 TerminateProcess(pi.hProcess, 9);
4506 }
4507 if (ta_buf[ta_len] == Ctrl_D)
4508 {
4509 CloseHandle(g_hChildStd_IN_Wr);
4510 g_hChildStd_IN_Wr = NULL;
4511 }
4512 }
4513
Bram Moolenaarf4140482020-02-15 23:06:45 +01004514 term_replace_bs_del_keycode(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004515
4516 /*
4517 * For pipes: echo the typed characters. For a pty this
4518 * does not seem to work.
4519 */
4520 for (i = ta_len; i < ta_len + len; ++i)
4521 {
4522 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4523 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004524 else if (has_mbyte)
4525 {
4526 int l = (*mb_ptr2len)(ta_buf + i);
4527
4528 msg_outtrans_len(ta_buf + i, l);
4529 i += l - 1;
4530 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004531 else
4532 msg_outtrans_len(ta_buf + i, 1);
4533 }
4534 windgoto(msg_row, msg_col);
4535 out_flush();
4536
4537 ta_len += len;
4538
4539 /*
4540 * Write the characters to the child, unless EOF has been
4541 * typed for pipes. Write one character at a time, to
4542 * avoid losing too much typeahead. When writing buffer
4543 * lines, drop the typed characters (only check for
4544 * CTRL-C).
4545 */
4546 if (options & SHELL_WRITE)
4547 ta_len = 0;
4548 else if (g_hChildStd_IN_Wr != NULL)
4549 {
4550 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4551 1, &len, NULL);
4552 // if we are typing in, we want to keep things reactive
4553 delay = 1;
4554 if (len > 0)
4555 {
4556 ta_len -= len;
4557 mch_memmove(ta_buf, ta_buf + len, ta_len);
4558 }
4559 }
4560 }
4561 }
4562 }
4563
4564 if (ta_len)
4565 ui_inchar_undo(ta_buf, ta_len);
4566
4567 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4568 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004569 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004570 break;
4571 }
4572
4573 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004574 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004575
Bram Moolenaar0f873732019-12-05 20:28:46 +01004576 // We start waiting for a very short time and then increase it, so
4577 // that we respond quickly when the process is quick, and don't
4578 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004579 if (delay < 50)
4580 delay += 10;
4581 }
4582
Bram Moolenaar0f873732019-12-05 20:28:46 +01004583 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004584 CloseHandle(g_hChildStd_OUT_Rd);
4585 if (g_hChildStd_IN_Wr != NULL)
4586 CloseHandle(g_hChildStd_IN_Wr);
4587
4588 WaitForSingleObject(pi.hProcess, INFINITE);
4589
Bram Moolenaar0f873732019-12-05 20:28:46 +01004590 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004591 GetExitCodeProcess(pi.hProcess, &ret);
4592
4593 if (options & SHELL_READ)
4594 {
4595 if (ga.ga_len > 0)
4596 {
4597 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01004598 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004599 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4600 }
4601 else
4602 curbuf->b_no_eol_lnum = 0;
4603 ga_clear(&ga);
4604 }
4605
Bram Moolenaar0f873732019-12-05 20:28:46 +01004606 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004607 CloseHandle(pi.hThread);
4608 CloseHandle(pi.hProcess);
4609
4610 return ret;
4611}
4612
4613 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004614mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004615{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004616 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004617 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004618 return mch_system_piped(cmd, options);
4619 else
4620 return mch_system_classic(cmd, options);
4621}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004622#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004623
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004624#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004625 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02004626mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004627{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004628 int ret;
4629 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004630 char_u *buf;
4631 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004632
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004633 // If the command starts and ends with double quotes, enclose the command
4634 // in parentheses.
4635 len = STRLEN(cmd);
4636 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
4637 {
4638 len += 3;
4639 buf = alloc(len);
4640 if (buf == NULL)
4641 return -1;
4642 vim_snprintf((char *)buf, len, "(%s)", cmd);
4643 wcmd = enc_to_utf16(buf, NULL);
4644 free(buf);
4645 }
4646 else
4647 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4648
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004649 if (wcmd == NULL)
4650 return -1;
4651
4652 ret = _wsystem(wcmd);
4653 vim_free(wcmd);
4654 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004655}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004656
4657#endif
4658
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004659 static int
4660mch_system(char *cmd, int options)
4661{
4662#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004663 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004664 return mch_system_g(cmd, options);
4665 else
4666 return mch_system_c(cmd, options);
4667#elif defined(FEAT_GUI_MSWIN)
4668 return mch_system_g(cmd, options);
4669#else
4670 return mch_system_c(cmd, options);
4671#endif
4672}
4673
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004674#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4675/*
4676 * Use a terminal window to run a shell command in.
4677 */
4678 static int
4679mch_call_shell_terminal(
4680 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004681 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004682{
4683 jobopt_T opt;
4684 char_u *newcmd = NULL;
4685 typval_T argvar[2];
4686 long_u cmdlen;
4687 int retval = -1;
4688 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004689 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004690 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004691 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004692
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004693 if (cmd == NULL)
4694 cmdlen = STRLEN(p_sh) + 1;
4695 else
4696 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004697 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004698 if (newcmd == NULL)
4699 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004700 if (cmd == NULL)
4701 {
4702 STRCPY(newcmd, p_sh);
4703 ch_log(NULL, "starting terminal to run a shell");
4704 }
4705 else
4706 {
4707 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4708 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4709 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004710
4711 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004712
4713 argvar[0].v_type = VAR_STRING;
4714 argvar[0].vval.v_string = newcmd;
4715 argvar[1].v_type = VAR_UNKNOWN;
4716 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004717 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004718 {
4719 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004720 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004721 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004722
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004723 job = term_getjob(buf->b_term);
4724 ++job->jv_refcount;
4725
Bram Moolenaar0f873732019-12-05 20:28:46 +01004726 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004727 aucmd_prepbuf(&aco, buf);
4728
4729 clear_oparg(&oa);
4730 while (term_use_loop())
4731 {
4732 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4733 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004734 // If terminal_loop() returns OK we got a key that is handled
4735 // in Normal model. We don't do redrawing anyway.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004736 if (terminal_loop(TRUE) == OK)
4737 normal_cmd(&oa, TRUE);
4738 }
4739 else
4740 normal_cmd(&oa, TRUE);
4741 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004742 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004743 ch_log(NULL, "system command finished");
4744
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004745 job_unref(job);
4746
Bram Moolenaar0f873732019-12-05 20:28:46 +01004747 // restore curwin/curbuf and a few other things
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004748 aucmd_restbuf(&aco);
4749
4750 wait_return(TRUE);
4751 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4752
4753 vim_free(newcmd);
4754 return retval;
4755}
4756#endif
4757
Bram Moolenaar071d4272004-06-13 20:20:40 +00004758/*
4759 * Either execute a command by calling the shell or start a new shell
4760 */
4761 int
4762mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004763 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004764 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00004765{
4766 int x = 0;
4767 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004768 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004769
Bram Moolenaar0f873732019-12-05 20:28:46 +01004770 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02004771 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004772 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004773 if (cmd == NULL)
4774 wcscat(szShellTitle, L" :sh");
4775 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004776 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004777 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004778
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004779 if (wn != NULL)
4780 {
4781 wcscat(szShellTitle, L" - !");
4782 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02004783 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004784 wcscat(szShellTitle, wn);
4785 SetConsoleTitleW(szShellTitle);
4786 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004787 }
4788 }
4789 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004790
4791 out_flush();
4792
4793#ifdef MCH_WRITE_DUMP
4794 if (fdDump)
4795 {
4796 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4797 fflush(fdDump);
4798 }
4799#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004800#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004801 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004802 if (
4803# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004804 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004805# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004806 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004807 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4808 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004809 char_u *cmdbase = cmd;
4810
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004811 if (cmdbase != NULL)
4812 // Skip a leading quote and (.
4813 while (*cmdbase == '"' || *cmdbase == '(')
4814 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004815
4816 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01004817 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
4818 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004819 {
4820 // Use a terminal window to run the command in.
4821 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004822 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004823 return x;
4824 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004825 }
4826#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004827
4828 /*
4829 * Catch all deadly signals while running the external command, because a
4830 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4831 */
4832 signal(SIGINT, SIG_IGN);
4833#if defined(__GNUC__) && !defined(__MINGW32__)
4834 signal(SIGKILL, SIG_IGN);
4835#else
4836 signal(SIGBREAK, SIG_IGN);
4837#endif
4838 signal(SIGILL, SIG_IGN);
4839 signal(SIGFPE, SIG_IGN);
4840 signal(SIGSEGV, SIG_IGN);
4841 signal(SIGTERM, SIG_IGN);
4842 signal(SIGABRT, SIG_IGN);
4843
4844 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004845 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00004846
4847 if (cmd == NULL)
4848 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004849 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004850 }
4851 else
4852 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004853 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004854 char_u *newcmd = NULL;
4855 char_u *cmdbase = cmd;
4856 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004857
Bram Moolenaar0f873732019-12-05 20:28:46 +01004858 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004859 if (*cmdbase == '"' )
4860 ++cmdbase;
4861 if (*cmdbase == '(')
4862 ++cmdbase;
4863
Bram Moolenaar1c465442017-03-12 20:10:05 +01004864 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004865 {
4866 STARTUPINFO si;
4867 PROCESS_INFORMATION pi;
4868 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004869 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004870 char_u *p;
4871
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004872 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004873 si.cb = sizeof(si);
4874 si.lpReserved = NULL;
4875 si.lpDesktop = NULL;
4876 si.lpTitle = NULL;
4877 si.dwFlags = 0;
4878 si.cbReserved2 = 0;
4879 si.lpReserved2 = NULL;
4880
4881 cmdbase = skipwhite(cmdbase + 5);
4882 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004883 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004884 {
4885 cmdbase = skipwhite(cmdbase + 4);
4886 si.dwFlags = STARTF_USESHOWWINDOW;
4887 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004888 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004889 }
4890 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004891 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004892 {
4893 cmdbase = skipwhite(cmdbase + 2);
4894 flags = CREATE_NO_WINDOW;
4895 si.dwFlags = STARTF_USESTDHANDLES;
4896 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004897 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004898 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004899 NULL, // Security att.
4900 OPEN_EXISTING, // Open flags
4901 FILE_ATTRIBUTE_NORMAL, // File att.
4902 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004903 si.hStdOutput = si.hStdInput;
4904 si.hStdError = si.hStdInput;
4905 }
4906
Bram Moolenaar0f873732019-12-05 20:28:46 +01004907 // Remove a trailing ", ) and )" if they have a match
4908 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004909 if (cmdbase > cmd)
4910 {
4911 p = cmdbase + STRLEN(cmdbase);
4912 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4913 *--p = NUL;
4914 if (p > cmdbase && p[-1] == ')'
4915 && (*cmd =='(' || cmd[1] == '('))
4916 *--p = NUL;
4917 }
4918
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004919 newcmd = cmdbase;
4920 unescape_shellxquote(cmdbase, p_sxe);
4921
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004922 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004923 * If creating new console, arguments are passed to the
4924 * 'cmd.exe' as-is. If it's not, arguments are not treated
4925 * correctly for current 'cmd.exe'. So unescape characters in
4926 * shellxescape except '|' for avoiding to be treated as
4927 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004928 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004929 if (flags != CREATE_NEW_CONSOLE)
4930 {
4931 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004932 char_u *cmd_shell = mch_getenv("COMSPEC");
4933
4934 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004935 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004936
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004937 subcmd = vim_strsave_escaped_ext(cmdbase,
4938 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004939 if (subcmd != NULL)
4940 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004941 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004942 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004943 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004944 if (newcmd != NULL)
4945 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004946 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004947 else
4948 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004949 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004950 }
4951 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004952
4953 /*
4954 * Now, start the command as a process, so that it doesn't
4955 * inherit our handles which causes unpleasant dangling swap
4956 * files if we exit before the spawned process
4957 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004958 if (vim_create_process((char *)newcmd, FALSE, flags,
4959 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004960 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004961 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4962 > (HINSTANCE)32)
4963 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004964 else
4965 {
4966 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01004967#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004968# ifdef VIMDLL
4969 if (gui.in_use)
4970# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00004971 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004972#endif
4973 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004974
4975 if (newcmd != cmdbase)
4976 vim_free(newcmd);
4977
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004978 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004979 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004980 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004981 CloseHandle(si.hStdInput);
4982 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004983 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004984 CloseHandle(pi.hThread);
4985 CloseHandle(pi.hProcess);
4986 }
4987 else
4988 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004989 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01004990#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004991 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004992 (!s_dont_use_vimrun && p_stmp ?
4993 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
4994 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004995#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004996 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004997
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004998 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004999 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005000 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005001#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005002 if (
5003# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005004 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005005# endif
5006 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005007 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005008 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5009 "External commands will not pause after completion.\n"
5010 "See :help win32-vimrun for more information.");
5011 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005012 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5013 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005014
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005015 if (wmsg != NULL && wtitle != NULL)
5016 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5017 vim_free(wmsg);
5018 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005019 need_vimrun_warning = FALSE;
5020 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005021 if (
5022# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005023 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005024# endif
5025 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005026 // Use vimrun to execute the command. It opens a console
5027 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005028 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005029 vimrun_path,
5030 (msg_silent != 0 || (options & SHELL_DOOUT))
5031 ? "-s " : "",
5032 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005033 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005034# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005035 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005036# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005037 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005038 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005039 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5040 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005041 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005042#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005043 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005044 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005045 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005046 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005047 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005048 }
5049 }
5050
5051 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005052 {
5053 // The shell may have messed with the mode, always set it.
5054 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005055 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005056 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005057
Bram Moolenaar0f873732019-12-05 20:28:46 +01005058 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005059 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005060#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005061 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005062 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005063#endif
5064 )
5065 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005066 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005067 msg_putchar('\n');
5068 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005069 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005070
5071 signal(SIGINT, SIG_DFL);
5072#if defined(__GNUC__) && !defined(__MINGW32__)
5073 signal(SIGKILL, SIG_DFL);
5074#else
5075 signal(SIGBREAK, SIG_DFL);
5076#endif
5077 signal(SIGILL, SIG_DFL);
5078 signal(SIGFPE, SIG_DFL);
5079 signal(SIGSEGV, SIG_DFL);
5080 signal(SIGTERM, SIG_DFL);
5081 signal(SIGABRT, SIG_DFL);
5082
5083 return x;
5084}
5085
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005086#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005087 static HANDLE
5088job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005089 char_u *fname,
5090 DWORD dwDesiredAccess,
5091 DWORD dwShareMode,
5092 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5093 DWORD dwCreationDisposition,
5094 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005095{
5096 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005097 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005098
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005099 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005100 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005101 return INVALID_HANDLE_VALUE;
5102
5103 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5104 lpSecurityAttributes, dwCreationDisposition,
5105 dwFlagsAndAttributes, NULL);
5106 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005107 return h;
5108}
5109
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005110/*
5111 * Turn the dictionary "env" into a NUL separated list that can be used as the
5112 * environment argument of vim_create_process().
5113 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005114 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005115win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005116{
5117 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005118 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005119 LPVOID base = GetEnvironmentStringsW();
5120
Bram Moolenaar0f873732019-12-05 20:28:46 +01005121 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005122 if (ga_grow(gap, 1) == FAIL)
5123 return;
5124
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005125 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005126 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005127 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005128 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005129 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005130 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005131 typval_T *item = &dict_lookup(hi)->di_tv;
5132 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005133 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005134 --todo;
5135 if (wkey != NULL && wval != NULL)
5136 {
5137 size_t n;
5138 size_t lkey = wcslen(wkey);
5139 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005140
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005141 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5142 continue;
5143 for (n = 0; n < lkey; n++)
5144 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5145 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5146 for (n = 0; n < lval; n++)
5147 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5148 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5149 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005150 vim_free(wkey);
5151 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005152 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005153 }
5154 }
5155
Bram Moolenaar355757a2020-02-10 22:06:32 +01005156 if (base)
5157 {
5158 WCHAR *p = (WCHAR*) base;
5159
5160 // for last \0
5161 if (ga_grow(gap, 1) == FAIL)
5162 return;
5163
5164 while (*p != 0 || *(p + 1) != 0)
5165 {
5166 if (ga_grow(gap, 1) == OK)
5167 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5168 p++;
5169 }
5170 FreeEnvironmentStrings(base);
5171 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5172 }
5173
Bram Moolenaar493359e2018-06-12 20:25:52 +02005174# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005175 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005176# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005177 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005178 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005179# endif
5180# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005181 char_u *version = get_vim_var_str(VV_VERSION);
5182 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005183# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005184 // size of "VIM_SERVERNAME=" and value,
5185 // plus "VIM_TERMINAL=" and value,
5186 // plus two terminating NULs
5187 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005188# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005189 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005190# endif
5191# ifdef FEAT_TERMINAL
5192 + 13 + version_len + 2
5193# endif
5194 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005195
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005196 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005197 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005198# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005199 for (n = 0; n < 15; n++)
5200 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5201 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005202 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005203 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5204 (WCHAR)servername[n];
5205 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005206# endif
5207# ifdef FEAT_TERMINAL
5208 if (is_terminal)
5209 {
5210 for (n = 0; n < 13; n++)
5211 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5212 (WCHAR)"VIM_TERMINAL="[n];
5213 for (n = 0; n < version_len; n++)
5214 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5215 (WCHAR)version[n];
5216 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5217 }
5218# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005219 }
5220 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005221# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005222}
5223
Bram Moolenaarb091f302019-01-19 14:37:00 +01005224/*
5225 * Create a pair of pipes.
5226 * Return TRUE for success, FALSE for failure.
5227 */
5228 static BOOL
5229create_pipe_pair(HANDLE handles[2])
5230{
5231 static LONG s;
5232 char name[64];
5233 SECURITY_ATTRIBUTES sa;
5234
5235 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5236 GetCurrentProcessId(),
5237 InterlockedIncrement(&s));
5238
5239 // Create named pipe. Max size of named pipe is 65535.
5240 handles[1] = CreateNamedPipe(
5241 name,
5242 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5243 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005244 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005245
5246 if (handles[1] == INVALID_HANDLE_VALUE)
5247 return FALSE;
5248
5249 sa.nLength = sizeof(sa);
5250 sa.bInheritHandle = TRUE;
5251 sa.lpSecurityDescriptor = NULL;
5252
5253 handles[0] = CreateFile(name,
5254 FILE_GENERIC_READ,
5255 FILE_SHARE_READ, &sa,
5256 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5257
5258 if (handles[0] == INVALID_HANDLE_VALUE)
5259 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005260 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005261 return FALSE;
5262 }
5263
5264 return TRUE;
5265}
5266
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005267 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005268mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005269{
5270 STARTUPINFO si;
5271 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005272 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005273 SECURITY_ATTRIBUTES saAttr;
5274 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005275 HANDLE ifd[2];
5276 HANDLE ofd[2];
5277 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005278 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005279
5280 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5281 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5282 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5283 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5284 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5285 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5286 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5287
5288 if (use_out_for_err && use_null_for_out)
5289 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005290
5291 ifd[0] = INVALID_HANDLE_VALUE;
5292 ifd[1] = INVALID_HANDLE_VALUE;
5293 ofd[0] = INVALID_HANDLE_VALUE;
5294 ofd[1] = INVALID_HANDLE_VALUE;
5295 efd[0] = INVALID_HANDLE_VALUE;
5296 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005297 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005298
Bram Moolenaar14207f42016-10-27 21:13:10 +02005299 jo = CreateJobObject(NULL, NULL);
5300 if (jo == NULL)
5301 {
5302 job->jv_status = JOB_FAILED;
5303 goto failed;
5304 }
5305
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005306 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005307 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005308
Bram Moolenaar76467df2016-02-12 19:30:26 +01005309 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005310 ZeroMemory(&si, sizeof(si));
5311 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005312 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005313 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005314
Bram Moolenaard8070362016-02-15 21:56:54 +01005315 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5316 saAttr.bInheritHandle = TRUE;
5317 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005318
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005319 if (use_file_for_in)
5320 {
5321 char_u *fname = options->jo_io_name[PART_IN];
5322
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005323 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5324 FILE_SHARE_READ | FILE_SHARE_WRITE,
5325 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5326 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005327 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005328 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005329 goto failed;
5330 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005331 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005332 else if (!use_null_for_in
5333 && (!create_pipe_pair(ifd)
5334 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005335 goto failed;
5336
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005337 if (use_file_for_out)
5338 {
5339 char_u *fname = options->jo_io_name[PART_OUT];
5340
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005341 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5342 FILE_SHARE_READ | FILE_SHARE_WRITE,
5343 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5344 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005345 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005346 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005347 goto failed;
5348 }
5349 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005350 else if (!use_null_for_out &&
5351 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005352 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005353 goto failed;
5354
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005355 if (use_file_for_err)
5356 {
5357 char_u *fname = options->jo_io_name[PART_ERR];
5358
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005359 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5360 FILE_SHARE_READ | FILE_SHARE_WRITE,
5361 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5362 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005363 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005364 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005365 goto failed;
5366 }
5367 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005368 else if (!use_out_for_err && !use_null_for_err &&
5369 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005370 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005371 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005372
Bram Moolenaard8070362016-02-15 21:56:54 +01005373 si.dwFlags |= STARTF_USESTDHANDLES;
5374 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005375 si.hStdOutput = ofd[1];
5376 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5377
5378 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5379 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005380 if (options->jo_set & JO_CHANNEL)
5381 {
5382 channel = options->jo_channel;
5383 if (channel != NULL)
5384 ++channel->ch_refcount;
5385 }
5386 else
5387 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005388 if (channel == NULL)
5389 goto failed;
5390 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005391
5392 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005393 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005394 CREATE_DEFAULT_ERROR_MODE |
5395 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005396 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005397 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005398 &si, &pi,
5399 ga.ga_data,
5400 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005401 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005402 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005403 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005404 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005405 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005406
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005407 ga_clear(&ga);
5408
Bram Moolenaar14207f42016-10-27 21:13:10 +02005409 if (!AssignProcessToJobObject(jo, pi.hProcess))
5410 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005411 // if failing, switch the way to terminate
5412 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005413 CloseHandle(jo);
5414 jo = NULL;
5415 }
5416 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005417 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005418 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005419 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005420 job->jv_status = JOB_STARTED;
5421
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005422 CloseHandle(ifd[0]);
5423 CloseHandle(ofd[1]);
5424 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005425 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005426
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005427 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005428 if (channel != NULL)
5429 {
5430 channel_set_pipes(channel,
5431 use_file_for_in || use_null_for_in
5432 ? INVALID_FD : (sock_T)ifd[1],
5433 use_file_for_out || use_null_for_out
5434 ? INVALID_FD : (sock_T)ofd[0],
5435 use_out_for_err || use_file_for_err || use_null_for_err
5436 ? INVALID_FD : (sock_T)efd[0]);
5437 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005438 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005439 return;
5440
5441failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005442 CloseHandle(ifd[0]);
5443 CloseHandle(ofd[0]);
5444 CloseHandle(efd[0]);
5445 CloseHandle(ifd[1]);
5446 CloseHandle(ofd[1]);
5447 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005448 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005449 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005450}
5451
5452 char *
5453mch_job_status(job_T *job)
5454{
5455 DWORD dwExitCode = 0;
5456
Bram Moolenaar76467df2016-02-12 19:30:26 +01005457 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5458 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005459 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005460 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005461 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005462 {
5463 ch_log(job->jv_channel, "Job ended");
5464 job->jv_status = JOB_ENDED;
5465 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005466 return "dead";
5467 }
5468 return "run";
5469}
5470
Bram Moolenaar97792de2016-10-15 18:36:49 +02005471 job_T *
5472mch_detect_ended_job(job_T *job_list)
5473{
5474 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5475 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5476 job_T *job = job_list;
5477
5478 while (job != NULL)
5479 {
5480 DWORD n;
5481 DWORD result;
5482
5483 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5484 && job != NULL; job = job->jv_next)
5485 {
5486 if (job->jv_status == JOB_STARTED)
5487 {
5488 jobHandles[n] = job->jv_proc_info.hProcess;
5489 jobArray[n] = job;
5490 ++n;
5491 }
5492 }
5493 if (n == 0)
5494 continue;
5495 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5496 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5497 {
5498 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5499
5500 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5501 return wait_job;
5502 }
5503 }
5504 return NULL;
5505}
5506
Bram Moolenaarfb630902016-10-29 14:55:00 +02005507 static BOOL
5508terminate_all(HANDLE process, int code)
5509{
5510 PROCESSENTRY32 pe;
5511 HANDLE h = INVALID_HANDLE_VALUE;
5512 DWORD pid = GetProcessId(process);
5513
5514 if (pid != 0)
5515 {
5516 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5517 if (h != INVALID_HANDLE_VALUE)
5518 {
5519 pe.dwSize = sizeof(PROCESSENTRY32);
5520 if (!Process32First(h, &pe))
5521 goto theend;
5522
5523 do
5524 {
5525 if (pe.th32ParentProcessID == pid)
5526 {
5527 HANDLE ph = OpenProcess(
5528 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5529 if (ph != NULL)
5530 {
5531 terminate_all(ph, code);
5532 CloseHandle(ph);
5533 }
5534 }
5535 } while (Process32Next(h, &pe));
5536
5537 CloseHandle(h);
5538 }
5539 }
5540
5541theend:
5542 return TerminateProcess(process, code);
5543}
5544
5545/*
5546 * Send a (deadly) signal to "job".
5547 * Return FAIL if it didn't work.
5548 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005549 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005550mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005551{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005552 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005553
Bram Moolenaar923d9262016-02-25 20:56:01 +01005554 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005555 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005556 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02005557 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005558 {
5559 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5560 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00005561 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005562 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01005563 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005564 }
5565
5566 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5567 return FAIL;
5568 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005569 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5570 job->jv_proc_info.dwProcessId)
5571 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005572 FreeConsole();
5573 return ret;
5574}
5575
5576/*
5577 * Clear the data related to "job".
5578 */
5579 void
5580mch_clear_job(job_T *job)
5581{
5582 if (job->jv_status != JOB_FAILED)
5583 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005584 if (job->jv_job_object != NULL)
5585 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005586 CloseHandle(job->jv_proc_info.hProcess);
5587 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005588}
5589#endif
5590
Bram Moolenaar071d4272004-06-13 20:20:40 +00005591
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005592#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005593
5594/*
5595 * Start termcap mode
5596 */
5597 static void
5598termcap_mode_start(void)
5599{
5600 DWORD cmodein;
5601
5602 if (g_fTermcapMode)
5603 return;
5604
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005605 if (!p_rs && USE_VTP)
5606 vtp_printf("\033[?1049h");
5607
Bram Moolenaar071d4272004-06-13 20:20:40 +00005608 SaveConsoleBuffer(&g_cbNonTermcap);
5609
5610 if (g_cbTermcap.IsValid)
5611 {
5612 /*
5613 * We've been in termcap mode before. Restore certain screen
5614 * characteristics, including the buffer size and the window
5615 * size. Since we will be redrawing the screen, we don't need
5616 * to restore the actual contents of the buffer.
5617 */
5618 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005619 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005620 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5621 Rows = g_cbTermcap.Info.dwSize.Y;
5622 Columns = g_cbTermcap.Info.dwSize.X;
5623 }
5624 else
5625 {
5626 /*
5627 * This is our first time entering termcap mode. Clear the console
5628 * screen buffer, and resize the buffer to match the current window
5629 * size. We will use this as the size of our editing environment.
5630 */
5631 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005632 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005633 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5634 }
5635
Bram Moolenaar071d4272004-06-13 20:20:40 +00005636 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005637
5638 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005639 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005640 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005641 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005642 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
5643 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005644 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005645 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005646 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005647 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5648 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005649 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005650 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005651
5652 redraw_later_clear();
5653 g_fTermcapMode = TRUE;
5654}
5655
5656
5657/*
5658 * End termcap mode
5659 */
5660 static void
5661termcap_mode_end(void)
5662{
5663 DWORD cmodein;
5664 ConsoleBuffer *cb;
5665 COORD coord;
5666 DWORD dwDummy;
5667
5668 if (!g_fTermcapMode)
5669 return;
5670
5671 SaveConsoleBuffer(&g_cbTermcap);
5672
5673 GetConsoleMode(g_hConIn, &cmodein);
5674 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005675 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5676 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005677
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005678# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005679 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005680# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005681 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005682# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005683 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01005684 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005685 SetConsoleCursorInfo(g_hConOut, &g_cci);
5686
5687 if (p_rs || exiting)
5688 {
5689 /*
5690 * Clear anything that happens to be on the current line.
5691 */
5692 coord.X = 0;
5693 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5694 FillConsoleOutputCharacter(g_hConOut, ' ',
5695 cb->Info.dwSize.X, coord, &dwDummy);
5696 /*
5697 * The following is just for aesthetics. If we are exiting without
5698 * restoring the screen, then we want to have a prompt string
5699 * appear at the bottom line. However, the command interpreter
5700 * seems to always advance the cursor one line before displaying
5701 * the prompt string, which causes the screen to scroll. To
5702 * counter this, move the cursor up one line before exiting.
5703 */
5704 if (exiting && !p_rs)
5705 coord.Y--;
5706 /*
5707 * Position the cursor at the leftmost column of the desired row.
5708 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005709 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005710 }
5711
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005712 if (!p_rs && USE_VTP)
Bram Moolenaar0afdcf82020-04-01 18:29:10 +02005713 vtp_printf("\033[?1049l");
5714
Bram Moolenaar071d4272004-06-13 20:20:40 +00005715 g_fTermcapMode = FALSE;
5716}
Bram Moolenaar0f873732019-12-05 20:28:46 +01005717#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005718
5719
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005720#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005721 void
5722mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005723 char_u *s UNUSED,
5724 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005725{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005726 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00005727}
5728
5729#else
5730
5731/*
5732 * clear `n' chars, starting from `coord'
5733 */
5734 static void
5735clear_chars(
5736 COORD coord,
5737 DWORD n)
5738{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005739 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02005740 {
5741 DWORD dwDummy;
5742
5743 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5744 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
5745 &dwDummy);
5746 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005747 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005748 {
5749 set_console_color_rgb();
5750 gotoxy(coord.X + 1, coord.Y + 1);
5751 vtp_printf("\033[%dX", n);
5752 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005753}
5754
5755
5756/*
5757 * Clear the screen
5758 */
5759 static void
5760clear_screen(void)
5761{
5762 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005763
5764 if (!USE_VTP)
5765 clear_chars(g_coord, Rows * Columns);
5766 else
5767 {
5768 set_console_color_rgb();
5769 gotoxy(1, 1);
5770 vtp_printf("\033[2J");
5771 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005772}
5773
5774
5775/*
5776 * Clear to end of display
5777 */
5778 static void
5779clear_to_end_of_display(void)
5780{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005781 COORD save = g_coord;
5782
5783 if (!USE_VTP)
5784 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005785 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005786 else
5787 {
5788 set_console_color_rgb();
5789 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5790 vtp_printf("\033[0J");
5791
5792 gotoxy(save.X + 1, save.Y + 1);
5793 g_coord = save;
5794 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005795}
5796
5797
5798/*
5799 * Clear to end of line
5800 */
5801 static void
5802clear_to_end_of_line(void)
5803{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005804 COORD save = g_coord;
5805
5806 if (!USE_VTP)
5807 clear_chars(g_coord, Columns - g_coord.X);
5808 else
5809 {
5810 set_console_color_rgb();
5811 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5812 vtp_printf("\033[0K");
5813
5814 gotoxy(save.X + 1, save.Y + 1);
5815 g_coord = save;
5816 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005817}
5818
5819
5820/*
5821 * Scroll the scroll region up by `cLines' lines
5822 */
5823 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005824scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005825{
5826 COORD oldcoord = g_coord;
5827
5828 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5829 delete_lines(cLines);
5830
5831 g_coord = oldcoord;
5832}
5833
5834
5835/*
5836 * Set the scroll region
5837 */
5838 static void
5839set_scroll_region(
5840 unsigned left,
5841 unsigned top,
5842 unsigned right,
5843 unsigned bottom)
5844{
5845 if (left >= right
5846 || top >= bottom
5847 || right > (unsigned) Columns - 1
5848 || bottom > (unsigned) Rows - 1)
5849 return;
5850
5851 g_srScrollRegion.Left = left;
5852 g_srScrollRegion.Top = top;
5853 g_srScrollRegion.Right = right;
5854 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005855}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005856
Bram Moolenaar6982f422019-02-16 16:48:01 +01005857 static void
5858set_scroll_region_tb(
5859 unsigned top,
5860 unsigned bottom)
5861{
5862 if (top >= bottom || bottom > (unsigned)Rows - 1)
5863 return;
5864
5865 g_srScrollRegion.Top = top;
5866 g_srScrollRegion.Bottom = bottom;
5867}
5868
5869 static void
5870set_scroll_region_lr(
5871 unsigned left,
5872 unsigned right)
5873{
5874 if (left >= right || right > (unsigned)Columns - 1)
5875 return;
5876
5877 g_srScrollRegion.Left = left;
5878 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005879}
5880
5881
5882/*
5883 * Insert `cLines' lines at the current cursor position
5884 */
5885 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005886insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005887{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005888 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005889 COORD dest;
5890 CHAR_INFO fill;
5891
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005892 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5893
Bram Moolenaar6982f422019-02-16 16:48:01 +01005894 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005895 dest.Y = g_coord.Y + cLines;
5896
Bram Moolenaar6982f422019-02-16 16:48:01 +01005897 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005898 source.Top = g_coord.Y;
5899 source.Right = g_srScrollRegion.Right;
5900 source.Bottom = g_srScrollRegion.Bottom - cLines;
5901
Bram Moolenaar6982f422019-02-16 16:48:01 +01005902 clip.Left = g_srScrollRegion.Left;
5903 clip.Top = g_coord.Y;
5904 clip.Right = g_srScrollRegion.Right;
5905 clip.Bottom = g_srScrollRegion.Bottom;
5906
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005907 fill.Char.AsciiChar = ' ';
5908 if (!USE_VTP)
5909 fill.Attributes = g_attrCurrent;
5910 else
5911 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005912
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005913 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005914
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005915 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5916
Bram Moolenaar6982f422019-02-16 16:48:01 +01005917 // Here we have to deal with a win32 console flake: If the scroll
5918 // region looks like abc and we scroll c to a and fill with d we get
5919 // cbd... if we scroll block c one line at a time to a, we get cdd...
5920 // vim expects cdd consistently... So we have to deal with that
5921 // here... (this also occurs scrolling the same way in the other
5922 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005923
5924 if (source.Bottom < dest.Y)
5925 {
5926 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005927 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005928
Bram Moolenaar6982f422019-02-16 16:48:01 +01005929 coord.X = source.Left;
5930 for (i = clip.Top; i < dest.Y; ++i)
5931 {
5932 coord.Y = i;
5933 clear_chars(coord, source.Right - source.Left + 1);
5934 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005935 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02005936
5937 if (USE_WT)
5938 {
5939 COORD coord;
5940 int i;
5941
5942 coord.X = source.Left;
5943 for (i = source.Top; i < dest.Y; ++i)
5944 {
5945 coord.Y = i;
5946 clear_chars(coord, source.Right - source.Left + 1);
5947 }
5948 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005949}
5950
5951
5952/*
5953 * Delete `cLines' lines at the current cursor position
5954 */
5955 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005956delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005957{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005958 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005959 COORD dest;
5960 CHAR_INFO fill;
5961 int nb;
5962
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005963 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5964
Bram Moolenaar6982f422019-02-16 16:48:01 +01005965 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005966 dest.Y = g_coord.Y;
5967
Bram Moolenaar6982f422019-02-16 16:48:01 +01005968 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005969 source.Top = g_coord.Y + cLines;
5970 source.Right = g_srScrollRegion.Right;
5971 source.Bottom = g_srScrollRegion.Bottom;
5972
Bram Moolenaar6982f422019-02-16 16:48:01 +01005973 clip.Left = g_srScrollRegion.Left;
5974 clip.Top = g_coord.Y;
5975 clip.Right = g_srScrollRegion.Right;
5976 clip.Bottom = g_srScrollRegion.Bottom;
5977
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005978 fill.Char.AsciiChar = ' ';
5979 if (!USE_VTP)
5980 fill.Attributes = g_attrCurrent;
5981 else
5982 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005983
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005984 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005985
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005986 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5987
Bram Moolenaar6982f422019-02-16 16:48:01 +01005988 // Here we have to deal with a win32 console flake; See insert_lines()
5989 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005990
5991 nb = dest.Y + (source.Bottom - source.Top) + 1;
5992
5993 if (nb < source.Top)
5994 {
5995 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005996 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005997
Bram Moolenaar6982f422019-02-16 16:48:01 +01005998 coord.X = source.Left;
5999 for (i = nb; i < clip.Bottom; ++i)
6000 {
6001 coord.Y = i;
6002 clear_chars(coord, source.Right - source.Left + 1);
6003 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006004 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006005
6006 if (USE_WT)
6007 {
6008 COORD coord;
6009 int i;
6010
6011 coord.X = source.Left;
6012 for (i = nb; i <= source.Bottom; ++i)
6013 {
6014 coord.Y = i;
6015 clear_chars(coord, source.Right - source.Left + 1);
6016 }
6017 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006018}
6019
6020
6021/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006022 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006023 */
6024 static void
6025gotoxy(
6026 unsigned x,
6027 unsigned y)
6028{
6029 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6030 return;
6031
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006032 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006033 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006034 // There are reports of double-width characters not displayed
6035 // correctly. This workaround should fix it, similar to how it's done
6036 // for VTP.
6037 g_coord.X = 0;
6038 SetConsoleCursorPosition(g_hConOut, g_coord);
6039
Bram Moolenaar2313b612019-09-27 14:14:32 +02006040 // external cursor coords are 1-based; internal are 0-based
6041 g_coord.X = x - 1;
6042 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006043 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006044 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006045 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006046 {
6047 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006048 // destruction. Insider build bug. Always enabled because it's cheap
6049 // and avoids mistakes with recognizing the build.
6050 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006051
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006052 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006053
6054 g_coord.X = x - 1;
6055 g_coord.Y = y - 1;
6056 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006057}
6058
6059
6060/*
6061 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006062 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006063 */
6064 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006065textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006066{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006067 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006068
6069 SetConsoleTextAttribute(g_hConOut, wAttr);
6070}
6071
6072
6073 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006074textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006075{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006076 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006077
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006078 if (!USE_VTP)
6079 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6080 else
6081 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006082}
6083
6084
6085 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006086textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006087{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006088 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006089
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006090 if (!USE_VTP)
6091 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6092 else
6093 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006094}
6095
6096
6097/*
6098 * restore the default text attribute (whatever we started with)
6099 */
6100 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006101normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006102{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006103 if (!USE_VTP)
6104 textattr(g_attrDefault);
6105 else
6106 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006107}
6108
6109
6110static WORD g_attrPreStandout = 0;
6111
6112/*
6113 * Make the text standout, by brightening it
6114 */
6115 static void
6116standout(void)
6117{
6118 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006119
Bram Moolenaar071d4272004-06-13 20:20:40 +00006120 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6121}
6122
6123
6124/*
6125 * Turn off standout mode
6126 */
6127 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006128standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006129{
6130 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006131 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006132
6133 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006134}
6135
6136
6137/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006138 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006139 */
6140 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006141mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006142{
6143 char_u *p;
6144 int n;
6145
6146 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6147 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006148 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006149# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006150 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006151# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006152 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006153 {
6154 p = T_ME + 2;
6155 n = getdigits(&p);
6156 if (*p == 'm' && n > 0)
6157 {
6158 cterm_normal_fg_color = (n & 0xf) + 1;
6159 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6160 }
6161 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006162# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006163 cterm_normal_fg_gui_color = INVALCOLOR;
6164 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006165# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006166}
6167
6168
6169/*
6170 * visual bell: flash the screen
6171 */
6172 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006173visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006174{
6175 COORD coordOrigin = {0, 0};
6176 WORD attrFlash = ~g_attrCurrent & 0xff;
6177
6178 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006179 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006180
6181 if (oldattrs == NULL)
6182 return;
6183 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6184 coordOrigin, &dwDummy);
6185 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6186 coordOrigin, &dwDummy);
6187
Bram Moolenaar0f873732019-12-05 20:28:46 +01006188 Sleep(15); // wait for 15 msec
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006189 if (!USE_VTP)
6190 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006191 coordOrigin, &dwDummy);
6192 vim_free(oldattrs);
6193}
6194
6195
6196/*
6197 * Make the cursor visible or invisible
6198 */
6199 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006200cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006201{
6202 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006203
6204 if (USE_VTP)
6205 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6206
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006207# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006208 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006209# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006210}
6211
6212
6213/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006214 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006215 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006216 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006217 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006218write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006219 char_u *pchBuf,
6220 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006221{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006222 COORD coord = g_coord;
6223 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006224 DWORD n, cchwritten;
6225 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006226 static WCHAR *unicodebuf = NULL;
6227 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006228 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006229 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006230 static WCHAR *utf8spbuf = NULL;
6231 static int utf8splength;
6232 static DWORD utf8spcells;
6233 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006234
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006235 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006236 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006237 utf8usingbuf = &unicodebuf;
6238 do
6239 {
6240 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6241 unicodebuf, unibuflen);
6242 if (length && length <= unibuflen)
6243 break;
6244 vim_free(unicodebuf);
6245 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6246 unibuflen = unibuflen ? 0 : length;
6247 } while(1);
6248 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006249 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006250 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6251 {
6252 if (utf8usingbuf != &utf8spbuf)
6253 {
6254 if (utf8spbuf == NULL)
6255 {
6256 cells = mb_string2cells((char_u *)" ", 1);
6257 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6258 utf8spbuf = LALLOC_MULT(WCHAR, length);
6259 if (utf8spbuf != NULL)
6260 {
6261 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6262 utf8usingbuf = &utf8spbuf;
6263 utf8splength = length;
6264 utf8spcells = cells;
6265 }
6266 }
6267 else
6268 {
6269 utf8usingbuf = &utf8spbuf;
6270 length = utf8splength;
6271 cells = utf8spcells;
6272 }
6273 }
6274 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006275
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006276 if (!USE_VTP)
6277 {
6278 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6279 coord, &written);
6280 // When writing fails or didn't write a single character, pretend one
6281 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006282 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006283 coord, &cchwritten) == 0
6284 || cchwritten == 0 || cchwritten == (DWORD)-1)
6285 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006286 }
6287 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006288 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006289 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006290 NULL) == 0 || cchwritten == 0)
6291 cchwritten = 1;
6292 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006293
K.Takata135e1522022-01-29 15:27:58 +00006294 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006295 {
6296 written = cbToWrite;
6297 g_coord.X += (SHORT)cells;
6298 }
6299 else
6300 {
6301 char_u *p = pchBuf;
6302 for (n = 0; n < cchwritten; n++)
6303 MB_CPTR_ADV(p);
6304 written = p - pchBuf;
6305 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006306 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006307
6308 while (g_coord.X > g_srScrollRegion.Right)
6309 {
6310 g_coord.X -= (SHORT) Columns;
6311 if (g_coord.Y < g_srScrollRegion.Bottom)
6312 g_coord.Y++;
6313 }
6314
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006315 // Cursor under VTP is always in the correct position, no need to reset.
6316 if (!USE_VTP)
6317 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006318
6319 return written;
6320}
6321
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006322 static char_u *
6323get_seq(
6324 int *args,
6325 int *count,
6326 char_u *head)
6327{
6328 int argc;
6329 char_u *p;
6330
6331 if (head == NULL || *head != '\033')
6332 return NULL;
6333
6334 argc = 0;
6335 p = head;
6336 ++p;
6337 do
6338 {
6339 ++p;
6340 args[argc] = getdigits(&p);
6341 argc += (argc < 15) ? 1 : 0;
6342 } while (*p == ';');
6343 *count = argc;
6344
6345 return p;
6346}
6347
6348 static char_u *
6349get_sgr(
6350 int *args,
6351 int *count,
6352 char_u *head)
6353{
6354 char_u *p = get_seq(args, count, head);
6355
6356 return (p && *p == 'm') ? ++p : NULL;
6357}
6358
6359/*
6360 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6361 */
6362 static char_u *
6363sgrn2(
6364 char_u *head,
6365 int n)
6366{
6367 int argc;
6368 int args[16];
6369 char_u *p = get_sgr(args, &argc, head);
6370
6371 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6372}
6373
6374/*
6375 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6376 */
6377 static char_u *
6378sgrnc(
6379 char_u *head,
6380 int n)
6381{
6382 int argc;
6383 int args[16];
6384 char_u *p = get_sgr(args, &argc, head);
6385
6386 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6387 ? p : NULL;
6388}
6389
6390 static char_u *
6391skipblank(char_u *q)
6392{
6393 char_u *p = q;
6394
6395 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6396 ++p;
6397 return p;
6398}
6399
6400/*
6401 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6402 * NULL.
6403 */
6404 static char_u *
6405sgrn2c(
6406 char_u *head,
6407 int n)
6408{
6409 char_u *p = sgrn2(head, n);
6410
6411 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6412}
6413
6414/*
6415 * If there is only a newline between the sequence immediately following it,
6416 * a pointer to the character following the newline is returned.
6417 * Otherwise NULL.
6418 */
6419 static char_u *
6420sgrn2cn(
6421 char_u *head,
6422 int n)
6423{
6424 char_u *p = sgrn2(head, n);
6425
6426 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6427}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006428
6429/*
6430 * mch_write(): write the output buffer to the screen, translating ESC
6431 * sequences into calls to console output routines.
6432 */
6433 void
6434mch_write(
6435 char_u *s,
6436 int len)
6437{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006438 char_u *end = s + len;
6439
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006440# ifdef VIMDLL
6441 if (gui.in_use)
6442 return;
6443# endif
6444
Bram Moolenaar071d4272004-06-13 20:20:40 +00006445 if (!term_console)
6446 {
6447 write(1, s, (unsigned)len);
6448 return;
6449 }
6450
Bram Moolenaar0f873732019-12-05 20:28:46 +01006451 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00006452 while (len--)
6453 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006454 int prefix = -1;
6455 char_u ch;
6456
6457 // While processing a sequence, on rare occasions it seems that another
6458 // sequence may be inserted asynchronously.
6459 if (len < 0)
6460 {
6461 redraw_all_later(CLEAR);
6462 return;
6463 }
6464
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006465 while (s + ++prefix < end)
6466 {
6467 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006468 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6469 && ch != '\a' && ch != '\033'))
6470 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006471 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006472
6473 if (p_wd)
6474 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006475 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006476 if (prefix != 0)
6477 prefix = 1;
6478 }
6479
6480 if (prefix != 0)
6481 {
6482 DWORD nWritten;
6483
6484 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006485# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006486 if (fdDump)
6487 {
6488 fputc('>', fdDump);
6489 fwrite(s, sizeof(char_u), nWritten, fdDump);
6490 fputs("<\n", fdDump);
6491 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006492# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006493 len -= (nWritten - 1);
6494 s += nWritten;
6495 }
6496 else if (s[0] == '\n')
6497 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006498 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00006499 if (g_coord.Y == g_srScrollRegion.Bottom)
6500 {
6501 scroll(1);
6502 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6503 }
6504 else
6505 {
6506 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6507 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006508# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006509 if (fdDump)
6510 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006511# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006512 s++;
6513 }
6514 else if (s[0] == '\r')
6515 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006516 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00006517 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006518# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006519 if (fdDump)
6520 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006521# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006522 s++;
6523 }
6524 else if (s[0] == '\b')
6525 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006526 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00006527 if (g_coord.X > g_srScrollRegion.Left)
6528 g_coord.X--;
6529 else if (g_coord.Y > g_srScrollRegion.Top)
6530 {
6531 g_coord.X = g_srScrollRegion.Right;
6532 g_coord.Y--;
6533 }
6534 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006535# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006536 if (fdDump)
6537 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006538# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006539 s++;
6540 }
6541 else if (s[0] == '\a')
6542 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006543 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00006544 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006545# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006546 if (fdDump)
6547 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006548# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006549 s++;
6550 }
6551 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6552 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006553# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006554 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006555# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006556 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006557 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006558 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006559
6560 switch (s[2])
6561 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006562 case '0': case '1': case '2': case '3': case '4':
6563 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006564 if (*(p = get_seq(args, &argc, s)) != 'm')
6565 goto notsgr;
6566
6567 p = s;
6568
6569 // Handling frequent optional sequences. Output to the screen
6570 // takes too long, so do not output as much as possible.
6571
6572 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
6573 // resetFG,FG,BG are omitted.
6574 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006575 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006576 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
6577 len = len + 1 - (int)(p - s);
6578 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006579 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006580 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006581
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006582 // If FG,BG,BG,FG of SGR are connected, the first FG can be
6583 // omitted.
6584 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
6585 p = sp;
6586
6587 // If FG,BG,FG,BG of SGR are connected, the first FG can be
6588 // omitted.
6589 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
6590 p = sp;
6591
6592 // If BG,BG of SGR are connected, the first BG can be omitted.
6593 if (sgrn2((sp = sgrn2(p, 48)), 48))
6594 p = sp;
6595
6596 // If restoreFG and FG are connected, the restoreFG can be
6597 // omitted.
6598 if (sgrn2((sp = sgrnc(p, 39)), 38))
6599 p = sp;
6600
6601 p = get_seq(args, &argc, p);
6602
6603notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006604 arg1 = args[0];
6605 arg2 = args[1];
6606 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006607 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006608 if (argc == 1 && args[0] == 0)
6609 normvideo();
6610 else if (argc == 1)
6611 {
6612 if (USE_VTP)
6613 textcolor((WORD) arg1);
6614 else
6615 textattr((WORD) arg1);
6616 }
6617 else if (USE_VTP)
6618 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006619 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006620 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006621 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006622 gotoxy(arg2, arg1);
6623 }
6624 else if (argc == 2 && *p == 'r')
6625 {
6626 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6627 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006628 else if (argc == 2 && *p == 'R')
6629 {
6630 set_scroll_region_tb(arg1, arg2);
6631 }
6632 else if (argc == 2 && *p == 'V')
6633 {
6634 set_scroll_region_lr(arg1, arg2);
6635 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006636 else if (argc == 1 && *p == 'A')
6637 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006638 gotoxy(g_coord.X + 1,
6639 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6640 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006641 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006642 {
6643 textbackground((WORD) arg1);
6644 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006645 else if (argc == 1 && *p == 'C')
6646 {
6647 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6648 g_coord.Y + 1);
6649 }
6650 else if (argc == 1 && *p == 'f')
6651 {
6652 textcolor((WORD) arg1);
6653 }
6654 else if (argc == 1 && *p == 'H')
6655 {
6656 gotoxy(1, arg1);
6657 }
6658 else if (argc == 1 && *p == 'L')
6659 {
6660 insert_lines(arg1);
6661 }
6662 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006663 {
6664 delete_lines(arg1);
6665 }
6666
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006667 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006668 s = p + 1;
6669 break;
6670
Bram Moolenaar071d4272004-06-13 20:20:40 +00006671 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006672 gotoxy(g_coord.X + 1,
6673 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6674 goto got3;
6675
6676 case 'B':
6677 visual_bell();
6678 goto got3;
6679
6680 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006681 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6682 g_coord.Y + 1);
6683 goto got3;
6684
6685 case 'E':
6686 termcap_mode_end();
6687 goto got3;
6688
6689 case 'F':
6690 standout();
6691 goto got3;
6692
6693 case 'f':
6694 standend();
6695 goto got3;
6696
6697 case 'H':
6698 gotoxy(1, 1);
6699 goto got3;
6700
6701 case 'j':
6702 clear_to_end_of_display();
6703 goto got3;
6704
6705 case 'J':
6706 clear_screen();
6707 goto got3;
6708
6709 case 'K':
6710 clear_to_end_of_line();
6711 goto got3;
6712
6713 case 'L':
6714 insert_lines(1);
6715 goto got3;
6716
6717 case 'M':
6718 delete_lines(1);
6719 goto got3;
6720
6721 case 'S':
6722 termcap_mode_start();
6723 goto got3;
6724
6725 case 'V':
6726 cursor_visible(TRUE);
6727 goto got3;
6728
6729 case 'v':
6730 cursor_visible(FALSE);
6731 goto got3;
6732
6733 got3:
6734 s += 3;
6735 len -= 2;
6736 }
6737
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006738# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006739 if (fdDump)
6740 {
6741 fputs("ESC | ", fdDump);
6742 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6743 fputc('\n', fdDump);
6744 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006745# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006746 }
6747 else
6748 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006749 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00006750 DWORD nWritten;
6751
6752 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006753# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006754 if (fdDump)
6755 {
6756 fputc('>', fdDump);
6757 fwrite(s, sizeof(char_u), nWritten, fdDump);
6758 fputs("<\n", fdDump);
6759 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006760# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006761
6762 len -= (nWritten - 1);
6763 s += nWritten;
6764 }
6765 }
6766
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006767# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006768 if (fdDump)
6769 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006770# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006771}
6772
Bram Moolenaar0f873732019-12-05 20:28:46 +01006773#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006774
6775
6776/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006777 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006778 */
6779 void
6780mch_delay(
6781 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02006782 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006783{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006784#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006785 Sleep((int)msec); // never wait for input
6786#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006787# ifdef VIMDLL
6788 if (gui.in_use)
6789 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006790 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006791 return;
6792 }
6793# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02006794 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006795# ifdef FEAT_MZSCHEME
6796 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6797 {
6798 int towait = p_mzq;
6799
Bram Moolenaar0f873732019-12-05 20:28:46 +01006800 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006801 while (msec > 0)
6802 {
6803 mzvim_check_threads();
6804 if (msec < towait)
6805 towait = msec;
6806 Sleep(towait);
6807 msec -= towait;
6808 }
6809 }
6810 else
6811# endif
6812 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006813 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006814 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006815#endif
6816}
6817
6818
6819/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006820 * This version of remove is not scared by a readonly (backup) file.
6821 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006822 * Return 0 for success, -1 for failure.
6823 */
6824 int
6825mch_remove(char_u *name)
6826{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006827 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006828 int n;
6829
Bram Moolenaar203258c2016-01-17 22:15:16 +01006830 /*
6831 * On Windows, deleting a directory's symbolic link is done by
6832 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6833 */
6834 if (mch_isdir(name) && mch_is_symbolic_link(name))
6835 return mch_rmdir(name);
6836
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006837 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6838
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006839 wn = enc_to_utf16(name, NULL);
6840 if (wn == NULL)
6841 return -1;
6842
6843 n = DeleteFileW(wn) ? 0 : -1;
6844 vim_free(wn);
6845 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006846}
6847
6848
6849/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006850 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006851 */
6852 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006853mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006854{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006855#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
6856# ifdef VIMDLL
6857 if (!gui.in_use)
6858# endif
6859 if (g_fCtrlCPressed || g_fCBrkPressed)
6860 {
6861 ctrl_break_was_pressed = g_fCBrkPressed;
6862 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6863 got_int = TRUE;
6864 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006865#endif
6866}
6867
Bram Moolenaar0f873732019-12-05 20:28:46 +01006868// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01006869#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006870
6871/*
6872 * How much main memory in KiB that can be used by VIM.
6873 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006874 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006875mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006876{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006877 MEMORYSTATUSEX ms;
6878
Bram Moolenaar0f873732019-12-05 20:28:46 +01006879 // Need to use GlobalMemoryStatusEx() when there is more memory than
6880 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006881 ms.dwLength = sizeof(MEMORYSTATUSEX);
6882 GlobalMemoryStatusEx(&ms);
6883 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006884 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006885 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006886 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006887 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006888 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006889 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006890 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006891 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006892 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01006893 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006894 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006895}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006896
Bram Moolenaar071d4272004-06-13 20:20:40 +00006897/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006898 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00006899 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6900 * file whose short file name is "FOO.BAR" (its long file name will
6901 * be correct: "foo.bar~"). Because a file can be accessed by
6902 * either its SFN or its LFN, "foo.bar" has effectively been
6903 * renamed to "foo.bar", which is not at all what was wanted. This
6904 * seems to happen only when renaming files with three-character
6905 * extensions by appending a suffix that does not include ".".
6906 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6907 *
6908 * There is another problem, which isn't really a bug but isn't right either:
6909 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6910 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6911 * service pack 6. Doesn't seem to happen on Windows 98.
6912 *
6913 * Like rename(), returns 0 upon success, non-zero upon failure.
6914 * Should probably set errno appropriately when errors occur.
6915 */
6916 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006917mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006918{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006919 WCHAR *p;
6920 int i;
6921 WCHAR szTempFile[_MAX_PATH + 1];
6922 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006923 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006924
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006925 // No need to play tricks unless the file name contains a "~" as the
6926 // seventh character.
6927 p = wold;
6928 for (i = 0; wold[i] != NUL; ++i)
6929 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6930 && wold[i + 1] != 0)
6931 p = wold + i + 1;
6932 if ((int)(wold + i - p) < 8 || p[6] != '~')
6933 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006934
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006935 // Get base path of new file name. Undocumented feature: If pszNewFile is
6936 // a directory, no error is returned and pszFilePart will be NULL.
6937 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006938 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006939 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006940
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006941 // Get (and create) a unique temporary file name in directory of new file
6942 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006943 return -2;
6944
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006945 // blow the temp file away
6946 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006947 return -3;
6948
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006949 // rename old file to the temp file
6950 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006951 return -4;
6952
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006953 // now create an empty file called pszOldFile; this prevents the operating
6954 // system using pszOldFile as an alias (SFN) if we're renaming within the
6955 // same directory. For example, we're editing a file called
6956 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6957 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
6958 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
6959 // cause all sorts of problems later in buf_write(). So, we create an
6960 // empty file called filena~1.txt and the system will have to find some
6961 // other SFN for filena~1.txt~, such as filena~2.txt
6962 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006963 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6964 return -5;
6965 if (!CloseHandle(hf))
6966 return -6;
6967
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006968 // rename the temp file to the new file
6969 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006970 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006971 // Renaming failed. Rename the file back to its old name, so that it
6972 // looks like nothing happened.
6973 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006974 return -7;
6975 }
6976
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006977 // Seems to be left around on Novell filesystems
6978 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006979
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006980 // finally, remove the empty old file
6981 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006982 return -8;
6983
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006984 return 0;
6985}
6986
6987
6988/*
6989 * Converts the filenames to UTF-16, then call mch_wrename().
6990 * Like rename(), returns 0 upon success, non-zero upon failure.
6991 */
6992 int
6993mch_rename(
6994 const char *pszOldFile,
6995 const char *pszNewFile)
6996{
6997 WCHAR *wold = NULL;
6998 WCHAR *wnew = NULL;
6999 int retval = -1;
7000
7001 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7002 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7003 if (wold != NULL && wnew != NULL)
7004 retval = mch_wrename(wold, wnew);
7005 vim_free(wold);
7006 vim_free(wnew);
7007 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007008}
7009
7010/*
7011 * Get the default shell for the current hardware platform
7012 */
7013 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007014default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007015{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007016 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007017}
7018
7019/*
7020 * mch_access() extends access() to do more detailed check on network drives.
7021 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7022 */
7023 int
7024mch_access(char *n, int p)
7025{
7026 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007027 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007028 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007029
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007030 wn = enc_to_utf16((char_u *)n, NULL);
7031 if (wn == NULL)
7032 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007033
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007034 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007035 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007036 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007037
7038 if (p & R_OK)
7039 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007040 // Read check is performed by seeing if we can do a find file on
7041 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007042 int i;
7043 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007044
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007045 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7046 TempNameW[i] = wn[i];
7047 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7048 TempNameW[i++] = '\\';
7049 TempNameW[i++] = '*';
7050 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007051
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007052 hFile = FindFirstFileW(TempNameW, &d);
7053 if (hFile == INVALID_HANDLE_VALUE)
7054 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007055 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007056 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007057 }
7058
7059 if (p & W_OK)
7060 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007061 // Trying to create a temporary file in the directory should catch
7062 // directories on read-only network shares. However, in
7063 // directories whose ACL allows writes but denies deletes will end
7064 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007065 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7066 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007067 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007068 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007069 }
7070 }
7071 else
7072 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007073 // Don't consider a file read-only if another process has opened it.
7074 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7075
Bram Moolenaar0f873732019-12-05 20:28:46 +01007076 // Trying to open the file for the required access does ACL, read-only
7077 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007078 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7079 | ((p & R_OK) ? GENERIC_READ : 0);
7080
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007081 hFile = CreateFileW(wn, access_mode, share_mode,
7082 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007083 if (hFile == INVALID_HANDLE_VALUE)
7084 goto getout;
7085 CloseHandle(hFile);
7086 }
7087
Bram Moolenaar0f873732019-12-05 20:28:46 +01007088 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007089getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007090 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007091 return retval;
7092}
7093
Bram Moolenaar071d4272004-06-13 20:20:40 +00007094/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007095 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007096 */
7097 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007098mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007099{
7100 WCHAR *wn;
7101 int f;
7102
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007103 wn = enc_to_utf16((char_u *)name, NULL);
7104 if (wn == NULL)
7105 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007106
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007107 f = _wopen(wn, flags, mode);
7108 vim_free(wn);
7109 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007110}
7111
7112/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007113 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007114 */
7115 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007116mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007117{
7118 WCHAR *wn, *wm;
7119 FILE *f = NULL;
7120
Bram Moolenaara12a1612019-01-24 16:39:02 +01007121#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007122 // Work around an annoying assertion in the Microsoft debug CRT
7123 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007124 char newMode = mode[strlen(mode) - 1];
7125 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007126
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007127 _get_fmode(&oldMode);
7128 if (newMode == 't')
7129 _set_fmode(_O_TEXT);
7130 else if (newMode == 'b')
7131 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007132#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007133 wn = enc_to_utf16((char_u *)name, NULL);
7134 wm = enc_to_utf16((char_u *)mode, NULL);
7135 if (wn != NULL && wm != NULL)
7136 f = _wfopen(wn, wm);
7137 vim_free(wn);
7138 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007139
Bram Moolenaara12a1612019-01-24 16:39:02 +01007140#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007141 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007142#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007143 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007144}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007145
Bram Moolenaar071d4272004-06-13 20:20:40 +00007146/*
7147 * SUB STREAM (aka info stream) handling:
7148 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007149 * NTFS can have sub streams for each file. The normal contents of a file is
7150 * stored in the main stream, and extra contents (author information, title and
7151 * so on) can be stored in a sub stream. After Windows 2000, the user can
7152 * access and store this information in sub streams via an explorer's property
7153 * menu item in the right click menu. This information in sub streams was lost
7154 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007155 *
7156 * Incomplete explanation:
7157 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7158 * More useful info and an example:
7159 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7160 */
7161
7162/*
7163 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7164 * and write to stream "substream" of file "to".
7165 * Errors are ignored.
7166 */
7167 static void
7168copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7169{
7170 HANDLE hTo;
7171 WCHAR *to_name;
7172
7173 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7174 wcscpy(to_name, to);
7175 wcscat(to_name, substream);
7176
7177 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7178 FILE_ATTRIBUTE_NORMAL, NULL);
7179 if (hTo != INVALID_HANDLE_VALUE)
7180 {
7181 long done;
7182 DWORD todo;
7183 DWORD readcnt, written;
7184 char buf[4096];
7185
Bram Moolenaar0f873732019-12-05 20:28:46 +01007186 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007187 for (done = 0; done < len; done += written)
7188 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007189 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007190 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7191 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007192 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7193 FALSE, FALSE, context)
7194 || readcnt != todo
7195 || !WriteFile(hTo, buf, todo, &written, NULL)
7196 || written != todo)
7197 break;
7198 }
7199 CloseHandle(hTo);
7200 }
7201
7202 free(to_name);
7203}
7204
7205/*
7206 * Copy info streams from file "from" to file "to".
7207 */
7208 static void
7209copy_infostreams(char_u *from, char_u *to)
7210{
7211 WCHAR *fromw;
7212 WCHAR *tow;
7213 HANDLE sh;
7214 WIN32_STREAM_ID sid;
7215 int headersize;
7216 WCHAR streamname[_MAX_PATH];
7217 DWORD readcount;
7218 void *context = NULL;
7219 DWORD lo, hi;
7220 int len;
7221
Bram Moolenaar0f873732019-12-05 20:28:46 +01007222 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007223 fromw = enc_to_utf16(from, NULL);
7224 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007225 if (fromw != NULL && tow != NULL)
7226 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007227 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007228 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7229 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7230 if (sh != INVALID_HANDLE_VALUE)
7231 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007232 // Use BackupRead() to find the info streams. Repeat until we
7233 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007234 for (;;)
7235 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007236 // Get the header to find the length of the stream name. If
7237 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007238 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007239 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007240 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7241 &readcount, FALSE, FALSE, &context)
7242 || readcount == 0)
7243 break;
7244
Bram Moolenaar0f873732019-12-05 20:28:46 +01007245 // We only deal with streams that have a name. The normal
7246 // file data appears to be without a name, even though docs
7247 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007248 if (sid.dwStreamNameSize > 0)
7249 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007250 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007251 if (!BackupRead(sh, (LPBYTE)streamname,
7252 sid.dwStreamNameSize,
7253 &readcount, FALSE, FALSE, &context))
7254 break;
7255
Bram Moolenaar0f873732019-12-05 20:28:46 +01007256 // Copy an info stream with a name ":anything:$DATA".
7257 // Skip "::$DATA", it has no stream name (examples suggest
7258 // it might be used for the normal file contents).
7259 // Note that BackupRead() counts bytes, but the name is in
7260 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007261 len = readcount / sizeof(WCHAR);
7262 streamname[len] = 0;
7263 if (len > 7 && wcsicmp(streamname + len - 6,
7264 L":$DATA") == 0)
7265 {
7266 streamname[len - 6] = 0;
7267 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007268 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007269 }
7270 }
7271
Bram Moolenaar0f873732019-12-05 20:28:46 +01007272 // Advance to the next stream. We might try seeking too far,
7273 // but BackupSeek() doesn't skip over stream borders, thus
7274 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007275 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007276 &lo, &hi, &context);
7277 }
7278
Bram Moolenaar0f873732019-12-05 20:28:46 +01007279 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007280 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7281
7282 CloseHandle(sh);
7283 }
7284 }
7285 vim_free(fromw);
7286 vim_free(tow);
7287}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007288
7289/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007290 * ntdll.dll definitions
7291 */
7292#define FileEaInformation 7
7293#ifndef STATUS_SUCCESS
7294# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7295#endif
7296
7297typedef struct _FILE_FULL_EA_INFORMATION_ {
7298 ULONG NextEntryOffset;
7299 UCHAR Flags;
7300 UCHAR EaNameLength;
7301 USHORT EaValueLength;
7302 CHAR EaName[1];
7303} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7304
7305typedef struct _FILE_EA_INFORMATION_ {
7306 ULONG EaSize;
7307} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7308
7309typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7310 PHANDLE FileHandle,
7311 ACCESS_MASK DesiredAccess,
7312 POBJECT_ATTRIBUTES ObjectAttributes,
7313 PIO_STATUS_BLOCK IoStatusBlock,
7314 ULONG ShareAccess,
7315 ULONG OpenOptions);
7316typedef NTSTATUS (NTAPI *PfnNtClose)(
7317 HANDLE Handle);
7318typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
7319 HANDLE FileHandle,
7320 PIO_STATUS_BLOCK IoStatusBlock,
7321 PVOID Buffer,
7322 ULONG Length);
7323typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7324 HANDLE FileHandle,
7325 PIO_STATUS_BLOCK IoStatusBlock,
7326 PVOID Buffer,
7327 ULONG Length,
7328 BOOLEAN ReturnSingleEntry,
7329 PVOID EaList,
7330 ULONG EaListLength,
7331 PULONG EaIndex,
7332 BOOLEAN RestartScan);
7333typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
7334 HANDLE FileHandle,
7335 PIO_STATUS_BLOCK IoStatusBlock,
7336 PVOID FileInformation,
7337 ULONG Length,
7338 FILE_INFORMATION_CLASS FileInformationClass);
7339typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7340 PUNICODE_STRING DestinationString,
7341 PCWSTR SourceString);
7342
7343PfnNtOpenFile pNtOpenFile = NULL;
7344PfnNtClose pNtClose = NULL;
7345PfnNtSetEaFile pNtSetEaFile = NULL;
7346PfnNtQueryEaFile pNtQueryEaFile = NULL;
7347PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7348PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
7349
7350/*
7351 * Load ntdll.dll functions.
7352 */
7353 static BOOL
7354load_ntdll(void)
7355{
7356 static int loaded = -1;
7357
7358 if (loaded == -1)
7359 {
7360 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7361 if (hNtdll != NULL)
7362 {
7363 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7364 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7365 pNtSetEaFile = (PfnNtSetEaFile)
7366 GetProcAddress(hNtdll, "NtSetEaFile");
7367 pNtQueryEaFile = (PfnNtQueryEaFile)
7368 GetProcAddress(hNtdll, "NtQueryEaFile");
7369 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7370 GetProcAddress(hNtdll, "NtQueryInformationFile");
7371 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7372 GetProcAddress(hNtdll, "RtlInitUnicodeString");
7373 }
7374 if (pNtOpenFile == NULL
7375 || pNtClose == NULL
7376 || pNtSetEaFile == NULL
7377 || pNtQueryEaFile == NULL
7378 || pNtQueryInformationFile == NULL
7379 || pRtlInitUnicodeString == NULL)
7380 loaded = FALSE;
7381 else
7382 loaded = TRUE;
7383 }
7384 return (BOOL) loaded;
7385}
7386
7387/*
7388 * Copy extended attributes (EA) from file "from" to file "to".
7389 */
7390 static void
7391copy_extattr(char_u *from, char_u *to)
7392{
7393 char_u *fromf = NULL;
7394 char_u *tof = NULL;
7395 WCHAR *fromw = NULL;
7396 WCHAR *tow = NULL;
7397 UNICODE_STRING u;
7398 HANDLE h;
7399 OBJECT_ATTRIBUTES oa;
7400 IO_STATUS_BLOCK iosb;
7401 FILE_EA_INFORMATION_ eainfo = {0};
7402 void *ea = NULL;
7403
7404 if (!load_ntdll())
7405 return;
7406
7407 // Convert the file names to the fully qualified object names.
7408 fromf = alloc(STRLEN(from) + 5);
7409 tof = alloc(STRLEN(to) + 5);
7410 if (fromf == NULL || tof == NULL)
7411 goto theend;
7412 STRCPY(fromf, "\\??\\");
7413 STRCAT(fromf, from);
7414 STRCPY(tof, "\\??\\");
7415 STRCAT(tof, to);
7416
7417 // Convert the names to wide characters.
7418 fromw = enc_to_utf16(fromf, NULL);
7419 tow = enc_to_utf16(tof, NULL);
7420 if (fromw == NULL || tow == NULL)
7421 goto theend;
7422
7423 // Get the EA.
7424 pRtlInitUnicodeString(&u, fromw);
7425 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7426 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7427 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7428 goto theend;
7429 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7430 FileEaInformation);
7431 if (eainfo.EaSize != 0)
7432 {
7433 ea = alloc(eainfo.EaSize);
7434 if (ea != NULL)
7435 {
7436 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7437 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7438 {
7439 vim_free(ea);
7440 ea = NULL;
7441 }
7442 }
7443 }
7444 pNtClose(h);
7445
7446 // Set the EA.
7447 if (ea != NULL)
7448 {
7449 pRtlInitUnicodeString(&u, tow);
7450 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7451 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7452 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7453 goto theend;
7454
7455 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
7456 pNtClose(h);
7457 }
7458
7459theend:
7460 vim_free(fromf);
7461 vim_free(tof);
7462 vim_free(fromw);
7463 vim_free(tow);
7464 vim_free(ea);
7465}
7466
7467/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007468 * Copy file attributes from file "from" to file "to".
7469 * For Windows NT and later we copy info streams.
7470 * Always returns zero, errors are ignored.
7471 */
7472 int
7473mch_copy_file_attribute(char_u *from, char_u *to)
7474{
Bram Moolenaar0f873732019-12-05 20:28:46 +01007475 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007476 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007477 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007478 return 0;
7479}
7480
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007481
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007482/*
K.Takatadc73b4b2021-06-08 18:32:36 +02007483 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007484 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007485static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007486static LPWSTR *ArglistW = NULL;
7487static int global_argc = 0;
7488static char **global_argv;
7489
Bram Moolenaar0f873732019-12-05 20:28:46 +01007490static int used_file_argc = 0; // last argument in global_argv[] used
7491 // for the argument list.
7492static int *used_file_indexes = NULL; // indexes in global_argv[] for
7493 // command line arguments added to
7494 // the argument list
7495static int used_file_count = 0; // nr of entries in used_file_indexes
7496static int used_file_literal = FALSE; // take file names literally
7497static int used_file_full_path = FALSE; // file name was full path
7498static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007499static int used_alist_count = 0;
7500
7501
7502/*
7503 * Get the command line arguments. Unicode version.
7504 * Returns argc. Zero when something fails.
7505 */
7506 int
7507get_cmd_argsW(char ***argvp)
7508{
7509 char **argv = NULL;
7510 int argc = 0;
7511 int i;
7512
Bram Moolenaar14993322014-09-09 12:25:33 +02007513 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007514 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7515 if (ArglistW != NULL)
7516 {
7517 argv = malloc((nArgsW + 1) * sizeof(char *));
7518 if (argv != NULL)
7519 {
7520 argc = nArgsW;
7521 argv[argc] = NULL;
7522 for (i = 0; i < argc; ++i)
7523 {
7524 int len;
7525
K.Takatadc73b4b2021-06-08 18:32:36 +02007526 // Convert each Unicode argument to UTF-8.
7527 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007528 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007529 (LPSTR *)&argv[i], &len, 0, 0);
7530 if (argv[i] == NULL)
7531 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007532 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007533 while (i > 0)
7534 free(argv[--i]);
7535 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007536 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007537 argc = 0;
7538 }
7539 }
7540 }
7541 }
7542
7543 global_argc = argc;
7544 global_argv = argv;
7545 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007546 {
7547 if (used_file_indexes != NULL)
7548 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007549 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007550 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007551
7552 if (argvp != NULL)
7553 *argvp = argv;
7554 return argc;
7555}
7556
7557 void
7558free_cmd_argsW(void)
7559{
7560 if (ArglistW != NULL)
7561 {
7562 GlobalFree(ArglistW);
7563 ArglistW = NULL;
7564 }
7565}
7566
7567/*
7568 * Remember "name" is an argument that was added to the argument list.
7569 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7570 * is called.
7571 */
7572 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007573used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007574{
7575 int i;
7576
7577 if (used_file_indexes == NULL)
7578 return;
7579 for (i = used_file_argc + 1; i < global_argc; ++i)
7580 if (STRCMP(global_argv[i], name) == 0)
7581 {
7582 used_file_argc = i;
7583 used_file_indexes[used_file_count++] = i;
7584 break;
7585 }
7586 used_file_literal = literal;
7587 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007588 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007589}
7590
7591/*
7592 * Remember the length of the argument list as it was. If it changes then we
7593 * leave it alone when 'encoding' is set.
7594 */
7595 void
7596set_alist_count(void)
7597{
7598 used_alist_count = GARGCOUNT;
7599}
7600
7601/*
7602 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02007603 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007604 * and convert them to 'encoding'.
7605 */
7606 void
7607fix_arg_enc(void)
7608{
7609 int i;
7610 int idx;
7611 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007612 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007613
Bram Moolenaar0f873732019-12-05 20:28:46 +01007614 // Safety checks:
7615 // - if argument count differs between the wide and non-wide argument
7616 // list, something must be wrong.
7617 // - the file name arguments must have been located.
7618 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007619 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007620 || ArglistW == NULL
7621 || used_file_indexes == NULL
7622 || used_file_count == 0
7623 || used_alist_count != GARGCOUNT)
7624 return;
7625
Bram Moolenaar0f873732019-12-05 20:28:46 +01007626 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007627 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007628 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007629 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00007630 for (i = 0; i < GARGCOUNT; ++i)
7631 fnum_list[i] = GARGLIST[i].ae_fnum;
7632
Bram Moolenaar0f873732019-12-05 20:28:46 +01007633 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007634 alist_clear(&global_alist);
7635 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007636 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007637
7638 for (i = 0; i < used_file_count; ++i)
7639 {
7640 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007641 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007642 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007643 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007644 int literal = used_file_literal;
7645
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007646#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01007647 // When using diff mode may need to concatenate file name to
7648 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007649 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7650 && !mch_isdir(alist_name(&GARGLIST[0])))
7651 {
7652 char_u *r;
7653
7654 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7655 if (r != NULL)
7656 {
7657 vim_free(str);
7658 str = r;
7659 }
7660 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007661#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01007662 // Re-use the old buffer by renaming it. When not using literal
7663 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00007664 if (used_file_literal)
7665 buf_set_name(fnum_list[i], str);
7666
Bram Moolenaar0f873732019-12-05 20:28:46 +01007667 // Check backtick literal. backtick literal is already expanded in
7668 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007669 if (literal == FALSE)
7670 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007671 size_t len = STRLEN(str);
7672
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007673 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7674 literal = TRUE;
7675 }
7676 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007677 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007678 }
7679
7680 if (!used_file_literal)
7681 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007682 // Now expand wildcards in the arguments.
7683 // Temporarily add '(' and ')' to 'isfname'. These are valid
7684 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00007685 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01007686 // Also, unset wildignore to not be influenced by this option.
7687 // The arguments specified in command-line should be kept even if
7688 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00007689 // Use :legacy so that it also works when in Vim9 script.
7690 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
7691 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007692 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00007693 do_cmdline_cmd(
7694 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
7695 do_cmdline_cmd(
7696 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007697 }
7698
Bram Moolenaar0f873732019-12-05 20:28:46 +01007699 // If wildcard expansion failed, we are editing the first file of the
7700 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007701 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7702 {
7703 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00007704 if (GARGCOUNT == 1 && used_file_full_path
7705 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
7706 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007707 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007708
7709 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007710}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007711
7712 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007713mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007714{
7715 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007716 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007717
Bram Moolenaar964b3742019-05-24 18:54:09 +02007718 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007719 if (envbuf == NULL)
7720 return -1;
7721
7722 sprintf((char *)envbuf, "%s=%s", var, value);
7723
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007724 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007725
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007726 vim_free(envbuf);
7727 if (p == NULL)
7728 return -1;
7729 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007730#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007731 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007732#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007733 // Unlike Un*x systems, we can free the string for _wputenv().
7734 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007735
7736 return 0;
7737}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007738
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007739/*
7740 * Support for 256 colors and 24-bit colors was added in Windows 10
7741 * version 1703 (Creators update).
7742 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007743#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7744
7745/*
7746 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02007747 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007748 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007749#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007750
7751/*
7752 * ConPTY differences between versions, need different logic.
7753 * version 1903 (May 2019 update).
7754 */
7755#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
7756
7757/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007758 * version 1909 (November 2019 update).
7759 */
7760#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
7761
7762/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007763 * Stay ahead of the next update, and when it's done, fix this.
7764 * version ? (2020 update, temporarily use the build number of insider preview)
7765 */
7766#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
7767
7768/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02007769 * Confirm until this version. Also the logic changes.
7770 * insider preview.
7771 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02007772#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007773
7774/*
7775 * Not stable now.
7776 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007777#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007778
7779 static void
7780vtp_flag_init(void)
7781{
7782 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007783#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007784 DWORD mode;
7785 HANDLE out;
7786
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007787# ifdef VIMDLL
7788 if (!gui.in_use)
7789# endif
7790 {
7791 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007792
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007793 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7794 GetConsoleMode(out, &mode);
7795 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7796 if (SetConsoleMode(out, mode) == 0)
7797 vtp_working = 0;
7798 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007799#endif
7800
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007801 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007802 conpty_working = 1;
7803 if (ver >= CONPTY_STABLE_BUILD)
7804 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007805
Bram Moolenaar57da6982019-09-13 22:30:11 +02007806 if (ver <= CONPTY_INSIDER_BUILD)
7807 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007808 if (ver <= CONPTY_1909_BUILD)
7809 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02007810 if (ver <= CONPTY_1903_BUILD)
7811 conpty_type = 2;
7812 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
7813 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007814
7815 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
7816 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007817}
7818
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007819#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007820
7821 static void
7822vtp_init(void)
7823{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007824 HMODULE hKerneldll;
7825 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007826# ifdef FEAT_TERMGUICOLORS
7827 COLORREF fg, bg;
7828# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007829
Bram Moolenaar0f873732019-12-05 20:28:46 +01007830 // Use functions supported from Vista
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007831 hKerneldll = GetModuleHandle("kernel32.dll");
7832 if (hKerneldll != NULL)
7833 {
7834 pGetConsoleScreenBufferInfoEx =
7835 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7836 hKerneldll, "GetConsoleScreenBufferInfoEx");
7837 pSetConsoleScreenBufferInfoEx =
7838 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7839 hKerneldll, "SetConsoleScreenBufferInfoEx");
7840 if (pGetConsoleScreenBufferInfoEx != NULL
7841 && pSetConsoleScreenBufferInfoEx != NULL)
7842 has_csbiex = TRUE;
7843 }
7844
7845 csbi.cbSize = sizeof(csbi);
7846 if (has_csbiex)
7847 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007848 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7849 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
Bram Moolenaardf543822020-01-30 11:53:59 +01007850 store_console_bg_rgb = save_console_bg_rgb;
7851 store_console_fg_rgb = save_console_fg_rgb;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007852
7853# ifdef FEAT_TERMGUICOLORS
7854 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7855 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7856 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7857 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7858 default_console_color_bg = bg;
7859 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007860# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007861
7862 set_console_color_rgb();
7863}
7864
7865 static void
7866vtp_exit(void)
7867{
Bram Moolenaardf543822020-01-30 11:53:59 +01007868 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007869}
7870
Bram Moolenaar06b7b582020-05-30 17:49:25 +02007871 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007872vtp_printf(
7873 char *format,
7874 ...)
7875{
7876 char_u buf[100];
7877 va_list list;
7878 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007879 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007880
7881 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007882 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007883 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007884 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007885 return (int)result;
7886}
7887
7888 static void
7889vtp_sgr_bulk(
7890 int arg)
7891{
7892 int args[1];
7893
7894 args[0] = arg;
7895 vtp_sgr_bulks(1, args);
7896}
7897
K.Takata6e1d31e2022-02-03 13:05:32 +00007898# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007899 if ((*p-- = "0123456789"[(n = x % 10)]) \
7900 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
7901 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
7902
K.Takata6e1d31e2022-02-03 13:05:32 +00007903# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007904 case x: \
7905 FAST256(newargs[x - 1]);
7906
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007907 static void
7908vtp_sgr_bulks(
7909 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007910 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007911{
K.Takata6e1d31e2022-02-03 13:05:32 +00007912# define MAXSGR 16
7913# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007914 char_u buf[SGRBUFSIZE];
7915 char_u *p;
7916 int in, out;
7917 int newargs[16];
7918 static int sgrfgr = -1, sgrfgg, sgrfgb;
7919 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007920
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007921 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007922 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007923 sgrfgr = sgrbgr = -1;
7924 vtp_printf("033[m");
7925 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007926 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007927
7928 in = out = 0;
7929 while (in < argc)
7930 {
7931 int s = args[in];
7932 int copylen = 1;
7933
7934 if (s == 38)
7935 {
7936 if (argc - in >= 5 && args[in + 1] == 2)
7937 {
7938 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
7939 && sgrfgb == args[in + 4])
7940 {
7941 in += 5;
7942 copylen = 0;
7943 }
7944 else
7945 {
7946 sgrfgr = args[in + 2];
7947 sgrfgg = args[in + 3];
7948 sgrfgb = args[in + 4];
7949 copylen = 5;
7950 }
7951 }
7952 else if (argc - in >= 3 && args[in + 1] == 5)
7953 {
7954 sgrfgr = -1;
7955 copylen = 3;
7956 }
7957 }
7958 else if (s == 48)
7959 {
7960 if (argc - in >= 5 && args[in + 1] == 2)
7961 {
7962 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
7963 && sgrbgb == args[in + 4])
7964 {
7965 in += 5;
7966 copylen = 0;
7967 }
7968 else
7969 {
7970 sgrbgr = args[in + 2];
7971 sgrbgg = args[in + 3];
7972 sgrbgb = args[in + 4];
7973 copylen = 5;
7974 }
7975 }
7976 else if (argc - in >= 3 && args[in + 1] == 5)
7977 {
7978 sgrbgr = -1;
7979 copylen = 3;
7980 }
7981 }
7982 else if (30 <= s && s <= 39)
7983 sgrfgr = -1;
7984 else if (90 <= s && s <= 97)
7985 sgrfgr = -1;
7986 else if (40 <= s && s <= 49)
7987 sgrbgr = -1;
7988 else if (100 <= s && s <= 107)
7989 sgrbgr = -1;
7990 else if (s == 0)
7991 sgrfgr = sgrbgr = -1;
7992
7993 while (copylen--)
7994 newargs[out++] = args[in++];
7995 }
7996
7997 p = &buf[sizeof(buf) - 1];
7998 *p-- = 'm';
7999
8000 switch (out)
8001 {
8002 int n, m;
8003 DWORD r;
8004
8005 FAST256CASE(16);
8006 *p-- = ';';
8007 FAST256CASE(15);
8008 *p-- = ';';
8009 FAST256CASE(14);
8010 *p-- = ';';
8011 FAST256CASE(13);
8012 *p-- = ';';
8013 FAST256CASE(12);
8014 *p-- = ';';
8015 FAST256CASE(11);
8016 *p-- = ';';
8017 FAST256CASE(10);
8018 *p-- = ';';
8019 FAST256CASE(9);
8020 *p-- = ';';
8021 FAST256CASE(8);
8022 *p-- = ';';
8023 FAST256CASE(7);
8024 *p-- = ';';
8025 FAST256CASE(6);
8026 *p-- = ';';
8027 FAST256CASE(5);
8028 *p-- = ';';
8029 FAST256CASE(4);
8030 *p-- = ';';
8031 FAST256CASE(3);
8032 *p-- = ';';
8033 FAST256CASE(2);
8034 *p-- = ';';
8035 FAST256CASE(1);
8036 *p-- = '[';
8037 *p = '\033';
8038 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8039 default:
8040 break;
8041 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008042}
8043
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008044 static void
8045wt_init(void)
8046{
8047 wt_working = (mch_getenv("WT_SESSION") != NULL);
8048}
8049
8050 int
8051use_wt(void)
8052{
8053 return USE_WT;
8054}
8055
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008056# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008057 static int
8058ctermtoxterm(
8059 int cterm)
8060{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008061 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008062
8063 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8064 return (((int)r << 16) | ((int)g << 8) | (int)b);
8065}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008066# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008067
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008068 static void
8069set_console_color_rgb(void)
8070{
8071# ifdef FEAT_TERMGUICOLORS
8072 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008073 guicolor_T fg, bg;
8074 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008075
8076 if (!USE_VTP)
8077 return;
8078
Bram Moolenaara050b942019-12-02 21:35:31 +01008079 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8080
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008081 if (USE_WT)
8082 {
8083 term_fg_rgb_color(fg);
8084 term_bg_rgb_color(bg);
8085 return;
8086 }
8087
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008088 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8089 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8090
8091 csbi.cbSize = sizeof(csbi);
8092 if (has_csbiex)
8093 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8094
8095 csbi.cbSize = sizeof(csbi);
8096 csbi.srWindow.Right += 1;
8097 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008098 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8099 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008100 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8101 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008102 if (has_csbiex)
8103 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8104# endif
8105}
8106
Bram Moolenaara050b942019-12-02 21:35:31 +01008107# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8108 void
8109get_default_console_color(
8110 int *cterm_fg,
8111 int *cterm_bg,
8112 guicolor_T *gui_fg,
8113 guicolor_T *gui_bg)
8114{
8115 int id;
8116 guicolor_T guifg = INVALCOLOR;
8117 guicolor_T guibg = INVALCOLOR;
8118 int ctermfg = 0;
8119 int ctermbg = 0;
8120
8121 id = syn_name2id((char_u *)"Normal");
8122 if (id > 0 && p_tgc)
8123 syn_id2colors(id, &guifg, &guibg);
8124 if (guifg == INVALCOLOR)
8125 {
8126 ctermfg = -1;
8127 if (id > 0)
8128 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8129 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
8130 : default_console_color_fg;
8131 cterm_normal_fg_gui_color = guifg;
8132 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8133 }
8134 if (guibg == INVALCOLOR)
8135 {
8136 ctermbg = -1;
8137 if (id > 0)
8138 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8139 guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8140 : default_console_color_bg;
8141 cterm_normal_bg_gui_color = guibg;
8142 ctermbg = ctermbg < 0 ? 0 : ctermbg;
8143 }
8144
8145 *cterm_fg = ctermfg;
8146 *cterm_bg = ctermbg;
8147 *gui_fg = guifg;
8148 *gui_bg = guibg;
8149}
8150# endif
8151
Bram Moolenaardf543822020-01-30 11:53:59 +01008152/*
8153 * Set the console colors to the original colors or the last set colors.
8154 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008155 static void
8156reset_console_color_rgb(void)
8157{
8158# ifdef FEAT_TERMGUICOLORS
8159 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8160
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008161 if (USE_WT)
8162 return;
8163
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008164 csbi.cbSize = sizeof(csbi);
8165 if (has_csbiex)
8166 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8167
8168 csbi.cbSize = sizeof(csbi);
8169 csbi.srWindow.Right += 1;
8170 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008171 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8172 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
8173 if (has_csbiex)
8174 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8175# endif
8176}
8177
8178/*
8179 * Set the console colors to the original colors.
8180 */
8181 static void
8182restore_console_color_rgb(void)
8183{
8184# ifdef FEAT_TERMGUICOLORS
8185 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8186
8187 csbi.cbSize = sizeof(csbi);
8188 if (has_csbiex)
8189 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8190
8191 csbi.cbSize = sizeof(csbi);
8192 csbi.srWindow.Right += 1;
8193 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008194 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8195 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008196 if (has_csbiex)
8197 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8198# endif
8199}
8200
8201 void
8202control_console_color_rgb(void)
8203{
8204 if (USE_VTP)
8205 set_console_color_rgb();
8206 else
8207 reset_console_color_rgb();
8208}
8209
8210 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008211use_vtp(void)
8212{
8213 return USE_VTP;
8214}
8215
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008216 int
8217is_term_win32(void)
8218{
8219 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8220}
8221
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008222 int
8223has_vtp_working(void)
8224{
8225 return vtp_working;
8226}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008227
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008228#endif
8229
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008230 int
8231has_conpty_working(void)
8232{
8233 return conpty_working;
8234}
8235
8236 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008237get_conpty_type(void)
8238{
8239 return conpty_type;
8240}
8241
8242 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008243is_conpty_stable(void)
8244{
8245 return conpty_stable;
8246}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008247
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008248 int
8249get_conpty_fix_type(void)
8250{
8251 return conpty_fix_type;
8252}
8253
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008254#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008255 void
8256resize_console_buf(void)
8257{
8258 CONSOLE_SCREEN_BUFFER_INFO csbi;
8259 COORD coord;
8260 SMALL_RECT newsize;
8261
8262 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8263 {
8264 coord.X = SRWIDTH(csbi.srWindow);
8265 coord.Y = SRHEIGHT(csbi.srWindow);
8266 SetConsoleScreenBufferSize(g_hConOut, coord);
8267
8268 newsize.Left = 0;
8269 newsize.Top = 0;
8270 newsize.Right = coord.X - 1;
8271 newsize.Bottom = coord.Y - 1;
8272 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8273
8274 SetConsoleScreenBufferSize(g_hConOut, coord);
8275 }
8276}
8277#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008278
8279 char *
8280GetWin32Error(void)
8281{
8282 char *msg = NULL;
8283 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8284 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
8285 if (msg != NULL)
8286 {
8287 // remove trailing \r\n
8288 char *pcrlf = strstr(msg, "\r\n");
8289 if (pcrlf != NULL)
8290 *pcrlf = '\0';
8291 }
8292 return msg;
8293}