blob: 13960d167e4da40d32e5d492cf04d7173a45a6c8 [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
33/* cproto fails on missing include files */
34#ifndef PROTO
35# include <process.h>
36#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000037
38#undef chdir
39#ifdef __GNUC__
40# ifndef __MINGW32__
41# include <dirent.h>
42# endif
43#else
44# include <direct.h>
45#endif
46
Bram Moolenaar82881492012-11-20 16:53:39 +010047#ifndef PROTO
Bram Moolenaar4f974752019-02-17 17:44:42 +010048# if defined(FEAT_TITLE) && !defined(FEAT_GUI_MSWIN)
Bram Moolenaar82881492012-11-20 16:53:39 +010049# include <shellapi.h>
50# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000051#endif
52
Bram Moolenaarfb630902016-10-29 14:55:00 +020053#ifdef FEAT_JOB_CHANNEL
54# include <tlhelp32.h>
55#endif
56
Bram Moolenaar071d4272004-06-13 20:20:40 +000057#ifdef __MINGW32__
58# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
59# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
60# endif
61# ifndef RIGHTMOST_BUTTON_PRESSED
62# define RIGHTMOST_BUTTON_PRESSED 0x0002
63# endif
64# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
65# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
66# endif
67# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
68# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
69# endif
70# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
71# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
72# endif
73
74/*
75 * EventFlags
76 */
77# ifndef MOUSE_MOVED
78# define MOUSE_MOVED 0x0001
79# endif
80# ifndef DOUBLE_CLICK
81# define DOUBLE_CLICK 0x0002
82# endif
83#endif
84
85/* Record all output and all keyboard & mouse input */
86/* #define MCH_WRITE_DUMP */
87
88#ifdef MCH_WRITE_DUMP
89FILE* fdDump = NULL;
90#endif
91
92/*
93 * When generating prototypes for Win32 on Unix, these lines make the syntax
94 * errors disappear. They do not need to be correct.
95 */
96#ifdef PROTO
97#define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000098typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000099typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000100typedef int ACCESS_MASK;
101typedef int BOOL;
102typedef int COLORREF;
103typedef int CONSOLE_CURSOR_INFO;
104typedef int COORD;
105typedef int DWORD;
106typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100107typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000108typedef int HDC;
109typedef int HFONT;
110typedef int HICON;
111typedef int HINSTANCE;
112typedef int HWND;
113typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200114typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000115typedef int KEY_EVENT_RECORD;
116typedef int LOGFONT;
117typedef int LPBOOL;
118typedef int LPCTSTR;
119typedef int LPDWORD;
120typedef int LPSTR;
121typedef int LPTSTR;
122typedef int LPVOID;
123typedef int MOUSE_EVENT_RECORD;
124typedef int PACL;
125typedef int PDWORD;
126typedef int PHANDLE;
127typedef int PRINTDLG;
128typedef int PSECURITY_DESCRIPTOR;
129typedef int PSID;
130typedef int SECURITY_INFORMATION;
131typedef int SHORT;
132typedef int SMALL_RECT;
133typedef int TEXTMETRIC;
134typedef int TOKEN_INFORMATION_CLASS;
135typedef int TRUSTEE;
136typedef int WORD;
137typedef int WCHAR;
138typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100139typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200140typedef int SE_OBJECT_TYPE;
141typedef int PSNSECINFO;
142typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100143typedef int STARTUPINFO;
144typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200145typedef int LPSECURITY_ATTRIBUTES;
146# define __stdcall /* empty */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000147#endif
148
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200149#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000150/* Win32 Console handles for input and output */
151static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
152static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
153
154/* Win32 Screen buffer,coordinate,console I/O information */
155static SMALL_RECT g_srScrollRegion;
156static COORD g_coord; /* 0-based, but external coords are 1-based */
157
158/* The attribute of the screen when the editor was started */
159static WORD g_attrDefault = 7; /* lightgray text on black background */
160static WORD g_attrCurrent;
161
162static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
163static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
164static int g_fForceExit = FALSE; /* set when forcefully exiting */
165
Bram Moolenaar071d4272004-06-13 20:20:40 +0000166static void scroll(unsigned cLines);
167static void set_scroll_region(unsigned left, unsigned top,
168 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100169static void set_scroll_region_tb(unsigned top, unsigned bottom);
170static void set_scroll_region_lr(unsigned left, unsigned right);
171static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000172static void delete_lines(unsigned cLines);
173static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000174static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000175static int s_cursor_visible = TRUE;
176static int did_create_conin = FALSE;
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200177#endif
178#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000179static int s_dont_use_vimrun = TRUE;
180static int need_vimrun_warning = FALSE;
181static char *vimrun_path = "vimrun ";
182#endif
183
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200184static int win32_getattrs(char_u *name);
185static int win32_setattrs(char_u *name, int attrs);
186static int win32_set_archive(char_u *name);
187
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100188static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200189static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100190static int conpty_stable = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100191static void vtp_flag_init();
192
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200193#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100194static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100195static void vtp_init();
196static void vtp_exit();
197static int vtp_printf(char *format, ...);
198static void vtp_sgr_bulk(int arg);
199static void vtp_sgr_bulks(int argc, int *argv);
200
201static guicolor_T save_console_bg_rgb;
202static guicolor_T save_console_fg_rgb;
203
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200204static int g_color_index_bg = 0;
205static int g_color_index_fg = 7;
206
207# ifdef FEAT_TERMGUICOLORS
208static int default_console_color_bg = 0x000000; // black
209static int default_console_color_fg = 0xc0c0c0; // white
210# endif
211
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100212# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200213# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100214# else
215# define USE_VTP 0
216# endif
217
218static void set_console_color_rgb(void);
219static void reset_console_color_rgb(void);
220#endif
221
222/* This flag is newly created from Windows 10 */
223#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
224# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
225#endif
226
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200227#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000228static int suppress_winsize = 1; /* don't fiddle with console */
229#endif
230
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200231static char_u *exe_path = NULL;
232
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100233static BOOL win8_or_later = FALSE;
234
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200235#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100236/* Dynamic loading for portability */
237typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
238{
239 ULONG cbSize;
240 COORD dwSize;
241 COORD dwCursorPosition;
242 WORD wAttributes;
243 SMALL_RECT srWindow;
244 COORD dwMaximumWindowSize;
245 WORD wPopupAttributes;
246 BOOL bFullscreenSupported;
247 COLORREF ColorTable[16];
248} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
249typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
250static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
251typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
252static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
253static BOOL has_csbiex = FALSE;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100254#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100255
256/*
257 * Get version number including build number
258 */
259typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
260# define MAKE_VER(major, minor, build) \
261 (((major) << 24) | ((minor) << 16) | (build))
262
263 static DWORD
264get_build_number(void)
265{
266 OSVERSIONINFOW osver = {sizeof(OSVERSIONINFOW)};
267 HMODULE hNtdll;
268 PfnRtlGetVersion pRtlGetVersion;
269 DWORD ver = MAKE_VER(0, 0, 0);
270
271 hNtdll = GetModuleHandle("ntdll.dll");
272 if (hNtdll != NULL)
273 {
274 pRtlGetVersion =
275 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
276 pRtlGetVersion(&osver);
277 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
278 min(osver.dwMinorVersion, 255),
279 min(osver.dwBuildNumber, 32767));
280 }
281 return ver;
282}
283
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200284#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100285/*
286 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100287 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100288 */
289 static BOOL
290read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100291 HANDLE hInput,
292 INPUT_RECORD *lpBuffer,
293 DWORD nLength,
294 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100295{
296 enum
297 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100298 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100299 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100300 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100301 static DWORD s_dwIndex = 0;
302 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100303 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100304 int head;
305 int tail;
306 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100307
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200308 if (nLength == -2)
309 return (s_dwMax > 0) ? TRUE : FALSE;
310
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100311 if (!win8_or_later)
312 {
313 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200314 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
315 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100316 }
317
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100318 if (s_dwMax == 0)
319 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100320 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200321 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
322 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100323 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100324 s_dwIndex = 0;
325 s_dwMax = dwEvents;
326 if (dwEvents == 0)
327 {
328 *lpEvents = 0;
329 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100330 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100331
332 if (s_dwMax > 1)
333 {
334 head = 0;
335 tail = s_dwMax - 1;
336 while (head != tail)
337 {
338 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
339 && s_irCache[head + 1].EventType
340 == WINDOW_BUFFER_SIZE_EVENT)
341 {
342 /* Remove duplicate event to avoid flicker. */
343 for (i = head; i < tail; ++i)
344 s_irCache[i] = s_irCache[i + 1];
345 --tail;
346 continue;
347 }
348 head++;
349 }
350 s_dwMax = tail + 1;
351 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100352 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100353
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100354 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200355 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100356 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100357 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100358 return TRUE;
359}
360
361/*
362 * Version of PeekConsoleInput() that works with IME.
363 */
364 static BOOL
365peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100366 HANDLE hInput,
367 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200368 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100369 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100370{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100371 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100372}
373
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100374# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200375 static DWORD
376msg_wait_for_multiple_objects(
377 DWORD nCount,
378 LPHANDLE pHandles,
379 BOOL fWaitAll,
380 DWORD dwMilliseconds,
381 DWORD dwWakeMask)
382{
383 if (read_console_input(NULL, NULL, -2, NULL))
384 return WAIT_OBJECT_0;
385 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
386 dwMilliseconds, dwWakeMask);
387}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100388# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200389
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100390# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200391 static DWORD
392wait_for_single_object(
393 HANDLE hHandle,
394 DWORD dwMilliseconds)
395{
396 if (read_console_input(NULL, NULL, -2, NULL))
397 return WAIT_OBJECT_0;
398 return WaitForSingleObject(hHandle, dwMilliseconds);
399}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100400# endif
401#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200402
Bram Moolenaar071d4272004-06-13 20:20:40 +0000403 static void
404get_exe_name(void)
405{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100406 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
407 * as the maximum length that works (plus a NUL byte). */
408#define MAX_ENV_PATH_LEN 8192
409 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200410 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000411
412 if (exe_name == NULL)
413 {
414 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100415 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000416 if (*temp != NUL)
417 exe_name = FullName_save((char_u *)temp, FALSE);
418 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000419
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200420 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000421 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200422 exe_path = vim_strnsave(exe_name,
423 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200424 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000425 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200426 /* Append our starting directory to $PATH, so that when doing
427 * "!xxd" it's found in our starting directory. Needed because
428 * SearchPath() also looks there. */
429 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100430 if (p == NULL
431 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200432 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100433 if (p == NULL || *p == NUL)
434 temp[0] = NUL;
435 else
436 {
437 STRCPY(temp, p);
438 STRCAT(temp, ";");
439 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200440 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100441 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200442 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000443 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000444 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000445}
446
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200447/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100448 * Unescape characters in "p" that appear in "escaped".
449 */
450 static void
451unescape_shellxquote(char_u *p, char_u *escaped)
452{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100453 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100454 int n;
455
456 while (*p != NUL)
457 {
458 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
459 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100460 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100461 p += n;
462 l -= n;
463 }
464}
465
466/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200467 * Load library "name".
468 */
469 HINSTANCE
470vimLoadLib(char *name)
471{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200472 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200473
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200474 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
475 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200476 if (exe_path == NULL)
477 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200478 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200479 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200480 WCHAR old_dirw[MAXPATHL];
481
482 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
483 {
484 /* Change directory to where the executable is, both to make
485 * sure we find a .dll there and to avoid looking for a .dll
486 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100487 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200488 dll = LoadLibrary(name);
489 SetCurrentDirectoryW(old_dirw);
490 return dll;
491 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200492 }
493 return dll;
494}
495
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200496#if defined(VIMDLL) || defined(PROTO)
497/*
498 * Check if the current executable file is for the GUI subsystem.
499 */
500 int
501mch_is_gui_executable(void)
502{
503 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
504 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
505 PIMAGE_NT_HEADERS pPE;
506
507 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
508 return FALSE;
509 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
510 if (pPE->Signature != IMAGE_NT_SIGNATURE)
511 return FALSE;
512 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
513 return TRUE;
514 return FALSE;
515}
516#endif
517
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100518#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
519/*
520 * Get related information about 'funcname' which is imported by 'hInst'.
521 * If 'info' is 0, return the function address.
522 * If 'info' is 1, return the module name which the function is imported from.
523 */
524 static void *
525get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
526{
527 PBYTE pImage = (PBYTE)hInst;
528 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
529 PIMAGE_NT_HEADERS pPE;
530 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
531 PIMAGE_THUNK_DATA pIAT; /* Import Address Table */
532 PIMAGE_THUNK_DATA pINT; /* Import Name Table */
533 PIMAGE_IMPORT_BY_NAME pImpName;
534
535 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
536 return NULL;
537 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
538 if (pPE->Signature != IMAGE_NT_SIGNATURE)
539 return NULL;
540 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
541 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
542 .VirtualAddress);
543 for (; pImpDesc->FirstThunk; ++pImpDesc)
544 {
545 if (!pImpDesc->OriginalFirstThunk)
546 continue;
547 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
548 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
549 for (; pIAT->u1.Function; ++pIAT, ++pINT)
550 {
551 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
552 continue;
553 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
554 + (UINT_PTR)(pINT->u1.AddressOfData));
555 if (strcmp((char *)pImpName->Name, funcname) == 0)
556 {
557 switch (info)
558 {
559 case 0:
560 return (void *)pIAT->u1.Function;
561 case 1:
562 return (void *)(pImage + pImpDesc->Name);
563 default:
564 return NULL;
565 }
566 }
567 }
568 }
569 return NULL;
570}
571
572/*
573 * Get the module handle which 'funcname' in 'hInst' is imported from.
574 */
575 HINSTANCE
576find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
577{
578 char *modulename;
579
580 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
581 if (modulename != NULL)
582 return GetModuleHandleA(modulename);
583 return NULL;
584}
585
586/*
587 * Get the address of 'funcname' which is imported by 'hInst' DLL.
588 */
589 void *
590get_dll_import_func(HINSTANCE hInst, const char *funcname)
591{
592 return get_imported_func_info(hInst, funcname, 0);
593}
594#endif
595
Bram Moolenaar071d4272004-06-13 20:20:40 +0000596#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
597# ifndef GETTEXT_DLL
598# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200599# define GETTEXT_DLL_ALT1 "libintl-8.dll"
600# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000601# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200602/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000603static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200604static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000605static char *null_libintl_textdomain(const char *);
606static char *null_libintl_bindtextdomain(const char *, const char *);
607static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100608static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000609
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200610static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000611char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200612char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
613 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000614char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
615char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000616 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000617char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
618 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100619int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000620
621 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100622dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000623{
624 int i;
625 static struct
626 {
627 char *name;
628 FARPROC *ptr;
629 } libintl_entry[] =
630 {
631 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200632 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000633 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
634 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
635 {NULL, NULL}
636 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100637 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000638
Bram Moolenaar7554c542018-10-06 15:03:15 +0200639 // No need to initialize twice.
640 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000641 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200642 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100643 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar7554c542018-10-06 15:03:15 +0200644#ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100645 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200646 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
647#endif
648#ifdef GETTEXT_DLL_ALT2
649 if (!hLibintlDLL)
650 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100651#endif
652 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000653 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200654 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000655 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200656 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100657 semsg(_(e_loadlib), GETTEXT_DLL);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200658 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000659 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200660 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000661 }
662 for (i = 0; libintl_entry[i].name != NULL
663 && libintl_entry[i].ptr != NULL; ++i)
664 {
665 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
666 libintl_entry[i].name)) == NULL)
667 {
668 dyn_libintl_end();
669 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000670 {
671 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100672 semsg(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000673 verbose_leave();
674 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000675 return 0;
676 }
677 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000678
679 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000680 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000681 "bind_textdomain_codeset");
682 if (dyn_libintl_bind_textdomain_codeset == NULL)
683 dyn_libintl_bind_textdomain_codeset =
684 null_libintl_bind_textdomain_codeset;
685
Bram Moolenaar0eb035c2019-04-02 22:15:55 +0200686 /* _wputenv() function for the libintl.dll is optional. */
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100687 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
688 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100689 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100690 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
691 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100692
Bram Moolenaar071d4272004-06-13 20:20:40 +0000693 return 1;
694}
695
696 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100697dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000698{
699 if (hLibintlDLL)
700 FreeLibrary(hLibintlDLL);
701 hLibintlDLL = NULL;
702 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200703 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000704 dyn_libintl_textdomain = null_libintl_textdomain;
705 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000706 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100707 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000708}
709
710 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000711null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000712{
713 return (char*)msgid;
714}
715
716 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200717null_libintl_ngettext(
718 const char *msgid,
719 const char *msgid_plural,
720 unsigned long n)
721{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200722 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200723}
724
Bram Moolenaaree695f72016-08-03 22:08:45 +0200725 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100726null_libintl_bindtextdomain(
727 const char *domainname UNUSED,
728 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000729{
730 return NULL;
731}
732
733 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100734null_libintl_bind_textdomain_codeset(
735 const char *domainname UNUSED,
736 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000737{
738 return NULL;
739}
740
741 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100742null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000743{
744 return NULL;
745}
746
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200747 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100748null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100749{
750 return 0;
751}
752
Bram Moolenaar071d4272004-06-13 20:20:40 +0000753#endif /* DYNAMIC_GETTEXT */
754
755/* This symbol is not defined in older versions of the SDK or Visual C++ */
756
757#ifndef VER_PLATFORM_WIN32_WINDOWS
758# define VER_PLATFORM_WIN32_WINDOWS 1
759#endif
760
761DWORD g_PlatformId;
762
763#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100764# ifndef PROTO
765# include <aclapi.h>
766# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200767# ifndef PROTECTED_DACL_SECURITY_INFORMATION
768# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
769# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000770#endif
771
Bram Moolenaar27515922013-06-29 15:36:26 +0200772#ifdef HAVE_ACL
773/*
774 * Enables or disables the specified privilege.
775 */
776 static BOOL
777win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
778{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100779 BOOL bResult;
780 LUID luid;
781 HANDLE hToken;
782 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200783
784 if (!OpenProcessToken(GetCurrentProcess(),
785 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
786 return FALSE;
787
788 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
789 {
790 CloseHandle(hToken);
791 return FALSE;
792 }
793
Bram Moolenaar45500912014-07-09 20:51:07 +0200794 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200795 tokenPrivileges.Privileges[0].Luid = luid;
796 tokenPrivileges.Privileges[0].Attributes = bEnable ?
797 SE_PRIVILEGE_ENABLED : 0;
798
799 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
800 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
801
802 CloseHandle(hToken);
803
804 return bResult && GetLastError() == ERROR_SUCCESS;
805}
806#endif
807
Bram Moolenaar071d4272004-06-13 20:20:40 +0000808/*
809 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
810 * VER_PLATFORM_WIN32_WINDOWS (Win95).
811 */
812 void
813PlatformId(void)
814{
815 static int done = FALSE;
816
817 if (!done)
818 {
819 OSVERSIONINFO ovi;
820
821 ovi.dwOSVersionInfoSize = sizeof(ovi);
822 GetVersionEx(&ovi);
823
824 g_PlatformId = ovi.dwPlatformId;
825
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100826 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
827 || ovi.dwMajorVersion > 6)
828 win8_or_later = TRUE;
829
Bram Moolenaar071d4272004-06-13 20:20:40 +0000830#ifdef HAVE_ACL
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200831 /* Enable privilege for getting or setting SACLs. */
832 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000833#endif
834 done = TRUE;
835 }
836}
837
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200838#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000839
840#define SHIFT (SHIFT_PRESSED)
841#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
842#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
843#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
844
845
846/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
847 * We map function keys to their ANSI terminal equivalents, as produced
848 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
849 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
850 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
851 * combinations of function/arrow/etc keys.
852 */
853
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000854static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000855{
856 WORD wVirtKey;
857 BOOL fAnsiKey;
858 int chAlone;
859 int chShift;
860 int chCtrl;
861 int chAlt;
862} VirtKeyMap[] =
863{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200864// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000865 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
866
867 { VK_F1, TRUE, ';', 'T', '^', 'h', },
868 { VK_F2, TRUE, '<', 'U', '_', 'i', },
869 { VK_F3, TRUE, '=', 'V', '`', 'j', },
870 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
871 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
872 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
873 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
874 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
875 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
876 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200877 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
878 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000879
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200880 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
881 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
882 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
883 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
884 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
885 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
886 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
887 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
888 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
889 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100890 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000891
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200892 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000893
894#if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200895 // Most people don't have F13-F20, but what the hell...
896 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
897 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
898 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
899 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
900 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
901 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
902 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
903 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000904#endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200905 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
906 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
907 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
908 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000909
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200910 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
911 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
912 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
913 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
914 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
915 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
916 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
917 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
918 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
919 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100920 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000921};
922
923
924#ifdef _MSC_VER
925// The ToAscii bug destroys several registers. Need to turn off optimization
926// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000927# pragma warning(push)
928# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000929# pragma optimize("", off)
930#endif
931
932#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200933# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000934#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200935# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000936#endif
937
938/* The return code indicates key code size. */
939 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +0000940win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000941 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000942{
943 UINT uMods = pker->dwControlKeyState;
944 static int s_iIsDead = 0;
945 static WORD awAnsiCode[2];
946 static BYTE abKeystate[256];
947
948
949 if (s_iIsDead == 2)
950 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200951 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000952 s_iIsDead = 0;
953 return 1;
954 }
955
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200956 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000957 return 1;
958
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200959 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000960
Bram Moolenaar071d4272004-06-13 20:20:40 +0000961 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200962 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000963
964 if (uMods & SHIFT_PRESSED)
965 abKeystate[VK_SHIFT] = 0x80;
966 if (uMods & CAPSLOCK_ON)
967 abKeystate[VK_CAPITAL] = 1;
968
969 if ((uMods & ALT_GR) == ALT_GR)
970 {
971 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
972 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
973 }
974
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200975 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
976 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000977
978 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200979 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000980
981 return s_iIsDead;
982}
983
984#ifdef _MSC_VER
985/* MUST switch optimization on again here, otherwise a call to
986 * decode_key_event() may crash (e.g. when hitting caps-lock) */
987# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000988# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000989
990# if (_MSC_VER < 1100)
991/* MUST turn off global optimisation for this next function, or
992 * pressing ctrl-minus in insert mode crashes Vim when built with
993 * VC4.1. -- negri. */
994# pragma optimize("g", off)
995# endif
996#endif
997
998static BOOL g_fJustGotFocus = FALSE;
999
1000/*
1001 * Decode a KEY_EVENT into one or two keystrokes
1002 */
1003 static BOOL
1004decode_key_event(
1005 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001006 WCHAR *pch,
1007 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001008 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001009 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001010{
1011 int i;
1012 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1013
1014 *pch = *pch2 = NUL;
1015 g_fJustGotFocus = FALSE;
1016
1017 /* ignore key up events */
1018 if (!pker->bKeyDown)
1019 return FALSE;
1020
1021 /* ignore some keystrokes */
1022 switch (pker->wVirtualKeyCode)
1023 {
1024 /* modifiers */
1025 case VK_SHIFT:
1026 case VK_CONTROL:
1027 case VK_MENU: /* Alt key */
1028 return FALSE;
1029
1030 default:
1031 break;
1032 }
1033
1034 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001035 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001036 {
1037 /* Ctrl-6 is Ctrl-^ */
1038 if (pker->wVirtualKeyCode == '6')
1039 {
1040 *pch = Ctrl_HAT;
1041 return TRUE;
1042 }
1043 /* Ctrl-2 is Ctrl-@ */
1044 else if (pker->wVirtualKeyCode == '2')
1045 {
1046 *pch = NUL;
1047 return TRUE;
1048 }
1049 /* Ctrl-- is Ctrl-_ */
1050 else if (pker->wVirtualKeyCode == 0xBD)
1051 {
1052 *pch = Ctrl__;
1053 return TRUE;
1054 }
1055 }
1056
1057 /* Shift-TAB */
1058 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1059 {
1060 *pch = K_NUL;
1061 *pch2 = '\017';
1062 return TRUE;
1063 }
1064
1065 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1066 {
1067 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1068 {
1069 if (nModifs == 0)
1070 *pch = VirtKeyMap[i].chAlone;
1071 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1072 *pch = VirtKeyMap[i].chShift;
1073 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1074 *pch = VirtKeyMap[i].chCtrl;
1075 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1076 *pch = VirtKeyMap[i].chAlt;
1077
1078 if (*pch != 0)
1079 {
1080 if (VirtKeyMap[i].fAnsiKey)
1081 {
1082 *pch2 = *pch;
1083 *pch = K_NUL;
1084 }
1085
1086 return TRUE;
1087 }
1088 }
1089 }
1090
1091 i = win32_kbd_patch_key(pker);
1092
1093 if (i < 0)
1094 *pch = NUL;
1095 else
1096 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001097 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001098
1099 if (pmodifiers != NULL)
1100 {
1101 /* Pass on the ALT key as a modifier, but only when not combined
1102 * with CTRL (which is ALTGR). */
1103 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1104 *pmodifiers |= MOD_MASK_ALT;
1105
1106 /* Pass on SHIFT only for special keys, because we don't know when
1107 * it's already included with the character. */
1108 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1109 *pmodifiers |= MOD_MASK_SHIFT;
1110
1111 /* Pass on CTRL only for non-special keys, because we don't know
1112 * when it's already included with the character. And not when
1113 * combined with ALT (which is ALTGR). */
1114 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1115 && *pch >= 0x20 && *pch < 0x80)
1116 *pmodifiers |= MOD_MASK_CTRL;
1117 }
1118 }
1119
1120 return (*pch != NUL);
1121}
1122
1123#ifdef _MSC_VER
1124# pragma optimize("", on)
1125#endif
1126
Bram Moolenaar4f974752019-02-17 17:44:42 +01001127#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001128
1129
Bram Moolenaar071d4272004-06-13 20:20:40 +00001130/*
1131 * For the GUI the mouse handling is in gui_w32.c.
1132 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001133#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001134 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001135mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001136{
1137}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001138#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001139static int g_fMouseAvail = FALSE; /* mouse present */
1140static int g_fMouseActive = FALSE; /* mouse enabled */
1141static int g_nMouseClick = -1; /* mouse status */
1142static int g_xMouse; /* mouse x coordinate */
1143static int g_yMouse; /* mouse y coordinate */
1144
1145/*
1146 * Enable or disable mouse input
1147 */
1148 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001149mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001150{
1151 DWORD cmodein;
1152
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001153# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001154 if (gui.in_use)
1155 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001156# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001157 if (!g_fMouseAvail)
1158 return;
1159
1160 g_fMouseActive = on;
1161 GetConsoleMode(g_hConIn, &cmodein);
1162
1163 if (g_fMouseActive)
1164 cmodein |= ENABLE_MOUSE_INPUT;
1165 else
1166 cmodein &= ~ENABLE_MOUSE_INPUT;
1167
1168 SetConsoleMode(g_hConIn, cmodein);
1169}
1170
Bram Moolenaar157d8132018-03-06 17:09:20 +01001171
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001172# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001173/*
1174 * Called when 'balloonevalterm' changed.
1175 */
1176 void
1177mch_bevalterm_changed(void)
1178{
1179 mch_setmouse(g_fMouseActive);
1180}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001181# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001182
Bram Moolenaar071d4272004-06-13 20:20:40 +00001183/*
1184 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1185 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1186 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1187 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1188 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1189 * and we return the mouse position in g_xMouse and g_yMouse.
1190 *
1191 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1192 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1193 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1194 *
1195 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1196 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1197 *
1198 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1199 * moves, even if it stays within the same character cell. We ignore
1200 * all MOUSE_MOVED messages if the position hasn't really changed, and
1201 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1202 * we're only interested in MOUSE_DRAG).
1203 *
1204 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1205 * 2-button mouses by pressing the left & right buttons simultaneously.
1206 * In practice, it's almost impossible to click both at the same time,
1207 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1208 * in such cases, if the user is clicking quickly.
1209 */
1210 static BOOL
1211decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001212 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001213{
1214 static int s_nOldButton = -1;
1215 static int s_nOldMouseClick = -1;
1216 static int s_xOldMouse = -1;
1217 static int s_yOldMouse = -1;
1218 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001219# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001220 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001221# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001222 static int s_cClicks = 1;
1223 static BOOL s_fReleased = TRUE;
1224 static DWORD s_dwLastClickTime = 0;
1225 static BOOL s_fNextIsMiddle = FALSE;
1226
1227 static DWORD cButtons = 0; /* number of buttons supported */
1228
1229 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1230 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1231 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1232 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1233
1234 int nButton;
1235
1236 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1237 cButtons = 2;
1238
1239 if (!g_fMouseAvail || !g_fMouseActive)
1240 {
1241 g_nMouseClick = -1;
1242 return FALSE;
1243 }
1244
1245 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1246 if (g_fJustGotFocus)
1247 {
1248 g_fJustGotFocus = FALSE;
1249 return FALSE;
1250 }
1251
1252 /* unprocessed mouse click? */
1253 if (g_nMouseClick != -1)
1254 return TRUE;
1255
1256 nButton = -1;
1257 g_xMouse = pmer->dwMousePosition.X;
1258 g_yMouse = pmer->dwMousePosition.Y;
1259
1260 if (pmer->dwEventFlags == MOUSE_MOVED)
1261 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001262 /* Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
Bram Moolenaar071d4272004-06-13 20:20:40 +00001263 * events even when the mouse moves only within a char cell.) */
1264 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1265 return FALSE;
1266 }
1267
1268 /* If no buttons are pressed... */
1269 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1270 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001271 nButton = MOUSE_RELEASE;
1272
Bram Moolenaar071d4272004-06-13 20:20:40 +00001273 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1274 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001275 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001276# ifdef FEAT_BEVAL_TERM
Bram Moolenaar157d8132018-03-06 17:09:20 +01001277 /* do return mouse move events when we want them */
1278 if (p_bevalterm)
1279 nButton = MOUSE_DRAG;
1280 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001281# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001282 return FALSE;
1283 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001284
Bram Moolenaar071d4272004-06-13 20:20:40 +00001285 s_fReleased = TRUE;
1286 }
1287 else /* one or more buttons pressed */
1288 {
1289 /* on a 2-button mouse, hold down left and right buttons
1290 * simultaneously to get MIDDLE. */
1291
1292 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1293 {
1294 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1295
1296 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001297 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001298 if (dwLR == LEFT || dwLR == RIGHT)
1299 {
1300 for (;;)
1301 {
1302 /* wait a short time for next input event */
1303 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1304 != WAIT_OBJECT_0)
1305 break;
1306 else
1307 {
1308 DWORD cRecords = 0;
1309 INPUT_RECORD ir;
1310 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1311
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001312 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001313
1314 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1315 || !(pmer2->dwButtonState & LEFT_RIGHT))
1316 break;
1317 else
1318 {
1319 if (pmer2->dwEventFlags != MOUSE_MOVED)
1320 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001321 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001322
1323 return decode_mouse_event(pmer2);
1324 }
1325 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1326 s_yOldMouse == pmer2->dwMousePosition.Y)
1327 {
1328 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001329 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001330
1331 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001332 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001333
1334 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1335 break;
1336 }
1337 else
1338 break;
1339 }
1340 }
1341 }
1342 }
1343 }
1344
1345 if (s_fNextIsMiddle)
1346 {
1347 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1348 ? MOUSE_DRAG : MOUSE_MIDDLE;
1349 s_fNextIsMiddle = FALSE;
1350 }
1351 else if (cButtons == 2 &&
1352 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1353 {
1354 nButton = MOUSE_MIDDLE;
1355
1356 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1357 {
1358 s_fNextIsMiddle = TRUE;
1359 nButton = MOUSE_RELEASE;
1360 }
1361 }
1362 else if ((pmer->dwButtonState & LEFT) == LEFT)
1363 nButton = MOUSE_LEFT;
1364 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1365 nButton = MOUSE_MIDDLE;
1366 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1367 nButton = MOUSE_RIGHT;
1368
1369 if (! s_fReleased && ! s_fNextIsMiddle
1370 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1371 return FALSE;
1372
1373 s_fReleased = s_fNextIsMiddle;
1374 }
1375
1376 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1377 {
1378 /* button pressed or released, without mouse moving */
1379 if (nButton != -1 && nButton != MOUSE_RELEASE)
1380 {
1381 DWORD dwCurrentTime = GetTickCount();
1382
1383 if (s_xOldMouse != g_xMouse
1384 || s_yOldMouse != g_yMouse
1385 || s_nOldButton != nButton
1386 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001387# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001388 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001389# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001390 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1391 {
1392 s_cClicks = 1;
1393 }
1394 else if (++s_cClicks > 4)
1395 {
1396 s_cClicks = 1;
1397 }
1398
1399 s_dwLastClickTime = dwCurrentTime;
1400 }
1401 }
1402 else if (pmer->dwEventFlags == MOUSE_MOVED)
1403 {
1404 if (nButton != -1 && nButton != MOUSE_RELEASE)
1405 nButton = MOUSE_DRAG;
1406
1407 s_cClicks = 1;
1408 }
1409
1410 if (nButton == -1)
1411 return FALSE;
1412
1413 if (nButton != MOUSE_RELEASE)
1414 s_nOldButton = nButton;
1415
1416 g_nMouseClick = nButton;
1417
1418 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1419 g_nMouseClick |= MOUSE_SHIFT;
1420 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1421 g_nMouseClick |= MOUSE_CTRL;
1422 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1423 g_nMouseClick |= MOUSE_ALT;
1424
1425 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1426 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1427
1428 /* only pass on interesting (i.e., different) mouse events */
1429 if (s_xOldMouse == g_xMouse
1430 && s_yOldMouse == g_yMouse
1431 && s_nOldMouseClick == g_nMouseClick)
1432 {
1433 g_nMouseClick = -1;
1434 return FALSE;
1435 }
1436
1437 s_xOldMouse = g_xMouse;
1438 s_yOldMouse = g_yMouse;
1439 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001440# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001441 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001442# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001443 s_nOldMouseClick = g_nMouseClick;
1444
1445 return TRUE;
1446}
1447
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001448#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001449
1450
1451#ifdef MCH_CURSOR_SHAPE
1452/*
1453 * Set the shape of the cursor.
1454 * 'thickness' can be from 1 (thin) to 99 (block)
1455 */
1456 static void
1457mch_set_cursor_shape(int thickness)
1458{
1459 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1460 ConsoleCursorInfo.dwSize = thickness;
1461 ConsoleCursorInfo.bVisible = s_cursor_visible;
1462
1463 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1464 if (s_cursor_visible)
1465 SetConsoleCursorPosition(g_hConOut, g_coord);
1466}
1467
1468 void
1469mch_update_cursor(void)
1470{
1471 int idx;
1472 int thickness;
1473
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001474# ifdef VIMDLL
1475 if (gui.in_use)
1476 return;
1477# endif
1478
Bram Moolenaar071d4272004-06-13 20:20:40 +00001479 /*
1480 * How the cursor is drawn depends on the current mode.
1481 */
1482 idx = get_shape_idx(FALSE);
1483
1484 if (shape_table[idx].shape == SHAPE_BLOCK)
1485 thickness = 99; /* 100 doesn't work on W95 */
1486 else
1487 thickness = shape_table[idx].percentage;
1488 mch_set_cursor_shape(thickness);
1489}
1490#endif
1491
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001492#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001493/*
1494 * Handle FOCUS_EVENT.
1495 */
1496 static void
1497handle_focus_event(INPUT_RECORD ir)
1498{
1499 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1500 ui_focus_change((int)g_fJustGotFocus);
1501}
1502
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001503static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1504
Bram Moolenaar071d4272004-06-13 20:20:40 +00001505/*
1506 * Wait until console input from keyboard or mouse is available,
1507 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001508 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001509 * Return TRUE if something is available FALSE if not.
1510 */
1511 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001512WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001513{
1514 DWORD dwNow = 0, dwEndTime = 0;
1515 INPUT_RECORD ir;
1516 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001517 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001518#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001519 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001520#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001521
1522 if (msec > 0)
1523 /* Wait until the specified time has elapsed. */
1524 dwEndTime = GetTickCount() + msec;
1525 else if (msec < 0)
1526 /* Wait forever. */
1527 dwEndTime = INFINITE;
1528
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001529 // We need to loop until the end of the time period, because
1530 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001531 for (;;)
1532 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001533 // Only process messages when waiting.
1534 if (msec != 0)
1535 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001536#ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001537 parse_queued_messages();
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001538#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001539#ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001540 mzvim_check_threads();
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001541#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001542#ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001543 serverProcessPendingMessages();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001544#endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001545 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001546
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001547 if (g_nMouseClick != -1
Bram Moolenaar071d4272004-06-13 20:20:40 +00001548#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001549 || (!ignore_input && input_available())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001550#endif
1551 )
1552 return TRUE;
1553
1554 if (msec > 0)
1555 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001556 /* If the specified wait time has passed, return. Beware that
1557 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001558 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001559 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001560 break;
1561 }
1562 if (msec != 0)
1563 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001564 DWORD dwWaitTime = dwEndTime - dwNow;
1565
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001566#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001567 /* Check channel while waiting for input. */
Bram Moolenaar9186a272016-02-23 19:34:01 +01001568 if (dwWaitTime > 100)
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001569 {
Bram Moolenaar9186a272016-02-23 19:34:01 +01001570 dwWaitTime = 100;
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001571 /* If there is readahead then parse_queued_messages() timed out
1572 * and we should call it again soon. */
1573 if (channel_any_readahead())
1574 dwWaitTime = 10;
1575 }
Bram Moolenaar9186a272016-02-23 19:34:01 +01001576#endif
Bram Moolenaarc3719bd2017-11-18 22:13:31 +01001577#ifdef FEAT_BEVAL_GUI
Bram Moolenaar59716a22017-03-01 20:32:44 +01001578 if (p_beval && dwWaitTime > 100)
1579 /* The 'balloonexpr' may indirectly invoke a callback while
1580 * waiting for a character, need to check often. */
1581 dwWaitTime = 100;
1582#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001583#ifdef FEAT_MZSCHEME
1584 if (mzthreads_allowed() && p_mzq > 0
1585 && (msec < 0 || (long)dwWaitTime > p_mzq))
1586 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1587#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001588#ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001589 // When waiting very briefly don't trigger timers.
1590 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001591 {
1592 long due_time;
1593
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001594 // Trigger timers and then get the time in msec until the next
1595 // one is due. Wait up to that time.
1596 due_time = check_due_timer();
1597 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001598 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001599 // timer may have used feedkeys().
1600 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001601 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001602 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1603 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001604 }
1605#endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001606 if (
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607#ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001608 // Wait for either an event on the console input or a
1609 // message in the client-server window.
1610 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1611 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001612#else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001613 wait_for_single_object(g_hConIn, dwWaitTime)
1614 != WAIT_OBJECT_0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001615#endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001616 )
1617 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001618 }
1619
1620 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001621 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001622
1623#ifdef FEAT_MBYTE_IME
1624 if (State & CMDLINE && msg_row == Rows - 1)
1625 {
1626 CONSOLE_SCREEN_BUFFER_INFO csbi;
1627
1628 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1629 {
1630 if (csbi.dwCursorPosition.Y != msg_row)
1631 {
1632 /* The screen is now messed up, must redraw the
1633 * command line and later all the windows. */
1634 redraw_all_later(CLEAR);
1635 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1636 redrawcmd();
1637 }
1638 }
1639 }
1640#endif
1641
1642 if (cRecords > 0)
1643 {
1644 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1645 {
1646#ifdef FEAT_MBYTE_IME
1647 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1648 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001649 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001650 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1651 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001652 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001653 continue;
1654 }
1655#endif
1656 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1657 NULL, FALSE))
1658 return TRUE;
1659 }
1660
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001661 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001662
1663 if (ir.EventType == FOCUS_EVENT)
1664 handle_focus_event(ir);
1665 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001666 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001667 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1668
1669 // Only call shell_resized() when the size actually change to
1670 // avoid the screen is cleard.
1671 if (dwSize.X != Columns || dwSize.Y != Rows)
1672 {
1673 CONSOLE_SCREEN_BUFFER_INFO csbi;
1674 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
1675 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
1676 ResizeConBuf(g_hConOut, dwSize);
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001677 shell_resized();
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001678 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001679 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001680 else if (ir.EventType == MOUSE_EVENT
1681 && decode_mouse_event(&ir.Event.MouseEvent))
1682 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001683 }
1684 else if (msec == 0)
1685 break;
1686 }
1687
1688#ifdef FEAT_CLIENTSERVER
1689 /* Something might have been received while we were waiting. */
1690 if (input_available())
1691 return TRUE;
1692#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001693
Bram Moolenaar071d4272004-06-13 20:20:40 +00001694 return FALSE;
1695}
1696
Bram Moolenaar071d4272004-06-13 20:20:40 +00001697/*
1698 * return non-zero if a character is available
1699 */
1700 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001701mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001702{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001703# ifdef VIMDLL
1704 if (gui.in_use)
1705 return TRUE;
1706# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001707 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001708}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001709
1710# if defined(FEAT_TERMINAL) || defined(PROTO)
1711/*
1712 * Check for any pending input or messages.
1713 */
1714 int
1715mch_check_messages(void)
1716{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001717# ifdef VIMDLL
1718 if (gui.in_use)
1719 return TRUE;
1720# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001721 return WaitForChar(0L, TRUE);
1722}
1723# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001724
1725/*
1726 * Create the console input. Used when reading stdin doesn't work.
1727 */
1728 static void
1729create_conin(void)
1730{
1731 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1732 FILE_SHARE_READ|FILE_SHARE_WRITE,
1733 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001734 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001735 did_create_conin = TRUE;
1736}
1737
1738/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001739 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001740 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001741 static WCHAR
1742tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001743{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001744 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001745
1746 for (;;)
1747 {
1748 INPUT_RECORD ir;
1749 DWORD cRecords = 0;
1750
1751#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001752 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001753 if (input_available())
1754 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001755 if (g_nMouseClick != -1)
1756 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001757#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001758 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001759 {
1760 if (did_create_conin)
1761 read_error_exit();
1762 create_conin();
1763 continue;
1764 }
1765
1766 if (ir.EventType == KEY_EVENT)
1767 {
1768 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1769 pmodifiers, TRUE))
1770 return ch;
1771 }
1772 else if (ir.EventType == FOCUS_EVENT)
1773 handle_focus_event(ir);
1774 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1775 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001776 else if (ir.EventType == MOUSE_EVENT)
1777 {
1778 if (decode_mouse_event(&ir.Event.MouseEvent))
1779 return 0;
1780 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001781 }
1782}
Bram Moolenaar4f974752019-02-17 17:44:42 +01001783#endif /* !FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001784
1785
1786/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001787 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001788 * Get one or more characters from the keyboard or the mouse.
1789 * If time == 0, do not wait for characters.
1790 * If time == n, wait a short time for characters.
1791 * If time == -1, wait forever for characters.
1792 * Returns the number of characters read into buf.
1793 */
1794 int
1795mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001796 char_u *buf UNUSED,
1797 int maxlen UNUSED,
1798 long time UNUSED,
1799 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001800{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001801#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001802
1803 int len;
1804 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001805#define TYPEAHEADLEN 20
1806 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1807 static int typeaheadlen = 0;
1808
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001809# ifdef VIMDLL
1810 if (gui.in_use)
1811 return 0;
1812# endif
1813
Bram Moolenaar071d4272004-06-13 20:20:40 +00001814 /* First use any typeahead that was kept because "buf" was too small. */
1815 if (typeaheadlen > 0)
1816 goto theend;
1817
Bram Moolenaar071d4272004-06-13 20:20:40 +00001818 if (time >= 0)
1819 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001820 if (!WaitForChar(time, FALSE)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001821 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001822 }
1823 else /* time == -1, wait forever */
1824 {
1825 mch_set_winsize_now(); /* Allow winsize changes from now on */
1826
Bram Moolenaar3918c952005-03-15 22:34:55 +00001827 /*
1828 * If there is no character available within 2 seconds (default)
1829 * write the autoscript file to disk. Or cause the CursorHold event
1830 * to be triggered.
1831 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001832 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001833 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001834 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001835 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001836 buf[0] = K_SPECIAL;
1837 buf[1] = KS_EXTRA;
1838 buf[2] = (int)KE_CURSORHOLD;
1839 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001840 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001841 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001842 }
1843 }
1844
1845 /*
1846 * Try to read as many characters as there are, until the buffer is full.
1847 */
1848
1849 /* we will get at least one key. Get more if they are available. */
1850 g_fCBrkPressed = FALSE;
1851
1852#ifdef MCH_WRITE_DUMP
1853 if (fdDump)
1854 fputc('[', fdDump);
1855#endif
1856
1857 /* Keep looping until there is something in the typeahead buffer and more
1858 * to get and still room in the buffer (up to two bytes for a char and
1859 * three bytes for a modifier). */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001860 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001861 && typeaheadlen + 5 <= TYPEAHEADLEN)
1862 {
1863 if (typebuf_changed(tb_change_cnt))
1864 {
1865 /* "buf" may be invalid now if a client put something in the
1866 * typeahead buffer and "buf" is in the typeahead buffer. */
1867 typeaheadlen = 0;
1868 break;
1869 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001870 if (g_nMouseClick != -1)
1871 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001872#ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001873 if (fdDump)
1874 fprintf(fdDump, "{%02x @ %d, %d}",
1875 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001876#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001877 typeahead[typeaheadlen++] = ESC + 128;
1878 typeahead[typeaheadlen++] = 'M';
1879 typeahead[typeaheadlen++] = g_nMouseClick;
1880 typeahead[typeaheadlen++] = g_xMouse + '!';
1881 typeahead[typeaheadlen++] = g_yMouse + '!';
1882 g_nMouseClick = -1;
1883 }
1884 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001885 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001886 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001887 int modifiers = 0;
1888
1889 c = tgetch(&modifiers, &ch2);
1890
1891 if (typebuf_changed(tb_change_cnt))
1892 {
1893 /* "buf" may be invalid now if a client put something in the
1894 * typeahead buffer and "buf" is in the typeahead buffer. */
1895 typeaheadlen = 0;
1896 break;
1897 }
1898
1899 if (c == Ctrl_C && ctrl_c_interrupts)
1900 {
1901#if defined(FEAT_CLIENTSERVER)
1902 trash_input_buf();
1903#endif
1904 got_int = TRUE;
1905 }
1906
Bram Moolenaar071d4272004-06-13 20:20:40 +00001907 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001908 {
1909 int n = 1;
1910
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001911 if (ch2 == NUL)
1912 {
1913 int i;
1914 char_u *p;
1915 WCHAR ch[2];
1916
1917 ch[0] = c;
1918 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1919 {
1920 ch[1] = tgetch(&modifiers, &ch2);
1921 n++;
1922 }
1923 p = utf16_to_enc(ch, &n);
1924 if (p != NULL)
1925 {
1926 for (i = 0; i < n; i++)
1927 typeahead[typeaheadlen + i] = p[i];
1928 vim_free(p);
1929 }
1930 }
1931 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001932 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001933 if (ch2 != NUL)
1934 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001935 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001936 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001937 switch (ch2)
1938 {
1939 case (WCHAR)'\324': // SHIFT+Insert
1940 case (WCHAR)'\325': // CTRL+Insert
1941 case (WCHAR)'\327': // SHIFT+Delete
1942 case (WCHAR)'\330': // CTRL+Delete
1943 typeahead[typeaheadlen + n] = (char_u)ch2;
1944 n++;
1945 break;
1946
1947 default:
1948 typeahead[typeaheadlen + n] = 3;
1949 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1950 n += 2;
1951 break;
1952 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001953 }
1954 else
1955 {
1956 typeahead[typeaheadlen + n] = 3;
1957 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1958 n += 2;
1959 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001960 }
1961
Bram Moolenaar071d4272004-06-13 20:20:40 +00001962 /* Use the ALT key to set the 8th bit of the character
1963 * when it's one byte, the 8th bit isn't set yet and not
1964 * using a double-byte encoding (would become a lead
1965 * byte). */
1966 if ((modifiers & MOD_MASK_ALT)
1967 && n == 1
1968 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001969 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00001970 )
1971 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001972 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1973 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001974 modifiers &= ~MOD_MASK_ALT;
1975 }
1976
1977 if (modifiers != 0)
1978 {
1979 /* Prepend modifiers to the character. */
1980 mch_memmove(typeahead + typeaheadlen + 3,
1981 typeahead + typeaheadlen, n);
1982 typeahead[typeaheadlen++] = K_SPECIAL;
1983 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1984 typeahead[typeaheadlen++] = modifiers;
1985 }
1986
1987 typeaheadlen += n;
1988
1989#ifdef MCH_WRITE_DUMP
1990 if (fdDump)
1991 fputc(c, fdDump);
1992#endif
1993 }
1994 }
1995 }
1996
1997#ifdef MCH_WRITE_DUMP
1998 if (fdDump)
1999 {
2000 fputs("]\n", fdDump);
2001 fflush(fdDump);
2002 }
2003#endif
2004
Bram Moolenaar071d4272004-06-13 20:20:40 +00002005theend:
2006 /* Move typeahead to "buf", as much as fits. */
2007 len = 0;
2008 while (len < maxlen && typeaheadlen > 0)
2009 {
2010 buf[len++] = typeahead[0];
2011 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2012 }
2013 return len;
2014
Bram Moolenaar4f974752019-02-17 17:44:42 +01002015#else /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002016 return 0;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002017#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002018}
2019
Bram Moolenaar82881492012-11-20 16:53:39 +01002020#ifndef PROTO
2021# ifndef __MINGW32__
2022# include <shellapi.h> /* required for FindExecutable() */
2023# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002024#endif
2025
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002026/*
Bram Moolenaar43663192017-03-05 14:29:12 +01002027 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2028 * If "use_path" is FALSE: Return TRUE if "name" exists.
2029 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2030 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002031 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002032 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002033 static int
Bram Moolenaar43663192017-03-05 14:29:12 +01002034executable_exists(char *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002035{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002036 WCHAR *p;
2037 WCHAR fnamew[_MAX_PATH];
2038 WCHAR *dumw;
2039 WCHAR *wcurpath, *wnewpath;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002040 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002041
Bram Moolenaar43663192017-03-05 14:29:12 +01002042 if (!use_path)
2043 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002044 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01002045 {
2046 if (path != NULL)
Bram Moolenaar066029e2017-03-05 15:19:32 +01002047 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002048 if (mch_isFullName((char_u *)name))
Bram Moolenaar066029e2017-03-05 15:19:32 +01002049 *path = vim_strsave((char_u *)name);
2050 else
2051 *path = FullName_save((char_u *)name, FALSE);
2052 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002053 return TRUE;
2054 }
2055 return FALSE;
2056 }
2057
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002058 p = enc_to_utf16((char_u *)name, NULL);
2059 if (p == NULL)
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002060 return FALSE;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002061
2062 wcurpath = _wgetenv(L"PATH");
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002063 wnewpath = ALLOC_MULT(WCHAR, wcslen(wcurpath) + 3);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002064 if (wnewpath == NULL)
2065 return FALSE;
2066 wcscpy(wnewpath, L".;");
2067 wcscat(wnewpath, wcurpath);
2068 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
2069 vim_free(wnewpath);
2070 vim_free(p);
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002071 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002072 return FALSE;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002073 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002074 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002075 if (path != NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002076 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002077 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002078}
2079
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002080#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2081 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002082/*
2083 * Bad parameter handler.
2084 *
2085 * Certain MS CRT functions will intentionally crash when passed invalid
2086 * parameters to highlight possible security holes. Setting this function as
2087 * the bad parameter handler will prevent the crash.
2088 *
2089 * In debug builds the parameters contain CRT information that might help track
2090 * down the source of a problem, but in non-debug builds the arguments are all
2091 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2092 * worth allowing these to make debugging of issues easier.
2093 */
2094 static void
2095bad_param_handler(const wchar_t *expression,
2096 const wchar_t *function,
2097 const wchar_t *file,
2098 unsigned int line,
2099 uintptr_t pReserved)
2100{
2101}
2102
2103# define SET_INVALID_PARAM_HANDLER \
2104 ((void)_set_invalid_parameter_handler(bad_param_handler))
2105#else
2106# define SET_INVALID_PARAM_HANDLER
2107#endif
2108
Bram Moolenaar4f974752019-02-17 17:44:42 +01002109#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002110
2111/*
2112 * GUI version of mch_init().
2113 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002114 static void
2115mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002116{
2117#ifndef __MINGW32__
2118 extern int _fmode;
2119#endif
2120
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002121 /* Silently handle invalid parameters to CRT functions */
2122 SET_INVALID_PARAM_HANDLER;
2123
Bram Moolenaar071d4272004-06-13 20:20:40 +00002124 /* Let critical errors result in a failure, not in a dialog box. Required
2125 * for the timestamp test to work on removed floppies. */
2126 SetErrorMode(SEM_FAILCRITICALERRORS);
2127
2128 _fmode = O_BINARY; /* we do our own CR-LF translation */
2129
2130 /* Specify window size. Is there a place to get the default from? */
2131 Rows = 25;
2132 Columns = 80;
2133
2134 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002135 {
2136 char_u vimrun_location[_MAX_PATH + 4];
2137
2138 /* First try in same directory as gvim.exe */
2139 STRCPY(vimrun_location, exe_name);
2140 STRCPY(gettail(vimrun_location), "vimrun.exe");
2141 if (mch_getperm(vimrun_location) >= 0)
2142 {
2143 if (*skiptowhite(vimrun_location) != NUL)
2144 {
2145 /* Enclose path with white space in double quotes. */
2146 mch_memmove(vimrun_location + 1, vimrun_location,
2147 STRLEN(vimrun_location) + 1);
2148 *vimrun_location = '"';
2149 STRCPY(gettail(vimrun_location), "vimrun\" ");
2150 }
2151 else
2152 STRCPY(gettail(vimrun_location), "vimrun ");
2153
2154 vimrun_path = (char *)vim_strsave(vimrun_location);
2155 s_dont_use_vimrun = FALSE;
2156 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002157 else if (executable_exists("vimrun.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002158 s_dont_use_vimrun = FALSE;
2159
2160 /* Don't give the warning for a missing vimrun.exe right now, but only
2161 * when vimrun was supposed to be used. Don't bother people that do
2162 * not need vimrun.exe. */
2163 if (s_dont_use_vimrun)
2164 need_vimrun_warning = TRUE;
2165 }
2166
2167 /*
2168 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2169 * Otherwise the default "findstr /n" is used.
2170 */
Bram Moolenaar43663192017-03-05 14:29:12 +01002171 if (!executable_exists("findstr.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002172 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2173
2174#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002175 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002176#endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002177
2178 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002179}
2180
2181
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002182#endif /* FEAT_GUI_MSWIN */
2183
2184#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002185
2186#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2187#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2188
2189/*
2190 * ClearConsoleBuffer()
2191 * Description:
2192 * Clears the entire contents of the console screen buffer, using the
2193 * specified attribute.
2194 * Returns:
2195 * TRUE on success
2196 */
2197 static BOOL
2198ClearConsoleBuffer(WORD wAttribute)
2199{
2200 CONSOLE_SCREEN_BUFFER_INFO csbi;
2201 COORD coord;
2202 DWORD NumCells, dummy;
2203
2204 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2205 return FALSE;
2206
2207 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2208 coord.X = 0;
2209 coord.Y = 0;
2210 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2211 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002212 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002213 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2214 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002215 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002216
2217 return TRUE;
2218}
2219
2220/*
2221 * FitConsoleWindow()
2222 * Description:
2223 * Checks if the console window will fit within given buffer dimensions.
2224 * Also, if requested, will shrink the window to fit.
2225 * Returns:
2226 * TRUE on success
2227 */
2228 static BOOL
2229FitConsoleWindow(
2230 COORD dwBufferSize,
2231 BOOL WantAdjust)
2232{
2233 CONSOLE_SCREEN_BUFFER_INFO csbi;
2234 COORD dwWindowSize;
2235 BOOL NeedAdjust = FALSE;
2236
2237 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2238 {
2239 /*
2240 * A buffer resize will fail if the current console window does
2241 * not lie completely within that buffer. To avoid this, we might
2242 * have to move and possibly shrink the window.
2243 */
2244 if (csbi.srWindow.Right >= dwBufferSize.X)
2245 {
2246 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2247 if (dwWindowSize.X > dwBufferSize.X)
2248 dwWindowSize.X = dwBufferSize.X;
2249 csbi.srWindow.Right = dwBufferSize.X - 1;
2250 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2251 NeedAdjust = TRUE;
2252 }
2253 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2254 {
2255 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2256 if (dwWindowSize.Y > dwBufferSize.Y)
2257 dwWindowSize.Y = dwBufferSize.Y;
2258 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2259 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2260 NeedAdjust = TRUE;
2261 }
2262 if (NeedAdjust && WantAdjust)
2263 {
2264 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2265 return FALSE;
2266 }
2267 return TRUE;
2268 }
2269
2270 return FALSE;
2271}
2272
2273typedef struct ConsoleBufferStruct
2274{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002275 BOOL IsValid;
2276 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002277 PCHAR_INFO Buffer;
2278 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002279 PSMALL_RECT Regions;
2280 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002281} ConsoleBuffer;
2282
2283/*
2284 * SaveConsoleBuffer()
2285 * Description:
2286 * Saves important information about the console buffer, including the
2287 * actual buffer contents. The saved information is suitable for later
2288 * restoration by RestoreConsoleBuffer().
2289 * Returns:
2290 * TRUE if all information was saved; FALSE otherwise
2291 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2292 */
2293 static BOOL
2294SaveConsoleBuffer(
2295 ConsoleBuffer *cb)
2296{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002297 DWORD NumCells;
2298 COORD BufferCoord;
2299 SMALL_RECT ReadRegion;
2300 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002301 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002302
Bram Moolenaar071d4272004-06-13 20:20:40 +00002303 if (cb == NULL)
2304 return FALSE;
2305
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002306 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002307 {
2308 cb->IsValid = FALSE;
2309 return FALSE;
2310 }
2311 cb->IsValid = TRUE;
2312
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002313 /*
2314 * Allocate a buffer large enough to hold the entire console screen
2315 * buffer. If this ConsoleBuffer structure has already been initialized
2316 * with a buffer of the correct size, then just use that one.
2317 */
2318 if (!cb->IsValid || cb->Buffer == NULL ||
2319 cb->BufferSize.X != cb->Info.dwSize.X ||
2320 cb->BufferSize.Y != cb->Info.dwSize.Y)
2321 {
2322 cb->BufferSize.X = cb->Info.dwSize.X;
2323 cb->BufferSize.Y = cb->Info.dwSize.Y;
2324 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2325 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002326 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002327 if (cb->Buffer == NULL)
2328 return FALSE;
2329 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002330
2331 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002332 * We will now copy the console screen buffer into our buffer.
2333 * ReadConsoleOutput() seems to be limited as far as how much you
2334 * can read at a time. Empirically, this number seems to be about
2335 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2336 * in chunks until it is all copied. The chunks will all have the
2337 * same horizontal characteristics, so initialize them now. The
2338 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002339 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002340 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002341 ReadRegion.Left = 0;
2342 ReadRegion.Right = cb->Info.dwSize.X - 1;
2343 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002344
2345 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2346 if (cb->Regions == NULL || numregions != cb->NumRegions)
2347 {
2348 cb->NumRegions = numregions;
2349 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002350 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002351 if (cb->Regions == NULL)
2352 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002353 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002354 return FALSE;
2355 }
2356 }
2357
2358 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002359 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002360 /*
2361 * Read into position (0, Y) in our buffer.
2362 */
2363 BufferCoord.Y = Y;
2364 /*
2365 * Read the region whose top left corner is (0, Y) and whose bottom
2366 * right corner is (width - 1, Y + Y_incr - 1). This should define
2367 * a region of size width by Y_incr. Don't worry if this region is
2368 * too large for the remaining buffer; it will be cropped.
2369 */
2370 ReadRegion.Top = Y;
2371 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002372 if (!ReadConsoleOutputW(g_hConOut, /* output handle */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002373 cb->Buffer, /* our buffer */
2374 cb->BufferSize, /* dimensions of our buffer */
2375 BufferCoord, /* offset in our buffer */
2376 &ReadRegion)) /* region to save */
2377 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002378 VIM_CLEAR(cb->Buffer);
2379 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002380 return FALSE;
2381 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002382 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002383 }
2384
2385 return TRUE;
2386}
2387
2388/*
2389 * RestoreConsoleBuffer()
2390 * Description:
2391 * Restores important information about the console buffer, including the
2392 * actual buffer contents, if desired. The information to restore is in
2393 * the same format used by SaveConsoleBuffer().
2394 * Returns:
2395 * TRUE on success
2396 */
2397 static BOOL
2398RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002399 ConsoleBuffer *cb,
2400 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002401{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002402 COORD BufferCoord;
2403 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002404 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002405
2406 if (cb == NULL || !cb->IsValid)
2407 return FALSE;
2408
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002409 /*
2410 * Before restoring the buffer contents, clear the current buffer, and
2411 * restore the cursor position and window information. Doing this now
2412 * prevents old buffer contents from "flashing" onto the screen.
2413 */
2414 if (RestoreScreen)
2415 ClearConsoleBuffer(cb->Info.wAttributes);
2416
2417 FitConsoleWindow(cb->Info.dwSize, TRUE);
2418 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2419 return FALSE;
2420 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2421 return FALSE;
2422
2423 if (!RestoreScreen)
2424 {
2425 /*
2426 * No need to restore the screen buffer contents, so we're done.
2427 */
2428 return TRUE;
2429 }
2430
2431 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2432 return FALSE;
2433 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2434 return FALSE;
2435
2436 /*
2437 * Restore the screen buffer contents.
2438 */
2439 if (cb->Buffer != NULL)
2440 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002441 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002442 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002443 BufferCoord.X = cb->Regions[i].Left;
2444 BufferCoord.Y = cb->Regions[i].Top;
2445 WriteRegion = cb->Regions[i];
2446 if (!WriteConsoleOutputW(g_hConOut, /* output handle */
2447 cb->Buffer, /* our buffer */
2448 cb->BufferSize, /* dimensions of our buffer */
2449 BufferCoord, /* offset in our buffer */
2450 &WriteRegion)) /* region to restore */
Bram Moolenaar444fda22017-08-11 20:37:00 +02002451 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002452 }
2453 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002454
2455 return TRUE;
2456}
2457
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002458#define FEAT_RESTORE_ORIG_SCREEN
2459#ifdef FEAT_RESTORE_ORIG_SCREEN
2460static ConsoleBuffer g_cbOrig = { 0 };
2461#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002462static ConsoleBuffer g_cbNonTermcap = { 0 };
2463static ConsoleBuffer g_cbTermcap = { 0 };
2464
2465#ifdef FEAT_TITLE
Bram Moolenaar071d4272004-06-13 20:20:40 +00002466char g_szOrigTitle[256] = { 0 };
2467HWND g_hWnd = NULL; /* also used in os_mswin.c */
2468static HICON g_hOrigIconSmall = NULL;
2469static HICON g_hOrigIcon = NULL;
2470static HICON g_hVimIcon = NULL;
2471static BOOL g_fCanChangeIcon = FALSE;
2472
2473/* ICON* are not defined in VC++ 4.0 */
2474#ifndef ICON_SMALL
2475#define ICON_SMALL 0
2476#endif
2477#ifndef ICON_BIG
2478#define ICON_BIG 1
2479#endif
2480/*
2481 * GetConsoleIcon()
2482 * Description:
2483 * Attempts to retrieve the small icon and/or the big icon currently in
2484 * use by a given window.
2485 * Returns:
2486 * TRUE on success
2487 */
2488 static BOOL
2489GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002490 HWND hWnd,
2491 HICON *phIconSmall,
2492 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493{
2494 if (hWnd == NULL)
2495 return FALSE;
2496
2497 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002498 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2499 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002500 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002501 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2502 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002503 return TRUE;
2504}
2505
2506/*
2507 * SetConsoleIcon()
2508 * Description:
2509 * Attempts to change the small icon and/or the big icon currently in
2510 * use by a given window.
2511 * Returns:
2512 * TRUE on success
2513 */
2514 static BOOL
2515SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002516 HWND hWnd,
2517 HICON hIconSmall,
2518 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002520 if (hWnd == NULL)
2521 return FALSE;
2522
2523 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002524 SendMessage(hWnd, WM_SETICON,
2525 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002526 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002527 SendMessage(hWnd, WM_SETICON,
2528 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002529 return TRUE;
2530}
2531
2532/*
2533 * SaveConsoleTitleAndIcon()
2534 * Description:
2535 * Saves the current console window title in g_szOrigTitle, for later
2536 * restoration. Also, attempts to obtain a handle to the console window,
2537 * and use it to save the small and big icons currently in use by the
2538 * console window. This is not always possible on some versions of Windows;
2539 * nor is it possible when running Vim remotely using Telnet (since the
2540 * console window the user sees is owned by a remote process).
2541 */
2542 static void
2543SaveConsoleTitleAndIcon(void)
2544{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002545 /* Save the original title. */
2546 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2547 return;
2548
2549 /*
2550 * Obtain a handle to the console window using GetConsoleWindow() from
2551 * KERNEL32.DLL; we need to handle in order to change the window icon.
2552 * This function only exists on NT-based Windows, starting with Windows
2553 * 2000. On older operating systems, we can't change the window icon
2554 * anyway.
2555 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002556 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002557 if (g_hWnd == NULL)
2558 return;
2559
2560 /* Save the original console window icon. */
2561 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2562 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2563 return;
2564
2565 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002566 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002567 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002568 if (g_hVimIcon != NULL)
2569 g_fCanChangeIcon = TRUE;
2570}
2571#endif
2572
2573static int g_fWindInitCalled = FALSE;
2574static int g_fTermcapMode = FALSE;
2575static CONSOLE_CURSOR_INFO g_cci;
2576static DWORD g_cmodein = 0;
2577static DWORD g_cmodeout = 0;
2578
2579/*
2580 * non-GUI version of mch_init().
2581 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002582 static void
2583mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002584{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002585#ifndef FEAT_RESTORE_ORIG_SCREEN
2586 CONSOLE_SCREEN_BUFFER_INFO csbi;
2587#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002588#ifndef __MINGW32__
2589 extern int _fmode;
2590#endif
2591
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002592 /* Silently handle invalid parameters to CRT functions */
2593 SET_INVALID_PARAM_HANDLER;
2594
Bram Moolenaar071d4272004-06-13 20:20:40 +00002595 /* Let critical errors result in a failure, not in a dialog box. Required
2596 * for the timestamp test to work on removed floppies. */
2597 SetErrorMode(SEM_FAILCRITICALERRORS);
2598
2599 _fmode = O_BINARY; /* we do our own CR-LF translation */
2600 out_flush();
2601
2602 /* Obtain handles for the standard Console I/O devices */
2603 if (read_cmd_fd == 0)
2604 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2605 else
2606 create_conin();
2607 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2608
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002609#ifdef FEAT_RESTORE_ORIG_SCREEN
2610 /* Save the initial console buffer for later restoration */
2611 SaveConsoleBuffer(&g_cbOrig);
2612 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2613#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002614 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002615 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2616 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2617#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002618 if (cterm_normal_fg_color == 0)
2619 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2620 if (cterm_normal_bg_color == 0)
2621 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2622
Bram Moolenaarbdace832019-03-02 10:13:42 +01002623 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002624 g_color_index_fg = g_attrDefault & 0xf;
2625 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2626
Bram Moolenaar071d4272004-06-13 20:20:40 +00002627 /* set termcap codes to current text attributes */
2628 update_tcap(g_attrCurrent);
2629
2630 GetConsoleCursorInfo(g_hConOut, &g_cci);
2631 GetConsoleMode(g_hConIn, &g_cmodein);
2632 GetConsoleMode(g_hConOut, &g_cmodeout);
2633
2634#ifdef FEAT_TITLE
2635 SaveConsoleTitleAndIcon();
2636 /*
2637 * Set both the small and big icons of the console window to Vim's icon.
2638 * Note that Vim presently only has one size of icon (32x32), but it
2639 * automatically gets scaled down to 16x16 when setting the small icon.
2640 */
2641 if (g_fCanChangeIcon)
2642 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2643#endif
2644
2645 ui_get_shellsize();
2646
2647#ifdef MCH_WRITE_DUMP
2648 fdDump = fopen("dump", "wt");
2649
2650 if (fdDump)
2651 {
2652 time_t t;
2653
2654 time(&t);
2655 fputs(ctime(&t), fdDump);
2656 fflush(fdDump);
2657 }
2658#endif
2659
2660 g_fWindInitCalled = TRUE;
2661
Bram Moolenaar071d4272004-06-13 20:20:40 +00002662 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002663
2664#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002665 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002666#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002667
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002668 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002669 vtp_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002670}
2671
2672/*
2673 * non-GUI version of mch_exit().
2674 * Shut down and exit with status `r'
2675 * Careful: mch_exit() may be called before mch_init()!
2676 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002677 static void
2678mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002679{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002680 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002681
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002682 vtp_exit();
2683
Bram Moolenaar955f1982017-02-05 15:10:51 +01002684 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002685 if (g_fWindInitCalled)
2686 settmode(TMODE_COOK);
2687
2688 ml_close_all(TRUE); /* remove all memfiles */
2689
2690 if (g_fWindInitCalled)
2691 {
2692#ifdef FEAT_TITLE
Bram Moolenaar40385db2018-08-07 22:31:44 +02002693 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002694 /*
2695 * Restore both the small and big icons of the console window to
2696 * what they were at startup. Don't do this when the window is
2697 * closed, Vim would hang here.
2698 */
2699 if (g_fCanChangeIcon && !g_fForceExit)
2700 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2701#endif
2702
2703#ifdef MCH_WRITE_DUMP
2704 if (fdDump)
2705 {
2706 time_t t;
2707
2708 time(&t);
2709 fputs(ctime(&t), fdDump);
2710 fclose(fdDump);
2711 }
2712 fdDump = NULL;
2713#endif
2714 }
2715
2716 SetConsoleCursorInfo(g_hConOut, &g_cci);
2717 SetConsoleMode(g_hConIn, g_cmodein);
2718 SetConsoleMode(g_hConOut, g_cmodeout);
2719
2720#ifdef DYNAMIC_GETTEXT
2721 dyn_libintl_end();
2722#endif
2723
2724 exit(r);
2725}
Bram Moolenaar4f974752019-02-17 17:44:42 +01002726#endif /* !FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002727
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002728 void
2729mch_init(void)
2730{
2731#ifdef VIMDLL
2732 if (gui.starting)
2733 mch_init_g();
2734 else
2735 mch_init_c();
2736#elif defined(FEAT_GUI_MSWIN)
2737 mch_init_g();
2738#else
2739 mch_init_c();
2740#endif
2741}
2742
2743 void
2744mch_exit(int r)
2745{
2746#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02002747 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002748 mch_exit_g(r);
2749 else
2750 mch_exit_c(r);
2751#elif defined(FEAT_GUI_MSWIN)
2752 mch_exit_g(r);
2753#else
2754 mch_exit_c(r);
2755#endif
2756}
2757
Bram Moolenaar071d4272004-06-13 20:20:40 +00002758/*
2759 * Do we have an interactive window?
2760 */
2761 int
2762mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002763 int argc UNUSED,
2764 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002765{
2766 get_exe_name();
2767
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002768#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002769 return OK; /* GUI always has a tty */
2770#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002771# ifdef VIMDLL
2772 if (gui.in_use)
2773 return OK;
2774# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002775 if (isatty(1))
2776 return OK;
2777 return FAIL;
2778#endif
2779}
2780
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002781/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002782 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002783 * When "len" is > 0, also expand short to long filenames.
2784 */
2785 void
2786fname_case(
2787 char_u *name,
2788 int len)
2789{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002790 int flen;
2791 WCHAR *p;
2792 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002793
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002794 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002795 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002796 return;
2797
2798 slash_adjust(name);
2799
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002800 p = enc_to_utf16(name, NULL);
2801 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002802 return;
2803
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002804 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002805 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002806 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002807
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002808 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002809 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002810 if (len > 0 || flen >= (int)STRLEN(q))
2811 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2812 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002813 }
2814 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002815 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002816}
2817
2818
2819/*
2820 * Insert user name in s[len].
2821 */
2822 int
2823mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002824 char_u *s,
2825 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002826{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002827 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2828 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002829
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002830 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002831 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002832 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002833
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002834 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002835 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002836 vim_strncpy(s, p, len - 1);
2837 vim_free(p);
2838 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002839 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002840 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002841 s[0] = NUL;
2842 return FAIL;
2843}
2844
2845
2846/*
2847 * Insert host name in s[len].
2848 */
2849 void
2850mch_get_host_name(
2851 char_u *s,
2852 int len)
2853{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002854 WCHAR wszHostName[256 + 1];
2855 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002856
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002857 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002858 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002859 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002860
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002861 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002862 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002863 vim_strncpy(s, p, len - 1);
2864 vim_free(p);
2865 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002866 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002867 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002868}
2869
2870
2871/*
2872 * return process ID
2873 */
2874 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002875mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002876{
2877 return (long)GetCurrentProcessId();
2878}
2879
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02002880/*
2881 * return TRUE if process "pid" is still running
2882 */
2883 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02002884mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02002885{
2886 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
2887 DWORD status = 0;
2888 int ret = FALSE;
2889
2890 if (hProcess == NULL)
2891 return FALSE; // might not have access
2892 if (GetExitCodeProcess(hProcess, &status) )
2893 ret = status == STILL_ACTIVE;
2894 CloseHandle(hProcess);
2895 return ret;
2896}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002897
2898/*
2899 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2900 * Return OK for success, FAIL for failure.
2901 */
2902 int
2903mch_dirname(
2904 char_u *buf,
2905 int len)
2906{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002907 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002908
Bram Moolenaar071d4272004-06-13 20:20:40 +00002909 /*
2910 * Originally this was:
2911 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2912 * But the Win32s known bug list says that getcwd() doesn't work
2913 * so use the Win32 system call instead. <Negri>
2914 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002915 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002916 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002917 WCHAR wcbuf[_MAX_PATH + 1];
2918 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002919
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002920 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002921 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002922 p = utf16_to_enc(wcbuf, NULL);
2923 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02002924 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002925 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00002926 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002927 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002928 }
2929 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002930 if (p == NULL)
2931 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002932
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002933 if (p != NULL)
2934 {
2935 vim_strncpy(buf, p, len - 1);
2936 vim_free(p);
2937 return OK;
2938 }
2939 }
2940 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002941}
2942
2943/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01002944 * Get file permissions for "name".
2945 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002946 */
2947 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002948mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002949{
Bram Moolenaar8767f522016-07-01 17:17:39 +02002950 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01002951 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002952
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002953 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01002954 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002955}
2956
2957
2958/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002959 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002960 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002961 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002962 */
2963 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002964mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002965{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002966 long n;
2967 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002968
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002969 p = enc_to_utf16(name, NULL);
2970 if (p == NULL)
2971 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002972
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002973 n = _wchmod(p, perm);
2974 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002975 if (n == -1)
2976 return FAIL;
2977
2978 win32_set_archive(name);
2979
2980 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002981}
2982
2983/*
2984 * Set hidden flag for "name".
2985 */
2986 void
2987mch_hide(char_u *name)
2988{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002989 int attrs = win32_getattrs(name);
2990 if (attrs == -1)
2991 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002992
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002993 attrs |= FILE_ATTRIBUTE_HIDDEN;
2994 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002995}
2996
2997/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01002998 * Return TRUE if file "name" exists and is hidden.
2999 */
3000 int
3001mch_ishidden(char_u *name)
3002{
3003 int f = win32_getattrs(name);
3004
3005 if (f == -1)
3006 return FALSE; /* file does not exist at all */
3007
3008 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3009}
3010
3011/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003012 * return TRUE if "name" is a directory
3013 * return FALSE if "name" is not a directory or upon error
3014 */
3015 int
3016mch_isdir(char_u *name)
3017{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003018 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003019
3020 if (f == -1)
3021 return FALSE; /* file does not exist at all */
3022
3023 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3024}
3025
3026/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003027 * return TRUE if "name" is a directory, NOT a symlink to a directory
3028 * return FALSE if "name" is not a directory
3029 * return FALSE for error
3030 */
3031 int
3032mch_isrealdir(char_u *name)
3033{
3034 return mch_isdir(name) && !mch_is_symbolic_link(name);
3035}
3036
3037/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003038 * Create directory "name".
3039 * Return 0 on success, -1 on error.
3040 */
3041 int
3042mch_mkdir(char_u *name)
3043{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003044 WCHAR *p;
3045 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003046
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003047 p = enc_to_utf16(name, NULL);
3048 if (p == NULL)
3049 return -1;
3050 retval = _wmkdir(p);
3051 vim_free(p);
3052 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003053}
3054
3055/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003056 * Delete directory "name".
3057 * Return 0 on success, -1 on error.
3058 */
3059 int
3060mch_rmdir(char_u *name)
3061{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003062 WCHAR *p;
3063 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003064
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003065 p = enc_to_utf16(name, NULL);
3066 if (p == NULL)
3067 return -1;
3068 retval = _wrmdir(p);
3069 vim_free(p);
3070 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003071}
3072
3073/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003074 * Return TRUE if file "fname" has more than one link.
3075 */
3076 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003077mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003078{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003079 BY_HANDLE_FILE_INFORMATION info;
3080
3081 return win32_fileinfo(fname, &info) == FILEINFO_OK
3082 && info.nNumberOfLinks > 1;
3083}
3084
3085/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003086 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003087 */
3088 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003089mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003090{
3091 HANDLE hFind;
3092 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003093 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003094 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003095 WIN32_FIND_DATAW findDataW;
3096
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003097 wn = enc_to_utf16(name, NULL);
3098 if (wn == NULL)
3099 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003100
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003101 hFind = FindFirstFileW(wn, &findDataW);
3102 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003103 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003104 {
3105 fileFlags = findDataW.dwFileAttributes;
3106 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003107 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003108 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003109
3110 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003111 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3112 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003113 res = TRUE;
3114
3115 return res;
3116}
3117
3118/*
3119 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3120 * link.
3121 */
3122 int
3123mch_is_linked(char_u *fname)
3124{
3125 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3126 return TRUE;
3127 return FALSE;
3128}
3129
3130/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003131 * Get the by-handle-file-information for "fname".
3132 * Returns FILEINFO_OK when OK.
3133 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3134 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3135 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3136 */
3137 int
3138win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3139{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003140 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003141 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003142 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003143
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003144 wn = enc_to_utf16(fname, NULL);
3145 if (wn == NULL)
3146 return FILEINFO_ENC_FAIL;
3147
3148 hFile = CreateFileW(wn, // file name
3149 GENERIC_READ, // access mode
3150 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3151 NULL, // security descriptor
3152 OPEN_EXISTING, // creation disposition
3153 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3154 NULL); // handle to template file
3155 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003156
3157 if (hFile != INVALID_HANDLE_VALUE)
3158 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003159 if (GetFileInformationByHandle(hFile, info) != 0)
3160 res = FILEINFO_OK;
3161 else
3162 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003163 CloseHandle(hFile);
3164 }
3165
Bram Moolenaar03f48552006-02-28 23:52:23 +00003166 return res;
3167}
3168
3169/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003170 * get file attributes for `name'
3171 * -1 : error
3172 * else FILE_ATTRIBUTE_* defined in winnt.h
3173 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003174 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003175win32_getattrs(char_u *name)
3176{
3177 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003178 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003179
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003180 p = enc_to_utf16(name, NULL);
3181 if (p == NULL)
3182 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003183
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003184 attr = GetFileAttributesW(p);
3185 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003186
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003187 return attr;
3188}
3189
3190/*
3191 * set file attributes for `name' to `attrs'
3192 *
3193 * return -1 for failure, 0 otherwise
3194 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003195 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003196win32_setattrs(char_u *name, int attrs)
3197{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003198 int res;
3199 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003200
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003201 p = enc_to_utf16(name, NULL);
3202 if (p == NULL)
3203 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003204
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003205 res = SetFileAttributesW(p, attrs);
3206 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003207
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003208 return res ? 0 : -1;
3209}
3210
3211/*
3212 * Set archive flag for "name".
3213 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003214 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003215win32_set_archive(char_u *name)
3216{
3217 int attrs = win32_getattrs(name);
3218 if (attrs == -1)
3219 return -1;
3220
3221 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3222 return win32_setattrs(name, attrs);
3223}
3224
3225/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003226 * Return TRUE if file or directory "name" is writable (not readonly).
3227 * Strange semantics of Win32: a readonly directory is writable, but you can't
3228 * delete a file. Let's say this means it is writable.
3229 */
3230 int
3231mch_writable(char_u *name)
3232{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003233 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003234
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003235 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3236 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003237}
3238
Bram Moolenaar071d4272004-06-13 20:20:40 +00003239/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003240 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003241 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003242 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3243 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003244 */
3245 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003246mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003247{
Bram Moolenaar86621892019-03-30 21:51:28 +01003248 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
3249 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
3250 // UTF-8.
3251 char_u buf[_MAX_PATH * 3];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003252 int len = (int)STRLEN(name);
Bram Moolenaar82956662018-10-06 15:18:45 +02003253 char_u *p, *saved;
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003254
Bram Moolenaar86621892019-03-30 21:51:28 +01003255 if (len >= sizeof(buf)) // safety check
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003256 return FALSE;
3257
Bram Moolenaar86621892019-03-30 21:51:28 +01003258 // Try using the name directly when a Unix-shell like 'shell'.
Bram Moolenaar82956662018-10-06 15:18:45 +02003259 if (strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaar43663192017-03-05 14:29:12 +01003260 if (executable_exists((char *)name, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003261 return TRUE;
3262
3263 /*
3264 * Loop over all extensions in $PATHEXT.
3265 */
Bram Moolenaar82956662018-10-06 15:18:45 +02003266 p = mch_getenv("PATHEXT");
3267 if (p == NULL)
3268 p = (char_u *)".com;.exe;.bat;.cmd";
3269 saved = vim_strsave(p);
3270 if (saved == NULL)
3271 return FALSE;
3272 p = saved;
3273 while (*p)
3274 {
3275 char_u *tmp = vim_strchr(p, ';');
3276
3277 if (tmp != NULL)
3278 *tmp = NUL;
3279 if (_stricoll((char *)name + len - STRLEN(p), (char *)p) == 0
3280 && executable_exists((char *)name, path, use_path))
3281 {
3282 vim_free(saved);
3283 return TRUE;
3284 }
3285 if (tmp == NULL)
3286 break;
3287 p = tmp + 1;
3288 }
3289 vim_free(saved);
3290
Bram Moolenaar86621892019-03-30 21:51:28 +01003291 vim_strncpy(buf, name, sizeof(buf) - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003292 p = mch_getenv("PATHEXT");
3293 if (p == NULL)
3294 p = (char_u *)".com;.exe;.bat;.cmd";
3295 while (*p)
3296 {
3297 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3298 {
3299 /* A single "." means no extension is added. */
3300 buf[len] = NUL;
3301 ++p;
3302 if (*p)
3303 ++p;
3304 }
3305 else
Bram Moolenaar86621892019-03-30 21:51:28 +01003306 copy_option_part(&p, buf + len, sizeof(buf) - len, ";");
Bram Moolenaar43663192017-03-05 14:29:12 +01003307 if (executable_exists((char *)buf, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003308 return TRUE;
3309 }
3310 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003311}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003312
3313/*
3314 * Check what "name" is:
3315 * NODE_NORMAL: file or directory (or doesn't exist)
3316 * NODE_WRITABLE: writable device, socket, fifo, etc.
3317 * NODE_OTHER: non-writable things
3318 */
3319 int
3320mch_nodetype(char_u *name)
3321{
3322 HANDLE hFile;
3323 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003324 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003325
Bram Moolenaar043545e2006-10-10 16:44:07 +00003326 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3327 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3328 * here. */
3329 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3330 return NODE_WRITABLE;
3331
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003332 wn = enc_to_utf16(name, NULL);
3333 if (wn == NULL)
3334 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003335
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003336 hFile = CreateFileW(wn, // file name
3337 GENERIC_WRITE, // access mode
3338 0, // share mode
3339 NULL, // security descriptor
3340 OPEN_EXISTING, // creation disposition
3341 0, // file attributes
3342 NULL); // handle to template file
3343 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003344 if (hFile == INVALID_HANDLE_VALUE)
3345 return NODE_NORMAL;
3346
3347 type = GetFileType(hFile);
3348 CloseHandle(hFile);
3349 if (type == FILE_TYPE_CHAR)
3350 return NODE_WRITABLE;
3351 if (type == FILE_TYPE_DISK)
3352 return NODE_NORMAL;
3353 return NODE_OTHER;
3354}
3355
3356#ifdef HAVE_ACL
3357struct my_acl
3358{
3359 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3360 PSID pSidOwner;
3361 PSID pSidGroup;
3362 PACL pDacl;
3363 PACL pSacl;
3364};
3365#endif
3366
3367/*
3368 * Return a pointer to the ACL of file "fname" in allocated memory.
3369 * Return NULL if the ACL is not available for whatever reason.
3370 */
3371 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003372mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003373{
3374#ifndef HAVE_ACL
3375 return (vim_acl_T)NULL;
3376#else
3377 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003378 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003379
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003380 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003381 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003382 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003383 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003384
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003385 wn = enc_to_utf16(fname, NULL);
3386 if (wn == NULL)
3387 return NULL;
3388
3389 // Try to retrieve the entire security descriptor.
3390 err = GetNamedSecurityInfoW(
3391 wn, // Abstract filename
3392 SE_FILE_OBJECT, // File Object
3393 OWNER_SECURITY_INFORMATION |
3394 GROUP_SECURITY_INFORMATION |
3395 DACL_SECURITY_INFORMATION |
3396 SACL_SECURITY_INFORMATION,
3397 &p->pSidOwner, // Ownership information.
3398 &p->pSidGroup, // Group membership.
3399 &p->pDacl, // Discretionary information.
3400 &p->pSacl, // For auditing purposes.
3401 &p->pSecurityDescriptor);
3402 if (err == ERROR_ACCESS_DENIED ||
3403 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003404 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003405 // Retrieve only DACL.
3406 (void)GetNamedSecurityInfoW(
3407 wn,
3408 SE_FILE_OBJECT,
3409 DACL_SECURITY_INFORMATION,
3410 NULL,
3411 NULL,
3412 &p->pDacl,
3413 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003414 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003415 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003416 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003417 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003418 mch_free_acl((vim_acl_T)p);
3419 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003420 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003421 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003422 }
3423
3424 return (vim_acl_T)p;
3425#endif
3426}
3427
Bram Moolenaar27515922013-06-29 15:36:26 +02003428#ifdef HAVE_ACL
3429/*
3430 * Check if "acl" contains inherited ACE.
3431 */
3432 static BOOL
3433is_acl_inherited(PACL acl)
3434{
3435 DWORD i;
3436 ACL_SIZE_INFORMATION acl_info;
3437 PACCESS_ALLOWED_ACE ace;
3438
3439 acl_info.AceCount = 0;
3440 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3441 for (i = 0; i < acl_info.AceCount; i++)
3442 {
3443 GetAce(acl, i, (LPVOID *)&ace);
3444 if (ace->Header.AceFlags & INHERITED_ACE)
3445 return TRUE;
3446 }
3447 return FALSE;
3448}
3449#endif
3450
Bram Moolenaar071d4272004-06-13 20:20:40 +00003451/*
3452 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3453 * Errors are ignored.
3454 * This must only be called with "acl" equal to what mch_get_acl() returned.
3455 */
3456 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003457mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003458{
3459#ifdef HAVE_ACL
3460 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003461 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003462 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003463
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003464 if (p == NULL)
3465 return;
3466
3467 wn = enc_to_utf16(fname, NULL);
3468 if (wn == NULL)
3469 return;
3470
3471 // Set security flags
3472 if (p->pSidOwner)
3473 sec_info |= OWNER_SECURITY_INFORMATION;
3474 if (p->pSidGroup)
3475 sec_info |= GROUP_SECURITY_INFORMATION;
3476 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003477 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003478 sec_info |= DACL_SECURITY_INFORMATION;
3479 // Do not inherit its parent's DACL.
3480 // If the DACL is inherited, Cygwin permissions would be changed.
3481 if (!is_acl_inherited(p->pDacl))
3482 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003483 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003484 if (p->pSacl)
3485 sec_info |= SACL_SECURITY_INFORMATION;
3486
3487 (void)SetNamedSecurityInfoW(
3488 wn, // Abstract filename
3489 SE_FILE_OBJECT, // File Object
3490 sec_info,
3491 p->pSidOwner, // Ownership information.
3492 p->pSidGroup, // Group membership.
3493 p->pDacl, // Discretionary information.
3494 p->pSacl // For auditing purposes.
3495 );
3496 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003497#endif
3498}
3499
3500 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003501mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003502{
3503#ifdef HAVE_ACL
3504 struct my_acl *p = (struct my_acl *)acl;
3505
3506 if (p != NULL)
3507 {
3508 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3509 vim_free(p);
3510 }
3511#endif
3512}
3513
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003514#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003515
3516/*
3517 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3518 */
3519 static BOOL WINAPI
3520handler_routine(
3521 DWORD dwCtrlType)
3522{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003523 INPUT_RECORD ir;
3524 DWORD out;
3525
Bram Moolenaar071d4272004-06-13 20:20:40 +00003526 switch (dwCtrlType)
3527 {
3528 case CTRL_C_EVENT:
3529 if (ctrl_c_interrupts)
3530 g_fCtrlCPressed = TRUE;
3531 return TRUE;
3532
3533 case CTRL_BREAK_EVENT:
3534 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003535 ctrl_break_was_pressed = TRUE;
3536 /* ReadConsoleInput is blocking, send a key event to continue. */
3537 ir.EventType = KEY_EVENT;
3538 ir.Event.KeyEvent.bKeyDown = TRUE;
3539 ir.Event.KeyEvent.wRepeatCount = 1;
3540 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3541 ir.Event.KeyEvent.wVirtualScanCode = 0;
3542 ir.Event.KeyEvent.dwControlKeyState = 0;
3543 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3544 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003545 return TRUE;
3546
3547 /* fatal events: shut down gracefully */
3548 case CTRL_CLOSE_EVENT:
3549 case CTRL_LOGOFF_EVENT:
3550 case CTRL_SHUTDOWN_EVENT:
3551 windgoto((int)Rows - 1, 0);
3552 g_fForceExit = TRUE;
3553
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003554 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003555 (dwCtrlType == CTRL_CLOSE_EVENT
3556 ? _("close")
3557 : dwCtrlType == CTRL_LOGOFF_EVENT
3558 ? _("logoff")
3559 : _("shutdown")));
3560#ifdef DEBUG
3561 OutputDebugString(IObuff);
3562#endif
3563
3564 preserve_exit(); /* output IObuff, preserve files and exit */
3565
3566 return TRUE; /* not reached */
3567
3568 default:
3569 return FALSE;
3570 }
3571}
3572
3573
3574/*
3575 * set the tty in (raw) ? "raw" : "cooked" mode
3576 */
3577 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003578mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003579{
3580 DWORD cmodein;
3581 DWORD cmodeout;
3582 BOOL bEnableHandler;
3583
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003584# ifdef VIMDLL
3585 if (gui.in_use)
3586 return;
3587# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003588 GetConsoleMode(g_hConIn, &cmodein);
3589 GetConsoleMode(g_hConOut, &cmodeout);
3590 if (tmode == TMODE_RAW)
3591 {
3592 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3593 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003594 if (g_fMouseActive)
3595 cmodein |= ENABLE_MOUSE_INPUT;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003596 cmodeout &= ~(
3597#ifdef FEAT_TERMGUICOLORS
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003598 /* Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003599 * VTP. */
3600 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
3601#else
3602 ENABLE_PROCESSED_OUTPUT |
3603#endif
3604 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003605 bEnableHandler = TRUE;
3606 }
3607 else /* cooked */
3608 {
3609 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3610 ENABLE_ECHO_INPUT);
3611 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3612 bEnableHandler = FALSE;
3613 }
3614 SetConsoleMode(g_hConIn, cmodein);
3615 SetConsoleMode(g_hConOut, cmodeout);
3616 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3617
3618#ifdef MCH_WRITE_DUMP
3619 if (fdDump)
3620 {
3621 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3622 tmode == TMODE_RAW ? "raw" :
3623 tmode == TMODE_COOK ? "cooked" : "normal",
3624 cmodein, cmodeout);
3625 fflush(fdDump);
3626 }
3627#endif
3628}
3629
3630
3631/*
3632 * Get the size of the current window in `Rows' and `Columns'
3633 * Return OK when size could be determined, FAIL otherwise.
3634 */
3635 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003636mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003637{
3638 CONSOLE_SCREEN_BUFFER_INFO csbi;
3639
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003640# ifdef VIMDLL
3641 if (gui.in_use)
3642 return OK;
3643# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003644 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3645 {
3646 /*
3647 * For some reason, we are trying to get the screen dimensions
3648 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3649 * variables are really intended to mean the size of Vim screen
3650 * while in termcap mode.
3651 */
3652 Rows = g_cbTermcap.Info.dwSize.Y;
3653 Columns = g_cbTermcap.Info.dwSize.X;
3654 }
3655 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3656 {
3657 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3658 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3659 }
3660 else
3661 {
3662 Rows = 25;
3663 Columns = 80;
3664 }
3665 return OK;
3666}
3667
3668/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003669 * Resize console buffer to 'COORD'
3670 */
3671 static void
3672ResizeConBuf(
3673 HANDLE hConsole,
3674 COORD coordScreen)
3675{
3676 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3677 {
3678#ifdef MCH_WRITE_DUMP
3679 if (fdDump)
3680 {
3681 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3682 GetLastError());
3683 fflush(fdDump);
3684 }
3685#endif
3686 }
3687}
3688
3689/*
3690 * Resize console window size to 'srWindowRect'
3691 */
3692 static void
3693ResizeWindow(
3694 HANDLE hConsole,
3695 SMALL_RECT srWindowRect)
3696{
3697 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
3698 {
3699#ifdef MCH_WRITE_DUMP
3700 if (fdDump)
3701 {
3702 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3703 GetLastError());
3704 fflush(fdDump);
3705 }
3706#endif
3707 }
3708}
3709
3710/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003711 * Set a console window to `xSize' * `ySize'
3712 */
3713 static void
3714ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003715 HANDLE hConsole,
3716 int xSize,
3717 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003718{
3719 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3720 SMALL_RECT srWindowRect; /* hold the new console size */
3721 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003722 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02003723 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003724
3725#ifdef MCH_WRITE_DUMP
3726 if (fdDump)
3727 {
3728 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3729 fflush(fdDump);
3730 }
3731#endif
3732
3733 /* get the largest size we can size the console window to */
3734 coordScreen = GetLargestConsoleWindowSize(hConsole);
3735
3736 /* define the new console window size and scroll position */
3737 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3738 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3739 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3740
3741 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3742 {
3743 int sx, sy;
3744
3745 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3746 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3747 if (sy < ySize || sx < xSize)
3748 {
3749 /*
3750 * Increasing number of lines/columns, do buffer first.
3751 * Use the maximal size in x and y direction.
3752 */
3753 if (sy < ySize)
3754 coordScreen.Y = ySize;
3755 else
3756 coordScreen.Y = sy;
3757 if (sx < xSize)
3758 coordScreen.X = xSize;
3759 else
3760 coordScreen.X = sx;
3761 SetConsoleScreenBufferSize(hConsole, coordScreen);
3762 }
3763 }
3764
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003765 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003766 coordScreen.X = xSize;
3767 coordScreen.Y = ySize;
3768
Bram Moolenaar2551c032018-08-23 22:38:31 +02003769 // In the new console call API, only the first time in reverse order
3770 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003771 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003772 ResizeWindow(hConsole, srWindowRect);
3773 ResizeConBuf(hConsole, coordScreen);
3774 }
3775 else
3776 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003777 // Workaround for a Windows 10 bug
3778 cursor.X = srWindowRect.Left;
3779 cursor.Y = srWindowRect.Top;
3780 SetConsoleCursorPosition(hConsole, cursor);
3781
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003782 ResizeConBuf(hConsole, coordScreen);
3783 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02003784 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003785 }
3786}
3787
3788
3789/*
3790 * Set the console window to `Rows' * `Columns'
3791 */
3792 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003793mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003794{
3795 COORD coordScreen;
3796
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003797# ifdef VIMDLL
3798 if (gui.in_use)
3799 return;
3800# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003801 /* Don't change window size while still starting up */
3802 if (suppress_winsize != 0)
3803 {
3804 suppress_winsize = 2;
3805 return;
3806 }
3807
3808 if (term_console)
3809 {
3810 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3811
3812 /* Clamp Rows and Columns to reasonable values */
3813 if (Rows > coordScreen.Y)
3814 Rows = coordScreen.Y;
3815 if (Columns > coordScreen.X)
3816 Columns = coordScreen.X;
3817
3818 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3819 }
3820}
3821
3822/*
3823 * Rows and/or Columns has changed.
3824 */
3825 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003826mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003827{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003828# ifdef VIMDLL
3829 if (gui.in_use)
3830 return;
3831# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003832 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3833}
3834
3835
3836/*
3837 * Called when started up, to set the winsize that was delayed.
3838 */
3839 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003840mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003841{
3842 if (suppress_winsize == 2)
3843 {
3844 suppress_winsize = 0;
3845 mch_set_shellsize();
3846 shell_resized();
3847 }
3848 suppress_winsize = 0;
3849}
Bram Moolenaar4f974752019-02-17 17:44:42 +01003850#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003851
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003852 static BOOL
3853vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003854 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003855 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01003856 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003857 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003858 PROCESS_INFORMATION *pi,
3859 LPVOID *env,
3860 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003861{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003862 BOOL ret = FALSE;
3863 WCHAR *wcmd, *wcwd = NULL;
3864
3865 wcmd = enc_to_utf16((char_u *)cmd, NULL);
3866 if (wcmd == NULL)
3867 return FALSE;
3868 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003869 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003870 wcwd = enc_to_utf16((char_u *)cwd, NULL);
3871 if (wcwd == NULL)
3872 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003873 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003874
3875 ret = CreateProcessW(
3876 NULL, // Executable name
3877 wcmd, // Command to execute
3878 NULL, // Process security attributes
3879 NULL, // Thread security attributes
3880 inherit_handles, // Inherit handles
3881 flags, // Creation flags
3882 env, // Environment
3883 wcwd, // Current directory
3884 (LPSTARTUPINFOW)si, // Startup information
3885 pi); // Process information
3886theend:
3887 vim_free(wcmd);
3888 vim_free(wcwd);
3889 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003890}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003891
3892
Bram Moolenaarb2964f22017-03-21 19:29:26 +01003893 static HINSTANCE
3894vim_shell_execute(
3895 char *cmd,
3896 INT n_show_cmd)
3897{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003898 HINSTANCE ret;
3899 WCHAR *wcmd;
3900
3901 wcmd = enc_to_utf16((char_u *)cmd, NULL);
3902 if (wcmd == NULL)
3903 return (HINSTANCE) 0;
3904
3905 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
3906 vim_free(wcmd);
3907 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01003908}
3909
3910
Bram Moolenaar4f974752019-02-17 17:44:42 +01003911#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003912
3913/*
3914 * Specialised version of system() for Win32 GUI mode.
3915 * This version proceeds as follows:
3916 * 1. Create a console window for use by the subprocess
3917 * 2. Run the subprocess (it gets the allocated console by default)
3918 * 3. Wait for the subprocess to terminate and get its exit code
3919 * 4. Prompt the user to press a key to close the console window
3920 */
3921 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003922mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003923{
3924 STARTUPINFO si;
3925 PROCESS_INFORMATION pi;
3926 DWORD ret = 0;
3927 HWND hwnd = GetFocus();
3928
3929 si.cb = sizeof(si);
3930 si.lpReserved = NULL;
3931 si.lpDesktop = NULL;
3932 si.lpTitle = NULL;
3933 si.dwFlags = STARTF_USESHOWWINDOW;
3934 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003935 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003936 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003937 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003938 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003939 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003940 else
3941 si.wShowWindow = SW_SHOWNORMAL;
3942 si.cbReserved2 = 0;
3943 si.lpReserved2 = NULL;
3944
Bram Moolenaar071d4272004-06-13 20:20:40 +00003945 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003946 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003947 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
3948 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003949
3950 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003951 {
3952#ifdef FEAT_GUI
3953 int delay = 1;
3954
3955 /* Keep updating the window while waiting for the shell to finish. */
3956 for (;;)
3957 {
3958 MSG msg;
3959
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003960 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003961 {
3962 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003963 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02003964 delay = 1;
3965 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003966 }
3967 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3968 break;
3969
3970 /* We start waiting for a very short time and then increase it, so
3971 * that we respond quickly when the process is quick, and don't
3972 * consume too much overhead when it's slow. */
3973 if (delay < 50)
3974 delay += 10;
3975 }
3976#else
3977 WaitForSingleObject(pi.hProcess, INFINITE);
3978#endif
3979
3980 /* Get the command exit code */
3981 GetExitCodeProcess(pi.hProcess, &ret);
3982 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003983
3984 /* Close the handles to the subprocess, so that it goes away */
3985 CloseHandle(pi.hThread);
3986 CloseHandle(pi.hProcess);
3987
3988 /* Try to get input focus back. Doesn't always work though. */
3989 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3990
3991 return ret;
3992}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003993
3994/*
3995 * Thread launched by the gui to send the current buffer data to the
3996 * process. This way avoid to hang up vim totally if the children
3997 * process take a long time to process the lines.
3998 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02003999 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004000sub_process_writer(LPVOID param)
4001{
4002 HANDLE g_hChildStd_IN_Wr = param;
4003 linenr_T lnum = curbuf->b_op_start.lnum;
4004 DWORD len = 0;
4005 DWORD l;
4006 char_u *lp = ml_get(lnum);
4007 char_u *s;
4008 int written = 0;
4009
4010 for (;;)
4011 {
4012 l = (DWORD)STRLEN(lp + written);
4013 if (l == 0)
4014 len = 0;
4015 else if (lp[written] == NL)
4016 {
4017 /* NL -> NUL translation */
4018 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4019 }
4020 else
4021 {
4022 s = vim_strchr(lp + written, NL);
4023 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4024 s == NULL ? l : (DWORD)(s - (lp + written)),
4025 &len, NULL);
4026 }
4027 if (len == (int)l)
4028 {
4029 /* Finished a line, add a NL, unless this line should not have
4030 * one. */
4031 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004032 || (!curbuf->b_p_bin
4033 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004034 || (lnum != curbuf->b_no_eol_lnum
4035 && (lnum != curbuf->b_ml.ml_line_count
4036 || curbuf->b_p_eol)))
4037 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004038 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4039 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004040 }
4041
4042 ++lnum;
4043 if (lnum > curbuf->b_op_end.lnum)
4044 break;
4045
4046 lp = ml_get(lnum);
4047 written = 0;
4048 }
4049 else if (len > 0)
4050 written += len;
4051 }
4052
4053 /* finished all the lines, close pipe */
4054 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004055 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004056}
4057
4058
4059# define BUFLEN 100 /* length for buffer, stolen from unix version */
4060
4061/*
4062 * This function read from the children's stdout and write the
4063 * data on screen or in the buffer accordingly.
4064 */
4065 static void
4066dump_pipe(int options,
4067 HANDLE g_hChildStd_OUT_Rd,
4068 garray_T *ga,
4069 char_u buffer[],
4070 DWORD *buffer_off)
4071{
4072 DWORD availableBytes = 0;
4073 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004074 int ret;
4075 DWORD len;
4076 DWORD toRead;
4077 int repeatCount;
4078
4079 /* we query the pipe to see if there is any data to read
4080 * to avoid to perform a blocking read */
4081 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4082 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004083 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004084 NULL, /* number of read bytes */
4085 &availableBytes, /* available bytes total */
4086 NULL); /* byteLeft */
4087
4088 repeatCount = 0;
4089 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004090 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004091 {
4092 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004093 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004094 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004095 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004096
4097 /* If we haven't read anything, there is a problem */
4098 if (len == 0)
4099 break;
4100
4101 availableBytes -= len;
4102
4103 if (options & SHELL_READ)
4104 {
4105 /* Do NUL -> NL translation, append NL separated
4106 * lines to the current buffer. */
4107 for (i = 0; i < len; ++i)
4108 {
4109 if (buffer[i] == NL)
4110 append_ga_line(ga);
4111 else if (buffer[i] == NUL)
4112 ga_append(ga, NL);
4113 else
4114 ga_append(ga, buffer[i]);
4115 }
4116 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004117 else if (has_mbyte)
4118 {
4119 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004120 int c;
4121 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004122
4123 len += *buffer_off;
4124 buffer[len] = NUL;
4125
4126 /* Check if the last character in buffer[] is
4127 * incomplete, keep these bytes for the next
4128 * round. */
4129 for (p = buffer; p < buffer + len; p += l)
4130 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004131 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004132 if (l == 0)
4133 l = 1; /* NUL byte? */
4134 else if (MB_BYTE2LEN(*p) != l)
4135 break;
4136 }
4137 if (p == buffer) /* no complete character */
4138 {
4139 /* avoid getting stuck at an illegal byte */
4140 if (len >= 12)
4141 ++p;
4142 else
4143 {
4144 *buffer_off = len;
4145 return;
4146 }
4147 }
4148 c = *p;
4149 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004150 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004151 if (p < buffer + len)
4152 {
4153 *p = c;
4154 *buffer_off = (DWORD)((buffer + len) - p);
4155 mch_memmove(buffer, p, *buffer_off);
4156 return;
4157 }
4158 *buffer_off = 0;
4159 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004160 else
4161 {
4162 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004163 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004164 }
4165
4166 windgoto(msg_row, msg_col);
4167 cursor_on();
4168 out_flush();
4169 }
4170}
4171
4172/*
4173 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4174 * for communication and doesn't open any new window.
4175 */
4176 static int
4177mch_system_piped(char *cmd, int options)
4178{
4179 STARTUPINFO si;
4180 PROCESS_INFORMATION pi;
4181 DWORD ret = 0;
4182
4183 HANDLE g_hChildStd_IN_Rd = NULL;
4184 HANDLE g_hChildStd_IN_Wr = NULL;
4185 HANDLE g_hChildStd_OUT_Rd = NULL;
4186 HANDLE g_hChildStd_OUT_Wr = NULL;
4187
4188 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4189 DWORD len;
4190
4191 /* buffer used to receive keys */
4192 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4193 int ta_len = 0; /* valid bytes in ta_buf[] */
4194
4195 DWORD i;
4196 int c;
4197 int noread_cnt = 0;
4198 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004199 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004200 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004201 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004202
4203 SECURITY_ATTRIBUTES saAttr;
4204
4205 /* Set the bInheritHandle flag so pipe handles are inherited. */
4206 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4207 saAttr.bInheritHandle = TRUE;
4208 saAttr.lpSecurityDescriptor = NULL;
4209
4210 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4211 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004212 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004213 /* Create a pipe for the child process's STDIN. */
4214 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4215 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004216 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004217 {
4218 CloseHandle(g_hChildStd_IN_Rd);
4219 CloseHandle(g_hChildStd_IN_Wr);
4220 CloseHandle(g_hChildStd_OUT_Rd);
4221 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004222 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004223 }
4224
4225 si.cb = sizeof(si);
4226 si.lpReserved = NULL;
4227 si.lpDesktop = NULL;
4228 si.lpTitle = NULL;
4229 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4230
4231 /* set-up our file redirection */
4232 si.hStdError = g_hChildStd_OUT_Wr;
4233 si.hStdOutput = g_hChildStd_OUT_Wr;
4234 si.hStdInput = g_hChildStd_IN_Rd;
4235 si.wShowWindow = SW_HIDE;
4236 si.cbReserved2 = 0;
4237 si.lpReserved2 = NULL;
4238
4239 if (options & SHELL_READ)
4240 ga_init2(&ga, 1, BUFLEN);
4241
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004242 if (cmd != NULL)
4243 {
4244 p = (char *)vim_strsave((char_u *)cmd);
4245 if (p != NULL)
4246 unescape_shellxquote((char_u *)p, p_sxe);
4247 else
4248 p = cmd;
4249 }
4250
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004251 /* Now, run the command.
4252 * About "Inherit handles" being TRUE: this command can be litigious,
4253 * handle inheritance was deactivated for pending temp file, but, if we
4254 * deactivate it, the pipes don't work for some reason. */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004255 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4256 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004257
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004258 if (p != cmd)
4259 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004260
4261 /* Close our unused side of the pipes */
4262 CloseHandle(g_hChildStd_IN_Rd);
4263 CloseHandle(g_hChildStd_OUT_Wr);
4264
4265 if (options & SHELL_WRITE)
4266 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004267 HANDLE thread = (HANDLE)
4268 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004269 0, /* default stack size */
4270 sub_process_writer, /* function to be executed */
4271 g_hChildStd_IN_Wr, /* parameter */
4272 0, /* creation flag, start immediately */
4273 NULL); /* we don't care about thread id */
4274 CloseHandle(thread);
4275 g_hChildStd_IN_Wr = NULL;
4276 }
4277
4278 /* Keep updating the window while waiting for the shell to finish. */
4279 for (;;)
4280 {
4281 MSG msg;
4282
Bram Moolenaar175d0702013-12-11 18:36:33 +01004283 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004284 {
4285 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004286 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004287 }
4288
4289 /* write pipe information in the window */
4290 if ((options & (SHELL_READ|SHELL_WRITE))
4291# ifdef FEAT_GUI
4292 || gui.in_use
4293# endif
4294 )
4295 {
4296 len = 0;
4297 if (!(options & SHELL_EXPAND)
4298 && ((options &
4299 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4300 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4301# ifdef FEAT_GUI
4302 || gui.in_use
4303# endif
4304 )
4305 && (ta_len > 0 || noread_cnt > 4))
4306 {
4307 if (ta_len == 0)
4308 {
4309 /* Get extra characters when we don't have any. Reset the
4310 * counter and timer. */
4311 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004312 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4313 }
4314 if (ta_len > 0 || len > 0)
4315 {
4316 /*
4317 * For pipes: Check for CTRL-C: send interrupt signal to
4318 * child. Check for CTRL-D: EOF, close pipe to child.
4319 */
4320 if (len == 1 && cmd != NULL)
4321 {
4322 if (ta_buf[ta_len] == Ctrl_C)
4323 {
4324 /* Learn what exit code is expected, for
4325 * now put 9 as SIGKILL */
4326 TerminateProcess(pi.hProcess, 9);
4327 }
4328 if (ta_buf[ta_len] == Ctrl_D)
4329 {
4330 CloseHandle(g_hChildStd_IN_Wr);
4331 g_hChildStd_IN_Wr = NULL;
4332 }
4333 }
4334
4335 /* replace K_BS by <BS> and K_DEL by <DEL> */
4336 for (i = ta_len; i < ta_len + len; ++i)
4337 {
4338 if (ta_buf[i] == CSI && len - i > 2)
4339 {
4340 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4341 if (c == K_DEL || c == K_KDEL || c == K_BS)
4342 {
4343 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4344 (size_t)(len - i - 2));
4345 if (c == K_DEL || c == K_KDEL)
4346 ta_buf[i] = DEL;
4347 else
4348 ta_buf[i] = Ctrl_H;
4349 len -= 2;
4350 }
4351 }
4352 else if (ta_buf[i] == '\r')
4353 ta_buf[i] = '\n';
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004354 if (has_mbyte)
4355 i += (*mb_ptr2len_len)(ta_buf + i,
4356 ta_len + len - i) - 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004357 }
4358
4359 /*
4360 * For pipes: echo the typed characters. For a pty this
4361 * does not seem to work.
4362 */
4363 for (i = ta_len; i < ta_len + len; ++i)
4364 {
4365 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4366 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004367 else if (has_mbyte)
4368 {
4369 int l = (*mb_ptr2len)(ta_buf + i);
4370
4371 msg_outtrans_len(ta_buf + i, l);
4372 i += l - 1;
4373 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004374 else
4375 msg_outtrans_len(ta_buf + i, 1);
4376 }
4377 windgoto(msg_row, msg_col);
4378 out_flush();
4379
4380 ta_len += len;
4381
4382 /*
4383 * Write the characters to the child, unless EOF has been
4384 * typed for pipes. Write one character at a time, to
4385 * avoid losing too much typeahead. When writing buffer
4386 * lines, drop the typed characters (only check for
4387 * CTRL-C).
4388 */
4389 if (options & SHELL_WRITE)
4390 ta_len = 0;
4391 else if (g_hChildStd_IN_Wr != NULL)
4392 {
4393 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4394 1, &len, NULL);
4395 // if we are typing in, we want to keep things reactive
4396 delay = 1;
4397 if (len > 0)
4398 {
4399 ta_len -= len;
4400 mch_memmove(ta_buf, ta_buf + len, ta_len);
4401 }
4402 }
4403 }
4404 }
4405 }
4406
4407 if (ta_len)
4408 ui_inchar_undo(ta_buf, ta_len);
4409
4410 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4411 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004412 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004413 break;
4414 }
4415
4416 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004417 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004418
4419 /* We start waiting for a very short time and then increase it, so
4420 * that we respond quickly when the process is quick, and don't
4421 * consume too much overhead when it's slow. */
4422 if (delay < 50)
4423 delay += 10;
4424 }
4425
4426 /* Close the pipe */
4427 CloseHandle(g_hChildStd_OUT_Rd);
4428 if (g_hChildStd_IN_Wr != NULL)
4429 CloseHandle(g_hChildStd_IN_Wr);
4430
4431 WaitForSingleObject(pi.hProcess, INFINITE);
4432
4433 /* Get the command exit code */
4434 GetExitCodeProcess(pi.hProcess, &ret);
4435
4436 if (options & SHELL_READ)
4437 {
4438 if (ga.ga_len > 0)
4439 {
4440 append_ga_line(&ga);
4441 /* remember that the NL was missing */
4442 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4443 }
4444 else
4445 curbuf->b_no_eol_lnum = 0;
4446 ga_clear(&ga);
4447 }
4448
4449 /* Close the handles to the subprocess, so that it goes away */
4450 CloseHandle(pi.hThread);
4451 CloseHandle(pi.hProcess);
4452
4453 return ret;
4454}
4455
4456 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004457mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004458{
4459 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004460 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004461 return mch_system_piped(cmd, options);
4462 else
4463 return mch_system_classic(cmd, options);
4464}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004465#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004466
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004467#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004468 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02004469mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004470{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004471 int ret;
4472 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004473 char_u *buf;
4474 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004475
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004476 // If the command starts and ends with double quotes, enclose the command
4477 // in parentheses.
4478 len = STRLEN(cmd);
4479 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
4480 {
4481 len += 3;
4482 buf = alloc(len);
4483 if (buf == NULL)
4484 return -1;
4485 vim_snprintf((char *)buf, len, "(%s)", cmd);
4486 wcmd = enc_to_utf16(buf, NULL);
4487 free(buf);
4488 }
4489 else
4490 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4491
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004492 if (wcmd == NULL)
4493 return -1;
4494
4495 ret = _wsystem(wcmd);
4496 vim_free(wcmd);
4497 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004498}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004499
4500#endif
4501
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004502 static int
4503mch_system(char *cmd, int options)
4504{
4505#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004506 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004507 return mch_system_g(cmd, options);
4508 else
4509 return mch_system_c(cmd, options);
4510#elif defined(FEAT_GUI_MSWIN)
4511 return mch_system_g(cmd, options);
4512#else
4513 return mch_system_c(cmd, options);
4514#endif
4515}
4516
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004517#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4518/*
4519 * Use a terminal window to run a shell command in.
4520 */
4521 static int
4522mch_call_shell_terminal(
4523 char_u *cmd,
4524 int options UNUSED) /* SHELL_*, see vim.h */
4525{
4526 jobopt_T opt;
4527 char_u *newcmd = NULL;
4528 typval_T argvar[2];
4529 long_u cmdlen;
4530 int retval = -1;
4531 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004532 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004533 aco_save_T aco;
4534 oparg_T oa; /* operator arguments */
4535
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004536 if (cmd == NULL)
4537 cmdlen = STRLEN(p_sh) + 1;
4538 else
4539 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004540 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004541 if (newcmd == NULL)
4542 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004543 if (cmd == NULL)
4544 {
4545 STRCPY(newcmd, p_sh);
4546 ch_log(NULL, "starting terminal to run a shell");
4547 }
4548 else
4549 {
4550 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4551 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4552 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004553
4554 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004555
4556 argvar[0].v_type = VAR_STRING;
4557 argvar[0].vval.v_string = newcmd;
4558 argvar[1].v_type = VAR_UNKNOWN;
4559 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004560 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004561 {
4562 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004563 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004564 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004565
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004566 job = term_getjob(buf->b_term);
4567 ++job->jv_refcount;
4568
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004569 /* Find a window to make "buf" curbuf. */
4570 aucmd_prepbuf(&aco, buf);
4571
4572 clear_oparg(&oa);
4573 while (term_use_loop())
4574 {
4575 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4576 {
4577 /* If terminal_loop() returns OK we got a key that is handled
4578 * in Normal model. We don't do redrawing anyway. */
4579 if (terminal_loop(TRUE) == OK)
4580 normal_cmd(&oa, TRUE);
4581 }
4582 else
4583 normal_cmd(&oa, TRUE);
4584 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004585 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004586 ch_log(NULL, "system command finished");
4587
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004588 job_unref(job);
4589
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004590 /* restore curwin/curbuf and a few other things */
4591 aucmd_restbuf(&aco);
4592
4593 wait_return(TRUE);
4594 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4595
4596 vim_free(newcmd);
4597 return retval;
4598}
4599#endif
4600
Bram Moolenaar071d4272004-06-13 20:20:40 +00004601/*
4602 * Either execute a command by calling the shell or start a new shell
4603 */
4604 int
4605mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004606 char_u *cmd,
4607 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004608{
4609 int x = 0;
4610 int tmode = cur_tmode;
4611#ifdef FEAT_TITLE
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004612 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004613
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004614 /* Change the title to reflect that we are in a subshell. */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004615 if (GetConsoleTitleW(szShellTitle,
4616 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004617 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004618 if (cmd == NULL)
4619 wcscat(szShellTitle, L" :sh");
4620 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004621 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004622 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004623
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004624 if (wn != NULL)
4625 {
4626 wcscat(szShellTitle, L" - !");
4627 if ((wcslen(szShellTitle) + wcslen(wn) <
4628 sizeof(szShellTitle)/sizeof(WCHAR)))
4629 wcscat(szShellTitle, wn);
4630 SetConsoleTitleW(szShellTitle);
4631 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004632 }
4633 }
4634 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004635#endif
4636
4637 out_flush();
4638
4639#ifdef MCH_WRITE_DUMP
4640 if (fdDump)
4641 {
4642 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4643 fflush(fdDump);
4644 }
4645#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004646#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004647 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004648 if (
4649# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004650 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004651# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004652 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004653 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4654 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004655 char_u *cmdbase = cmd;
4656
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004657 if (cmdbase != NULL)
4658 // Skip a leading quote and (.
4659 while (*cmdbase == '"' || *cmdbase == '(')
4660 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004661
4662 // Check the command does not begin with "start "
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004663 if (cmdbase == NULL
4664 || STRNICMP(cmdbase, "start", 5) != 0 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004665 {
4666 // Use a terminal window to run the command in.
4667 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004668# ifdef FEAT_TITLE
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004669 resettitle();
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004670# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004671 return x;
4672 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004673 }
4674#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004675
4676 /*
4677 * Catch all deadly signals while running the external command, because a
4678 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4679 */
4680 signal(SIGINT, SIG_IGN);
4681#if defined(__GNUC__) && !defined(__MINGW32__)
4682 signal(SIGKILL, SIG_IGN);
4683#else
4684 signal(SIGBREAK, SIG_IGN);
4685#endif
4686 signal(SIGILL, SIG_IGN);
4687 signal(SIGFPE, SIG_IGN);
4688 signal(SIGSEGV, SIG_IGN);
4689 signal(SIGTERM, SIG_IGN);
4690 signal(SIGABRT, SIG_IGN);
4691
4692 if (options & SHELL_COOKED)
4693 settmode(TMODE_COOK); /* set to normal mode */
4694
4695 if (cmd == NULL)
4696 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004697 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004698 }
4699 else
4700 {
4701 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004702 char_u *newcmd = NULL;
4703 char_u *cmdbase = cmd;
4704 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004705
4706 /* Skip a leading ", ( and "(. */
4707 if (*cmdbase == '"' )
4708 ++cmdbase;
4709 if (*cmdbase == '(')
4710 ++cmdbase;
4711
Bram Moolenaar1c465442017-03-12 20:10:05 +01004712 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004713 {
4714 STARTUPINFO si;
4715 PROCESS_INFORMATION pi;
4716 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004717 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004718 char_u *p;
4719
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004720 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004721 si.cb = sizeof(si);
4722 si.lpReserved = NULL;
4723 si.lpDesktop = NULL;
4724 si.lpTitle = NULL;
4725 si.dwFlags = 0;
4726 si.cbReserved2 = 0;
4727 si.lpReserved2 = NULL;
4728
4729 cmdbase = skipwhite(cmdbase + 5);
4730 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004731 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004732 {
4733 cmdbase = skipwhite(cmdbase + 4);
4734 si.dwFlags = STARTF_USESHOWWINDOW;
4735 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004736 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004737 }
4738 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004739 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004740 {
4741 cmdbase = skipwhite(cmdbase + 2);
4742 flags = CREATE_NO_WINDOW;
4743 si.dwFlags = STARTF_USESTDHANDLES;
4744 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004745 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004746 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004747 NULL, // Security att.
4748 OPEN_EXISTING, // Open flags
4749 FILE_ATTRIBUTE_NORMAL, // File att.
4750 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004751 si.hStdOutput = si.hStdInput;
4752 si.hStdError = si.hStdInput;
4753 }
4754
4755 /* Remove a trailing ", ) and )" if they have a match
4756 * at the start of the command. */
4757 if (cmdbase > cmd)
4758 {
4759 p = cmdbase + STRLEN(cmdbase);
4760 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4761 *--p = NUL;
4762 if (p > cmdbase && p[-1] == ')'
4763 && (*cmd =='(' || cmd[1] == '('))
4764 *--p = NUL;
4765 }
4766
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004767 newcmd = cmdbase;
4768 unescape_shellxquote(cmdbase, p_sxe);
4769
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004770 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004771 * If creating new console, arguments are passed to the
4772 * 'cmd.exe' as-is. If it's not, arguments are not treated
4773 * correctly for current 'cmd.exe'. So unescape characters in
4774 * shellxescape except '|' for avoiding to be treated as
4775 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004776 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004777 if (flags != CREATE_NEW_CONSOLE)
4778 {
4779 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004780 char_u *cmd_shell = mch_getenv("COMSPEC");
4781
4782 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004783 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004784
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004785 subcmd = vim_strsave_escaped_ext(cmdbase,
4786 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004787 if (subcmd != NULL)
4788 {
4789 /* make "cmd.exe /c arguments" */
4790 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004791 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004792 if (newcmd != NULL)
4793 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004794 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004795 else
4796 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004797 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004798 }
4799 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004800
4801 /*
4802 * Now, start the command as a process, so that it doesn't
4803 * inherit our handles which causes unpleasant dangling swap
4804 * files if we exit before the spawned process
4805 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004806 if (vim_create_process((char *)newcmd, FALSE, flags,
4807 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004808 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004809 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4810 > (HINSTANCE)32)
4811 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004812 else
4813 {
4814 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01004815#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004816# ifdef VIMDLL
4817 if (gui.in_use)
4818# endif
4819 emsg(_("E371: Command not found"));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004820#endif
4821 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004822
4823 if (newcmd != cmdbase)
4824 vim_free(newcmd);
4825
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004826 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004827 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004828 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004829 CloseHandle(si.hStdInput);
4830 }
4831 /* Close the handles to the subprocess, so that it goes away */
4832 CloseHandle(pi.hThread);
4833 CloseHandle(pi.hProcess);
4834 }
4835 else
4836 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004837 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01004838#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004839 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004840 (!s_dont_use_vimrun && p_stmp ?
4841 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
4842 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004843#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004844 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004845
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004846 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004847 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004848 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01004849#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004850 if (
4851# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004852 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004853# endif
4854 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004855 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01004856 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
4857 "External commands will not pause after completion.\n"
4858 "See :help win32-vimrun for more information.");
4859 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004860 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
4861 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01004862
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004863 if (wmsg != NULL && wtitle != NULL)
4864 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
4865 vim_free(wmsg);
4866 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004867 need_vimrun_warning = FALSE;
4868 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004869 if (
4870# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004871 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004872# endif
4873 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02004874 // Use vimrun to execute the command. It opens a console
4875 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004876 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004877 vimrun_path,
4878 (msg_silent != 0 || (options & SHELL_DOOUT))
4879 ? "-s " : "",
4880 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02004881 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004882# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02004883 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004884# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02004885 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02004886 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004887 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
4888 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004889 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004890#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004891 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004892 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004893 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004894 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004895 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004896 }
4897 }
4898
4899 if (tmode == TMODE_RAW)
4900 settmode(TMODE_RAW); /* set to raw mode */
4901
4902 /* Print the return value, unless "vimrun" was used. */
4903 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01004904#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004905 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004906 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004907#endif
4908 )
4909 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004910 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004911 msg_putchar('\n');
4912 }
4913#ifdef FEAT_TITLE
4914 resettitle();
4915#endif
4916
4917 signal(SIGINT, SIG_DFL);
4918#if defined(__GNUC__) && !defined(__MINGW32__)
4919 signal(SIGKILL, SIG_DFL);
4920#else
4921 signal(SIGBREAK, SIG_DFL);
4922#endif
4923 signal(SIGILL, SIG_DFL);
4924 signal(SIGFPE, SIG_DFL);
4925 signal(SIGSEGV, SIG_DFL);
4926 signal(SIGTERM, SIG_DFL);
4927 signal(SIGABRT, SIG_DFL);
4928
4929 return x;
4930}
4931
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01004932#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004933 static HANDLE
4934job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01004935 char_u *fname,
4936 DWORD dwDesiredAccess,
4937 DWORD dwShareMode,
4938 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
4939 DWORD dwCreationDisposition,
4940 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004941{
4942 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004943 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004944
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004945 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004946 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004947 return INVALID_HANDLE_VALUE;
4948
4949 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
4950 lpSecurityAttributes, dwCreationDisposition,
4951 dwFlagsAndAttributes, NULL);
4952 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004953 return h;
4954}
4955
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004956/*
4957 * Turn the dictionary "env" into a NUL separated list that can be used as the
4958 * environment argument of vim_create_process().
4959 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004960 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004961win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004962{
4963 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004964 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004965 LPVOID base = GetEnvironmentStringsW();
4966
4967 /* for last \0 */
4968 if (ga_grow(gap, 1) == FAIL)
4969 return;
4970
4971 if (base)
4972 {
4973 WCHAR *p = (WCHAR*) base;
4974
4975 /* for last \0 */
4976 if (ga_grow(gap, 1) == FAIL)
4977 return;
4978
4979 while (*p != 0 || *(p + 1) != 0)
4980 {
4981 if (ga_grow(gap, 1) == OK)
4982 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
4983 p++;
4984 }
4985 FreeEnvironmentStrings(base);
4986 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
4987 }
4988
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004989 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004990 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004991 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004992 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004993 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004994 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004995 typval_T *item = &dict_lookup(hi)->di_tv;
4996 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004997 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004998 --todo;
4999 if (wkey != NULL && wval != NULL)
5000 {
5001 size_t n;
5002 size_t lkey = wcslen(wkey);
5003 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005004
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005005 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5006 continue;
5007 for (n = 0; n < lkey; n++)
5008 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5009 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5010 for (n = 0; n < lval; n++)
5011 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5012 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5013 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005014 vim_free(wkey);
5015 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005016 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005017 }
5018 }
5019
Bram Moolenaar493359e2018-06-12 20:25:52 +02005020# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005021 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005022# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005023 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005024 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005025# endif
5026# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005027 char_u *version = get_vim_var_str(VV_VERSION);
5028 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005029# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005030 // size of "VIM_SERVERNAME=" and value,
5031 // plus "VIM_TERMINAL=" and value,
5032 // plus two terminating NULs
5033 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005034# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005035 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005036# endif
5037# ifdef FEAT_TERMINAL
5038 + 13 + version_len + 2
5039# endif
5040 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005041
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005042 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005043 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005044# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005045 for (n = 0; n < 15; n++)
5046 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5047 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005048 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005049 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5050 (WCHAR)servername[n];
5051 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005052# endif
5053# ifdef FEAT_TERMINAL
5054 if (is_terminal)
5055 {
5056 for (n = 0; n < 13; n++)
5057 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5058 (WCHAR)"VIM_TERMINAL="[n];
5059 for (n = 0; n < version_len; n++)
5060 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5061 (WCHAR)version[n];
5062 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5063 }
5064# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005065 }
5066 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005067# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005068}
5069
Bram Moolenaarb091f302019-01-19 14:37:00 +01005070/*
5071 * Create a pair of pipes.
5072 * Return TRUE for success, FALSE for failure.
5073 */
5074 static BOOL
5075create_pipe_pair(HANDLE handles[2])
5076{
5077 static LONG s;
5078 char name[64];
5079 SECURITY_ATTRIBUTES sa;
5080
5081 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5082 GetCurrentProcessId(),
5083 InterlockedIncrement(&s));
5084
5085 // Create named pipe. Max size of named pipe is 65535.
5086 handles[1] = CreateNamedPipe(
5087 name,
5088 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5089 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005090 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005091
5092 if (handles[1] == INVALID_HANDLE_VALUE)
5093 return FALSE;
5094
5095 sa.nLength = sizeof(sa);
5096 sa.bInheritHandle = TRUE;
5097 sa.lpSecurityDescriptor = NULL;
5098
5099 handles[0] = CreateFile(name,
5100 FILE_GENERIC_READ,
5101 FILE_SHARE_READ, &sa,
5102 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5103
5104 if (handles[0] == INVALID_HANDLE_VALUE)
5105 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005106 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005107 return FALSE;
5108 }
5109
5110 return TRUE;
5111}
5112
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005113 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005114mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005115{
5116 STARTUPINFO si;
5117 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005118 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005119 SECURITY_ATTRIBUTES saAttr;
5120 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005121 HANDLE ifd[2];
5122 HANDLE ofd[2];
5123 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005124 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005125
5126 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5127 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5128 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5129 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5130 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5131 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5132 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5133
5134 if (use_out_for_err && use_null_for_out)
5135 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005136
5137 ifd[0] = INVALID_HANDLE_VALUE;
5138 ifd[1] = INVALID_HANDLE_VALUE;
5139 ofd[0] = INVALID_HANDLE_VALUE;
5140 ofd[1] = INVALID_HANDLE_VALUE;
5141 efd[0] = INVALID_HANDLE_VALUE;
5142 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005143 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005144
Bram Moolenaar14207f42016-10-27 21:13:10 +02005145 jo = CreateJobObject(NULL, NULL);
5146 if (jo == NULL)
5147 {
5148 job->jv_status = JOB_FAILED;
5149 goto failed;
5150 }
5151
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005152 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005153 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005154
Bram Moolenaar76467df2016-02-12 19:30:26 +01005155 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005156 ZeroMemory(&si, sizeof(si));
5157 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005158 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005159 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005160
Bram Moolenaard8070362016-02-15 21:56:54 +01005161 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5162 saAttr.bInheritHandle = TRUE;
5163 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005164
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005165 if (use_file_for_in)
5166 {
5167 char_u *fname = options->jo_io_name[PART_IN];
5168
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005169 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5170 FILE_SHARE_READ | FILE_SHARE_WRITE,
5171 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5172 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005173 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005174 semsg(_(e_notopen), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005175 goto failed;
5176 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005177 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005178 else if (!use_null_for_in
5179 && (!create_pipe_pair(ifd)
5180 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005181 goto failed;
5182
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005183 if (use_file_for_out)
5184 {
5185 char_u *fname = options->jo_io_name[PART_OUT];
5186
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005187 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5188 FILE_SHARE_READ | FILE_SHARE_WRITE,
5189 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5190 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005191 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005192 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005193 goto failed;
5194 }
5195 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005196 else if (!use_null_for_out &&
5197 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005198 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005199 goto failed;
5200
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005201 if (use_file_for_err)
5202 {
5203 char_u *fname = options->jo_io_name[PART_ERR];
5204
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005205 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5206 FILE_SHARE_READ | FILE_SHARE_WRITE,
5207 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5208 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005209 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005210 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005211 goto failed;
5212 }
5213 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005214 else if (!use_out_for_err && !use_null_for_err &&
5215 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005216 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005217 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005218
Bram Moolenaard8070362016-02-15 21:56:54 +01005219 si.dwFlags |= STARTF_USESTDHANDLES;
5220 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005221 si.hStdOutput = ofd[1];
5222 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5223
5224 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5225 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005226 if (options->jo_set & JO_CHANNEL)
5227 {
5228 channel = options->jo_channel;
5229 if (channel != NULL)
5230 ++channel->ch_refcount;
5231 }
5232 else
5233 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005234 if (channel == NULL)
5235 goto failed;
5236 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005237
5238 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005239 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005240 CREATE_DEFAULT_ERROR_MODE |
5241 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005242 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005243 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005244 &si, &pi,
5245 ga.ga_data,
5246 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005247 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005248 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005249 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005250 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005251 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005252
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005253 ga_clear(&ga);
5254
Bram Moolenaar14207f42016-10-27 21:13:10 +02005255 if (!AssignProcessToJobObject(jo, pi.hProcess))
5256 {
5257 /* if failing, switch the way to terminate
5258 * process with TerminateProcess. */
5259 CloseHandle(jo);
5260 jo = NULL;
5261 }
5262 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005263 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005264 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005265 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005266 job->jv_status = JOB_STARTED;
5267
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005268 CloseHandle(ifd[0]);
5269 CloseHandle(ofd[1]);
5270 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005271 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005272
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005273 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005274 if (channel != NULL)
5275 {
5276 channel_set_pipes(channel,
5277 use_file_for_in || use_null_for_in
5278 ? INVALID_FD : (sock_T)ifd[1],
5279 use_file_for_out || use_null_for_out
5280 ? INVALID_FD : (sock_T)ofd[0],
5281 use_out_for_err || use_file_for_err || use_null_for_err
5282 ? INVALID_FD : (sock_T)efd[0]);
5283 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005284 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005285 return;
5286
5287failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005288 CloseHandle(ifd[0]);
5289 CloseHandle(ofd[0]);
5290 CloseHandle(efd[0]);
5291 CloseHandle(ifd[1]);
5292 CloseHandle(ofd[1]);
5293 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005294 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005295 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005296}
5297
5298 char *
5299mch_job_status(job_T *job)
5300{
5301 DWORD dwExitCode = 0;
5302
Bram Moolenaar76467df2016-02-12 19:30:26 +01005303 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5304 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005305 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005306 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005307 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005308 {
5309 ch_log(job->jv_channel, "Job ended");
5310 job->jv_status = JOB_ENDED;
5311 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005312 return "dead";
5313 }
5314 return "run";
5315}
5316
Bram Moolenaar97792de2016-10-15 18:36:49 +02005317 job_T *
5318mch_detect_ended_job(job_T *job_list)
5319{
5320 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5321 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5322 job_T *job = job_list;
5323
5324 while (job != NULL)
5325 {
5326 DWORD n;
5327 DWORD result;
5328
5329 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5330 && job != NULL; job = job->jv_next)
5331 {
5332 if (job->jv_status == JOB_STARTED)
5333 {
5334 jobHandles[n] = job->jv_proc_info.hProcess;
5335 jobArray[n] = job;
5336 ++n;
5337 }
5338 }
5339 if (n == 0)
5340 continue;
5341 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5342 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5343 {
5344 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5345
5346 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5347 return wait_job;
5348 }
5349 }
5350 return NULL;
5351}
5352
Bram Moolenaarfb630902016-10-29 14:55:00 +02005353 static BOOL
5354terminate_all(HANDLE process, int code)
5355{
5356 PROCESSENTRY32 pe;
5357 HANDLE h = INVALID_HANDLE_VALUE;
5358 DWORD pid = GetProcessId(process);
5359
5360 if (pid != 0)
5361 {
5362 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5363 if (h != INVALID_HANDLE_VALUE)
5364 {
5365 pe.dwSize = sizeof(PROCESSENTRY32);
5366 if (!Process32First(h, &pe))
5367 goto theend;
5368
5369 do
5370 {
5371 if (pe.th32ParentProcessID == pid)
5372 {
5373 HANDLE ph = OpenProcess(
5374 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5375 if (ph != NULL)
5376 {
5377 terminate_all(ph, code);
5378 CloseHandle(ph);
5379 }
5380 }
5381 } while (Process32Next(h, &pe));
5382
5383 CloseHandle(h);
5384 }
5385 }
5386
5387theend:
5388 return TerminateProcess(process, code);
5389}
5390
5391/*
5392 * Send a (deadly) signal to "job".
5393 * Return FAIL if it didn't work.
5394 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005395 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005396mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005397{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005398 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005399
Bram Moolenaar923d9262016-02-25 20:56:01 +01005400 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005401 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005402 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005403 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005404 {
5405 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5406 job->jv_channel->ch_killing = TRUE;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005407 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005408 }
Bram Moolenaarfb630902016-10-29 14:55:00 +02005409 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005410 }
5411
5412 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5413 return FAIL;
5414 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005415 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5416 job->jv_proc_info.dwProcessId)
5417 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005418 FreeConsole();
5419 return ret;
5420}
5421
5422/*
5423 * Clear the data related to "job".
5424 */
5425 void
5426mch_clear_job(job_T *job)
5427{
5428 if (job->jv_status != JOB_FAILED)
5429 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005430 if (job->jv_job_object != NULL)
5431 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005432 CloseHandle(job->jv_proc_info.hProcess);
5433 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005434}
5435#endif
5436
Bram Moolenaar071d4272004-06-13 20:20:40 +00005437
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005438#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005439
5440/*
5441 * Start termcap mode
5442 */
5443 static void
5444termcap_mode_start(void)
5445{
5446 DWORD cmodein;
5447
5448 if (g_fTermcapMode)
5449 return;
5450
5451 SaveConsoleBuffer(&g_cbNonTermcap);
5452
5453 if (g_cbTermcap.IsValid)
5454 {
5455 /*
5456 * We've been in termcap mode before. Restore certain screen
5457 * characteristics, including the buffer size and the window
5458 * size. Since we will be redrawing the screen, we don't need
5459 * to restore the actual contents of the buffer.
5460 */
5461 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005462 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005463 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5464 Rows = g_cbTermcap.Info.dwSize.Y;
5465 Columns = g_cbTermcap.Info.dwSize.X;
5466 }
5467 else
5468 {
5469 /*
5470 * This is our first time entering termcap mode. Clear the console
5471 * screen buffer, and resize the buffer to match the current window
5472 * size. We will use this as the size of our editing environment.
5473 */
5474 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005475 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005476 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5477 }
5478
5479#ifdef FEAT_TITLE
5480 resettitle();
5481#endif
5482
5483 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005484 if (g_fMouseActive)
5485 cmodein |= ENABLE_MOUSE_INPUT;
5486 else
5487 cmodein &= ~ENABLE_MOUSE_INPUT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005488 cmodein |= ENABLE_WINDOW_INPUT;
5489 SetConsoleMode(g_hConIn, cmodein);
5490
5491 redraw_later_clear();
5492 g_fTermcapMode = TRUE;
5493}
5494
5495
5496/*
5497 * End termcap mode
5498 */
5499 static void
5500termcap_mode_end(void)
5501{
5502 DWORD cmodein;
5503 ConsoleBuffer *cb;
5504 COORD coord;
5505 DWORD dwDummy;
5506
5507 if (!g_fTermcapMode)
5508 return;
5509
5510 SaveConsoleBuffer(&g_cbTermcap);
5511
5512 GetConsoleMode(g_hConIn, &cmodein);
5513 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5514 SetConsoleMode(g_hConIn, cmodein);
5515
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005516#ifdef FEAT_RESTORE_ORIG_SCREEN
5517 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5518#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005519 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005520#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005521 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005522 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005523 SetConsoleCursorInfo(g_hConOut, &g_cci);
5524
5525 if (p_rs || exiting)
5526 {
5527 /*
5528 * Clear anything that happens to be on the current line.
5529 */
5530 coord.X = 0;
5531 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5532 FillConsoleOutputCharacter(g_hConOut, ' ',
5533 cb->Info.dwSize.X, coord, &dwDummy);
5534 /*
5535 * The following is just for aesthetics. If we are exiting without
5536 * restoring the screen, then we want to have a prompt string
5537 * appear at the bottom line. However, the command interpreter
5538 * seems to always advance the cursor one line before displaying
5539 * the prompt string, which causes the screen to scroll. To
5540 * counter this, move the cursor up one line before exiting.
5541 */
5542 if (exiting && !p_rs)
5543 coord.Y--;
5544 /*
5545 * Position the cursor at the leftmost column of the desired row.
5546 */
5547 SetConsoleCursorPosition(g_hConOut, coord);
5548 }
5549
5550 g_fTermcapMode = FALSE;
5551}
Bram Moolenaar4f974752019-02-17 17:44:42 +01005552#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005553
5554
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005555#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005556 void
5557mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005558 char_u *s UNUSED,
5559 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005560{
5561 /* never used */
5562}
5563
5564#else
5565
5566/*
5567 * clear `n' chars, starting from `coord'
5568 */
5569 static void
5570clear_chars(
5571 COORD coord,
5572 DWORD n)
5573{
5574 DWORD dwDummy;
5575
5576 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005577
5578 if (!USE_VTP)
5579 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5580 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005581 {
5582 set_console_color_rgb();
5583 gotoxy(coord.X + 1, coord.Y + 1);
5584 vtp_printf("\033[%dX", n);
5585 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005586}
5587
5588
5589/*
5590 * Clear the screen
5591 */
5592 static void
5593clear_screen(void)
5594{
5595 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005596
5597 if (!USE_VTP)
5598 clear_chars(g_coord, Rows * Columns);
5599 else
5600 {
5601 set_console_color_rgb();
5602 gotoxy(1, 1);
5603 vtp_printf("\033[2J");
5604 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005605}
5606
5607
5608/*
5609 * Clear to end of display
5610 */
5611 static void
5612clear_to_end_of_display(void)
5613{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005614 COORD save = g_coord;
5615
5616 if (!USE_VTP)
5617 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005618 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005619 else
5620 {
5621 set_console_color_rgb();
5622 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5623 vtp_printf("\033[0J");
5624
5625 gotoxy(save.X + 1, save.Y + 1);
5626 g_coord = save;
5627 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005628}
5629
5630
5631/*
5632 * Clear to end of line
5633 */
5634 static void
5635clear_to_end_of_line(void)
5636{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005637 COORD save = g_coord;
5638
5639 if (!USE_VTP)
5640 clear_chars(g_coord, Columns - g_coord.X);
5641 else
5642 {
5643 set_console_color_rgb();
5644 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5645 vtp_printf("\033[0K");
5646
5647 gotoxy(save.X + 1, save.Y + 1);
5648 g_coord = save;
5649 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005650}
5651
5652
5653/*
5654 * Scroll the scroll region up by `cLines' lines
5655 */
5656 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005657scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005658{
5659 COORD oldcoord = g_coord;
5660
5661 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5662 delete_lines(cLines);
5663
5664 g_coord = oldcoord;
5665}
5666
5667
5668/*
5669 * Set the scroll region
5670 */
5671 static void
5672set_scroll_region(
5673 unsigned left,
5674 unsigned top,
5675 unsigned right,
5676 unsigned bottom)
5677{
5678 if (left >= right
5679 || top >= bottom
5680 || right > (unsigned) Columns - 1
5681 || bottom > (unsigned) Rows - 1)
5682 return;
5683
5684 g_srScrollRegion.Left = left;
5685 g_srScrollRegion.Top = top;
5686 g_srScrollRegion.Right = right;
5687 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005688}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005689
Bram Moolenaar6982f422019-02-16 16:48:01 +01005690 static void
5691set_scroll_region_tb(
5692 unsigned top,
5693 unsigned bottom)
5694{
5695 if (top >= bottom || bottom > (unsigned)Rows - 1)
5696 return;
5697
5698 g_srScrollRegion.Top = top;
5699 g_srScrollRegion.Bottom = bottom;
5700}
5701
5702 static void
5703set_scroll_region_lr(
5704 unsigned left,
5705 unsigned right)
5706{
5707 if (left >= right || right > (unsigned)Columns - 1)
5708 return;
5709
5710 g_srScrollRegion.Left = left;
5711 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005712}
5713
5714
5715/*
5716 * Insert `cLines' lines at the current cursor position
5717 */
5718 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005719insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005720{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005721 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005722 COORD dest;
5723 CHAR_INFO fill;
5724
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005725 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5726
Bram Moolenaar6982f422019-02-16 16:48:01 +01005727 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005728 dest.Y = g_coord.Y + cLines;
5729
Bram Moolenaar6982f422019-02-16 16:48:01 +01005730 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005731 source.Top = g_coord.Y;
5732 source.Right = g_srScrollRegion.Right;
5733 source.Bottom = g_srScrollRegion.Bottom - cLines;
5734
Bram Moolenaar6982f422019-02-16 16:48:01 +01005735 clip.Left = g_srScrollRegion.Left;
5736 clip.Top = g_coord.Y;
5737 clip.Right = g_srScrollRegion.Right;
5738 clip.Bottom = g_srScrollRegion.Bottom;
5739
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005740 fill.Char.AsciiChar = ' ';
5741 if (!USE_VTP)
5742 fill.Attributes = g_attrCurrent;
5743 else
5744 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005745
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005746 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005747
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005748 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5749
Bram Moolenaar6982f422019-02-16 16:48:01 +01005750 // Here we have to deal with a win32 console flake: If the scroll
5751 // region looks like abc and we scroll c to a and fill with d we get
5752 // cbd... if we scroll block c one line at a time to a, we get cdd...
5753 // vim expects cdd consistently... So we have to deal with that
5754 // here... (this also occurs scrolling the same way in the other
5755 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005756
5757 if (source.Bottom < dest.Y)
5758 {
5759 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005760 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005761
Bram Moolenaar6982f422019-02-16 16:48:01 +01005762 coord.X = source.Left;
5763 for (i = clip.Top; i < dest.Y; ++i)
5764 {
5765 coord.Y = i;
5766 clear_chars(coord, source.Right - source.Left + 1);
5767 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005768 }
5769}
5770
5771
5772/*
5773 * Delete `cLines' lines at the current cursor position
5774 */
5775 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005776delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005777{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005778 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005779 COORD dest;
5780 CHAR_INFO fill;
5781 int nb;
5782
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005783 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5784
Bram Moolenaar6982f422019-02-16 16:48:01 +01005785 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005786 dest.Y = g_coord.Y;
5787
Bram Moolenaar6982f422019-02-16 16:48:01 +01005788 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005789 source.Top = g_coord.Y + cLines;
5790 source.Right = g_srScrollRegion.Right;
5791 source.Bottom = g_srScrollRegion.Bottom;
5792
Bram Moolenaar6982f422019-02-16 16:48:01 +01005793 clip.Left = g_srScrollRegion.Left;
5794 clip.Top = g_coord.Y;
5795 clip.Right = g_srScrollRegion.Right;
5796 clip.Bottom = g_srScrollRegion.Bottom;
5797
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005798 fill.Char.AsciiChar = ' ';
5799 if (!USE_VTP)
5800 fill.Attributes = g_attrCurrent;
5801 else
5802 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005803
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005804 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005805
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005806 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5807
Bram Moolenaar6982f422019-02-16 16:48:01 +01005808 // Here we have to deal with a win32 console flake; See insert_lines()
5809 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005810
5811 nb = dest.Y + (source.Bottom - source.Top) + 1;
5812
5813 if (nb < source.Top)
5814 {
5815 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005816 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005817
Bram Moolenaar6982f422019-02-16 16:48:01 +01005818 coord.X = source.Left;
5819 for (i = nb; i < clip.Bottom; ++i)
5820 {
5821 coord.Y = i;
5822 clear_chars(coord, source.Right - source.Left + 1);
5823 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005824 }
5825}
5826
5827
5828/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02005829 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005830 */
5831 static void
5832gotoxy(
5833 unsigned x,
5834 unsigned y)
5835{
5836 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5837 return;
5838
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005839 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02005840 {
5841 // external cursor coords are 1-based; internal are 0-based
5842 g_coord.X = x - 1;
5843 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005844 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02005845 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005846 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02005847 {
5848 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02005849 // destruction. Insider build bug. Always enabled because it's cheap
5850 // and avoids mistakes with recognizing the build.
5851 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02005852
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005853 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02005854
5855 g_coord.X = x - 1;
5856 g_coord.Y = y - 1;
5857 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005858}
5859
5860
5861/*
5862 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005863 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005864 */
5865 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005866textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005867{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005868 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005869
5870 SetConsoleTextAttribute(g_hConOut, wAttr);
5871}
5872
5873
5874 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005875textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005876{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005877 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005878
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005879 if (!USE_VTP)
5880 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5881 else
5882 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005883}
5884
5885
5886 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005887textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005888{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005889 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005890
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005891 if (!USE_VTP)
5892 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5893 else
5894 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005895}
5896
5897
5898/*
5899 * restore the default text attribute (whatever we started with)
5900 */
5901 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005902normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005903{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005904 if (!USE_VTP)
5905 textattr(g_attrDefault);
5906 else
5907 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005908}
5909
5910
5911static WORD g_attrPreStandout = 0;
5912
5913/*
5914 * Make the text standout, by brightening it
5915 */
5916 static void
5917standout(void)
5918{
5919 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005920
Bram Moolenaar071d4272004-06-13 20:20:40 +00005921 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5922}
5923
5924
5925/*
5926 * Turn off standout mode
5927 */
5928 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005929standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005930{
5931 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005932 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005933
5934 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005935}
5936
5937
5938/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005939 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005940 */
5941 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005942mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005943{
5944 char_u *p;
5945 int n;
5946
5947 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5948 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005949 if (
5950#ifdef FEAT_TERMGUICOLORS
5951 !p_tgc &&
5952#endif
5953 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005954 {
5955 p = T_ME + 2;
5956 n = getdigits(&p);
5957 if (*p == 'm' && n > 0)
5958 {
5959 cterm_normal_fg_color = (n & 0xf) + 1;
5960 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5961 }
5962 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005963#ifdef FEAT_TERMGUICOLORS
5964 cterm_normal_fg_gui_color = INVALCOLOR;
5965 cterm_normal_bg_gui_color = INVALCOLOR;
5966#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005967}
5968
5969
5970/*
5971 * visual bell: flash the screen
5972 */
5973 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005974visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005975{
5976 COORD coordOrigin = {0, 0};
5977 WORD attrFlash = ~g_attrCurrent & 0xff;
5978
5979 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005980 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005981
5982 if (oldattrs == NULL)
5983 return;
5984 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5985 coordOrigin, &dwDummy);
5986 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5987 coordOrigin, &dwDummy);
5988
5989 Sleep(15); /* wait for 15 msec */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005990 if (!USE_VTP)
5991 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005992 coordOrigin, &dwDummy);
5993 vim_free(oldattrs);
5994}
5995
5996
5997/*
5998 * Make the cursor visible or invisible
5999 */
6000 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006001cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006002{
6003 s_cursor_visible = fVisible;
6004#ifdef MCH_CURSOR_SHAPE
6005 mch_update_cursor();
6006#endif
6007}
6008
6009
6010/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006011 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006012 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006013 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006014 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006015write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006016 char_u *pchBuf,
6017 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006018{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006019 COORD coord = g_coord;
6020 DWORD written;
6021 DWORD n, cchwritten, cells;
6022 static WCHAR *unicodebuf = NULL;
6023 static int unibuflen = 0;
6024 int length;
6025 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006026
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006027 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
6028 if (unicodebuf == NULL || length > unibuflen)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006029 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006030 vim_free(unicodebuf);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006031 unicodebuf = LALLOC_MULT(WCHAR, length);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006032 unibuflen = length;
6033 }
6034 MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6035 unicodebuf, unibuflen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006036
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006037 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006038
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006039 if (!USE_VTP)
6040 {
6041 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6042 coord, &written);
6043 // When writing fails or didn't write a single character, pretend one
6044 // character was written, otherwise we get stuck.
6045 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
6046 coord, &cchwritten) == 0
6047 || cchwritten == 0 || cchwritten == (DWORD)-1)
6048 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006049 }
6050 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006051 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006052 if (WriteConsoleW(g_hConOut, unicodebuf, length, &cchwritten,
6053 NULL) == 0 || cchwritten == 0)
6054 cchwritten = 1;
6055 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006056
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006057 if (cchwritten == length)
6058 {
6059 written = cbToWrite;
6060 g_coord.X += (SHORT)cells;
6061 }
6062 else
6063 {
6064 char_u *p = pchBuf;
6065 for (n = 0; n < cchwritten; n++)
6066 MB_CPTR_ADV(p);
6067 written = p - pchBuf;
6068 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006069 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006070
6071 while (g_coord.X > g_srScrollRegion.Right)
6072 {
6073 g_coord.X -= (SHORT) Columns;
6074 if (g_coord.Y < g_srScrollRegion.Bottom)
6075 g_coord.Y++;
6076 }
6077
6078 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6079
6080 return written;
6081}
6082
6083
6084/*
6085 * mch_write(): write the output buffer to the screen, translating ESC
6086 * sequences into calls to console output routines.
6087 */
6088 void
6089mch_write(
6090 char_u *s,
6091 int len)
6092{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006093# ifdef VIMDLL
6094 if (gui.in_use)
6095 return;
6096# endif
6097
Bram Moolenaar071d4272004-06-13 20:20:40 +00006098 s[len] = NUL;
6099
6100 if (!term_console)
6101 {
6102 write(1, s, (unsigned)len);
6103 return;
6104 }
6105
6106 /* translate ESC | sequences into faked bios calls */
6107 while (len--)
6108 {
6109 /* optimization: use one single write_chars for runs of text,
6110 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006111 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006112
6113 if (p_wd)
6114 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006115 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006116 if (prefix != 0)
6117 prefix = 1;
6118 }
6119
6120 if (prefix != 0)
6121 {
6122 DWORD nWritten;
6123
6124 nWritten = write_chars(s, prefix);
6125#ifdef MCH_WRITE_DUMP
6126 if (fdDump)
6127 {
6128 fputc('>', fdDump);
6129 fwrite(s, sizeof(char_u), nWritten, fdDump);
6130 fputs("<\n", fdDump);
6131 }
6132#endif
6133 len -= (nWritten - 1);
6134 s += nWritten;
6135 }
6136 else if (s[0] == '\n')
6137 {
6138 /* \n, newline: go to the beginning of the next line or scroll */
6139 if (g_coord.Y == g_srScrollRegion.Bottom)
6140 {
6141 scroll(1);
6142 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6143 }
6144 else
6145 {
6146 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6147 }
6148#ifdef MCH_WRITE_DUMP
6149 if (fdDump)
6150 fputs("\\n\n", fdDump);
6151#endif
6152 s++;
6153 }
6154 else if (s[0] == '\r')
6155 {
6156 /* \r, carriage return: go to beginning of line */
6157 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
6158#ifdef MCH_WRITE_DUMP
6159 if (fdDump)
6160 fputs("\\r\n", fdDump);
6161#endif
6162 s++;
6163 }
6164 else if (s[0] == '\b')
6165 {
6166 /* \b, backspace: move cursor one position left */
6167 if (g_coord.X > g_srScrollRegion.Left)
6168 g_coord.X--;
6169 else if (g_coord.Y > g_srScrollRegion.Top)
6170 {
6171 g_coord.X = g_srScrollRegion.Right;
6172 g_coord.Y--;
6173 }
6174 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6175#ifdef MCH_WRITE_DUMP
6176 if (fdDump)
6177 fputs("\\b\n", fdDump);
6178#endif
6179 s++;
6180 }
6181 else if (s[0] == '\a')
6182 {
6183 /* \a, bell */
6184 MessageBeep(0xFFFFFFFF);
6185#ifdef MCH_WRITE_DUMP
6186 if (fdDump)
6187 fputs("\\a\n", fdDump);
6188#endif
6189 s++;
6190 }
6191 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6192 {
6193#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006194 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006195#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006196 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006197 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006198
6199 switch (s[2])
6200 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006201 case '0': case '1': case '2': case '3': case '4':
6202 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006203 p = s + 1;
6204 do
6205 {
6206 ++p;
6207 args[argc] = getdigits(&p);
6208 argc += (argc < 15) ? 1 : 0;
6209 if (p > s + len)
6210 break;
6211 } while (*p == ';');
6212
Bram Moolenaar071d4272004-06-13 20:20:40 +00006213 if (p > s + len)
6214 break;
6215
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006216 arg1 = args[0];
6217 arg2 = args[1];
6218 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006219 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006220 if (argc == 1 && args[0] == 0)
6221 normvideo();
6222 else if (argc == 1)
6223 {
6224 if (USE_VTP)
6225 textcolor((WORD) arg1);
6226 else
6227 textattr((WORD) arg1);
6228 }
6229 else if (USE_VTP)
6230 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006231 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006232 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006233 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006234 gotoxy(arg2, arg1);
6235 }
6236 else if (argc == 2 && *p == 'r')
6237 {
6238 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6239 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006240 else if (argc == 2 && *p == 'R')
6241 {
6242 set_scroll_region_tb(arg1, arg2);
6243 }
6244 else if (argc == 2 && *p == 'V')
6245 {
6246 set_scroll_region_lr(arg1, arg2);
6247 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006248 else if (argc == 1 && *p == 'A')
6249 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006250 gotoxy(g_coord.X + 1,
6251 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6252 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006253 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006254 {
6255 textbackground((WORD) arg1);
6256 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006257 else if (argc == 1 && *p == 'C')
6258 {
6259 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6260 g_coord.Y + 1);
6261 }
6262 else if (argc == 1 && *p == 'f')
6263 {
6264 textcolor((WORD) arg1);
6265 }
6266 else if (argc == 1 && *p == 'H')
6267 {
6268 gotoxy(1, arg1);
6269 }
6270 else if (argc == 1 && *p == 'L')
6271 {
6272 insert_lines(arg1);
6273 }
6274 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006275 {
6276 delete_lines(arg1);
6277 }
6278
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006279 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006280 s = p + 1;
6281 break;
6282
Bram Moolenaar071d4272004-06-13 20:20:40 +00006283 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006284 gotoxy(g_coord.X + 1,
6285 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6286 goto got3;
6287
6288 case 'B':
6289 visual_bell();
6290 goto got3;
6291
6292 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006293 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6294 g_coord.Y + 1);
6295 goto got3;
6296
6297 case 'E':
6298 termcap_mode_end();
6299 goto got3;
6300
6301 case 'F':
6302 standout();
6303 goto got3;
6304
6305 case 'f':
6306 standend();
6307 goto got3;
6308
6309 case 'H':
6310 gotoxy(1, 1);
6311 goto got3;
6312
6313 case 'j':
6314 clear_to_end_of_display();
6315 goto got3;
6316
6317 case 'J':
6318 clear_screen();
6319 goto got3;
6320
6321 case 'K':
6322 clear_to_end_of_line();
6323 goto got3;
6324
6325 case 'L':
6326 insert_lines(1);
6327 goto got3;
6328
6329 case 'M':
6330 delete_lines(1);
6331 goto got3;
6332
6333 case 'S':
6334 termcap_mode_start();
6335 goto got3;
6336
6337 case 'V':
6338 cursor_visible(TRUE);
6339 goto got3;
6340
6341 case 'v':
6342 cursor_visible(FALSE);
6343 goto got3;
6344
6345 got3:
6346 s += 3;
6347 len -= 2;
6348 }
6349
6350#ifdef MCH_WRITE_DUMP
6351 if (fdDump)
6352 {
6353 fputs("ESC | ", fdDump);
6354 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6355 fputc('\n', fdDump);
6356 }
6357#endif
6358 }
6359 else
6360 {
6361 /* Write a single character */
6362 DWORD nWritten;
6363
6364 nWritten = write_chars(s, 1);
6365#ifdef MCH_WRITE_DUMP
6366 if (fdDump)
6367 {
6368 fputc('>', fdDump);
6369 fwrite(s, sizeof(char_u), nWritten, fdDump);
6370 fputs("<\n", fdDump);
6371 }
6372#endif
6373
6374 len -= (nWritten - 1);
6375 s += nWritten;
6376 }
6377 }
6378
6379#ifdef MCH_WRITE_DUMP
6380 if (fdDump)
6381 fflush(fdDump);
6382#endif
6383}
6384
Bram Moolenaar4f974752019-02-17 17:44:42 +01006385#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006386
6387
6388/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006389 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006390 */
6391 void
6392mch_delay(
6393 long msec,
Bram Moolenaar1266d672017-02-01 13:43:36 +01006394 int ignoreinput UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006395{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006396#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006397 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006398#else /* Console */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006399# ifdef VIMDLL
6400 if (gui.in_use)
6401 {
6402 Sleep((int)msec); /* never wait for input */
6403 return;
6404 }
6405# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006406 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006407# ifdef FEAT_MZSCHEME
6408 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6409 {
6410 int towait = p_mzq;
6411
6412 /* if msec is large enough, wait by portions in p_mzq */
6413 while (msec > 0)
6414 {
6415 mzvim_check_threads();
6416 if (msec < towait)
6417 towait = msec;
6418 Sleep(towait);
6419 msec -= towait;
6420 }
6421 }
6422 else
6423# endif
6424 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006425 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006426 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006427#endif
6428}
6429
6430
6431/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006432 * This version of remove is not scared by a readonly (backup) file.
6433 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006434 * Return 0 for success, -1 for failure.
6435 */
6436 int
6437mch_remove(char_u *name)
6438{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006439 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006440 int n;
6441
Bram Moolenaar203258c2016-01-17 22:15:16 +01006442 /*
6443 * On Windows, deleting a directory's symbolic link is done by
6444 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6445 */
6446 if (mch_isdir(name) && mch_is_symbolic_link(name))
6447 return mch_rmdir(name);
6448
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006449 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6450
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006451 wn = enc_to_utf16(name, NULL);
6452 if (wn == NULL)
6453 return -1;
6454
6455 n = DeleteFileW(wn) ? 0 : -1;
6456 vim_free(wn);
6457 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006458}
6459
6460
6461/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006462 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006463 */
6464 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006465mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006466{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006467#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
6468# ifdef VIMDLL
6469 if (!gui.in_use)
6470# endif
6471 if (g_fCtrlCPressed || g_fCBrkPressed)
6472 {
6473 ctrl_break_was_pressed = g_fCBrkPressed;
6474 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6475 got_int = TRUE;
6476 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006477#endif
6478}
6479
Bram Moolenaaree273972016-01-02 21:11:51 +01006480/* physical RAM to leave for the OS */
6481#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006482
6483/*
6484 * How much main memory in KiB that can be used by VIM.
6485 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006486 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006487mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006488{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006489 MEMORYSTATUSEX ms;
6490
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006491 /* Need to use GlobalMemoryStatusEx() when there is more memory than
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006492 * what fits in 32 bits. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006493 ms.dwLength = sizeof(MEMORYSTATUSEX);
6494 GlobalMemoryStatusEx(&ms);
6495 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006496 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006497 /* Process address space fits in physical RAM, use all of it. */
6498 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006499 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006500 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006501 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006502 /* Catch old NT box or perverse hardware setup. */
6503 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006504 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006505 /* Use physical RAM less reserve for OS + data. */
6506 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006507}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006508
Bram Moolenaar071d4272004-06-13 20:20:40 +00006509/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006510 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00006511 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6512 * file whose short file name is "FOO.BAR" (its long file name will
6513 * be correct: "foo.bar~"). Because a file can be accessed by
6514 * either its SFN or its LFN, "foo.bar" has effectively been
6515 * renamed to "foo.bar", which is not at all what was wanted. This
6516 * seems to happen only when renaming files with three-character
6517 * extensions by appending a suffix that does not include ".".
6518 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6519 *
6520 * There is another problem, which isn't really a bug but isn't right either:
6521 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6522 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6523 * service pack 6. Doesn't seem to happen on Windows 98.
6524 *
6525 * Like rename(), returns 0 upon success, non-zero upon failure.
6526 * Should probably set errno appropriately when errors occur.
6527 */
6528 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006529mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006530{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006531 WCHAR *p;
6532 int i;
6533 WCHAR szTempFile[_MAX_PATH + 1];
6534 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006535 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006536
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006537 // No need to play tricks unless the file name contains a "~" as the
6538 // seventh character.
6539 p = wold;
6540 for (i = 0; wold[i] != NUL; ++i)
6541 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6542 && wold[i + 1] != 0)
6543 p = wold + i + 1;
6544 if ((int)(wold + i - p) < 8 || p[6] != '~')
6545 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006546
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006547 // Get base path of new file name. Undocumented feature: If pszNewFile is
6548 // a directory, no error is returned and pszFilePart will be NULL.
6549 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006550 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006551 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006552
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006553 // Get (and create) a unique temporary file name in directory of new file
6554 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006555 return -2;
6556
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006557 // blow the temp file away
6558 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006559 return -3;
6560
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006561 // rename old file to the temp file
6562 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006563 return -4;
6564
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006565 // now create an empty file called pszOldFile; this prevents the operating
6566 // system using pszOldFile as an alias (SFN) if we're renaming within the
6567 // same directory. For example, we're editing a file called
6568 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6569 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
6570 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
6571 // cause all sorts of problems later in buf_write(). So, we create an
6572 // empty file called filena~1.txt and the system will have to find some
6573 // other SFN for filena~1.txt~, such as filena~2.txt
6574 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006575 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6576 return -5;
6577 if (!CloseHandle(hf))
6578 return -6;
6579
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006580 // rename the temp file to the new file
6581 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006582 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006583 // Renaming failed. Rename the file back to its old name, so that it
6584 // looks like nothing happened.
6585 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006586 return -7;
6587 }
6588
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006589 // Seems to be left around on Novell filesystems
6590 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006591
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006592 // finally, remove the empty old file
6593 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006594 return -8;
6595
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006596 return 0;
6597}
6598
6599
6600/*
6601 * Converts the filenames to UTF-16, then call mch_wrename().
6602 * Like rename(), returns 0 upon success, non-zero upon failure.
6603 */
6604 int
6605mch_rename(
6606 const char *pszOldFile,
6607 const char *pszNewFile)
6608{
6609 WCHAR *wold = NULL;
6610 WCHAR *wnew = NULL;
6611 int retval = -1;
6612
6613 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6614 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
6615 if (wold != NULL && wnew != NULL)
6616 retval = mch_wrename(wold, wnew);
6617 vim_free(wold);
6618 vim_free(wnew);
6619 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006620}
6621
6622/*
6623 * Get the default shell for the current hardware platform
6624 */
6625 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006626default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006627{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006628 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006629}
6630
6631/*
6632 * mch_access() extends access() to do more detailed check on network drives.
6633 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6634 */
6635 int
6636mch_access(char *n, int p)
6637{
6638 HANDLE hFile;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006639 int retval = -1; /* default: fail */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006640 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006641
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006642 wn = enc_to_utf16((char_u *)n, NULL);
6643 if (wn == NULL)
6644 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006645
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006646 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006647 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006648 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006649
6650 if (p & R_OK)
6651 {
6652 /* Read check is performed by seeing if we can do a find file on
6653 * the directory for any file. */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006654 int i;
6655 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006656
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006657 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6658 TempNameW[i] = wn[i];
6659 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6660 TempNameW[i++] = '\\';
6661 TempNameW[i++] = '*';
6662 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006663
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006664 hFile = FindFirstFileW(TempNameW, &d);
6665 if (hFile == INVALID_HANDLE_VALUE)
6666 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006667 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006668 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006669 }
6670
6671 if (p & W_OK)
6672 {
6673 /* Trying to create a temporary file in the directory should catch
6674 * directories on read-only network shares. However, in
6675 * directories whose ACL allows writes but denies deletes will end
6676 * up keeping the temporary file :-(. */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006677 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6678 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006679 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006680 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006681 }
6682 }
6683 else
6684 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02006685 // Don't consider a file read-only if another process has opened it.
6686 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
6687
Bram Moolenaar071d4272004-06-13 20:20:40 +00006688 /* Trying to open the file for the required access does ACL, read-only
6689 * network share, and file attribute checks. */
Bram Moolenaar5aa98962018-05-06 17:09:38 +02006690 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
6691 | ((p & R_OK) ? GENERIC_READ : 0);
6692
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006693 hFile = CreateFileW(wn, access_mode, share_mode,
6694 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006695 if (hFile == INVALID_HANDLE_VALUE)
6696 goto getout;
6697 CloseHandle(hFile);
6698 }
6699
6700 retval = 0; /* success */
6701getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00006702 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006703 return retval;
6704}
6705
Bram Moolenaar071d4272004-06-13 20:20:40 +00006706/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006707 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006708 */
6709 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006710mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006711{
6712 WCHAR *wn;
6713 int f;
6714
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006715 wn = enc_to_utf16((char_u *)name, NULL);
6716 if (wn == NULL)
6717 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006718
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006719 f = _wopen(wn, flags, mode);
6720 vim_free(wn);
6721 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006722}
6723
6724/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006725 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006726 */
6727 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006728mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006729{
6730 WCHAR *wn, *wm;
6731 FILE *f = NULL;
6732
Bram Moolenaara12a1612019-01-24 16:39:02 +01006733#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006734 /* Work around an annoying assertion in the Microsoft debug CRT
6735 * when mode's text/binary setting doesn't match _get_fmode(). */
6736 char newMode = mode[strlen(mode) - 1];
6737 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006738
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006739 _get_fmode(&oldMode);
6740 if (newMode == 't')
6741 _set_fmode(_O_TEXT);
6742 else if (newMode == 'b')
6743 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01006744#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006745 wn = enc_to_utf16((char_u *)name, NULL);
6746 wm = enc_to_utf16((char_u *)mode, NULL);
6747 if (wn != NULL && wm != NULL)
6748 f = _wfopen(wn, wm);
6749 vim_free(wn);
6750 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006751
Bram Moolenaara12a1612019-01-24 16:39:02 +01006752#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006753 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01006754#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006755 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006756}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006757
Bram Moolenaar071d4272004-06-13 20:20:40 +00006758/*
6759 * SUB STREAM (aka info stream) handling:
6760 *
6761 * NTFS can have sub streams for each file. Normal contents of file is
6762 * stored in the main stream, and extra contents (author information and
6763 * title and so on) can be stored in sub stream. After Windows 2000, user
6764 * can access and store those informations in sub streams via explorer's
6765 * property menuitem in right click menu. Those informations in sub streams
6766 * were lost when copying only the main stream. So we have to copy sub
6767 * streams.
6768 *
6769 * Incomplete explanation:
6770 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6771 * More useful info and an example:
6772 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6773 */
6774
6775/*
6776 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6777 * and write to stream "substream" of file "to".
6778 * Errors are ignored.
6779 */
6780 static void
6781copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6782{
6783 HANDLE hTo;
6784 WCHAR *to_name;
6785
6786 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6787 wcscpy(to_name, to);
6788 wcscat(to_name, substream);
6789
6790 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6791 FILE_ATTRIBUTE_NORMAL, NULL);
6792 if (hTo != INVALID_HANDLE_VALUE)
6793 {
6794 long done;
6795 DWORD todo;
6796 DWORD readcnt, written;
6797 char buf[4096];
6798
6799 /* Copy block of bytes at a time. Abort when something goes wrong. */
6800 for (done = 0; done < len; done += written)
6801 {
6802 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006803 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6804 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006805 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6806 FALSE, FALSE, context)
6807 || readcnt != todo
6808 || !WriteFile(hTo, buf, todo, &written, NULL)
6809 || written != todo)
6810 break;
6811 }
6812 CloseHandle(hTo);
6813 }
6814
6815 free(to_name);
6816}
6817
6818/*
6819 * Copy info streams from file "from" to file "to".
6820 */
6821 static void
6822copy_infostreams(char_u *from, char_u *to)
6823{
6824 WCHAR *fromw;
6825 WCHAR *tow;
6826 HANDLE sh;
6827 WIN32_STREAM_ID sid;
6828 int headersize;
6829 WCHAR streamname[_MAX_PATH];
6830 DWORD readcount;
6831 void *context = NULL;
6832 DWORD lo, hi;
6833 int len;
6834
6835 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006836 fromw = enc_to_utf16(from, NULL);
6837 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006838 if (fromw != NULL && tow != NULL)
6839 {
6840 /* Open the file for reading. */
6841 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6842 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6843 if (sh != INVALID_HANDLE_VALUE)
6844 {
6845 /* Use BackupRead() to find the info streams. Repeat until we
6846 * have done them all.*/
6847 for (;;)
6848 {
6849 /* Get the header to find the length of the stream name. If
6850 * the "readcount" is zero we have done all info streams. */
6851 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006852 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006853 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6854 &readcount, FALSE, FALSE, &context)
6855 || readcount == 0)
6856 break;
6857
6858 /* We only deal with streams that have a name. The normal
6859 * file data appears to be without a name, even though docs
6860 * suggest it is called "::$DATA". */
6861 if (sid.dwStreamNameSize > 0)
6862 {
6863 /* Read the stream name. */
6864 if (!BackupRead(sh, (LPBYTE)streamname,
6865 sid.dwStreamNameSize,
6866 &readcount, FALSE, FALSE, &context))
6867 break;
6868
6869 /* Copy an info stream with a name ":anything:$DATA".
6870 * Skip "::$DATA", it has no stream name (examples suggest
6871 * it might be used for the normal file contents).
6872 * Note that BackupRead() counts bytes, but the name is in
6873 * wide characters. */
6874 len = readcount / sizeof(WCHAR);
6875 streamname[len] = 0;
6876 if (len > 7 && wcsicmp(streamname + len - 6,
6877 L":$DATA") == 0)
6878 {
6879 streamname[len - 6] = 0;
6880 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006881 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006882 }
6883 }
6884
6885 /* Advance to the next stream. We might try seeking too far,
6886 * but BackupSeek() doesn't skip over stream borders, thus
6887 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006888 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006889 &lo, &hi, &context);
6890 }
6891
6892 /* Clear the context. */
6893 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6894
6895 CloseHandle(sh);
6896 }
6897 }
6898 vim_free(fromw);
6899 vim_free(tow);
6900}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006901
6902/*
6903 * Copy file attributes from file "from" to file "to".
6904 * For Windows NT and later we copy info streams.
6905 * Always returns zero, errors are ignored.
6906 */
6907 int
6908mch_copy_file_attribute(char_u *from, char_u *to)
6909{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006910 /* File streams only work on Windows NT and later. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006911 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006912 return 0;
6913}
6914
6915#if defined(MYRESETSTKOFLW) || defined(PROTO)
6916/*
6917 * Recreate a destroyed stack guard page in win32.
6918 * Written by Benjamin Peterson.
6919 */
6920
6921/* These magic numbers are from the MS header files */
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01006922# define MIN_STACK_WINNT 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00006923
6924/*
6925 * This function does the same thing as _resetstkoflw(), which is only
6926 * available in DevStudio .net and later.
6927 * Returns 0 for failure, 1 for success.
6928 */
6929 int
6930myresetstkoflw(void)
6931{
6932 BYTE *pStackPtr;
6933 BYTE *pGuardPage;
6934 BYTE *pStackBase;
6935 BYTE *pLowestPossiblePage;
6936 MEMORY_BASIC_INFORMATION mbi;
6937 SYSTEM_INFO si;
6938 DWORD nPageSize;
6939 DWORD dummy;
6940
Bram Moolenaar071d4272004-06-13 20:20:40 +00006941 /* We need to know the system page size. */
6942 GetSystemInfo(&si);
6943 nPageSize = si.dwPageSize;
6944
6945 /* ...and the current stack pointer */
6946 pStackPtr = (BYTE*)_alloca(1);
6947
6948 /* ...and the base of the stack. */
6949 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6950 return 0;
6951 pStackBase = (BYTE*)mbi.AllocationBase;
6952
6953 /* ...and the page thats min_stack_req pages away from stack base; this is
6954 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006955 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006956
Bram Moolenaar071d4272004-06-13 20:20:40 +00006957 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006958 /* We want the first committed page in the stack Start at the stack
6959 * base and move forward through memory until we find a committed block.
6960 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006961 BYTE *pBlock = pStackBase;
6962
Bram Moolenaara466c992005-07-09 21:03:22 +00006963 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006964 {
6965 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6966 return 0;
6967
6968 pBlock += mbi.RegionSize;
6969
6970 if (mbi.State & MEM_COMMIT)
6971 break;
6972 }
6973
6974 /* mbi now describes the first committed block in the stack. */
6975 if (mbi.Protect & PAGE_GUARD)
6976 return 1;
6977
6978 /* decide where the guard page should start */
6979 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6980 pGuardPage = pLowestPossiblePage;
6981 else
6982 pGuardPage = (BYTE*)mbi.BaseAddress;
6983
6984 /* allocate the guard page */
6985 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6986 return 0;
6987
6988 /* apply the guard attribute to the page */
6989 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6990 &dummy))
6991 return 0;
6992 }
6993
6994 return 1;
6995}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006996#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006997
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006998
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006999/*
7000 * The command line arguments in UCS2
7001 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007002static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007003static LPWSTR *ArglistW = NULL;
7004static int global_argc = 0;
7005static char **global_argv;
7006
7007static int used_file_argc = 0; /* last argument in global_argv[] used
7008 for the argument list. */
7009static int *used_file_indexes = NULL; /* indexes in global_argv[] for
7010 command line arguments added to
7011 the argument list */
7012static int used_file_count = 0; /* nr of entries in used_file_indexes */
7013static int used_file_literal = FALSE; /* take file names literally */
7014static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007015static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007016static int used_alist_count = 0;
7017
7018
7019/*
7020 * Get the command line arguments. Unicode version.
7021 * Returns argc. Zero when something fails.
7022 */
7023 int
7024get_cmd_argsW(char ***argvp)
7025{
7026 char **argv = NULL;
7027 int argc = 0;
7028 int i;
7029
Bram Moolenaar14993322014-09-09 12:25:33 +02007030 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007031 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7032 if (ArglistW != NULL)
7033 {
7034 argv = malloc((nArgsW + 1) * sizeof(char *));
7035 if (argv != NULL)
7036 {
7037 argc = nArgsW;
7038 argv[argc] = NULL;
7039 for (i = 0; i < argc; ++i)
7040 {
7041 int len;
7042
7043 /* Convert each Unicode argument to the current codepage. */
7044 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007045 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007046 (LPSTR *)&argv[i], &len, 0, 0);
7047 if (argv[i] == NULL)
7048 {
7049 /* Out of memory, clear everything. */
7050 while (i > 0)
7051 free(argv[--i]);
7052 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007053 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007054 argc = 0;
7055 }
7056 }
7057 }
7058 }
7059
7060 global_argc = argc;
7061 global_argv = argv;
7062 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007063 {
7064 if (used_file_indexes != NULL)
7065 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007066 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007067 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007068
7069 if (argvp != NULL)
7070 *argvp = argv;
7071 return argc;
7072}
7073
7074 void
7075free_cmd_argsW(void)
7076{
7077 if (ArglistW != NULL)
7078 {
7079 GlobalFree(ArglistW);
7080 ArglistW = NULL;
7081 }
7082}
7083
7084/*
7085 * Remember "name" is an argument that was added to the argument list.
7086 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7087 * is called.
7088 */
7089 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007090used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007091{
7092 int i;
7093
7094 if (used_file_indexes == NULL)
7095 return;
7096 for (i = used_file_argc + 1; i < global_argc; ++i)
7097 if (STRCMP(global_argv[i], name) == 0)
7098 {
7099 used_file_argc = i;
7100 used_file_indexes[used_file_count++] = i;
7101 break;
7102 }
7103 used_file_literal = literal;
7104 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007105 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007106}
7107
7108/*
7109 * Remember the length of the argument list as it was. If it changes then we
7110 * leave it alone when 'encoding' is set.
7111 */
7112 void
7113set_alist_count(void)
7114{
7115 used_alist_count = GARGCOUNT;
7116}
7117
7118/*
7119 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7120 * has been changed while starting up. Use the UCS-2 command line arguments
7121 * and convert them to 'encoding'.
7122 */
7123 void
7124fix_arg_enc(void)
7125{
7126 int i;
7127 int idx;
7128 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007129 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007130
7131 /* Safety checks:
7132 * - if argument count differs between the wide and non-wide argument
7133 * list, something must be wrong.
7134 * - the file name arguments must have been located.
7135 * - the length of the argument list wasn't changed by the user.
7136 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007137 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007138 || ArglistW == NULL
7139 || used_file_indexes == NULL
7140 || used_file_count == 0
7141 || used_alist_count != GARGCOUNT)
7142 return;
7143
Bram Moolenaar86b68352004-12-27 21:59:20 +00007144 /* Remember the buffer numbers for the arguments. */
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007145 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007146 if (fnum_list == NULL)
7147 return; /* out of memory */
7148 for (i = 0; i < GARGCOUNT; ++i)
7149 fnum_list[i] = GARGLIST[i].ae_fnum;
7150
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007151 /* Clear the argument list. Make room for the new arguments. */
7152 alist_clear(&global_alist);
7153 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007154 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007155
7156 for (i = 0; i < used_file_count; ++i)
7157 {
7158 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007159 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007160 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007161 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007162 int literal = used_file_literal;
7163
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007164# ifdef FEAT_DIFF
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007165 /* When using diff mode may need to concatenate file name to
7166 * directory name. Just like it's done in main(). */
7167 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7168 && !mch_isdir(alist_name(&GARGLIST[0])))
7169 {
7170 char_u *r;
7171
7172 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7173 if (r != NULL)
7174 {
7175 vim_free(str);
7176 str = r;
7177 }
7178 }
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007179# endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007180 /* Re-use the old buffer by renaming it. When not using literal
7181 * names it's done by alist_expand() below. */
7182 if (used_file_literal)
7183 buf_set_name(fnum_list[i], str);
7184
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007185 /* Check backtick literal. backtick literal is already expanded in
7186 * main.c, so this part add str as literal. */
7187 if (literal == FALSE)
7188 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007189 size_t len = STRLEN(str);
7190
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007191 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7192 literal = TRUE;
7193 }
7194 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007195 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007196 }
7197
7198 if (!used_file_literal)
7199 {
7200 /* Now expand wildcards in the arguments. */
7201 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7202 * filename characters but are excluded from 'isfname' to make
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007203 * "gf" work on a file name in parenthesis (e.g.: see vim.h).
7204 * Also, unset wildignore to not be influenced by this option.
7205 * The arguments specified in command-line should be kept even if
7206 * encoding options were changed. */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007207 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007208 do_cmdline_cmd((char_u *)":let SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007209 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007210 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007211 do_cmdline_cmd((char_u *)":let &wig = SaVe_WIG|unlet SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007212 }
7213
7214 /* If wildcard expansion failed, we are editing the first file of the
7215 * arglist and there is no file name: Edit the first argument now. */
7216 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7217 {
7218 do_cmdline_cmd((char_u *)":rewind");
7219 if (GARGCOUNT == 1 && used_file_full_path)
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007220 (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007221 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007222
7223 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007224}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007225
7226 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007227mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007228{
7229 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007230 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007231
Bram Moolenaar964b3742019-05-24 18:54:09 +02007232 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007233 if (envbuf == NULL)
7234 return -1;
7235
7236 sprintf((char *)envbuf, "%s=%s", var, value);
7237
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007238 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007239
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007240 vim_free(envbuf);
7241 if (p == NULL)
7242 return -1;
7243 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007244#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007245 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007246#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007247 // Unlike Un*x systems, we can free the string for _wputenv().
7248 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007249
7250 return 0;
7251}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007252
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007253/*
7254 * Support for 256 colors and 24-bit colors was added in Windows 10
7255 * version 1703 (Creators update).
7256 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007257#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7258
7259/*
7260 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02007261 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007262 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007263#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007264
7265/*
7266 * ConPTY differences between versions, need different logic.
7267 * version 1903 (May 2019 update).
7268 */
7269#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
7270
7271/*
7272 * Confirm until this version. Also the logic changes.
7273 * insider preview.
7274 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02007275#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007276
7277/*
7278 * Not stable now.
7279 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007280#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007281
7282 static void
7283vtp_flag_init(void)
7284{
7285 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007286#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007287 DWORD mode;
7288 HANDLE out;
7289
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007290# ifdef VIMDLL
7291 if (!gui.in_use)
7292# endif
7293 {
7294 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007295
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007296 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7297 GetConsoleMode(out, &mode);
7298 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7299 if (SetConsoleMode(out, mode) == 0)
7300 vtp_working = 0;
7301 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007302#endif
7303
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007304 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007305 conpty_working = 1;
7306 if (ver >= CONPTY_STABLE_BUILD)
7307 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007308
Bram Moolenaar57da6982019-09-13 22:30:11 +02007309 if (ver <= CONPTY_INSIDER_BUILD)
7310 conpty_type = 3;
7311 if (ver <= CONPTY_1903_BUILD)
7312 conpty_type = 2;
7313 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
7314 conpty_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007315}
7316
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007317#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007318
7319 static void
7320vtp_init(void)
7321{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007322 HMODULE hKerneldll;
7323 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007324# ifdef FEAT_TERMGUICOLORS
7325 COLORREF fg, bg;
7326# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007327
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007328 /* Use functions supported from Vista */
7329 hKerneldll = GetModuleHandle("kernel32.dll");
7330 if (hKerneldll != NULL)
7331 {
7332 pGetConsoleScreenBufferInfoEx =
7333 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7334 hKerneldll, "GetConsoleScreenBufferInfoEx");
7335 pSetConsoleScreenBufferInfoEx =
7336 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7337 hKerneldll, "SetConsoleScreenBufferInfoEx");
7338 if (pGetConsoleScreenBufferInfoEx != NULL
7339 && pSetConsoleScreenBufferInfoEx != NULL)
7340 has_csbiex = TRUE;
7341 }
7342
7343 csbi.cbSize = sizeof(csbi);
7344 if (has_csbiex)
7345 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007346 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7347 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
7348
7349# ifdef FEAT_TERMGUICOLORS
7350 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7351 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7352 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7353 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7354 default_console_color_bg = bg;
7355 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007356# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007357
7358 set_console_color_rgb();
7359}
7360
7361 static void
7362vtp_exit(void)
7363{
7364 reset_console_color_rgb();
7365}
7366
7367 static int
7368vtp_printf(
7369 char *format,
7370 ...)
7371{
7372 char_u buf[100];
7373 va_list list;
7374 DWORD result;
7375
7376 va_start(list, format);
7377 vim_vsnprintf((char *)buf, 100, (char *)format, list);
7378 va_end(list);
7379 WriteConsoleA(g_hConOut, buf, (DWORD)STRLEN(buf), &result, NULL);
7380 return (int)result;
7381}
7382
7383 static void
7384vtp_sgr_bulk(
7385 int arg)
7386{
7387 int args[1];
7388
7389 args[0] = arg;
7390 vtp_sgr_bulks(1, args);
7391}
7392
7393 static void
7394vtp_sgr_bulks(
7395 int argc,
7396 int *args
7397)
7398{
7399 /* 2('\033[') + 4('255.') * 16 + NUL */
7400 char_u buf[2 + (4 * 16) + 1];
7401 char_u *p;
7402 int i;
7403
7404 p = buf;
7405 *p++ = '\033';
7406 *p++ = '[';
7407
7408 for (i = 0; i < argc; ++i)
7409 {
7410 p += vim_snprintf((char *)p, 4, "%d", args[i] & 0xff);
7411 *p++ = ';';
7412 }
7413 p--;
7414 *p++ = 'm';
7415 *p = NUL;
7416 vtp_printf((char *)buf);
7417}
7418
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007419# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007420 static int
7421ctermtoxterm(
7422 int cterm)
7423{
Bram Moolenaar9894e392018-05-05 14:29:06 +02007424 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007425
7426 cterm_color2rgb(cterm, &r, &g, &b, &idx);
7427 return (((int)r << 16) | ((int)g << 8) | (int)b);
7428}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007429# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007430
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007431 static void
7432set_console_color_rgb(void)
7433{
7434# ifdef FEAT_TERMGUICOLORS
7435 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7436 int id;
7437 guicolor_T fg = INVALCOLOR;
7438 guicolor_T bg = INVALCOLOR;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007439 int ctermfg;
7440 int ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007441
7442 if (!USE_VTP)
7443 return;
7444
7445 id = syn_name2id((char_u *)"Normal");
Bram Moolenaard5a58862019-03-07 06:40:27 +01007446 if (id > 0 && p_tgc)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007447 syn_id2colors(id, &fg, &bg);
7448 if (fg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007449 {
7450 ctermfg = -1;
7451 if (id > 0)
7452 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007453 fg = ctermfg != -1 ? ctermtoxterm(ctermfg) : default_console_color_fg;
7454 cterm_normal_fg_gui_color = fg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007455 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007456 if (bg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007457 {
7458 ctermbg = -1;
7459 if (id > 0)
7460 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007461 bg = ctermbg != -1 ? ctermtoxterm(ctermbg) : default_console_color_bg;
7462 cterm_normal_bg_gui_color = bg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007463 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007464 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7465 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7466
7467 csbi.cbSize = sizeof(csbi);
7468 if (has_csbiex)
7469 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7470
7471 csbi.cbSize = sizeof(csbi);
7472 csbi.srWindow.Right += 1;
7473 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007474 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
7475 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007476 if (has_csbiex)
7477 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7478# endif
7479}
7480
7481 static void
7482reset_console_color_rgb(void)
7483{
7484# ifdef FEAT_TERMGUICOLORS
7485 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7486
7487 csbi.cbSize = sizeof(csbi);
7488 if (has_csbiex)
7489 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7490
7491 csbi.cbSize = sizeof(csbi);
7492 csbi.srWindow.Right += 1;
7493 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007494 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
7495 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007496 if (has_csbiex)
7497 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7498# endif
7499}
7500
7501 void
7502control_console_color_rgb(void)
7503{
7504 if (USE_VTP)
7505 set_console_color_rgb();
7506 else
7507 reset_console_color_rgb();
7508}
7509
7510 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007511use_vtp(void)
7512{
7513 return USE_VTP;
7514}
7515
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007516 int
7517is_term_win32(void)
7518{
7519 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
7520}
7521
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007522 int
7523has_vtp_working(void)
7524{
7525 return vtp_working;
7526}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007527
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01007528#endif
7529
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007530 int
7531has_conpty_working(void)
7532{
7533 return conpty_working;
7534}
7535
7536 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02007537get_conpty_type(void)
7538{
7539 return conpty_type;
7540}
7541
7542 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007543is_conpty_stable(void)
7544{
7545 return conpty_stable;
7546}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01007547
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007548#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01007549 void
7550resize_console_buf(void)
7551{
7552 CONSOLE_SCREEN_BUFFER_INFO csbi;
7553 COORD coord;
7554 SMALL_RECT newsize;
7555
7556 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
7557 {
7558 coord.X = SRWIDTH(csbi.srWindow);
7559 coord.Y = SRHEIGHT(csbi.srWindow);
7560 SetConsoleScreenBufferSize(g_hConOut, coord);
7561
7562 newsize.Left = 0;
7563 newsize.Top = 0;
7564 newsize.Right = coord.X - 1;
7565 newsize.Bottom = coord.Y - 1;
7566 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
7567
7568 SetConsoleScreenBufferSize(g_hConOut, coord);
7569 }
7570}
7571#endif