blob: 2912b0df75a30c1af352786b1eb5f1528fe6281f [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 Moolenaar071d4272004-06-13 20:20:40 +0000149#if defined(__BORLANDC__)
150/* Strangely Borland uses a non-standard name. */
151# define wcsicmp(a, b) wcscmpi((a), (b))
152#endif
153
Bram Moolenaar4f974752019-02-17 17:44:42 +0100154#ifndef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000155/* Win32 Console handles for input and output */
156static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
157static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
158
159/* Win32 Screen buffer,coordinate,console I/O information */
160static SMALL_RECT g_srScrollRegion;
161static COORD g_coord; /* 0-based, but external coords are 1-based */
162
163/* The attribute of the screen when the editor was started */
164static WORD g_attrDefault = 7; /* lightgray text on black background */
165static WORD g_attrCurrent;
166
167static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
168static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
169static int g_fForceExit = FALSE; /* set when forcefully exiting */
170
Bram Moolenaar071d4272004-06-13 20:20:40 +0000171static void scroll(unsigned cLines);
172static void set_scroll_region(unsigned left, unsigned top,
173 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100174static void set_scroll_region_tb(unsigned top, unsigned bottom);
175static void set_scroll_region_lr(unsigned left, unsigned right);
176static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000177static void delete_lines(unsigned cLines);
178static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000179static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000180static int s_cursor_visible = TRUE;
181static int did_create_conin = FALSE;
182#else
183static int s_dont_use_vimrun = TRUE;
184static int need_vimrun_warning = FALSE;
185static char *vimrun_path = "vimrun ";
186#endif
187
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200188static int win32_getattrs(char_u *name);
189static int win32_setattrs(char_u *name, int attrs);
190static int win32_set_archive(char_u *name);
191
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100192static int conpty_working = 0;
193static int conpty_stable = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100194static void vtp_flag_init();
195
Bram Moolenaar4f974752019-02-17 17:44:42 +0100196#ifndef FEAT_GUI_MSWIN
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100197static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100198static void vtp_init();
199static void vtp_exit();
200static int vtp_printf(char *format, ...);
201static void vtp_sgr_bulk(int arg);
202static void vtp_sgr_bulks(int argc, int *argv);
203
204static guicolor_T save_console_bg_rgb;
205static guicolor_T save_console_fg_rgb;
206
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200207static int g_color_index_bg = 0;
208static int g_color_index_fg = 7;
209
210# ifdef FEAT_TERMGUICOLORS
211static int default_console_color_bg = 0x000000; // black
212static int default_console_color_fg = 0xc0c0c0; // white
213# endif
214
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100215# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200216# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100217# else
218# define USE_VTP 0
219# endif
220
221static void set_console_color_rgb(void);
222static void reset_console_color_rgb(void);
223#endif
224
225/* This flag is newly created from Windows 10 */
226#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
227# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
228#endif
229
Bram Moolenaar4f974752019-02-17 17:44:42 +0100230#ifndef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000231static int suppress_winsize = 1; /* don't fiddle with console */
232#endif
233
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200234static char_u *exe_path = NULL;
235
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100236static BOOL win8_or_later = FALSE;
237
Bram Moolenaar4f974752019-02-17 17:44:42 +0100238#ifndef FEAT_GUI_MSWIN
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100239/* Dynamic loading for portability */
240typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
241{
242 ULONG cbSize;
243 COORD dwSize;
244 COORD dwCursorPosition;
245 WORD wAttributes;
246 SMALL_RECT srWindow;
247 COORD dwMaximumWindowSize;
248 WORD wPopupAttributes;
249 BOOL bFullscreenSupported;
250 COLORREF ColorTable[16];
251} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
252typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
253static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
254typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
255static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
256static BOOL has_csbiex = FALSE;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100257#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100258
259/*
260 * Get version number including build number
261 */
262typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
263# define MAKE_VER(major, minor, build) \
264 (((major) << 24) | ((minor) << 16) | (build))
265
266 static DWORD
267get_build_number(void)
268{
269 OSVERSIONINFOW osver = {sizeof(OSVERSIONINFOW)};
270 HMODULE hNtdll;
271 PfnRtlGetVersion pRtlGetVersion;
272 DWORD ver = MAKE_VER(0, 0, 0);
273
274 hNtdll = GetModuleHandle("ntdll.dll");
275 if (hNtdll != NULL)
276 {
277 pRtlGetVersion =
278 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
279 pRtlGetVersion(&osver);
280 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
281 min(osver.dwMinorVersion, 255),
282 min(osver.dwBuildNumber, 32767));
283 }
284 return ver;
285}
286
Bram Moolenaar4f974752019-02-17 17:44:42 +0100287#ifndef FEAT_GUI_MSWIN
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100288/*
289 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100290 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100291 */
292 static BOOL
293read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100294 HANDLE hInput,
295 INPUT_RECORD *lpBuffer,
296 DWORD nLength,
297 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100298{
299 enum
300 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100301 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100302 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100303 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100304 static DWORD s_dwIndex = 0;
305 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100306 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100307 int head;
308 int tail;
309 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100310
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200311 if (nLength == -2)
312 return (s_dwMax > 0) ? TRUE : FALSE;
313
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100314 if (!win8_or_later)
315 {
316 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200317 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
318 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100319 }
320
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100321 if (s_dwMax == 0)
322 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100323 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200324 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
325 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100326 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100327 s_dwIndex = 0;
328 s_dwMax = dwEvents;
329 if (dwEvents == 0)
330 {
331 *lpEvents = 0;
332 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100333 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100334
335 if (s_dwMax > 1)
336 {
337 head = 0;
338 tail = s_dwMax - 1;
339 while (head != tail)
340 {
341 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
342 && s_irCache[head + 1].EventType
343 == WINDOW_BUFFER_SIZE_EVENT)
344 {
345 /* Remove duplicate event to avoid flicker. */
346 for (i = head; i < tail; ++i)
347 s_irCache[i] = s_irCache[i + 1];
348 --tail;
349 continue;
350 }
351 head++;
352 }
353 s_dwMax = tail + 1;
354 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100355 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100356
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100357 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200358 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100359 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100360 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100361 return TRUE;
362}
363
364/*
365 * Version of PeekConsoleInput() that works with IME.
366 */
367 static BOOL
368peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100369 HANDLE hInput,
370 INPUT_RECORD *lpBuffer,
371 DWORD nLength,
372 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100373{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100374 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100375}
376
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100377# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200378 static DWORD
379msg_wait_for_multiple_objects(
380 DWORD nCount,
381 LPHANDLE pHandles,
382 BOOL fWaitAll,
383 DWORD dwMilliseconds,
384 DWORD dwWakeMask)
385{
386 if (read_console_input(NULL, NULL, -2, NULL))
387 return WAIT_OBJECT_0;
388 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
389 dwMilliseconds, dwWakeMask);
390}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100391# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200392
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100393# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200394 static DWORD
395wait_for_single_object(
396 HANDLE hHandle,
397 DWORD dwMilliseconds)
398{
399 if (read_console_input(NULL, NULL, -2, NULL))
400 return WAIT_OBJECT_0;
401 return WaitForSingleObject(hHandle, dwMilliseconds);
402}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100403# endif
404#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200405
Bram Moolenaar071d4272004-06-13 20:20:40 +0000406 static void
407get_exe_name(void)
408{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100409 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
410 * as the maximum length that works (plus a NUL byte). */
411#define MAX_ENV_PATH_LEN 8192
412 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200413 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000414
415 if (exe_name == NULL)
416 {
417 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100418 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000419 if (*temp != NUL)
420 exe_name = FullName_save((char_u *)temp, FALSE);
421 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000422
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200423 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000424 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200425 exe_path = vim_strnsave(exe_name,
426 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200427 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000428 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200429 /* Append our starting directory to $PATH, so that when doing
430 * "!xxd" it's found in our starting directory. Needed because
431 * SearchPath() also looks there. */
432 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100433 if (p == NULL
434 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200435 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100436 if (p == NULL || *p == NUL)
437 temp[0] = NUL;
438 else
439 {
440 STRCPY(temp, p);
441 STRCAT(temp, ";");
442 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200443 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100444 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200445 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000446 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000447 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000448}
449
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200450/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100451 * Unescape characters in "p" that appear in "escaped".
452 */
453 static void
454unescape_shellxquote(char_u *p, char_u *escaped)
455{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100456 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100457 int n;
458
459 while (*p != NUL)
460 {
461 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
462 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100463 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100464 p += n;
465 l -= n;
466 }
467}
468
469/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200470 * Load library "name".
471 */
472 HINSTANCE
473vimLoadLib(char *name)
474{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200475 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200476
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200477 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
478 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200479 if (exe_path == NULL)
480 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200481 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200482 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200483 WCHAR old_dirw[MAXPATHL];
484
485 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
486 {
487 /* Change directory to where the executable is, both to make
488 * sure we find a .dll there and to avoid looking for a .dll
489 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100490 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200491 dll = LoadLibrary(name);
492 SetCurrentDirectoryW(old_dirw);
493 return dll;
494 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200495 }
496 return dll;
497}
498
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100499#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
500/*
501 * Get related information about 'funcname' which is imported by 'hInst'.
502 * If 'info' is 0, return the function address.
503 * If 'info' is 1, return the module name which the function is imported from.
504 */
505 static void *
506get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
507{
508 PBYTE pImage = (PBYTE)hInst;
509 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
510 PIMAGE_NT_HEADERS pPE;
511 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
512 PIMAGE_THUNK_DATA pIAT; /* Import Address Table */
513 PIMAGE_THUNK_DATA pINT; /* Import Name Table */
514 PIMAGE_IMPORT_BY_NAME pImpName;
515
516 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
517 return NULL;
518 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
519 if (pPE->Signature != IMAGE_NT_SIGNATURE)
520 return NULL;
521 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
522 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
523 .VirtualAddress);
524 for (; pImpDesc->FirstThunk; ++pImpDesc)
525 {
526 if (!pImpDesc->OriginalFirstThunk)
527 continue;
528 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
529 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
530 for (; pIAT->u1.Function; ++pIAT, ++pINT)
531 {
532 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
533 continue;
534 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
535 + (UINT_PTR)(pINT->u1.AddressOfData));
536 if (strcmp((char *)pImpName->Name, funcname) == 0)
537 {
538 switch (info)
539 {
540 case 0:
541 return (void *)pIAT->u1.Function;
542 case 1:
543 return (void *)(pImage + pImpDesc->Name);
544 default:
545 return NULL;
546 }
547 }
548 }
549 }
550 return NULL;
551}
552
553/*
554 * Get the module handle which 'funcname' in 'hInst' is imported from.
555 */
556 HINSTANCE
557find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
558{
559 char *modulename;
560
561 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
562 if (modulename != NULL)
563 return GetModuleHandleA(modulename);
564 return NULL;
565}
566
567/*
568 * Get the address of 'funcname' which is imported by 'hInst' DLL.
569 */
570 void *
571get_dll_import_func(HINSTANCE hInst, const char *funcname)
572{
573 return get_imported_func_info(hInst, funcname, 0);
574}
575#endif
576
Bram Moolenaar071d4272004-06-13 20:20:40 +0000577#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
578# ifndef GETTEXT_DLL
579# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200580# define GETTEXT_DLL_ALT1 "libintl-8.dll"
581# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000582# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200583/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000584static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200585static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000586static char *null_libintl_textdomain(const char *);
587static char *null_libintl_bindtextdomain(const char *, const char *);
588static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100589static int null_libintl_putenv(const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100590static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000591
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200592static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000593char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200594char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
595 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000596char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
597char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000598 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000599char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
600 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100601int (*dyn_libintl_putenv)(const char *) = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100602int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000603
604 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100605dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000606{
607 int i;
608 static struct
609 {
610 char *name;
611 FARPROC *ptr;
612 } libintl_entry[] =
613 {
614 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200615 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000616 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
617 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
618 {NULL, NULL}
619 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100620 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000621
Bram Moolenaar7554c542018-10-06 15:03:15 +0200622 // No need to initialize twice.
623 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000624 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200625 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100626 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar7554c542018-10-06 15:03:15 +0200627#ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100628 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200629 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
630#endif
631#ifdef GETTEXT_DLL_ALT2
632 if (!hLibintlDLL)
633 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100634#endif
635 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000636 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200637 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000638 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200639 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100640 semsg(_(e_loadlib), GETTEXT_DLL);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200641 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000642 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200643 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000644 }
645 for (i = 0; libintl_entry[i].name != NULL
646 && libintl_entry[i].ptr != NULL; ++i)
647 {
648 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
649 libintl_entry[i].name)) == NULL)
650 {
651 dyn_libintl_end();
652 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000653 {
654 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100655 semsg(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000656 verbose_leave();
657 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000658 return 0;
659 }
660 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000661
662 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000663 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000664 "bind_textdomain_codeset");
665 if (dyn_libintl_bind_textdomain_codeset == NULL)
666 dyn_libintl_bind_textdomain_codeset =
667 null_libintl_bind_textdomain_codeset;
668
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100669 /* _putenv() function for the libintl.dll is optional. */
670 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
671 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100672 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100673 dyn_libintl_putenv = (void *)GetProcAddress(hmsvcrt, "_putenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100674 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
675 }
676 if (dyn_libintl_putenv == NULL || dyn_libintl_putenv == _putenv)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100677 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100678 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
679 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100680
Bram Moolenaar071d4272004-06-13 20:20:40 +0000681 return 1;
682}
683
684 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100685dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000686{
687 if (hLibintlDLL)
688 FreeLibrary(hLibintlDLL);
689 hLibintlDLL = NULL;
690 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200691 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000692 dyn_libintl_textdomain = null_libintl_textdomain;
693 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000694 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100695 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100696 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000697}
698
699 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000700null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000701{
702 return (char*)msgid;
703}
704
705 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200706null_libintl_ngettext(
707 const char *msgid,
708 const char *msgid_plural,
709 unsigned long n)
710{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200711 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200712}
713
Bram Moolenaaree695f72016-08-03 22:08:45 +0200714 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100715null_libintl_bindtextdomain(
716 const char *domainname UNUSED,
717 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000718{
719 return NULL;
720}
721
722 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100723null_libintl_bind_textdomain_codeset(
724 const char *domainname UNUSED,
725 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000726{
727 return NULL;
728}
729
730 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100731null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000732{
733 return NULL;
734}
735
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200736 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100737null_libintl_putenv(const char *envstring UNUSED)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100738{
739 return 0;
740}
741
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200742 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100743null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100744{
745 return 0;
746}
747
Bram Moolenaar071d4272004-06-13 20:20:40 +0000748#endif /* DYNAMIC_GETTEXT */
749
750/* This symbol is not defined in older versions of the SDK or Visual C++ */
751
752#ifndef VER_PLATFORM_WIN32_WINDOWS
753# define VER_PLATFORM_WIN32_WINDOWS 1
754#endif
755
756DWORD g_PlatformId;
757
758#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100759# ifndef PROTO
760# include <aclapi.h>
761# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200762# ifndef PROTECTED_DACL_SECURITY_INFORMATION
763# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
764# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000765#endif
766
Bram Moolenaar27515922013-06-29 15:36:26 +0200767#ifdef HAVE_ACL
768/*
769 * Enables or disables the specified privilege.
770 */
771 static BOOL
772win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
773{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100774 BOOL bResult;
775 LUID luid;
776 HANDLE hToken;
777 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200778
779 if (!OpenProcessToken(GetCurrentProcess(),
780 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
781 return FALSE;
782
783 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
784 {
785 CloseHandle(hToken);
786 return FALSE;
787 }
788
Bram Moolenaar45500912014-07-09 20:51:07 +0200789 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200790 tokenPrivileges.Privileges[0].Luid = luid;
791 tokenPrivileges.Privileges[0].Attributes = bEnable ?
792 SE_PRIVILEGE_ENABLED : 0;
793
794 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
795 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
796
797 CloseHandle(hToken);
798
799 return bResult && GetLastError() == ERROR_SUCCESS;
800}
801#endif
802
Bram Moolenaar071d4272004-06-13 20:20:40 +0000803/*
804 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
805 * VER_PLATFORM_WIN32_WINDOWS (Win95).
806 */
807 void
808PlatformId(void)
809{
810 static int done = FALSE;
811
812 if (!done)
813 {
814 OSVERSIONINFO ovi;
815
816 ovi.dwOSVersionInfoSize = sizeof(ovi);
817 GetVersionEx(&ovi);
818
819 g_PlatformId = ovi.dwPlatformId;
820
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100821 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
822 || ovi.dwMajorVersion > 6)
823 win8_or_later = TRUE;
824
Bram Moolenaar071d4272004-06-13 20:20:40 +0000825#ifdef HAVE_ACL
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200826 /* Enable privilege for getting or setting SACLs. */
827 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000828#endif
829 done = TRUE;
830 }
831}
832
Bram Moolenaar4f974752019-02-17 17:44:42 +0100833#ifndef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000834
835#define SHIFT (SHIFT_PRESSED)
836#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
837#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
838#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
839
840
841/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
842 * We map function keys to their ANSI terminal equivalents, as produced
843 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
844 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
845 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
846 * combinations of function/arrow/etc keys.
847 */
848
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000849static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000850{
851 WORD wVirtKey;
852 BOOL fAnsiKey;
853 int chAlone;
854 int chShift;
855 int chCtrl;
856 int chAlt;
857} VirtKeyMap[] =
858{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200859// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000860 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
861
862 { VK_F1, TRUE, ';', 'T', '^', 'h', },
863 { VK_F2, TRUE, '<', 'U', '_', 'i', },
864 { VK_F3, TRUE, '=', 'V', '`', 'j', },
865 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
866 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
867 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
868 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
869 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
870 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
871 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200872 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
873 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000874
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200875 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
876 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
877 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
878 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
879 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
880 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
881 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
882 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
883 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
884 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000885
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200886 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000887
888#if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200889 // Most people don't have F13-F20, but what the hell...
890 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
891 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
892 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
893 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
894 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
895 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
896 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
897 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000898#endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200899 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
900 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
901 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
902 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000903
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200904 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
905 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
906 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
907 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
908 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
909 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
910 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
911 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
912 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
913 // Sorry, out of number space! <negri>
914 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
915
Bram Moolenaar071d4272004-06-13 20:20:40 +0000916};
917
918
919#ifdef _MSC_VER
920// The ToAscii bug destroys several registers. Need to turn off optimization
921// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000922# pragma warning(push)
923# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000924# pragma optimize("", off)
925#endif
926
927#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200928# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000929#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200930# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000931#endif
932
933/* The return code indicates key code size. */
934 static int
935#ifdef __BORLANDC__
936 __stdcall
937#endif
938win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000939 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000940{
941 UINT uMods = pker->dwControlKeyState;
942 static int s_iIsDead = 0;
943 static WORD awAnsiCode[2];
944 static BYTE abKeystate[256];
945
946
947 if (s_iIsDead == 2)
948 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200949 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000950 s_iIsDead = 0;
951 return 1;
952 }
953
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200954 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000955 return 1;
956
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200957 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000958
Bram Moolenaar071d4272004-06-13 20:20:40 +0000959 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200960 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000961
962 if (uMods & SHIFT_PRESSED)
963 abKeystate[VK_SHIFT] = 0x80;
964 if (uMods & CAPSLOCK_ON)
965 abKeystate[VK_CAPITAL] = 1;
966
967 if ((uMods & ALT_GR) == ALT_GR)
968 {
969 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
970 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
971 }
972
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200973 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
974 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000975
976 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200977 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000978
979 return s_iIsDead;
980}
981
982#ifdef _MSC_VER
983/* MUST switch optimization on again here, otherwise a call to
984 * decode_key_event() may crash (e.g. when hitting caps-lock) */
985# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000986# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000987
988# if (_MSC_VER < 1100)
989/* MUST turn off global optimisation for this next function, or
990 * pressing ctrl-minus in insert mode crashes Vim when built with
991 * VC4.1. -- negri. */
992# pragma optimize("g", off)
993# endif
994#endif
995
996static BOOL g_fJustGotFocus = FALSE;
997
998/*
999 * Decode a KEY_EVENT into one or two keystrokes
1000 */
1001 static BOOL
1002decode_key_event(
1003 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001004 WCHAR *pch,
1005 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001006 int *pmodifiers,
1007 BOOL fDoPost)
1008{
1009 int i;
1010 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1011
1012 *pch = *pch2 = NUL;
1013 g_fJustGotFocus = FALSE;
1014
1015 /* ignore key up events */
1016 if (!pker->bKeyDown)
1017 return FALSE;
1018
1019 /* ignore some keystrokes */
1020 switch (pker->wVirtualKeyCode)
1021 {
1022 /* modifiers */
1023 case VK_SHIFT:
1024 case VK_CONTROL:
1025 case VK_MENU: /* Alt key */
1026 return FALSE;
1027
1028 default:
1029 break;
1030 }
1031
1032 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001033 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001034 {
1035 /* Ctrl-6 is Ctrl-^ */
1036 if (pker->wVirtualKeyCode == '6')
1037 {
1038 *pch = Ctrl_HAT;
1039 return TRUE;
1040 }
1041 /* Ctrl-2 is Ctrl-@ */
1042 else if (pker->wVirtualKeyCode == '2')
1043 {
1044 *pch = NUL;
1045 return TRUE;
1046 }
1047 /* Ctrl-- is Ctrl-_ */
1048 else if (pker->wVirtualKeyCode == 0xBD)
1049 {
1050 *pch = Ctrl__;
1051 return TRUE;
1052 }
1053 }
1054
1055 /* Shift-TAB */
1056 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1057 {
1058 *pch = K_NUL;
1059 *pch2 = '\017';
1060 return TRUE;
1061 }
1062
1063 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1064 {
1065 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1066 {
1067 if (nModifs == 0)
1068 *pch = VirtKeyMap[i].chAlone;
1069 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1070 *pch = VirtKeyMap[i].chShift;
1071 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1072 *pch = VirtKeyMap[i].chCtrl;
1073 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1074 *pch = VirtKeyMap[i].chAlt;
1075
1076 if (*pch != 0)
1077 {
1078 if (VirtKeyMap[i].fAnsiKey)
1079 {
1080 *pch2 = *pch;
1081 *pch = K_NUL;
1082 }
1083
1084 return TRUE;
1085 }
1086 }
1087 }
1088
1089 i = win32_kbd_patch_key(pker);
1090
1091 if (i < 0)
1092 *pch = NUL;
1093 else
1094 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001095 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001096
1097 if (pmodifiers != NULL)
1098 {
1099 /* Pass on the ALT key as a modifier, but only when not combined
1100 * with CTRL (which is ALTGR). */
1101 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1102 *pmodifiers |= MOD_MASK_ALT;
1103
1104 /* Pass on SHIFT only for special keys, because we don't know when
1105 * it's already included with the character. */
1106 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1107 *pmodifiers |= MOD_MASK_SHIFT;
1108
1109 /* Pass on CTRL only for non-special keys, because we don't know
1110 * when it's already included with the character. And not when
1111 * combined with ALT (which is ALTGR). */
1112 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1113 && *pch >= 0x20 && *pch < 0x80)
1114 *pmodifiers |= MOD_MASK_CTRL;
1115 }
1116 }
1117
1118 return (*pch != NUL);
1119}
1120
1121#ifdef _MSC_VER
1122# pragma optimize("", on)
1123#endif
1124
Bram Moolenaar4f974752019-02-17 17:44:42 +01001125#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001126
1127
1128#ifdef FEAT_MOUSE
1129
1130/*
1131 * For the GUI the mouse handling is in gui_w32.c.
1132 */
Bram Moolenaar4f974752019-02-17 17:44:42 +01001133# ifdef FEAT_GUI_MSWIN
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}
1138# else
1139static 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
1153 if (!g_fMouseAvail)
1154 return;
1155
1156 g_fMouseActive = on;
1157 GetConsoleMode(g_hConIn, &cmodein);
1158
1159 if (g_fMouseActive)
1160 cmodein |= ENABLE_MOUSE_INPUT;
1161 else
1162 cmodein &= ~ENABLE_MOUSE_INPUT;
1163
1164 SetConsoleMode(g_hConIn, cmodein);
1165}
1166
Bram Moolenaar157d8132018-03-06 17:09:20 +01001167
1168#if defined(FEAT_BEVAL_TERM) || defined(PROTO)
1169/*
1170 * Called when 'balloonevalterm' changed.
1171 */
1172 void
1173mch_bevalterm_changed(void)
1174{
1175 mch_setmouse(g_fMouseActive);
1176}
1177#endif
1178
Bram Moolenaar071d4272004-06-13 20:20:40 +00001179/*
1180 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1181 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1182 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1183 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1184 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1185 * and we return the mouse position in g_xMouse and g_yMouse.
1186 *
1187 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1188 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1189 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1190 *
1191 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1192 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1193 *
1194 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1195 * moves, even if it stays within the same character cell. We ignore
1196 * all MOUSE_MOVED messages if the position hasn't really changed, and
1197 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1198 * we're only interested in MOUSE_DRAG).
1199 *
1200 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1201 * 2-button mouses by pressing the left & right buttons simultaneously.
1202 * In practice, it's almost impossible to click both at the same time,
1203 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1204 * in such cases, if the user is clicking quickly.
1205 */
1206 static BOOL
1207decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001208 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001209{
1210 static int s_nOldButton = -1;
1211 static int s_nOldMouseClick = -1;
1212 static int s_xOldMouse = -1;
1213 static int s_yOldMouse = -1;
1214 static linenr_T s_old_topline = 0;
1215#ifdef FEAT_DIFF
1216 static int s_old_topfill = 0;
1217#endif
1218 static int s_cClicks = 1;
1219 static BOOL s_fReleased = TRUE;
1220 static DWORD s_dwLastClickTime = 0;
1221 static BOOL s_fNextIsMiddle = FALSE;
1222
1223 static DWORD cButtons = 0; /* number of buttons supported */
1224
1225 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1226 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1227 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1228 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1229
1230 int nButton;
1231
1232 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1233 cButtons = 2;
1234
1235 if (!g_fMouseAvail || !g_fMouseActive)
1236 {
1237 g_nMouseClick = -1;
1238 return FALSE;
1239 }
1240
1241 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1242 if (g_fJustGotFocus)
1243 {
1244 g_fJustGotFocus = FALSE;
1245 return FALSE;
1246 }
1247
1248 /* unprocessed mouse click? */
1249 if (g_nMouseClick != -1)
1250 return TRUE;
1251
1252 nButton = -1;
1253 g_xMouse = pmer->dwMousePosition.X;
1254 g_yMouse = pmer->dwMousePosition.Y;
1255
1256 if (pmer->dwEventFlags == MOUSE_MOVED)
1257 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001258 /* Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
Bram Moolenaar071d4272004-06-13 20:20:40 +00001259 * events even when the mouse moves only within a char cell.) */
1260 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1261 return FALSE;
1262 }
1263
1264 /* If no buttons are pressed... */
1265 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1266 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001267 nButton = MOUSE_RELEASE;
1268
Bram Moolenaar071d4272004-06-13 20:20:40 +00001269 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1270 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001271 {
1272#ifdef FEAT_BEVAL_TERM
1273 /* do return mouse move events when we want them */
1274 if (p_bevalterm)
1275 nButton = MOUSE_DRAG;
1276 else
1277#endif
1278 return FALSE;
1279 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001280
Bram Moolenaar071d4272004-06-13 20:20:40 +00001281 s_fReleased = TRUE;
1282 }
1283 else /* one or more buttons pressed */
1284 {
1285 /* on a 2-button mouse, hold down left and right buttons
1286 * simultaneously to get MIDDLE. */
1287
1288 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1289 {
1290 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1291
1292 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001293 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001294 if (dwLR == LEFT || dwLR == RIGHT)
1295 {
1296 for (;;)
1297 {
1298 /* wait a short time for next input event */
1299 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1300 != WAIT_OBJECT_0)
1301 break;
1302 else
1303 {
1304 DWORD cRecords = 0;
1305 INPUT_RECORD ir;
1306 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1307
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001308 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001309
1310 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1311 || !(pmer2->dwButtonState & LEFT_RIGHT))
1312 break;
1313 else
1314 {
1315 if (pmer2->dwEventFlags != MOUSE_MOVED)
1316 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001317 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001318
1319 return decode_mouse_event(pmer2);
1320 }
1321 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1322 s_yOldMouse == pmer2->dwMousePosition.Y)
1323 {
1324 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001325 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001326
1327 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001328 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001329
1330 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1331 break;
1332 }
1333 else
1334 break;
1335 }
1336 }
1337 }
1338 }
1339 }
1340
1341 if (s_fNextIsMiddle)
1342 {
1343 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1344 ? MOUSE_DRAG : MOUSE_MIDDLE;
1345 s_fNextIsMiddle = FALSE;
1346 }
1347 else if (cButtons == 2 &&
1348 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1349 {
1350 nButton = MOUSE_MIDDLE;
1351
1352 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1353 {
1354 s_fNextIsMiddle = TRUE;
1355 nButton = MOUSE_RELEASE;
1356 }
1357 }
1358 else if ((pmer->dwButtonState & LEFT) == LEFT)
1359 nButton = MOUSE_LEFT;
1360 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1361 nButton = MOUSE_MIDDLE;
1362 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1363 nButton = MOUSE_RIGHT;
1364
1365 if (! s_fReleased && ! s_fNextIsMiddle
1366 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1367 return FALSE;
1368
1369 s_fReleased = s_fNextIsMiddle;
1370 }
1371
1372 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1373 {
1374 /* button pressed or released, without mouse moving */
1375 if (nButton != -1 && nButton != MOUSE_RELEASE)
1376 {
1377 DWORD dwCurrentTime = GetTickCount();
1378
1379 if (s_xOldMouse != g_xMouse
1380 || s_yOldMouse != g_yMouse
1381 || s_nOldButton != nButton
1382 || s_old_topline != curwin->w_topline
1383#ifdef FEAT_DIFF
1384 || s_old_topfill != curwin->w_topfill
1385#endif
1386 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1387 {
1388 s_cClicks = 1;
1389 }
1390 else if (++s_cClicks > 4)
1391 {
1392 s_cClicks = 1;
1393 }
1394
1395 s_dwLastClickTime = dwCurrentTime;
1396 }
1397 }
1398 else if (pmer->dwEventFlags == MOUSE_MOVED)
1399 {
1400 if (nButton != -1 && nButton != MOUSE_RELEASE)
1401 nButton = MOUSE_DRAG;
1402
1403 s_cClicks = 1;
1404 }
1405
1406 if (nButton == -1)
1407 return FALSE;
1408
1409 if (nButton != MOUSE_RELEASE)
1410 s_nOldButton = nButton;
1411
1412 g_nMouseClick = nButton;
1413
1414 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1415 g_nMouseClick |= MOUSE_SHIFT;
1416 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1417 g_nMouseClick |= MOUSE_CTRL;
1418 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1419 g_nMouseClick |= MOUSE_ALT;
1420
1421 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1422 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1423
1424 /* only pass on interesting (i.e., different) mouse events */
1425 if (s_xOldMouse == g_xMouse
1426 && s_yOldMouse == g_yMouse
1427 && s_nOldMouseClick == g_nMouseClick)
1428 {
1429 g_nMouseClick = -1;
1430 return FALSE;
1431 }
1432
1433 s_xOldMouse = g_xMouse;
1434 s_yOldMouse = g_yMouse;
1435 s_old_topline = curwin->w_topline;
1436#ifdef FEAT_DIFF
1437 s_old_topfill = curwin->w_topfill;
1438#endif
1439 s_nOldMouseClick = g_nMouseClick;
1440
1441 return TRUE;
1442}
1443
Bram Moolenaar4f974752019-02-17 17:44:42 +01001444# endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001445#endif /* FEAT_MOUSE */
1446
1447
1448#ifdef MCH_CURSOR_SHAPE
1449/*
1450 * Set the shape of the cursor.
1451 * 'thickness' can be from 1 (thin) to 99 (block)
1452 */
1453 static void
1454mch_set_cursor_shape(int thickness)
1455{
1456 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1457 ConsoleCursorInfo.dwSize = thickness;
1458 ConsoleCursorInfo.bVisible = s_cursor_visible;
1459
1460 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1461 if (s_cursor_visible)
1462 SetConsoleCursorPosition(g_hConOut, g_coord);
1463}
1464
1465 void
1466mch_update_cursor(void)
1467{
1468 int idx;
1469 int thickness;
1470
1471 /*
1472 * How the cursor is drawn depends on the current mode.
1473 */
1474 idx = get_shape_idx(FALSE);
1475
1476 if (shape_table[idx].shape == SHAPE_BLOCK)
1477 thickness = 99; /* 100 doesn't work on W95 */
1478 else
1479 thickness = shape_table[idx].percentage;
1480 mch_set_cursor_shape(thickness);
1481}
1482#endif
1483
Bram Moolenaar4f974752019-02-17 17:44:42 +01001484#ifndef FEAT_GUI_MSWIN /* this isn't used for the GUI */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001485/*
1486 * Handle FOCUS_EVENT.
1487 */
1488 static void
1489handle_focus_event(INPUT_RECORD ir)
1490{
1491 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1492 ui_focus_change((int)g_fJustGotFocus);
1493}
1494
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001495static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1496
Bram Moolenaar071d4272004-06-13 20:20:40 +00001497/*
1498 * Wait until console input from keyboard or mouse is available,
1499 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001500 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001501 * Return TRUE if something is available FALSE if not.
1502 */
1503 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001504WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001505{
1506 DWORD dwNow = 0, dwEndTime = 0;
1507 INPUT_RECORD ir;
1508 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001509 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001510#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001511 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001512#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001513
1514 if (msec > 0)
1515 /* Wait until the specified time has elapsed. */
1516 dwEndTime = GetTickCount() + msec;
1517 else if (msec < 0)
1518 /* Wait forever. */
1519 dwEndTime = INFINITE;
1520
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001521 // We need to loop until the end of the time period, because
1522 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001523 for (;;)
1524 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001525 // Only process messages when waiting.
1526 if (msec != 0)
1527 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001528#ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001529 parse_queued_messages();
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001530#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001531#ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001532 mzvim_check_threads();
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001533#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001534#ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001535 serverProcessPendingMessages();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001536#endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001537 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001538
Bram Moolenaar071d4272004-06-13 20:20:40 +00001539 if (0
1540#ifdef FEAT_MOUSE
1541 || g_nMouseClick != -1
1542#endif
1543#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001544 || (!ignore_input && input_available())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001545#endif
1546 )
1547 return TRUE;
1548
1549 if (msec > 0)
1550 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001551 /* If the specified wait time has passed, return. Beware that
1552 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001553 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001554 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001555 break;
1556 }
1557 if (msec != 0)
1558 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001559 DWORD dwWaitTime = dwEndTime - dwNow;
1560
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001561#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001562 /* Check channel while waiting for input. */
Bram Moolenaar9186a272016-02-23 19:34:01 +01001563 if (dwWaitTime > 100)
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001564 {
Bram Moolenaar9186a272016-02-23 19:34:01 +01001565 dwWaitTime = 100;
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001566 /* If there is readahead then parse_queued_messages() timed out
1567 * and we should call it again soon. */
1568 if (channel_any_readahead())
1569 dwWaitTime = 10;
1570 }
Bram Moolenaar9186a272016-02-23 19:34:01 +01001571#endif
Bram Moolenaarc3719bd2017-11-18 22:13:31 +01001572#ifdef FEAT_BEVAL_GUI
Bram Moolenaar59716a22017-03-01 20:32:44 +01001573 if (p_beval && dwWaitTime > 100)
1574 /* The 'balloonexpr' may indirectly invoke a callback while
1575 * waiting for a character, need to check often. */
1576 dwWaitTime = 100;
1577#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001578#ifdef FEAT_MZSCHEME
1579 if (mzthreads_allowed() && p_mzq > 0
1580 && (msec < 0 || (long)dwWaitTime > p_mzq))
1581 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1582#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001583#ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001584 // When waiting very briefly don't trigger timers.
1585 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001586 {
1587 long due_time;
1588
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001589 // Trigger timers and then get the time in msec until the next
1590 // one is due. Wait up to that time.
1591 due_time = check_due_timer();
1592 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001593 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001594 // timer may have used feedkeys().
1595 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001596 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001597 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1598 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001599 }
1600#endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001601 if (
Bram Moolenaar071d4272004-06-13 20:20:40 +00001602#ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001603 // Wait for either an event on the console input or a
1604 // message in the client-server window.
1605 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1606 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607#else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001608 wait_for_single_object(g_hConIn, dwWaitTime)
1609 != WAIT_OBJECT_0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001610#endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001611 )
1612 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001613 }
1614
1615 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001616 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001617
1618#ifdef FEAT_MBYTE_IME
1619 if (State & CMDLINE && msg_row == Rows - 1)
1620 {
1621 CONSOLE_SCREEN_BUFFER_INFO csbi;
1622
1623 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1624 {
1625 if (csbi.dwCursorPosition.Y != msg_row)
1626 {
1627 /* The screen is now messed up, must redraw the
1628 * command line and later all the windows. */
1629 redraw_all_later(CLEAR);
1630 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1631 redrawcmd();
1632 }
1633 }
1634 }
1635#endif
1636
1637 if (cRecords > 0)
1638 {
1639 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1640 {
1641#ifdef FEAT_MBYTE_IME
1642 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1643 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001644 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001645 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1646 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001647 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001648 continue;
1649 }
1650#endif
1651 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1652 NULL, FALSE))
1653 return TRUE;
1654 }
1655
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001656 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001657
1658 if (ir.EventType == FOCUS_EVENT)
1659 handle_focus_event(ir);
1660 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001661 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001662 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1663
1664 // Only call shell_resized() when the size actually change to
1665 // avoid the screen is cleard.
1666 if (dwSize.X != Columns || dwSize.Y != Rows)
1667 {
1668 CONSOLE_SCREEN_BUFFER_INFO csbi;
1669 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
1670 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
1671 ResizeConBuf(g_hConOut, dwSize);
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001672 shell_resized();
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001673 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001674 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001675#ifdef FEAT_MOUSE
1676 else if (ir.EventType == MOUSE_EVENT
1677 && decode_mouse_event(&ir.Event.MouseEvent))
1678 return TRUE;
1679#endif
1680 }
1681 else if (msec == 0)
1682 break;
1683 }
1684
1685#ifdef FEAT_CLIENTSERVER
1686 /* Something might have been received while we were waiting. */
1687 if (input_available())
1688 return TRUE;
1689#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001690
Bram Moolenaar071d4272004-06-13 20:20:40 +00001691 return FALSE;
1692}
1693
1694#ifndef FEAT_GUI_MSWIN
1695/*
1696 * return non-zero if a character is available
1697 */
1698 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001699mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001700{
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001701 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001702}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001703
1704# if defined(FEAT_TERMINAL) || defined(PROTO)
1705/*
1706 * Check for any pending input or messages.
1707 */
1708 int
1709mch_check_messages(void)
1710{
1711 return WaitForChar(0L, TRUE);
1712}
1713# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001714#endif
1715
1716/*
1717 * Create the console input. Used when reading stdin doesn't work.
1718 */
1719 static void
1720create_conin(void)
1721{
1722 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1723 FILE_SHARE_READ|FILE_SHARE_WRITE,
1724 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001725 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001726 did_create_conin = TRUE;
1727}
1728
1729/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001730 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001731 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001732 static WCHAR
1733tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001734{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001735 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001736
1737 for (;;)
1738 {
1739 INPUT_RECORD ir;
1740 DWORD cRecords = 0;
1741
1742#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001743 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001744 if (input_available())
1745 return 0;
1746# ifdef FEAT_MOUSE
1747 if (g_nMouseClick != -1)
1748 return 0;
1749# endif
1750#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001751 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001752 {
1753 if (did_create_conin)
1754 read_error_exit();
1755 create_conin();
1756 continue;
1757 }
1758
1759 if (ir.EventType == KEY_EVENT)
1760 {
1761 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1762 pmodifiers, TRUE))
1763 return ch;
1764 }
1765 else if (ir.EventType == FOCUS_EVENT)
1766 handle_focus_event(ir);
1767 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1768 shell_resized();
1769#ifdef FEAT_MOUSE
1770 else if (ir.EventType == MOUSE_EVENT)
1771 {
1772 if (decode_mouse_event(&ir.Event.MouseEvent))
1773 return 0;
1774 }
1775#endif
1776 }
1777}
Bram Moolenaar4f974752019-02-17 17:44:42 +01001778#endif /* !FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001779
1780
1781/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001782 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001783 * Get one or more characters from the keyboard or the mouse.
1784 * If time == 0, do not wait for characters.
1785 * If time == n, wait a short time for characters.
1786 * If time == -1, wait forever for characters.
1787 * Returns the number of characters read into buf.
1788 */
1789 int
1790mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001791 char_u *buf UNUSED,
1792 int maxlen UNUSED,
1793 long time UNUSED,
1794 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001795{
Bram Moolenaar4f974752019-02-17 17:44:42 +01001796#ifndef FEAT_GUI_MSWIN /* this isn't used for the GUI */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001797
1798 int len;
1799 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001800#define TYPEAHEADLEN 20
1801 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1802 static int typeaheadlen = 0;
1803
1804 /* First use any typeahead that was kept because "buf" was too small. */
1805 if (typeaheadlen > 0)
1806 goto theend;
1807
Bram Moolenaar071d4272004-06-13 20:20:40 +00001808 if (time >= 0)
1809 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001810 if (!WaitForChar(time, FALSE)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001811 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001812 }
1813 else /* time == -1, wait forever */
1814 {
1815 mch_set_winsize_now(); /* Allow winsize changes from now on */
1816
Bram Moolenaar3918c952005-03-15 22:34:55 +00001817 /*
1818 * If there is no character available within 2 seconds (default)
1819 * write the autoscript file to disk. Or cause the CursorHold event
1820 * to be triggered.
1821 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001822 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001823 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001824 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001825 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001826 buf[0] = K_SPECIAL;
1827 buf[1] = KS_EXTRA;
1828 buf[2] = (int)KE_CURSORHOLD;
1829 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001830 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001831 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001832 }
1833 }
1834
1835 /*
1836 * Try to read as many characters as there are, until the buffer is full.
1837 */
1838
1839 /* we will get at least one key. Get more if they are available. */
1840 g_fCBrkPressed = FALSE;
1841
1842#ifdef MCH_WRITE_DUMP
1843 if (fdDump)
1844 fputc('[', fdDump);
1845#endif
1846
1847 /* Keep looping until there is something in the typeahead buffer and more
1848 * to get and still room in the buffer (up to two bytes for a char and
1849 * three bytes for a modifier). */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001850 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001851 && typeaheadlen + 5 <= TYPEAHEADLEN)
1852 {
1853 if (typebuf_changed(tb_change_cnt))
1854 {
1855 /* "buf" may be invalid now if a client put something in the
1856 * typeahead buffer and "buf" is in the typeahead buffer. */
1857 typeaheadlen = 0;
1858 break;
1859 }
1860#ifdef FEAT_MOUSE
1861 if (g_nMouseClick != -1)
1862 {
1863# ifdef MCH_WRITE_DUMP
1864 if (fdDump)
1865 fprintf(fdDump, "{%02x @ %d, %d}",
1866 g_nMouseClick, g_xMouse, g_yMouse);
1867# endif
1868 typeahead[typeaheadlen++] = ESC + 128;
1869 typeahead[typeaheadlen++] = 'M';
1870 typeahead[typeaheadlen++] = g_nMouseClick;
1871 typeahead[typeaheadlen++] = g_xMouse + '!';
1872 typeahead[typeaheadlen++] = g_yMouse + '!';
1873 g_nMouseClick = -1;
1874 }
1875 else
1876#endif
1877 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001878 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001879 int modifiers = 0;
1880
1881 c = tgetch(&modifiers, &ch2);
1882
1883 if (typebuf_changed(tb_change_cnt))
1884 {
1885 /* "buf" may be invalid now if a client put something in the
1886 * typeahead buffer and "buf" is in the typeahead buffer. */
1887 typeaheadlen = 0;
1888 break;
1889 }
1890
1891 if (c == Ctrl_C && ctrl_c_interrupts)
1892 {
1893#if defined(FEAT_CLIENTSERVER)
1894 trash_input_buf();
1895#endif
1896 got_int = TRUE;
1897 }
1898
1899#ifdef FEAT_MOUSE
1900 if (g_nMouseClick == -1)
1901#endif
1902 {
1903 int n = 1;
1904
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001905 if (ch2 == NUL)
1906 {
1907 int i;
1908 char_u *p;
1909 WCHAR ch[2];
1910
1911 ch[0] = c;
1912 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1913 {
1914 ch[1] = tgetch(&modifiers, &ch2);
1915 n++;
1916 }
1917 p = utf16_to_enc(ch, &n);
1918 if (p != NULL)
1919 {
1920 for (i = 0; i < n; i++)
1921 typeahead[typeaheadlen + i] = p[i];
1922 vim_free(p);
1923 }
1924 }
1925 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001926 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001927 if (ch2 != NUL)
1928 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001929 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001930 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001931 switch (ch2)
1932 {
1933 case (WCHAR)'\324': // SHIFT+Insert
1934 case (WCHAR)'\325': // CTRL+Insert
1935 case (WCHAR)'\327': // SHIFT+Delete
1936 case (WCHAR)'\330': // CTRL+Delete
1937 typeahead[typeaheadlen + n] = (char_u)ch2;
1938 n++;
1939 break;
1940
1941 default:
1942 typeahead[typeaheadlen + n] = 3;
1943 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1944 n += 2;
1945 break;
1946 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001947 }
1948 else
1949 {
1950 typeahead[typeaheadlen + n] = 3;
1951 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1952 n += 2;
1953 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001954 }
1955
Bram Moolenaar071d4272004-06-13 20:20:40 +00001956 /* Use the ALT key to set the 8th bit of the character
1957 * when it's one byte, the 8th bit isn't set yet and not
1958 * using a double-byte encoding (would become a lead
1959 * byte). */
1960 if ((modifiers & MOD_MASK_ALT)
1961 && n == 1
1962 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001963 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00001964 )
1965 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001966 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1967 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001968 modifiers &= ~MOD_MASK_ALT;
1969 }
1970
1971 if (modifiers != 0)
1972 {
1973 /* Prepend modifiers to the character. */
1974 mch_memmove(typeahead + typeaheadlen + 3,
1975 typeahead + typeaheadlen, n);
1976 typeahead[typeaheadlen++] = K_SPECIAL;
1977 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1978 typeahead[typeaheadlen++] = modifiers;
1979 }
1980
1981 typeaheadlen += n;
1982
1983#ifdef MCH_WRITE_DUMP
1984 if (fdDump)
1985 fputc(c, fdDump);
1986#endif
1987 }
1988 }
1989 }
1990
1991#ifdef MCH_WRITE_DUMP
1992 if (fdDump)
1993 {
1994 fputs("]\n", fdDump);
1995 fflush(fdDump);
1996 }
1997#endif
1998
Bram Moolenaar071d4272004-06-13 20:20:40 +00001999theend:
2000 /* Move typeahead to "buf", as much as fits. */
2001 len = 0;
2002 while (len < maxlen && typeaheadlen > 0)
2003 {
2004 buf[len++] = typeahead[0];
2005 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2006 }
2007 return len;
2008
Bram Moolenaar4f974752019-02-17 17:44:42 +01002009#else /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002010 return 0;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002011#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002012}
2013
Bram Moolenaar82881492012-11-20 16:53:39 +01002014#ifndef PROTO
2015# ifndef __MINGW32__
2016# include <shellapi.h> /* required for FindExecutable() */
2017# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002018#endif
2019
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002020/*
Bram Moolenaar43663192017-03-05 14:29:12 +01002021 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2022 * If "use_path" is FALSE: Return TRUE if "name" exists.
2023 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2024 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002025 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002026 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002027 static int
Bram Moolenaar43663192017-03-05 14:29:12 +01002028executable_exists(char *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002029{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002030 char *dum;
2031 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002032 char *curpath, *newpath;
2033 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002034
Bram Moolenaar43663192017-03-05 14:29:12 +01002035 if (!use_path)
2036 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002037 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01002038 {
2039 if (path != NULL)
Bram Moolenaar066029e2017-03-05 15:19:32 +01002040 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002041 if (mch_isFullName((char_u *)name))
Bram Moolenaar066029e2017-03-05 15:19:32 +01002042 *path = vim_strsave((char_u *)name);
2043 else
2044 *path = FullName_save((char_u *)name, FALSE);
2045 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002046 return TRUE;
2047 }
2048 return FALSE;
2049 }
2050
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002051 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002052 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002053 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002054 WCHAR fnamew[_MAX_PATH];
2055 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002056 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002057
2058 if (p != NULL)
2059 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002060 wcurpath = _wgetenv(L"PATH");
2061 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
2062 * sizeof(WCHAR));
2063 if (wnewpath == NULL)
2064 return FALSE;
2065 wcscpy(wnewpath, L".;");
2066 wcscat(wnewpath, wcurpath);
2067 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
2068 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002069 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002070 if (n == 0)
2071 return FALSE;
2072 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
2073 return FALSE;
2074 if (path != NULL)
2075 *path = utf16_to_enc(fnamew, NULL);
2076 return TRUE;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002077 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002078 }
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002079
2080 curpath = getenv("PATH");
2081 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
2082 if (newpath == NULL)
2083 return FALSE;
2084 STRCPY(newpath, ".;");
2085 STRCAT(newpath, curpath);
2086 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
2087 vim_free(newpath);
2088 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002089 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002090 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002091 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002092 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002093 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002094 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002095}
2096
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002097#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2098 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002099/*
2100 * Bad parameter handler.
2101 *
2102 * Certain MS CRT functions will intentionally crash when passed invalid
2103 * parameters to highlight possible security holes. Setting this function as
2104 * the bad parameter handler will prevent the crash.
2105 *
2106 * In debug builds the parameters contain CRT information that might help track
2107 * down the source of a problem, but in non-debug builds the arguments are all
2108 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2109 * worth allowing these to make debugging of issues easier.
2110 */
2111 static void
2112bad_param_handler(const wchar_t *expression,
2113 const wchar_t *function,
2114 const wchar_t *file,
2115 unsigned int line,
2116 uintptr_t pReserved)
2117{
2118}
2119
2120# define SET_INVALID_PARAM_HANDLER \
2121 ((void)_set_invalid_parameter_handler(bad_param_handler))
2122#else
2123# define SET_INVALID_PARAM_HANDLER
2124#endif
2125
Bram Moolenaar4f974752019-02-17 17:44:42 +01002126#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002127
2128/*
2129 * GUI version of mch_init().
2130 */
2131 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002132mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002133{
2134#ifndef __MINGW32__
2135 extern int _fmode;
2136#endif
2137
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002138 /* Silently handle invalid parameters to CRT functions */
2139 SET_INVALID_PARAM_HANDLER;
2140
Bram Moolenaar071d4272004-06-13 20:20:40 +00002141 /* Let critical errors result in a failure, not in a dialog box. Required
2142 * for the timestamp test to work on removed floppies. */
2143 SetErrorMode(SEM_FAILCRITICALERRORS);
2144
2145 _fmode = O_BINARY; /* we do our own CR-LF translation */
2146
2147 /* Specify window size. Is there a place to get the default from? */
2148 Rows = 25;
2149 Columns = 80;
2150
2151 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002152 {
2153 char_u vimrun_location[_MAX_PATH + 4];
2154
2155 /* First try in same directory as gvim.exe */
2156 STRCPY(vimrun_location, exe_name);
2157 STRCPY(gettail(vimrun_location), "vimrun.exe");
2158 if (mch_getperm(vimrun_location) >= 0)
2159 {
2160 if (*skiptowhite(vimrun_location) != NUL)
2161 {
2162 /* Enclose path with white space in double quotes. */
2163 mch_memmove(vimrun_location + 1, vimrun_location,
2164 STRLEN(vimrun_location) + 1);
2165 *vimrun_location = '"';
2166 STRCPY(gettail(vimrun_location), "vimrun\" ");
2167 }
2168 else
2169 STRCPY(gettail(vimrun_location), "vimrun ");
2170
2171 vimrun_path = (char *)vim_strsave(vimrun_location);
2172 s_dont_use_vimrun = FALSE;
2173 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002174 else if (executable_exists("vimrun.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002175 s_dont_use_vimrun = FALSE;
2176
2177 /* Don't give the warning for a missing vimrun.exe right now, but only
2178 * when vimrun was supposed to be used. Don't bother people that do
2179 * not need vimrun.exe. */
2180 if (s_dont_use_vimrun)
2181 need_vimrun_warning = TRUE;
2182 }
2183
2184 /*
2185 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2186 * Otherwise the default "findstr /n" is used.
2187 */
Bram Moolenaar43663192017-03-05 14:29:12 +01002188 if (!executable_exists("findstr.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002189 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2190
2191#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002192 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002193#endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002194
2195 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002196}
2197
2198
Bram Moolenaar4f974752019-02-17 17:44:42 +01002199#else /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002200
2201#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2202#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2203
2204/*
2205 * ClearConsoleBuffer()
2206 * Description:
2207 * Clears the entire contents of the console screen buffer, using the
2208 * specified attribute.
2209 * Returns:
2210 * TRUE on success
2211 */
2212 static BOOL
2213ClearConsoleBuffer(WORD wAttribute)
2214{
2215 CONSOLE_SCREEN_BUFFER_INFO csbi;
2216 COORD coord;
2217 DWORD NumCells, dummy;
2218
2219 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2220 return FALSE;
2221
2222 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2223 coord.X = 0;
2224 coord.Y = 0;
2225 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2226 coord, &dummy))
2227 {
2228 return FALSE;
2229 }
2230 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2231 coord, &dummy))
2232 {
2233 return FALSE;
2234 }
2235
2236 return TRUE;
2237}
2238
2239/*
2240 * FitConsoleWindow()
2241 * Description:
2242 * Checks if the console window will fit within given buffer dimensions.
2243 * Also, if requested, will shrink the window to fit.
2244 * Returns:
2245 * TRUE on success
2246 */
2247 static BOOL
2248FitConsoleWindow(
2249 COORD dwBufferSize,
2250 BOOL WantAdjust)
2251{
2252 CONSOLE_SCREEN_BUFFER_INFO csbi;
2253 COORD dwWindowSize;
2254 BOOL NeedAdjust = FALSE;
2255
2256 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2257 {
2258 /*
2259 * A buffer resize will fail if the current console window does
2260 * not lie completely within that buffer. To avoid this, we might
2261 * have to move and possibly shrink the window.
2262 */
2263 if (csbi.srWindow.Right >= dwBufferSize.X)
2264 {
2265 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2266 if (dwWindowSize.X > dwBufferSize.X)
2267 dwWindowSize.X = dwBufferSize.X;
2268 csbi.srWindow.Right = dwBufferSize.X - 1;
2269 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2270 NeedAdjust = TRUE;
2271 }
2272 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2273 {
2274 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2275 if (dwWindowSize.Y > dwBufferSize.Y)
2276 dwWindowSize.Y = dwBufferSize.Y;
2277 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2278 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2279 NeedAdjust = TRUE;
2280 }
2281 if (NeedAdjust && WantAdjust)
2282 {
2283 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2284 return FALSE;
2285 }
2286 return TRUE;
2287 }
2288
2289 return FALSE;
2290}
2291
2292typedef struct ConsoleBufferStruct
2293{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002294 BOOL IsValid;
2295 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002296 PCHAR_INFO Buffer;
2297 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002298 PSMALL_RECT Regions;
2299 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002300} ConsoleBuffer;
2301
2302/*
2303 * SaveConsoleBuffer()
2304 * Description:
2305 * Saves important information about the console buffer, including the
2306 * actual buffer contents. The saved information is suitable for later
2307 * restoration by RestoreConsoleBuffer().
2308 * Returns:
2309 * TRUE if all information was saved; FALSE otherwise
2310 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2311 */
2312 static BOOL
2313SaveConsoleBuffer(
2314 ConsoleBuffer *cb)
2315{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002316 DWORD NumCells;
2317 COORD BufferCoord;
2318 SMALL_RECT ReadRegion;
2319 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002320 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002321
Bram Moolenaar071d4272004-06-13 20:20:40 +00002322 if (cb == NULL)
2323 return FALSE;
2324
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002325 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002326 {
2327 cb->IsValid = FALSE;
2328 return FALSE;
2329 }
2330 cb->IsValid = TRUE;
2331
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002332 /*
2333 * Allocate a buffer large enough to hold the entire console screen
2334 * buffer. If this ConsoleBuffer structure has already been initialized
2335 * with a buffer of the correct size, then just use that one.
2336 */
2337 if (!cb->IsValid || cb->Buffer == NULL ||
2338 cb->BufferSize.X != cb->Info.dwSize.X ||
2339 cb->BufferSize.Y != cb->Info.dwSize.Y)
2340 {
2341 cb->BufferSize.X = cb->Info.dwSize.X;
2342 cb->BufferSize.Y = cb->Info.dwSize.Y;
2343 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2344 vim_free(cb->Buffer);
2345 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2346 if (cb->Buffer == NULL)
2347 return FALSE;
2348 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002349
2350 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002351 * We will now copy the console screen buffer into our buffer.
2352 * ReadConsoleOutput() seems to be limited as far as how much you
2353 * can read at a time. Empirically, this number seems to be about
2354 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2355 * in chunks until it is all copied. The chunks will all have the
2356 * same horizontal characteristics, so initialize them now. The
2357 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002358 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002359 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002360 ReadRegion.Left = 0;
2361 ReadRegion.Right = cb->Info.dwSize.X - 1;
2362 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002363
2364 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2365 if (cb->Regions == NULL || numregions != cb->NumRegions)
2366 {
2367 cb->NumRegions = numregions;
2368 vim_free(cb->Regions);
2369 cb->Regions = (PSMALL_RECT)alloc(cb->NumRegions * sizeof(SMALL_RECT));
2370 if (cb->Regions == NULL)
2371 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002372 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002373 return FALSE;
2374 }
2375 }
2376
2377 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002378 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002379 /*
2380 * Read into position (0, Y) in our buffer.
2381 */
2382 BufferCoord.Y = Y;
2383 /*
2384 * Read the region whose top left corner is (0, Y) and whose bottom
2385 * right corner is (width - 1, Y + Y_incr - 1). This should define
2386 * a region of size width by Y_incr. Don't worry if this region is
2387 * too large for the remaining buffer; it will be cropped.
2388 */
2389 ReadRegion.Top = Y;
2390 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002391 if (!ReadConsoleOutputW(g_hConOut, /* output handle */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002392 cb->Buffer, /* our buffer */
2393 cb->BufferSize, /* dimensions of our buffer */
2394 BufferCoord, /* offset in our buffer */
2395 &ReadRegion)) /* region to save */
2396 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002397 VIM_CLEAR(cb->Buffer);
2398 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002399 return FALSE;
2400 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002401 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002402 }
2403
2404 return TRUE;
2405}
2406
2407/*
2408 * RestoreConsoleBuffer()
2409 * Description:
2410 * Restores important information about the console buffer, including the
2411 * actual buffer contents, if desired. The information to restore is in
2412 * the same format used by SaveConsoleBuffer().
2413 * Returns:
2414 * TRUE on success
2415 */
2416 static BOOL
2417RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002418 ConsoleBuffer *cb,
2419 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002420{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002421 COORD BufferCoord;
2422 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002423 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002424
2425 if (cb == NULL || !cb->IsValid)
2426 return FALSE;
2427
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002428 /*
2429 * Before restoring the buffer contents, clear the current buffer, and
2430 * restore the cursor position and window information. Doing this now
2431 * prevents old buffer contents from "flashing" onto the screen.
2432 */
2433 if (RestoreScreen)
2434 ClearConsoleBuffer(cb->Info.wAttributes);
2435
2436 FitConsoleWindow(cb->Info.dwSize, TRUE);
2437 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2438 return FALSE;
2439 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2440 return FALSE;
2441
2442 if (!RestoreScreen)
2443 {
2444 /*
2445 * No need to restore the screen buffer contents, so we're done.
2446 */
2447 return TRUE;
2448 }
2449
2450 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2451 return FALSE;
2452 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2453 return FALSE;
2454
2455 /*
2456 * Restore the screen buffer contents.
2457 */
2458 if (cb->Buffer != NULL)
2459 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002460 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002461 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002462 BufferCoord.X = cb->Regions[i].Left;
2463 BufferCoord.Y = cb->Regions[i].Top;
2464 WriteRegion = cb->Regions[i];
2465 if (!WriteConsoleOutputW(g_hConOut, /* output handle */
2466 cb->Buffer, /* our buffer */
2467 cb->BufferSize, /* dimensions of our buffer */
2468 BufferCoord, /* offset in our buffer */
2469 &WriteRegion)) /* region to restore */
2470 {
2471 return FALSE;
2472 }
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002473 }
2474 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002475
2476 return TRUE;
2477}
2478
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002479#define FEAT_RESTORE_ORIG_SCREEN
2480#ifdef FEAT_RESTORE_ORIG_SCREEN
2481static ConsoleBuffer g_cbOrig = { 0 };
2482#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002483static ConsoleBuffer g_cbNonTermcap = { 0 };
2484static ConsoleBuffer g_cbTermcap = { 0 };
2485
2486#ifdef FEAT_TITLE
2487#ifdef __BORLANDC__
2488typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2489#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002490typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002491#endif
2492char g_szOrigTitle[256] = { 0 };
2493HWND g_hWnd = NULL; /* also used in os_mswin.c */
2494static HICON g_hOrigIconSmall = NULL;
2495static HICON g_hOrigIcon = NULL;
2496static HICON g_hVimIcon = NULL;
2497static BOOL g_fCanChangeIcon = FALSE;
2498
2499/* ICON* are not defined in VC++ 4.0 */
2500#ifndef ICON_SMALL
2501#define ICON_SMALL 0
2502#endif
2503#ifndef ICON_BIG
2504#define ICON_BIG 1
2505#endif
2506/*
2507 * GetConsoleIcon()
2508 * Description:
2509 * Attempts to retrieve 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
2515GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002516 HWND hWnd,
2517 HICON *phIconSmall,
2518 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519{
2520 if (hWnd == NULL)
2521 return FALSE;
2522
2523 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002524 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2525 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002526 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002527 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2528 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002529 return TRUE;
2530}
2531
2532/*
2533 * SetConsoleIcon()
2534 * Description:
2535 * Attempts to change the small icon and/or the big icon currently in
2536 * use by a given window.
2537 * Returns:
2538 * TRUE on success
2539 */
2540 static BOOL
2541SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002542 HWND hWnd,
2543 HICON hIconSmall,
2544 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002545{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002546 if (hWnd == NULL)
2547 return FALSE;
2548
2549 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002550 SendMessage(hWnd, WM_SETICON,
2551 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002552 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002553 SendMessage(hWnd, WM_SETICON,
2554 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002555 return TRUE;
2556}
2557
2558/*
2559 * SaveConsoleTitleAndIcon()
2560 * Description:
2561 * Saves the current console window title in g_szOrigTitle, for later
2562 * restoration. Also, attempts to obtain a handle to the console window,
2563 * and use it to save the small and big icons currently in use by the
2564 * console window. This is not always possible on some versions of Windows;
2565 * nor is it possible when running Vim remotely using Telnet (since the
2566 * console window the user sees is owned by a remote process).
2567 */
2568 static void
2569SaveConsoleTitleAndIcon(void)
2570{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002571 /* Save the original title. */
2572 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2573 return;
2574
2575 /*
2576 * Obtain a handle to the console window using GetConsoleWindow() from
2577 * KERNEL32.DLL; we need to handle in order to change the window icon.
2578 * This function only exists on NT-based Windows, starting with Windows
2579 * 2000. On older operating systems, we can't change the window icon
2580 * anyway.
2581 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002582 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002583 if (g_hWnd == NULL)
2584 return;
2585
2586 /* Save the original console window icon. */
2587 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2588 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2589 return;
2590
2591 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002592 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002593 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002594 if (g_hVimIcon != NULL)
2595 g_fCanChangeIcon = TRUE;
2596}
2597#endif
2598
2599static int g_fWindInitCalled = FALSE;
2600static int g_fTermcapMode = FALSE;
2601static CONSOLE_CURSOR_INFO g_cci;
2602static DWORD g_cmodein = 0;
2603static DWORD g_cmodeout = 0;
2604
2605/*
2606 * non-GUI version of mch_init().
2607 */
2608 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002609mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002610{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002611#ifndef FEAT_RESTORE_ORIG_SCREEN
2612 CONSOLE_SCREEN_BUFFER_INFO csbi;
2613#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002614#ifndef __MINGW32__
2615 extern int _fmode;
2616#endif
2617
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002618 /* Silently handle invalid parameters to CRT functions */
2619 SET_INVALID_PARAM_HANDLER;
2620
Bram Moolenaar071d4272004-06-13 20:20:40 +00002621 /* Let critical errors result in a failure, not in a dialog box. Required
2622 * for the timestamp test to work on removed floppies. */
2623 SetErrorMode(SEM_FAILCRITICALERRORS);
2624
2625 _fmode = O_BINARY; /* we do our own CR-LF translation */
2626 out_flush();
2627
2628 /* Obtain handles for the standard Console I/O devices */
2629 if (read_cmd_fd == 0)
2630 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2631 else
2632 create_conin();
2633 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2634
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002635#ifdef FEAT_RESTORE_ORIG_SCREEN
2636 /* Save the initial console buffer for later restoration */
2637 SaveConsoleBuffer(&g_cbOrig);
2638 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2639#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002640 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002641 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2642 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2643#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002644 if (cterm_normal_fg_color == 0)
2645 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2646 if (cterm_normal_bg_color == 0)
2647 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2648
Bram Moolenaarbdace832019-03-02 10:13:42 +01002649 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002650 g_color_index_fg = g_attrDefault & 0xf;
2651 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2652
Bram Moolenaar071d4272004-06-13 20:20:40 +00002653 /* set termcap codes to current text attributes */
2654 update_tcap(g_attrCurrent);
2655
2656 GetConsoleCursorInfo(g_hConOut, &g_cci);
2657 GetConsoleMode(g_hConIn, &g_cmodein);
2658 GetConsoleMode(g_hConOut, &g_cmodeout);
2659
2660#ifdef FEAT_TITLE
2661 SaveConsoleTitleAndIcon();
2662 /*
2663 * Set both the small and big icons of the console window to Vim's icon.
2664 * Note that Vim presently only has one size of icon (32x32), but it
2665 * automatically gets scaled down to 16x16 when setting the small icon.
2666 */
2667 if (g_fCanChangeIcon)
2668 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2669#endif
2670
2671 ui_get_shellsize();
2672
2673#ifdef MCH_WRITE_DUMP
2674 fdDump = fopen("dump", "wt");
2675
2676 if (fdDump)
2677 {
2678 time_t t;
2679
2680 time(&t);
2681 fputs(ctime(&t), fdDump);
2682 fflush(fdDump);
2683 }
2684#endif
2685
2686 g_fWindInitCalled = TRUE;
2687
2688#ifdef FEAT_MOUSE
2689 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2690#endif
2691
2692#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002693 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002694#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002695
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002696 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002697 vtp_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002698}
2699
2700/*
2701 * non-GUI version of mch_exit().
2702 * Shut down and exit with status `r'
2703 * Careful: mch_exit() may be called before mch_init()!
2704 */
2705 void
2706mch_exit(int r)
2707{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002708 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002709
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002710 vtp_exit();
2711
Bram Moolenaar955f1982017-02-05 15:10:51 +01002712 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002713 if (g_fWindInitCalled)
2714 settmode(TMODE_COOK);
2715
2716 ml_close_all(TRUE); /* remove all memfiles */
2717
2718 if (g_fWindInitCalled)
2719 {
2720#ifdef FEAT_TITLE
Bram Moolenaar40385db2018-08-07 22:31:44 +02002721 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002722 /*
2723 * Restore both the small and big icons of the console window to
2724 * what they were at startup. Don't do this when the window is
2725 * closed, Vim would hang here.
2726 */
2727 if (g_fCanChangeIcon && !g_fForceExit)
2728 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2729#endif
2730
2731#ifdef MCH_WRITE_DUMP
2732 if (fdDump)
2733 {
2734 time_t t;
2735
2736 time(&t);
2737 fputs(ctime(&t), fdDump);
2738 fclose(fdDump);
2739 }
2740 fdDump = NULL;
2741#endif
2742 }
2743
2744 SetConsoleCursorInfo(g_hConOut, &g_cci);
2745 SetConsoleMode(g_hConIn, g_cmodein);
2746 SetConsoleMode(g_hConOut, g_cmodeout);
2747
2748#ifdef DYNAMIC_GETTEXT
2749 dyn_libintl_end();
2750#endif
2751
2752 exit(r);
2753}
Bram Moolenaar4f974752019-02-17 17:44:42 +01002754#endif /* !FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002755
Bram Moolenaar071d4272004-06-13 20:20:40 +00002756/*
2757 * Do we have an interactive window?
2758 */
2759 int
2760mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002761 int argc UNUSED,
2762 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002763{
2764 get_exe_name();
2765
Bram Moolenaar4f974752019-02-17 17:44:42 +01002766#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002767 return OK; /* GUI always has a tty */
2768#else
2769 if (isatty(1))
2770 return OK;
2771 return FAIL;
2772#endif
2773}
2774
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002775/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002776 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002777 * When "len" is > 0, also expand short to long filenames.
2778 */
2779 void
2780fname_case(
2781 char_u *name,
2782 int len)
2783{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002784 int flen;
2785 WCHAR *p;
2786 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002787
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002788 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002789 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002790 return;
2791
2792 slash_adjust(name);
2793
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002794 p = enc_to_utf16(name, NULL);
2795 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002796 return;
2797
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002798 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002799 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002800 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002801
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002802 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002803 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002804 if (len > 0 || flen >= (int)STRLEN(q))
2805 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2806 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002807 }
2808 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002809 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002810}
2811
2812
2813/*
2814 * Insert user name in s[len].
2815 */
2816 int
2817mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002818 char_u *s,
2819 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002820{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002821 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002822 DWORD cch = sizeof szUserName;
2823
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002824 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2825 {
2826 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2827 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2828
2829 if (GetUserNameW(wszUserName, &wcch))
2830 {
2831 char_u *p = utf16_to_enc(wszUserName, NULL);
2832
2833 if (p != NULL)
2834 {
2835 vim_strncpy(s, p, len - 1);
2836 vim_free(p);
2837 return OK;
2838 }
2839 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002840 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002841 if (GetUserName(szUserName, &cch))
2842 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002843 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002844 return OK;
2845 }
2846 s[0] = NUL;
2847 return FAIL;
2848}
2849
2850
2851/*
2852 * Insert host name in s[len].
2853 */
2854 void
2855mch_get_host_name(
2856 char_u *s,
2857 int len)
2858{
2859 DWORD cch = len;
2860
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002861 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2862 {
2863 WCHAR wszHostName[256 + 1];
2864 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2865
2866 if (GetComputerNameW(wszHostName, &wcch))
2867 {
2868 char_u *p = utf16_to_enc(wszHostName, NULL);
2869
2870 if (p != NULL)
2871 {
2872 vim_strncpy(s, p, len - 1);
2873 vim_free(p);
2874 return;
2875 }
2876 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002877 }
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002878 if (!GetComputerName((LPSTR)s, &cch))
2879 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002880}
2881
2882
2883/*
2884 * return process ID
2885 */
2886 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002887mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002888{
2889 return (long)GetCurrentProcessId();
2890}
2891
2892
2893/*
2894 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2895 * Return OK for success, FAIL for failure.
2896 */
2897 int
2898mch_dirname(
2899 char_u *buf,
2900 int len)
2901{
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002902 char_u abuf[_MAX_PATH + 1];
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02002903 DWORD lfnlen;
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002904
Bram Moolenaar071d4272004-06-13 20:20:40 +00002905 /*
2906 * Originally this was:
2907 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2908 * But the Win32s known bug list says that getcwd() doesn't work
2909 * so use the Win32 system call instead. <Negri>
2910 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002911 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2912 {
2913 WCHAR wbuf[_MAX_PATH + 1];
2914
2915 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2916 {
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002917 WCHAR wcbuf[_MAX_PATH + 1];
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02002918 char_u *p = NULL;
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002919
2920 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02002921 {
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002922 p = utf16_to_enc(wcbuf, NULL);
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02002923 if (STRLEN(p) >= (size_t)len)
2924 {
2925 // long path name is too long, fall back to short one
2926 vim_free(p);
2927 p = NULL;
2928 }
2929 }
2930 if (p == NULL)
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002931 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002932
2933 if (p != NULL)
2934 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002935 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002936 vim_free(p);
2937 return OK;
2938 }
2939 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002940 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002941 }
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002942 if (GetCurrentDirectory(len, (LPSTR)buf) == 0)
2943 return FAIL;
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02002944 lfnlen = GetLongPathNameA((LPCSTR)buf, (LPSTR)abuf, _MAX_PATH);
2945 if (lfnlen == 0 || lfnlen >= (DWORD)len)
2946 // Failed to get long path name or it's too long: fall back to the
2947 // short path name.
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002948 return OK;
2949
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02002950 STRCPY(buf, abuf);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002951 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002952}
2953
2954/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01002955 * Get file permissions for "name".
2956 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002957 */
2958 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002959mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002960{
Bram Moolenaar8767f522016-07-01 17:17:39 +02002961 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01002962 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002963
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002964 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01002965 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002966}
2967
2968
2969/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002970 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002971 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002972 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002973 */
2974 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002975mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002976{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002977 long n = -1;
2978
Bram Moolenaar071d4272004-06-13 20:20:40 +00002979 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2980 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002981 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002982
2983 if (p != NULL)
2984 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002985 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002986 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002987 if (n == -1)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002988 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002989 }
2990 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002991 if (n == -1)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002992 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002993 if (n == -1)
2994 return FAIL;
2995
2996 win32_set_archive(name);
2997
2998 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002999}
3000
3001/*
3002 * Set hidden flag for "name".
3003 */
3004 void
3005mch_hide(char_u *name)
3006{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003007 int attrs = win32_getattrs(name);
3008 if (attrs == -1)
3009 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003010
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003011 attrs |= FILE_ATTRIBUTE_HIDDEN;
3012 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003013}
3014
3015/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003016 * Return TRUE if file "name" exists and is hidden.
3017 */
3018 int
3019mch_ishidden(char_u *name)
3020{
3021 int f = win32_getattrs(name);
3022
3023 if (f == -1)
3024 return FALSE; /* file does not exist at all */
3025
3026 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3027}
3028
3029/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003030 * return TRUE if "name" is a directory
3031 * return FALSE if "name" is not a directory or upon error
3032 */
3033 int
3034mch_isdir(char_u *name)
3035{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003036 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003037
3038 if (f == -1)
3039 return FALSE; /* file does not exist at all */
3040
3041 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3042}
3043
3044/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003045 * return TRUE if "name" is a directory, NOT a symlink to a directory
3046 * return FALSE if "name" is not a directory
3047 * return FALSE for error
3048 */
3049 int
3050mch_isrealdir(char_u *name)
3051{
3052 return mch_isdir(name) && !mch_is_symbolic_link(name);
3053}
3054
3055/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003056 * Create directory "name".
3057 * Return 0 on success, -1 on error.
3058 */
3059 int
3060mch_mkdir(char_u *name)
3061{
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003062 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3063 {
3064 WCHAR *p;
3065 int retval;
3066
3067 p = enc_to_utf16(name, NULL);
3068 if (p == NULL)
3069 return -1;
3070 retval = _wmkdir(p);
3071 vim_free(p);
3072 return retval;
3073 }
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003074 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003075}
3076
3077/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003078 * Delete directory "name".
3079 * Return 0 on success, -1 on error.
3080 */
3081 int
3082mch_rmdir(char_u *name)
3083{
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003084 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3085 {
3086 WCHAR *p;
3087 int retval;
3088
3089 p = enc_to_utf16(name, NULL);
3090 if (p == NULL)
3091 return -1;
3092 retval = _wrmdir(p);
3093 vim_free(p);
3094 return retval;
3095 }
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003096 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003097}
3098
3099/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003100 * Return TRUE if file "fname" has more than one link.
3101 */
3102 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003103mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003104{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003105 BY_HANDLE_FILE_INFORMATION info;
3106
3107 return win32_fileinfo(fname, &info) == FILEINFO_OK
3108 && info.nNumberOfLinks > 1;
3109}
3110
3111/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003112 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003113 */
3114 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003115mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003116{
3117 HANDLE hFind;
3118 int res = FALSE;
3119 WIN32_FIND_DATAA findDataA;
3120 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003121 WCHAR *wn = NULL;
3122 WIN32_FIND_DATAW findDataW;
3123
3124 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003125 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003126 if (wn != NULL)
3127 {
3128 hFind = FindFirstFileW(wn, &findDataW);
3129 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003130 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003131 {
3132 fileFlags = findDataW.dwFileAttributes;
3133 reparseTag = findDataW.dwReserved0;
3134 }
3135 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003136 else
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003137 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003138 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003139 if (hFind != INVALID_HANDLE_VALUE)
3140 {
3141 fileFlags = findDataA.dwFileAttributes;
3142 reparseTag = findDataA.dwReserved0;
3143 }
3144 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003145
3146 if (hFind != INVALID_HANDLE_VALUE)
3147 FindClose(hFind);
3148
3149 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003150 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3151 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003152 res = TRUE;
3153
3154 return res;
3155}
3156
3157/*
3158 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3159 * link.
3160 */
3161 int
3162mch_is_linked(char_u *fname)
3163{
3164 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3165 return TRUE;
3166 return FALSE;
3167}
3168
3169/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003170 * Get the by-handle-file-information for "fname".
3171 * Returns FILEINFO_OK when OK.
3172 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3173 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3174 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3175 */
3176 int
3177win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3178{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003179 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003180 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003181 WCHAR *wn = NULL;
3182
3183 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003184 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003185 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003186 if (wn == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003187 return FILEINFO_ENC_FAIL;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003188 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003189 if (wn != NULL)
3190 {
3191 hFile = CreateFileW(wn, /* file name */
3192 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003193 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003194 NULL, /* security descriptor */
3195 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003196 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003197 NULL); /* handle to template file */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003198 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003199 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003200 else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003201 hFile = CreateFile((LPCSTR)fname, /* file name */
3202 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003203 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003204 NULL, /* security descriptor */
3205 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003206 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003207 NULL); /* handle to template file */
3208
3209 if (hFile != INVALID_HANDLE_VALUE)
3210 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003211 if (GetFileInformationByHandle(hFile, info) != 0)
3212 res = FILEINFO_OK;
3213 else
3214 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003215 CloseHandle(hFile);
3216 }
3217
Bram Moolenaar03f48552006-02-28 23:52:23 +00003218 return res;
3219}
3220
3221/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003222 * get file attributes for `name'
3223 * -1 : error
3224 * else FILE_ATTRIBUTE_* defined in winnt.h
3225 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003226 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003227win32_getattrs(char_u *name)
3228{
3229 int attr;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003230 WCHAR *p = NULL;
3231
3232 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3233 p = enc_to_utf16(name, NULL);
3234
3235 if (p != NULL)
3236 {
3237 attr = GetFileAttributesW(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003238 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003239 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003240 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003241 attr = GetFileAttributes((char *)name);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003242
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003243 return attr;
3244}
3245
3246/*
3247 * set file attributes for `name' to `attrs'
3248 *
3249 * return -1 for failure, 0 otherwise
3250 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003251 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003252win32_setattrs(char_u *name, int attrs)
3253{
3254 int res;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003255 WCHAR *p = NULL;
3256
3257 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3258 p = enc_to_utf16(name, NULL);
3259
3260 if (p != NULL)
3261 {
3262 res = SetFileAttributesW(p, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003263 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003264 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003265 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003266 res = SetFileAttributes((char *)name, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003267
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003268 return res ? 0 : -1;
3269}
3270
3271/*
3272 * Set archive flag for "name".
3273 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003274 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003275win32_set_archive(char_u *name)
3276{
3277 int attrs = win32_getattrs(name);
3278 if (attrs == -1)
3279 return -1;
3280
3281 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3282 return win32_setattrs(name, attrs);
3283}
3284
3285/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003286 * Return TRUE if file or directory "name" is writable (not readonly).
3287 * Strange semantics of Win32: a readonly directory is writable, but you can't
3288 * delete a file. Let's say this means it is writable.
3289 */
3290 int
3291mch_writable(char_u *name)
3292{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003293 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003294
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003295 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3296 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003297}
3298
Bram Moolenaar071d4272004-06-13 20:20:40 +00003299/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003300 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003301 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003302 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3303 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003304 */
3305 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003306mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003307{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003308 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003309 int len = (int)STRLEN(name);
Bram Moolenaar82956662018-10-06 15:18:45 +02003310 char_u *p, *saved;
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003311
3312 if (len >= _MAX_PATH) /* safety check */
3313 return FALSE;
3314
Bram Moolenaar82956662018-10-06 15:18:45 +02003315 /* Ty using the name directly when a Unix-shell like 'shell'. */
3316 if (strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaar43663192017-03-05 14:29:12 +01003317 if (executable_exists((char *)name, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003318 return TRUE;
3319
3320 /*
3321 * Loop over all extensions in $PATHEXT.
3322 */
Bram Moolenaar82956662018-10-06 15:18:45 +02003323 p = mch_getenv("PATHEXT");
3324 if (p == NULL)
3325 p = (char_u *)".com;.exe;.bat;.cmd";
3326 saved = vim_strsave(p);
3327 if (saved == NULL)
3328 return FALSE;
3329 p = saved;
3330 while (*p)
3331 {
3332 char_u *tmp = vim_strchr(p, ';');
3333
3334 if (tmp != NULL)
3335 *tmp = NUL;
3336 if (_stricoll((char *)name + len - STRLEN(p), (char *)p) == 0
3337 && executable_exists((char *)name, path, use_path))
3338 {
3339 vim_free(saved);
3340 return TRUE;
3341 }
3342 if (tmp == NULL)
3343 break;
3344 p = tmp + 1;
3345 }
3346 vim_free(saved);
3347
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003348 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003349 p = mch_getenv("PATHEXT");
3350 if (p == NULL)
3351 p = (char_u *)".com;.exe;.bat;.cmd";
3352 while (*p)
3353 {
3354 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3355 {
3356 /* A single "." means no extension is added. */
3357 buf[len] = NUL;
3358 ++p;
3359 if (*p)
3360 ++p;
3361 }
3362 else
3363 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaar43663192017-03-05 14:29:12 +01003364 if (executable_exists((char *)buf, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003365 return TRUE;
3366 }
3367 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003368}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003369
3370/*
3371 * Check what "name" is:
3372 * NODE_NORMAL: file or directory (or doesn't exist)
3373 * NODE_WRITABLE: writable device, socket, fifo, etc.
3374 * NODE_OTHER: non-writable things
3375 */
3376 int
3377mch_nodetype(char_u *name)
3378{
3379 HANDLE hFile;
3380 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003381 WCHAR *wn = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003382
Bram Moolenaar043545e2006-10-10 16:44:07 +00003383 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3384 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3385 * here. */
3386 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3387 return NODE_WRITABLE;
3388
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003389 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003390 wn = enc_to_utf16(name, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003391
3392 if (wn != NULL)
3393 {
3394 hFile = CreateFileW(wn, /* file name */
3395 GENERIC_WRITE, /* access mode */
3396 0, /* share mode */
3397 NULL, /* security descriptor */
3398 OPEN_EXISTING, /* creation disposition */
3399 0, /* file attributes */
3400 NULL); /* handle to template file */
3401 vim_free(wn);
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003402 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003403 else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003404 hFile = CreateFile((LPCSTR)name, /* file name */
3405 GENERIC_WRITE, /* access mode */
3406 0, /* share mode */
3407 NULL, /* security descriptor */
3408 OPEN_EXISTING, /* creation disposition */
3409 0, /* file attributes */
3410 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003411
3412 if (hFile == INVALID_HANDLE_VALUE)
3413 return NODE_NORMAL;
3414
3415 type = GetFileType(hFile);
3416 CloseHandle(hFile);
3417 if (type == FILE_TYPE_CHAR)
3418 return NODE_WRITABLE;
3419 if (type == FILE_TYPE_DISK)
3420 return NODE_NORMAL;
3421 return NODE_OTHER;
3422}
3423
3424#ifdef HAVE_ACL
3425struct my_acl
3426{
3427 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3428 PSID pSidOwner;
3429 PSID pSidGroup;
3430 PACL pDacl;
3431 PACL pSacl;
3432};
3433#endif
3434
3435/*
3436 * Return a pointer to the ACL of file "fname" in allocated memory.
3437 * Return NULL if the ACL is not available for whatever reason.
3438 */
3439 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003440mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003441{
3442#ifndef HAVE_ACL
3443 return (vim_acl_T)NULL;
3444#else
3445 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003446 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003447
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003448 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3449 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003450 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003451 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003452
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003453 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3454 wn = enc_to_utf16(fname, NULL);
3455 if (wn != NULL)
3456 {
3457 /* Try to retrieve the entire security descriptor. */
3458 err = GetNamedSecurityInfoW(
3459 wn, // Abstract filename
3460 SE_FILE_OBJECT, // File Object
3461 OWNER_SECURITY_INFORMATION |
3462 GROUP_SECURITY_INFORMATION |
3463 DACL_SECURITY_INFORMATION |
3464 SACL_SECURITY_INFORMATION,
3465 &p->pSidOwner, // Ownership information.
3466 &p->pSidGroup, // Group membership.
3467 &p->pDacl, // Discretionary information.
3468 &p->pSacl, // For auditing purposes.
3469 &p->pSecurityDescriptor);
3470 if (err == ERROR_ACCESS_DENIED ||
3471 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003472 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003473 /* Retrieve only DACL. */
3474 (void)GetNamedSecurityInfoW(
3475 wn,
3476 SE_FILE_OBJECT,
3477 DACL_SECURITY_INFORMATION,
3478 NULL,
3479 NULL,
3480 &p->pDacl,
3481 NULL,
3482 &p->pSecurityDescriptor);
Bram Moolenaar27515922013-06-29 15:36:26 +02003483 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003484 if (p->pSecurityDescriptor == NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003485 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003486 mch_free_acl((vim_acl_T)p);
3487 p = NULL;
3488 }
3489 vim_free(wn);
3490 }
3491 else
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003492 {
3493 /* Try to retrieve the entire security descriptor. */
3494 err = GetNamedSecurityInfo(
3495 (LPSTR)fname, // Abstract filename
3496 SE_FILE_OBJECT, // File Object
3497 OWNER_SECURITY_INFORMATION |
3498 GROUP_SECURITY_INFORMATION |
3499 DACL_SECURITY_INFORMATION |
3500 SACL_SECURITY_INFORMATION,
3501 &p->pSidOwner, // Ownership information.
3502 &p->pSidGroup, // Group membership.
3503 &p->pDacl, // Discretionary information.
3504 &p->pSacl, // For auditing purposes.
3505 &p->pSecurityDescriptor);
3506 if (err == ERROR_ACCESS_DENIED ||
3507 err == ERROR_PRIVILEGE_NOT_HELD)
3508 {
3509 /* Retrieve only DACL. */
3510 (void)GetNamedSecurityInfo(
3511 (LPSTR)fname,
3512 SE_FILE_OBJECT,
3513 DACL_SECURITY_INFORMATION,
3514 NULL,
3515 NULL,
3516 &p->pDacl,
3517 NULL,
3518 &p->pSecurityDescriptor);
3519 }
3520 if (p->pSecurityDescriptor == NULL)
3521 {
3522 mch_free_acl((vim_acl_T)p);
3523 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003524 }
3525 }
3526 }
3527
3528 return (vim_acl_T)p;
3529#endif
3530}
3531
Bram Moolenaar27515922013-06-29 15:36:26 +02003532#ifdef HAVE_ACL
3533/*
3534 * Check if "acl" contains inherited ACE.
3535 */
3536 static BOOL
3537is_acl_inherited(PACL acl)
3538{
3539 DWORD i;
3540 ACL_SIZE_INFORMATION acl_info;
3541 PACCESS_ALLOWED_ACE ace;
3542
3543 acl_info.AceCount = 0;
3544 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3545 for (i = 0; i < acl_info.AceCount; i++)
3546 {
3547 GetAce(acl, i, (LPVOID *)&ace);
3548 if (ace->Header.AceFlags & INHERITED_ACE)
3549 return TRUE;
3550 }
3551 return FALSE;
3552}
3553#endif
3554
Bram Moolenaar071d4272004-06-13 20:20:40 +00003555/*
3556 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3557 * Errors are ignored.
3558 * This must only be called with "acl" equal to what mch_get_acl() returned.
3559 */
3560 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003561mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003562{
3563#ifdef HAVE_ACL
3564 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003565 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003566
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003567 if (p != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003568 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003569 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003570
3571 /* Set security flags */
3572 if (p->pSidOwner)
3573 sec_info |= OWNER_SECURITY_INFORMATION;
3574 if (p->pSidGroup)
3575 sec_info |= GROUP_SECURITY_INFORMATION;
3576 if (p->pDacl)
3577 {
3578 sec_info |= DACL_SECURITY_INFORMATION;
3579 /* Do not inherit its parent's DACL.
3580 * If the DACL is inherited, Cygwin permissions would be changed.
3581 */
3582 if (!is_acl_inherited(p->pDacl))
3583 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3584 }
3585 if (p->pSacl)
3586 sec_info |= SACL_SECURITY_INFORMATION;
3587
Bram Moolenaar27515922013-06-29 15:36:26 +02003588 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3589 wn = enc_to_utf16(fname, NULL);
3590 if (wn != NULL)
3591 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003592 (void)SetNamedSecurityInfoW(
Bram Moolenaar27515922013-06-29 15:36:26 +02003593 wn, // Abstract filename
3594 SE_FILE_OBJECT, // File Object
3595 sec_info,
3596 p->pSidOwner, // Ownership information.
3597 p->pSidGroup, // Group membership.
3598 p->pDacl, // Discretionary information.
3599 p->pSacl // For auditing purposes.
3600 );
3601 vim_free(wn);
3602 }
3603 else
Bram Moolenaar27515922013-06-29 15:36:26 +02003604 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003605 (void)SetNamedSecurityInfo(
Bram Moolenaar27515922013-06-29 15:36:26 +02003606 (LPSTR)fname, // Abstract filename
3607 SE_FILE_OBJECT, // File Object
3608 sec_info,
3609 p->pSidOwner, // Ownership information.
3610 p->pSidGroup, // Group membership.
3611 p->pDacl, // Discretionary information.
3612 p->pSacl // For auditing purposes.
3613 );
3614 }
3615 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003616#endif
3617}
3618
3619 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003620mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003621{
3622#ifdef HAVE_ACL
3623 struct my_acl *p = (struct my_acl *)acl;
3624
3625 if (p != NULL)
3626 {
3627 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3628 vim_free(p);
3629 }
3630#endif
3631}
3632
Bram Moolenaar4f974752019-02-17 17:44:42 +01003633#ifndef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003634
3635/*
3636 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3637 */
3638 static BOOL WINAPI
3639handler_routine(
3640 DWORD dwCtrlType)
3641{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003642 INPUT_RECORD ir;
3643 DWORD out;
3644
Bram Moolenaar071d4272004-06-13 20:20:40 +00003645 switch (dwCtrlType)
3646 {
3647 case CTRL_C_EVENT:
3648 if (ctrl_c_interrupts)
3649 g_fCtrlCPressed = TRUE;
3650 return TRUE;
3651
3652 case CTRL_BREAK_EVENT:
3653 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003654 ctrl_break_was_pressed = TRUE;
3655 /* ReadConsoleInput is blocking, send a key event to continue. */
3656 ir.EventType = KEY_EVENT;
3657 ir.Event.KeyEvent.bKeyDown = TRUE;
3658 ir.Event.KeyEvent.wRepeatCount = 1;
3659 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3660 ir.Event.KeyEvent.wVirtualScanCode = 0;
3661 ir.Event.KeyEvent.dwControlKeyState = 0;
3662 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3663 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003664 return TRUE;
3665
3666 /* fatal events: shut down gracefully */
3667 case CTRL_CLOSE_EVENT:
3668 case CTRL_LOGOFF_EVENT:
3669 case CTRL_SHUTDOWN_EVENT:
3670 windgoto((int)Rows - 1, 0);
3671 g_fForceExit = TRUE;
3672
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003673 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003674 (dwCtrlType == CTRL_CLOSE_EVENT
3675 ? _("close")
3676 : dwCtrlType == CTRL_LOGOFF_EVENT
3677 ? _("logoff")
3678 : _("shutdown")));
3679#ifdef DEBUG
3680 OutputDebugString(IObuff);
3681#endif
3682
3683 preserve_exit(); /* output IObuff, preserve files and exit */
3684
3685 return TRUE; /* not reached */
3686
3687 default:
3688 return FALSE;
3689 }
3690}
3691
3692
3693/*
3694 * set the tty in (raw) ? "raw" : "cooked" mode
3695 */
3696 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003697mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003698{
3699 DWORD cmodein;
3700 DWORD cmodeout;
3701 BOOL bEnableHandler;
3702
3703 GetConsoleMode(g_hConIn, &cmodein);
3704 GetConsoleMode(g_hConOut, &cmodeout);
3705 if (tmode == TMODE_RAW)
3706 {
3707 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3708 ENABLE_ECHO_INPUT);
3709#ifdef FEAT_MOUSE
3710 if (g_fMouseActive)
3711 cmodein |= ENABLE_MOUSE_INPUT;
3712#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003713 cmodeout &= ~(
3714#ifdef FEAT_TERMGUICOLORS
3715 /* Do not turn off the ENABLE_PROCESSRD_OUTPUT flag when using
3716 * VTP. */
3717 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
3718#else
3719 ENABLE_PROCESSED_OUTPUT |
3720#endif
3721 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003722 bEnableHandler = TRUE;
3723 }
3724 else /* cooked */
3725 {
3726 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3727 ENABLE_ECHO_INPUT);
3728 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3729 bEnableHandler = FALSE;
3730 }
3731 SetConsoleMode(g_hConIn, cmodein);
3732 SetConsoleMode(g_hConOut, cmodeout);
3733 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3734
3735#ifdef MCH_WRITE_DUMP
3736 if (fdDump)
3737 {
3738 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3739 tmode == TMODE_RAW ? "raw" :
3740 tmode == TMODE_COOK ? "cooked" : "normal",
3741 cmodein, cmodeout);
3742 fflush(fdDump);
3743 }
3744#endif
3745}
3746
3747
3748/*
3749 * Get the size of the current window in `Rows' and `Columns'
3750 * Return OK when size could be determined, FAIL otherwise.
3751 */
3752 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003753mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003754{
3755 CONSOLE_SCREEN_BUFFER_INFO csbi;
3756
3757 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3758 {
3759 /*
3760 * For some reason, we are trying to get the screen dimensions
3761 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3762 * variables are really intended to mean the size of Vim screen
3763 * while in termcap mode.
3764 */
3765 Rows = g_cbTermcap.Info.dwSize.Y;
3766 Columns = g_cbTermcap.Info.dwSize.X;
3767 }
3768 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3769 {
3770 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3771 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3772 }
3773 else
3774 {
3775 Rows = 25;
3776 Columns = 80;
3777 }
3778 return OK;
3779}
3780
3781/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003782 * Resize console buffer to 'COORD'
3783 */
3784 static void
3785ResizeConBuf(
3786 HANDLE hConsole,
3787 COORD coordScreen)
3788{
3789 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3790 {
3791#ifdef MCH_WRITE_DUMP
3792 if (fdDump)
3793 {
3794 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3795 GetLastError());
3796 fflush(fdDump);
3797 }
3798#endif
3799 }
3800}
3801
3802/*
3803 * Resize console window size to 'srWindowRect'
3804 */
3805 static void
3806ResizeWindow(
3807 HANDLE hConsole,
3808 SMALL_RECT srWindowRect)
3809{
3810 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
3811 {
3812#ifdef MCH_WRITE_DUMP
3813 if (fdDump)
3814 {
3815 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3816 GetLastError());
3817 fflush(fdDump);
3818 }
3819#endif
3820 }
3821}
3822
3823/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003824 * Set a console window to `xSize' * `ySize'
3825 */
3826 static void
3827ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003828 HANDLE hConsole,
3829 int xSize,
3830 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003831{
3832 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3833 SMALL_RECT srWindowRect; /* hold the new console size */
3834 COORD coordScreen;
Bram Moolenaar2551c032018-08-23 22:38:31 +02003835 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003836
3837#ifdef MCH_WRITE_DUMP
3838 if (fdDump)
3839 {
3840 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3841 fflush(fdDump);
3842 }
3843#endif
3844
3845 /* get the largest size we can size the console window to */
3846 coordScreen = GetLargestConsoleWindowSize(hConsole);
3847
3848 /* define the new console window size and scroll position */
3849 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3850 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3851 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3852
3853 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3854 {
3855 int sx, sy;
3856
3857 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3858 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3859 if (sy < ySize || sx < xSize)
3860 {
3861 /*
3862 * Increasing number of lines/columns, do buffer first.
3863 * Use the maximal size in x and y direction.
3864 */
3865 if (sy < ySize)
3866 coordScreen.Y = ySize;
3867 else
3868 coordScreen.Y = sy;
3869 if (sx < xSize)
3870 coordScreen.X = xSize;
3871 else
3872 coordScreen.X = sx;
3873 SetConsoleScreenBufferSize(hConsole, coordScreen);
3874 }
3875 }
3876
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003877 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003878 coordScreen.X = xSize;
3879 coordScreen.Y = ySize;
3880
Bram Moolenaar2551c032018-08-23 22:38:31 +02003881 // In the new console call API, only the first time in reverse order
3882 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003883 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003884 ResizeWindow(hConsole, srWindowRect);
3885 ResizeConBuf(hConsole, coordScreen);
3886 }
3887 else
3888 {
3889 ResizeConBuf(hConsole, coordScreen);
3890 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02003891 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003892 }
3893}
3894
3895
3896/*
3897 * Set the console window to `Rows' * `Columns'
3898 */
3899 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003900mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003901{
3902 COORD coordScreen;
3903
3904 /* Don't change window size while still starting up */
3905 if (suppress_winsize != 0)
3906 {
3907 suppress_winsize = 2;
3908 return;
3909 }
3910
3911 if (term_console)
3912 {
3913 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3914
3915 /* Clamp Rows and Columns to reasonable values */
3916 if (Rows > coordScreen.Y)
3917 Rows = coordScreen.Y;
3918 if (Columns > coordScreen.X)
3919 Columns = coordScreen.X;
3920
3921 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3922 }
3923}
3924
3925/*
3926 * Rows and/or Columns has changed.
3927 */
3928 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003929mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003930{
3931 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3932}
3933
3934
3935/*
3936 * Called when started up, to set the winsize that was delayed.
3937 */
3938 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003939mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003940{
3941 if (suppress_winsize == 2)
3942 {
3943 suppress_winsize = 0;
3944 mch_set_shellsize();
3945 shell_resized();
3946 }
3947 suppress_winsize = 0;
3948}
Bram Moolenaar4f974752019-02-17 17:44:42 +01003949#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003950
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003951 static BOOL
3952vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003953 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003954 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01003955 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003956 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003957 PROCESS_INFORMATION *pi,
3958 LPVOID *env,
3959 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003960{
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003961 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3962 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003963 BOOL ret;
3964 WCHAR *wcmd, *wcwd = NULL;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003965
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003966 wcmd = enc_to_utf16((char_u *)cmd, NULL);
3967 if (wcmd == NULL)
3968 goto fallback;
3969 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003970 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003971 wcwd = enc_to_utf16((char_u *)cwd, NULL);
3972 if (wcwd == NULL)
3973 {
3974 vim_free(wcmd);
3975 goto fallback;
3976 }
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003977 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003978
3979 ret = CreateProcessW(
3980 NULL, /* Executable name */
3981 wcmd, /* Command to execute */
3982 NULL, /* Process security attributes */
3983 NULL, /* Thread security attributes */
3984 inherit_handles, /* Inherit handles */
3985 flags, /* Creation flags */
3986 env, /* Environment */
3987 wcwd, /* Current directory */
3988 (LPSTARTUPINFOW)si, /* Startup information */
3989 pi); /* Process information */
3990 vim_free(wcmd);
Bram Moolenaarbdace832019-03-02 10:13:42 +01003991 vim_free(wcwd);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003992 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003993 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003994fallback:
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003995 return CreateProcess(
3996 NULL, /* Executable name */
3997 cmd, /* Command to execute */
3998 NULL, /* Process security attributes */
3999 NULL, /* Thread security attributes */
4000 inherit_handles, /* Inherit handles */
4001 flags, /* Creation flags */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004002 env, /* Environment */
4003 cwd, /* Current directory */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004004 si, /* Startup information */
4005 pi); /* Process information */
4006}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004007
4008
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004009 static HINSTANCE
4010vim_shell_execute(
4011 char *cmd,
4012 INT n_show_cmd)
4013{
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004014 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4015 {
4016 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
4017 if (wcmd != NULL)
4018 {
4019 HINSTANCE ret;
4020 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4021 vim_free(wcmd);
4022 return ret;
4023 }
4024 }
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004025 return ShellExecute(NULL, NULL, cmd, NULL, NULL, n_show_cmd);
4026}
4027
4028
Bram Moolenaar4f974752019-02-17 17:44:42 +01004029#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004030
4031/*
4032 * Specialised version of system() for Win32 GUI mode.
4033 * This version proceeds as follows:
4034 * 1. Create a console window for use by the subprocess
4035 * 2. Run the subprocess (it gets the allocated console by default)
4036 * 3. Wait for the subprocess to terminate and get its exit code
4037 * 4. Prompt the user to press a key to close the console window
4038 */
4039 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004040mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004041{
4042 STARTUPINFO si;
4043 PROCESS_INFORMATION pi;
4044 DWORD ret = 0;
4045 HWND hwnd = GetFocus();
4046
4047 si.cb = sizeof(si);
4048 si.lpReserved = NULL;
4049 si.lpDesktop = NULL;
4050 si.lpTitle = NULL;
4051 si.dwFlags = STARTF_USESHOWWINDOW;
4052 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004053 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004054 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004055 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004056 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004057 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004058 else
4059 si.wShowWindow = SW_SHOWNORMAL;
4060 si.cbReserved2 = 0;
4061 si.lpReserved2 = NULL;
4062
Bram Moolenaar071d4272004-06-13 20:20:40 +00004063 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004064 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004065 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4066 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004067
4068 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004069 {
4070#ifdef FEAT_GUI
4071 int delay = 1;
4072
4073 /* Keep updating the window while waiting for the shell to finish. */
4074 for (;;)
4075 {
4076 MSG msg;
4077
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004078 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004079 {
4080 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004081 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004082 delay = 1;
4083 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004084 }
4085 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4086 break;
4087
4088 /* We start waiting for a very short time and then increase it, so
4089 * that we respond quickly when the process is quick, and don't
4090 * consume too much overhead when it's slow. */
4091 if (delay < 50)
4092 delay += 10;
4093 }
4094#else
4095 WaitForSingleObject(pi.hProcess, INFINITE);
4096#endif
4097
4098 /* Get the command exit code */
4099 GetExitCodeProcess(pi.hProcess, &ret);
4100 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004101
4102 /* Close the handles to the subprocess, so that it goes away */
4103 CloseHandle(pi.hThread);
4104 CloseHandle(pi.hProcess);
4105
4106 /* Try to get input focus back. Doesn't always work though. */
4107 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4108
4109 return ret;
4110}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004111
4112/*
4113 * Thread launched by the gui to send the current buffer data to the
4114 * process. This way avoid to hang up vim totally if the children
4115 * process take a long time to process the lines.
4116 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004117 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004118sub_process_writer(LPVOID param)
4119{
4120 HANDLE g_hChildStd_IN_Wr = param;
4121 linenr_T lnum = curbuf->b_op_start.lnum;
4122 DWORD len = 0;
4123 DWORD l;
4124 char_u *lp = ml_get(lnum);
4125 char_u *s;
4126 int written = 0;
4127
4128 for (;;)
4129 {
4130 l = (DWORD)STRLEN(lp + written);
4131 if (l == 0)
4132 len = 0;
4133 else if (lp[written] == NL)
4134 {
4135 /* NL -> NUL translation */
4136 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4137 }
4138 else
4139 {
4140 s = vim_strchr(lp + written, NL);
4141 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4142 s == NULL ? l : (DWORD)(s - (lp + written)),
4143 &len, NULL);
4144 }
4145 if (len == (int)l)
4146 {
4147 /* Finished a line, add a NL, unless this line should not have
4148 * one. */
4149 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004150 || (!curbuf->b_p_bin
4151 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004152 || (lnum != curbuf->b_no_eol_lnum
4153 && (lnum != curbuf->b_ml.ml_line_count
4154 || curbuf->b_p_eol)))
4155 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004156 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4157 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004158 }
4159
4160 ++lnum;
4161 if (lnum > curbuf->b_op_end.lnum)
4162 break;
4163
4164 lp = ml_get(lnum);
4165 written = 0;
4166 }
4167 else if (len > 0)
4168 written += len;
4169 }
4170
4171 /* finished all the lines, close pipe */
4172 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004173 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004174}
4175
4176
4177# define BUFLEN 100 /* length for buffer, stolen from unix version */
4178
4179/*
4180 * This function read from the children's stdout and write the
4181 * data on screen or in the buffer accordingly.
4182 */
4183 static void
4184dump_pipe(int options,
4185 HANDLE g_hChildStd_OUT_Rd,
4186 garray_T *ga,
4187 char_u buffer[],
4188 DWORD *buffer_off)
4189{
4190 DWORD availableBytes = 0;
4191 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004192 int ret;
4193 DWORD len;
4194 DWORD toRead;
4195 int repeatCount;
4196
4197 /* we query the pipe to see if there is any data to read
4198 * to avoid to perform a blocking read */
4199 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4200 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004201 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004202 NULL, /* number of read bytes */
4203 &availableBytes, /* available bytes total */
4204 NULL); /* byteLeft */
4205
4206 repeatCount = 0;
4207 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004208 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004209 {
4210 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004211 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004212 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004213 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004214
4215 /* If we haven't read anything, there is a problem */
4216 if (len == 0)
4217 break;
4218
4219 availableBytes -= len;
4220
4221 if (options & SHELL_READ)
4222 {
4223 /* Do NUL -> NL translation, append NL separated
4224 * lines to the current buffer. */
4225 for (i = 0; i < len; ++i)
4226 {
4227 if (buffer[i] == NL)
4228 append_ga_line(ga);
4229 else if (buffer[i] == NUL)
4230 ga_append(ga, NL);
4231 else
4232 ga_append(ga, buffer[i]);
4233 }
4234 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004235 else if (has_mbyte)
4236 {
4237 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004238 int c;
4239 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004240
4241 len += *buffer_off;
4242 buffer[len] = NUL;
4243
4244 /* Check if the last character in buffer[] is
4245 * incomplete, keep these bytes for the next
4246 * round. */
4247 for (p = buffer; p < buffer + len; p += l)
4248 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004249 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004250 if (l == 0)
4251 l = 1; /* NUL byte? */
4252 else if (MB_BYTE2LEN(*p) != l)
4253 break;
4254 }
4255 if (p == buffer) /* no complete character */
4256 {
4257 /* avoid getting stuck at an illegal byte */
4258 if (len >= 12)
4259 ++p;
4260 else
4261 {
4262 *buffer_off = len;
4263 return;
4264 }
4265 }
4266 c = *p;
4267 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004268 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004269 if (p < buffer + len)
4270 {
4271 *p = c;
4272 *buffer_off = (DWORD)((buffer + len) - p);
4273 mch_memmove(buffer, p, *buffer_off);
4274 return;
4275 }
4276 *buffer_off = 0;
4277 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004278 else
4279 {
4280 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004281 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004282 }
4283
4284 windgoto(msg_row, msg_col);
4285 cursor_on();
4286 out_flush();
4287 }
4288}
4289
4290/*
4291 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4292 * for communication and doesn't open any new window.
4293 */
4294 static int
4295mch_system_piped(char *cmd, int options)
4296{
4297 STARTUPINFO si;
4298 PROCESS_INFORMATION pi;
4299 DWORD ret = 0;
4300
4301 HANDLE g_hChildStd_IN_Rd = NULL;
4302 HANDLE g_hChildStd_IN_Wr = NULL;
4303 HANDLE g_hChildStd_OUT_Rd = NULL;
4304 HANDLE g_hChildStd_OUT_Wr = NULL;
4305
4306 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4307 DWORD len;
4308
4309 /* buffer used to receive keys */
4310 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4311 int ta_len = 0; /* valid bytes in ta_buf[] */
4312
4313 DWORD i;
4314 int c;
4315 int noread_cnt = 0;
4316 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004317 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004318 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004319 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004320
4321 SECURITY_ATTRIBUTES saAttr;
4322
4323 /* Set the bInheritHandle flag so pipe handles are inherited. */
4324 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4325 saAttr.bInheritHandle = TRUE;
4326 saAttr.lpSecurityDescriptor = NULL;
4327
4328 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4329 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004330 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004331 /* Create a pipe for the child process's STDIN. */
4332 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4333 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004334 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004335 {
4336 CloseHandle(g_hChildStd_IN_Rd);
4337 CloseHandle(g_hChildStd_IN_Wr);
4338 CloseHandle(g_hChildStd_OUT_Rd);
4339 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004340 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004341 }
4342
4343 si.cb = sizeof(si);
4344 si.lpReserved = NULL;
4345 si.lpDesktop = NULL;
4346 si.lpTitle = NULL;
4347 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4348
4349 /* set-up our file redirection */
4350 si.hStdError = g_hChildStd_OUT_Wr;
4351 si.hStdOutput = g_hChildStd_OUT_Wr;
4352 si.hStdInput = g_hChildStd_IN_Rd;
4353 si.wShowWindow = SW_HIDE;
4354 si.cbReserved2 = 0;
4355 si.lpReserved2 = NULL;
4356
4357 if (options & SHELL_READ)
4358 ga_init2(&ga, 1, BUFLEN);
4359
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004360 if (cmd != NULL)
4361 {
4362 p = (char *)vim_strsave((char_u *)cmd);
4363 if (p != NULL)
4364 unescape_shellxquote((char_u *)p, p_sxe);
4365 else
4366 p = cmd;
4367 }
4368
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004369 /* Now, run the command.
4370 * About "Inherit handles" being TRUE: this command can be litigious,
4371 * handle inheritance was deactivated for pending temp file, but, if we
4372 * deactivate it, the pipes don't work for some reason. */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004373 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4374 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004375
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004376 if (p != cmd)
4377 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004378
4379 /* Close our unused side of the pipes */
4380 CloseHandle(g_hChildStd_IN_Rd);
4381 CloseHandle(g_hChildStd_OUT_Wr);
4382
4383 if (options & SHELL_WRITE)
4384 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004385 HANDLE thread = (HANDLE)
4386 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004387 0, /* default stack size */
4388 sub_process_writer, /* function to be executed */
4389 g_hChildStd_IN_Wr, /* parameter */
4390 0, /* creation flag, start immediately */
4391 NULL); /* we don't care about thread id */
4392 CloseHandle(thread);
4393 g_hChildStd_IN_Wr = NULL;
4394 }
4395
4396 /* Keep updating the window while waiting for the shell to finish. */
4397 for (;;)
4398 {
4399 MSG msg;
4400
Bram Moolenaar175d0702013-12-11 18:36:33 +01004401 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004402 {
4403 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004404 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004405 }
4406
4407 /* write pipe information in the window */
4408 if ((options & (SHELL_READ|SHELL_WRITE))
4409# ifdef FEAT_GUI
4410 || gui.in_use
4411# endif
4412 )
4413 {
4414 len = 0;
4415 if (!(options & SHELL_EXPAND)
4416 && ((options &
4417 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4418 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4419# ifdef FEAT_GUI
4420 || gui.in_use
4421# endif
4422 )
4423 && (ta_len > 0 || noread_cnt > 4))
4424 {
4425 if (ta_len == 0)
4426 {
4427 /* Get extra characters when we don't have any. Reset the
4428 * counter and timer. */
4429 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004430 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4431 }
4432 if (ta_len > 0 || len > 0)
4433 {
4434 /*
4435 * For pipes: Check for CTRL-C: send interrupt signal to
4436 * child. Check for CTRL-D: EOF, close pipe to child.
4437 */
4438 if (len == 1 && cmd != NULL)
4439 {
4440 if (ta_buf[ta_len] == Ctrl_C)
4441 {
4442 /* Learn what exit code is expected, for
4443 * now put 9 as SIGKILL */
4444 TerminateProcess(pi.hProcess, 9);
4445 }
4446 if (ta_buf[ta_len] == Ctrl_D)
4447 {
4448 CloseHandle(g_hChildStd_IN_Wr);
4449 g_hChildStd_IN_Wr = NULL;
4450 }
4451 }
4452
4453 /* replace K_BS by <BS> and K_DEL by <DEL> */
4454 for (i = ta_len; i < ta_len + len; ++i)
4455 {
4456 if (ta_buf[i] == CSI && len - i > 2)
4457 {
4458 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4459 if (c == K_DEL || c == K_KDEL || c == K_BS)
4460 {
4461 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4462 (size_t)(len - i - 2));
4463 if (c == K_DEL || c == K_KDEL)
4464 ta_buf[i] = DEL;
4465 else
4466 ta_buf[i] = Ctrl_H;
4467 len -= 2;
4468 }
4469 }
4470 else if (ta_buf[i] == '\r')
4471 ta_buf[i] = '\n';
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004472 if (has_mbyte)
4473 i += (*mb_ptr2len_len)(ta_buf + i,
4474 ta_len + len - i) - 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004475 }
4476
4477 /*
4478 * For pipes: echo the typed characters. For a pty this
4479 * does not seem to work.
4480 */
4481 for (i = ta_len; i < ta_len + len; ++i)
4482 {
4483 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4484 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004485 else if (has_mbyte)
4486 {
4487 int l = (*mb_ptr2len)(ta_buf + i);
4488
4489 msg_outtrans_len(ta_buf + i, l);
4490 i += l - 1;
4491 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004492 else
4493 msg_outtrans_len(ta_buf + i, 1);
4494 }
4495 windgoto(msg_row, msg_col);
4496 out_flush();
4497
4498 ta_len += len;
4499
4500 /*
4501 * Write the characters to the child, unless EOF has been
4502 * typed for pipes. Write one character at a time, to
4503 * avoid losing too much typeahead. When writing buffer
4504 * lines, drop the typed characters (only check for
4505 * CTRL-C).
4506 */
4507 if (options & SHELL_WRITE)
4508 ta_len = 0;
4509 else if (g_hChildStd_IN_Wr != NULL)
4510 {
4511 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4512 1, &len, NULL);
4513 // if we are typing in, we want to keep things reactive
4514 delay = 1;
4515 if (len > 0)
4516 {
4517 ta_len -= len;
4518 mch_memmove(ta_buf, ta_buf + len, ta_len);
4519 }
4520 }
4521 }
4522 }
4523 }
4524
4525 if (ta_len)
4526 ui_inchar_undo(ta_buf, ta_len);
4527
4528 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4529 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004530 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004531 break;
4532 }
4533
4534 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004535 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004536
4537 /* We start waiting for a very short time and then increase it, so
4538 * that we respond quickly when the process is quick, and don't
4539 * consume too much overhead when it's slow. */
4540 if (delay < 50)
4541 delay += 10;
4542 }
4543
4544 /* Close the pipe */
4545 CloseHandle(g_hChildStd_OUT_Rd);
4546 if (g_hChildStd_IN_Wr != NULL)
4547 CloseHandle(g_hChildStd_IN_Wr);
4548
4549 WaitForSingleObject(pi.hProcess, INFINITE);
4550
4551 /* Get the command exit code */
4552 GetExitCodeProcess(pi.hProcess, &ret);
4553
4554 if (options & SHELL_READ)
4555 {
4556 if (ga.ga_len > 0)
4557 {
4558 append_ga_line(&ga);
4559 /* remember that the NL was missing */
4560 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4561 }
4562 else
4563 curbuf->b_no_eol_lnum = 0;
4564 ga_clear(&ga);
4565 }
4566
4567 /* Close the handles to the subprocess, so that it goes away */
4568 CloseHandle(pi.hThread);
4569 CloseHandle(pi.hProcess);
4570
4571 return ret;
4572}
4573
4574 static int
4575mch_system(char *cmd, int options)
4576{
4577 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004578 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004579 return mch_system_piped(cmd, options);
4580 else
4581 return mch_system_classic(cmd, options);
4582}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004583#else
4584
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004585 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004586mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004587{
4588 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4589 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004590 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004591 if (wcmd != NULL)
4592 {
4593 int ret = _wsystem(wcmd);
4594 vim_free(wcmd);
4595 return ret;
4596 }
4597 }
4598 return system(cmd);
4599}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004600
4601#endif
4602
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004603#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4604/*
4605 * Use a terminal window to run a shell command in.
4606 */
4607 static int
4608mch_call_shell_terminal(
4609 char_u *cmd,
4610 int options UNUSED) /* SHELL_*, see vim.h */
4611{
4612 jobopt_T opt;
4613 char_u *newcmd = NULL;
4614 typval_T argvar[2];
4615 long_u cmdlen;
4616 int retval = -1;
4617 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004618 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004619 aco_save_T aco;
4620 oparg_T oa; /* operator arguments */
4621
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004622 if (cmd == NULL)
4623 cmdlen = STRLEN(p_sh) + 1;
4624 else
4625 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004626 newcmd = lalloc(cmdlen, TRUE);
4627 if (newcmd == NULL)
4628 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004629 if (cmd == NULL)
4630 {
4631 STRCPY(newcmd, p_sh);
4632 ch_log(NULL, "starting terminal to run a shell");
4633 }
4634 else
4635 {
4636 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4637 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4638 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004639
4640 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004641
4642 argvar[0].v_type = VAR_STRING;
4643 argvar[0].vval.v_string = newcmd;
4644 argvar[1].v_type = VAR_UNKNOWN;
4645 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004646 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004647 {
4648 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004649 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004650 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004651
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004652 job = term_getjob(buf->b_term);
4653 ++job->jv_refcount;
4654
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004655 /* Find a window to make "buf" curbuf. */
4656 aucmd_prepbuf(&aco, buf);
4657
4658 clear_oparg(&oa);
4659 while (term_use_loop())
4660 {
4661 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4662 {
4663 /* If terminal_loop() returns OK we got a key that is handled
4664 * in Normal model. We don't do redrawing anyway. */
4665 if (terminal_loop(TRUE) == OK)
4666 normal_cmd(&oa, TRUE);
4667 }
4668 else
4669 normal_cmd(&oa, TRUE);
4670 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004671 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004672 ch_log(NULL, "system command finished");
4673
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004674 job_unref(job);
4675
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004676 /* restore curwin/curbuf and a few other things */
4677 aucmd_restbuf(&aco);
4678
4679 wait_return(TRUE);
4680 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4681
4682 vim_free(newcmd);
4683 return retval;
4684}
4685#endif
4686
Bram Moolenaar071d4272004-06-13 20:20:40 +00004687/*
4688 * Either execute a command by calling the shell or start a new shell
4689 */
4690 int
4691mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004692 char_u *cmd,
4693 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004694{
4695 int x = 0;
4696 int tmode = cur_tmode;
4697#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004698 char szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004699 int did_set_title = FALSE;
4700
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004701 /* Change the title to reflect that we are in a subshell. */
4702 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4703 {
4704 WCHAR szShellTitle[512];
4705
4706 if (GetConsoleTitleW(szShellTitle,
4707 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4708 {
4709 if (cmd == NULL)
4710 wcscat(szShellTitle, L" :sh");
4711 else
4712 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004713 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004714
4715 if (wn != NULL)
4716 {
4717 wcscat(szShellTitle, L" - !");
4718 if ((wcslen(szShellTitle) + wcslen(wn) <
4719 sizeof(szShellTitle)/sizeof(WCHAR)))
4720 wcscat(szShellTitle, wn);
4721 SetConsoleTitleW(szShellTitle);
4722 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004723 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004724 }
4725 }
4726 }
4727 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004728 if (!did_set_title)
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004729 /* Change the title to reflect that we are in a subshell. */
4730 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004731 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004732 if (cmd == NULL)
4733 strcat(szShellTitle, " :sh");
4734 else
4735 {
4736 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004737 if ((strlen(szShellTitle) + strlen((char *)cmd)
4738 < sizeof(szShellTitle)))
4739 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004740 }
4741 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004742 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004743#endif
4744
4745 out_flush();
4746
4747#ifdef MCH_WRITE_DUMP
4748 if (fdDump)
4749 {
4750 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4751 fflush(fdDump);
4752 }
4753#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004754#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4755 /* TODO: make the terminal window work with input or output redirected. */
4756 if (vim_strchr(p_go, GO_TERMINAL) != NULL
4757 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4758 {
4759 /* Use a terminal window to run the command in. */
4760 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004761# ifdef FEAT_TITLE
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004762 resettitle();
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004763# endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004764 return x;
4765 }
4766#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004767
4768 /*
4769 * Catch all deadly signals while running the external command, because a
4770 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4771 */
4772 signal(SIGINT, SIG_IGN);
4773#if defined(__GNUC__) && !defined(__MINGW32__)
4774 signal(SIGKILL, SIG_IGN);
4775#else
4776 signal(SIGBREAK, SIG_IGN);
4777#endif
4778 signal(SIGILL, SIG_IGN);
4779 signal(SIGFPE, SIG_IGN);
4780 signal(SIGSEGV, SIG_IGN);
4781 signal(SIGTERM, SIG_IGN);
4782 signal(SIGABRT, SIG_IGN);
4783
4784 if (options & SHELL_COOKED)
4785 settmode(TMODE_COOK); /* set to normal mode */
4786
4787 if (cmd == NULL)
4788 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004789 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004790 }
4791 else
4792 {
4793 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004794 char_u *newcmd = NULL;
4795 char_u *cmdbase = cmd;
4796 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004797
4798 /* Skip a leading ", ( and "(. */
4799 if (*cmdbase == '"' )
4800 ++cmdbase;
4801 if (*cmdbase == '(')
4802 ++cmdbase;
4803
Bram Moolenaar1c465442017-03-12 20:10:05 +01004804 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004805 {
4806 STARTUPINFO si;
4807 PROCESS_INFORMATION pi;
4808 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004809 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004810 char_u *p;
4811
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004812 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004813 si.cb = sizeof(si);
4814 si.lpReserved = NULL;
4815 si.lpDesktop = NULL;
4816 si.lpTitle = NULL;
4817 si.dwFlags = 0;
4818 si.cbReserved2 = 0;
4819 si.lpReserved2 = NULL;
4820
4821 cmdbase = skipwhite(cmdbase + 5);
4822 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004823 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004824 {
4825 cmdbase = skipwhite(cmdbase + 4);
4826 si.dwFlags = STARTF_USESHOWWINDOW;
4827 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004828 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004829 }
4830 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004831 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004832 {
4833 cmdbase = skipwhite(cmdbase + 2);
4834 flags = CREATE_NO_WINDOW;
4835 si.dwFlags = STARTF_USESTDHANDLES;
4836 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004837 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004838 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004839 NULL, // Security att.
4840 OPEN_EXISTING, // Open flags
4841 FILE_ATTRIBUTE_NORMAL, // File att.
4842 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004843 si.hStdOutput = si.hStdInput;
4844 si.hStdError = si.hStdInput;
4845 }
4846
4847 /* Remove a trailing ", ) and )" if they have a match
4848 * at the start of the command. */
4849 if (cmdbase > cmd)
4850 {
4851 p = cmdbase + STRLEN(cmdbase);
4852 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4853 *--p = NUL;
4854 if (p > cmdbase && p[-1] == ')'
4855 && (*cmd =='(' || cmd[1] == '('))
4856 *--p = NUL;
4857 }
4858
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004859 newcmd = cmdbase;
4860 unescape_shellxquote(cmdbase, p_sxe);
4861
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004862 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004863 * If creating new console, arguments are passed to the
4864 * 'cmd.exe' as-is. If it's not, arguments are not treated
4865 * correctly for current 'cmd.exe'. So unescape characters in
4866 * shellxescape except '|' for avoiding to be treated as
4867 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004868 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004869 if (flags != CREATE_NEW_CONSOLE)
4870 {
4871 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004872 char_u *cmd_shell = mch_getenv("COMSPEC");
4873
4874 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004875 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004876
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004877 subcmd = vim_strsave_escaped_ext(cmdbase,
4878 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004879 if (subcmd != NULL)
4880 {
4881 /* make "cmd.exe /c arguments" */
4882 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004883 newcmd = lalloc(cmdlen, TRUE);
4884 if (newcmd != NULL)
4885 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004886 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004887 else
4888 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004889 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004890 }
4891 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004892
4893 /*
4894 * Now, start the command as a process, so that it doesn't
4895 * inherit our handles which causes unpleasant dangling swap
4896 * files if we exit before the spawned process
4897 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004898 if (vim_create_process((char *)newcmd, FALSE, flags,
4899 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004900 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004901 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4902 > (HINSTANCE)32)
4903 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004904 else
4905 {
4906 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01004907#ifdef FEAT_GUI_MSWIN
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004908 emsg(_("E371: Command not found"));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004909#endif
4910 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004911
4912 if (newcmd != cmdbase)
4913 vim_free(newcmd);
4914
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004915 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004916 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004917 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004918 CloseHandle(si.hStdInput);
4919 }
4920 /* Close the handles to the subprocess, so that it goes away */
4921 CloseHandle(pi.hThread);
4922 CloseHandle(pi.hProcess);
4923 }
4924 else
4925 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004926 cmdlen = (
Bram Moolenaar4f974752019-02-17 17:44:42 +01004927#ifdef FEAT_GUI_MSWIN
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004928 (!p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004929#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004930 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4931
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004932 newcmd = lalloc(cmdlen, TRUE);
4933 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004934 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01004935#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004936 if (need_vimrun_warning)
4937 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01004938 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
4939 "External commands will not pause after completion.\n"
4940 "See :help win32-vimrun for more information.");
4941 char *title = _("Vim Warning");
Bram Moolenaar63e43442016-11-19 17:28:44 +01004942 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4943 {
4944 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
4945 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
4946
4947 if (wmsg != NULL && wtitle != NULL)
4948 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
4949 vim_free(wmsg);
4950 vim_free(wtitle);
4951 }
4952 else
Bram Moolenaar63e43442016-11-19 17:28:44 +01004953 MessageBox(NULL, msg, title, MB_ICONWARNING);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004954 need_vimrun_warning = FALSE;
4955 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004956 if (!s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004957 /* Use vimrun to execute the command. It opens a console
4958 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004959 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004960 vimrun_path,
4961 (msg_silent != 0 || (options & SHELL_DOOUT))
4962 ? "-s " : "",
4963 p_sh, p_shcf, cmd);
4964 else
4965#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004966 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004967 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004968 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004969 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004970 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004971 }
4972 }
4973
4974 if (tmode == TMODE_RAW)
4975 settmode(TMODE_RAW); /* set to raw mode */
4976
4977 /* Print the return value, unless "vimrun" was used. */
4978 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01004979#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004980 && ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004981#endif
4982 )
4983 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004984 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004985 msg_putchar('\n');
4986 }
4987#ifdef FEAT_TITLE
4988 resettitle();
4989#endif
4990
4991 signal(SIGINT, SIG_DFL);
4992#if defined(__GNUC__) && !defined(__MINGW32__)
4993 signal(SIGKILL, SIG_DFL);
4994#else
4995 signal(SIGBREAK, SIG_DFL);
4996#endif
4997 signal(SIGILL, SIG_DFL);
4998 signal(SIGFPE, SIG_DFL);
4999 signal(SIGSEGV, SIG_DFL);
5000 signal(SIGTERM, SIG_DFL);
5001 signal(SIGABRT, SIG_DFL);
5002
5003 return x;
5004}
5005
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005006#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005007 static HANDLE
5008job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005009 char_u *fname,
5010 DWORD dwDesiredAccess,
5011 DWORD dwShareMode,
5012 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5013 DWORD dwCreationDisposition,
5014 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005015{
5016 HANDLE h;
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005017 WCHAR *wn = NULL;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005018
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005019 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5020 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005021 wn = enc_to_utf16(fname, NULL);
5022 if (wn != NULL)
5023 {
5024 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5025 lpSecurityAttributes, dwCreationDisposition,
5026 dwFlagsAndAttributes, NULL);
5027 vim_free(wn);
5028 }
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005029 }
5030 if (wn == NULL)
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005031 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
5032 lpSecurityAttributes, dwCreationDisposition,
5033 dwFlagsAndAttributes, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005034 return h;
5035}
5036
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005037/*
5038 * Turn the dictionary "env" into a NUL separated list that can be used as the
5039 * environment argument of vim_create_process().
5040 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005041 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005042win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005043{
5044 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005045 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005046 LPVOID base = GetEnvironmentStringsW();
5047
5048 /* for last \0 */
5049 if (ga_grow(gap, 1) == FAIL)
5050 return;
5051
5052 if (base)
5053 {
5054 WCHAR *p = (WCHAR*) base;
5055
5056 /* for last \0 */
5057 if (ga_grow(gap, 1) == FAIL)
5058 return;
5059
5060 while (*p != 0 || *(p + 1) != 0)
5061 {
5062 if (ga_grow(gap, 1) == OK)
5063 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5064 p++;
5065 }
5066 FreeEnvironmentStrings(base);
5067 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5068 }
5069
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005070 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005071 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005072 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005073 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005074 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005075 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005076 typval_T *item = &dict_lookup(hi)->di_tv;
5077 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005078 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005079 --todo;
5080 if (wkey != NULL && wval != NULL)
5081 {
5082 size_t n;
5083 size_t lkey = wcslen(wkey);
5084 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005085
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005086 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5087 continue;
5088 for (n = 0; n < lkey; n++)
5089 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5090 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5091 for (n = 0; n < lval; n++)
5092 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5093 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5094 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005095 vim_free(wkey);
5096 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005097 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005098 }
5099 }
5100
Bram Moolenaar493359e2018-06-12 20:25:52 +02005101# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005102 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005103# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005104 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005105 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005106# endif
5107# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005108 char_u *version = get_vim_var_str(VV_VERSION);
5109 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005110# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005111 // size of "VIM_SERVERNAME=" and value,
5112 // plus "VIM_TERMINAL=" and value,
5113 // plus two terminating NULs
5114 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005115# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005116 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005117# endif
5118# ifdef FEAT_TERMINAL
5119 + 13 + version_len + 2
5120# endif
5121 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005122
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005123 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005124 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005125# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005126 for (n = 0; n < 15; n++)
5127 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5128 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005129 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005130 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5131 (WCHAR)servername[n];
5132 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005133# endif
5134# ifdef FEAT_TERMINAL
5135 if (is_terminal)
5136 {
5137 for (n = 0; n < 13; n++)
5138 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5139 (WCHAR)"VIM_TERMINAL="[n];
5140 for (n = 0; n < version_len; n++)
5141 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5142 (WCHAR)version[n];
5143 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5144 }
5145# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005146 }
5147 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005148# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005149}
5150
Bram Moolenaarb091f302019-01-19 14:37:00 +01005151/*
5152 * Create a pair of pipes.
5153 * Return TRUE for success, FALSE for failure.
5154 */
5155 static BOOL
5156create_pipe_pair(HANDLE handles[2])
5157{
5158 static LONG s;
5159 char name[64];
5160 SECURITY_ATTRIBUTES sa;
5161
5162 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5163 GetCurrentProcessId(),
5164 InterlockedIncrement(&s));
5165
5166 // Create named pipe. Max size of named pipe is 65535.
5167 handles[1] = CreateNamedPipe(
5168 name,
5169 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5170 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005171 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005172
5173 if (handles[1] == INVALID_HANDLE_VALUE)
5174 return FALSE;
5175
5176 sa.nLength = sizeof(sa);
5177 sa.bInheritHandle = TRUE;
5178 sa.lpSecurityDescriptor = NULL;
5179
5180 handles[0] = CreateFile(name,
5181 FILE_GENERIC_READ,
5182 FILE_SHARE_READ, &sa,
5183 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5184
5185 if (handles[0] == INVALID_HANDLE_VALUE)
5186 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005187 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005188 return FALSE;
5189 }
5190
5191 return TRUE;
5192}
5193
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005194 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005195mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005196{
5197 STARTUPINFO si;
5198 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005199 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005200 SECURITY_ATTRIBUTES saAttr;
5201 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005202 HANDLE ifd[2];
5203 HANDLE ofd[2];
5204 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005205 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005206
5207 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5208 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5209 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5210 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5211 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5212 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5213 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5214
5215 if (use_out_for_err && use_null_for_out)
5216 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005217
5218 ifd[0] = INVALID_HANDLE_VALUE;
5219 ifd[1] = INVALID_HANDLE_VALUE;
5220 ofd[0] = INVALID_HANDLE_VALUE;
5221 ofd[1] = INVALID_HANDLE_VALUE;
5222 efd[0] = INVALID_HANDLE_VALUE;
5223 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005224 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005225
Bram Moolenaar14207f42016-10-27 21:13:10 +02005226 jo = CreateJobObject(NULL, NULL);
5227 if (jo == NULL)
5228 {
5229 job->jv_status = JOB_FAILED;
5230 goto failed;
5231 }
5232
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005233 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005234 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005235
Bram Moolenaar76467df2016-02-12 19:30:26 +01005236 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005237 ZeroMemory(&si, sizeof(si));
5238 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005239 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005240 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005241
Bram Moolenaard8070362016-02-15 21:56:54 +01005242 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5243 saAttr.bInheritHandle = TRUE;
5244 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005245
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005246 if (use_file_for_in)
5247 {
5248 char_u *fname = options->jo_io_name[PART_IN];
5249
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005250 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5251 FILE_SHARE_READ | FILE_SHARE_WRITE,
5252 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5253 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005254 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005255 semsg(_(e_notopen), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005256 goto failed;
5257 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005258 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005259 else if (!use_null_for_in
5260 && (!create_pipe_pair(ifd)
5261 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005262 goto failed;
5263
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005264 if (use_file_for_out)
5265 {
5266 char_u *fname = options->jo_io_name[PART_OUT];
5267
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005268 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5269 FILE_SHARE_READ | FILE_SHARE_WRITE,
5270 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5271 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005272 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005273 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005274 goto failed;
5275 }
5276 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005277 else if (!use_null_for_out &&
5278 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005279 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005280 goto failed;
5281
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005282 if (use_file_for_err)
5283 {
5284 char_u *fname = options->jo_io_name[PART_ERR];
5285
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005286 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5287 FILE_SHARE_READ | FILE_SHARE_WRITE,
5288 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5289 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005290 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005291 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005292 goto failed;
5293 }
5294 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005295 else if (!use_out_for_err && !use_null_for_err &&
5296 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005297 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005298 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005299
Bram Moolenaard8070362016-02-15 21:56:54 +01005300 si.dwFlags |= STARTF_USESTDHANDLES;
5301 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005302 si.hStdOutput = ofd[1];
5303 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5304
5305 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5306 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005307 if (options->jo_set & JO_CHANNEL)
5308 {
5309 channel = options->jo_channel;
5310 if (channel != NULL)
5311 ++channel->ch_refcount;
5312 }
5313 else
5314 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005315 if (channel == NULL)
5316 goto failed;
5317 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005318
5319 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005320 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005321 CREATE_DEFAULT_ERROR_MODE |
5322 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005323 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005324 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005325 &si, &pi,
5326 ga.ga_data,
5327 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005328 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005329 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005330 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005331 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005332 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005333
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005334 ga_clear(&ga);
5335
Bram Moolenaar14207f42016-10-27 21:13:10 +02005336 if (!AssignProcessToJobObject(jo, pi.hProcess))
5337 {
5338 /* if failing, switch the way to terminate
5339 * process with TerminateProcess. */
5340 CloseHandle(jo);
5341 jo = NULL;
5342 }
5343 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005344 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005345 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005346 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005347 job->jv_status = JOB_STARTED;
5348
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005349 CloseHandle(ifd[0]);
5350 CloseHandle(ofd[1]);
5351 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005352 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005353
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005354 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005355 if (channel != NULL)
5356 {
5357 channel_set_pipes(channel,
5358 use_file_for_in || use_null_for_in
5359 ? INVALID_FD : (sock_T)ifd[1],
5360 use_file_for_out || use_null_for_out
5361 ? INVALID_FD : (sock_T)ofd[0],
5362 use_out_for_err || use_file_for_err || use_null_for_err
5363 ? INVALID_FD : (sock_T)efd[0]);
5364 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005365 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005366 return;
5367
5368failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005369 CloseHandle(ifd[0]);
5370 CloseHandle(ofd[0]);
5371 CloseHandle(efd[0]);
5372 CloseHandle(ifd[1]);
5373 CloseHandle(ofd[1]);
5374 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005375 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005376 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005377}
5378
5379 char *
5380mch_job_status(job_T *job)
5381{
5382 DWORD dwExitCode = 0;
5383
Bram Moolenaar76467df2016-02-12 19:30:26 +01005384 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5385 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005386 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005387 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005388 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005389 {
5390 ch_log(job->jv_channel, "Job ended");
5391 job->jv_status = JOB_ENDED;
5392 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005393 return "dead";
5394 }
5395 return "run";
5396}
5397
Bram Moolenaar97792de2016-10-15 18:36:49 +02005398 job_T *
5399mch_detect_ended_job(job_T *job_list)
5400{
5401 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5402 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5403 job_T *job = job_list;
5404
5405 while (job != NULL)
5406 {
5407 DWORD n;
5408 DWORD result;
5409
5410 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5411 && job != NULL; job = job->jv_next)
5412 {
5413 if (job->jv_status == JOB_STARTED)
5414 {
5415 jobHandles[n] = job->jv_proc_info.hProcess;
5416 jobArray[n] = job;
5417 ++n;
5418 }
5419 }
5420 if (n == 0)
5421 continue;
5422 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5423 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5424 {
5425 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5426
5427 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5428 return wait_job;
5429 }
5430 }
5431 return NULL;
5432}
5433
Bram Moolenaarfb630902016-10-29 14:55:00 +02005434 static BOOL
5435terminate_all(HANDLE process, int code)
5436{
5437 PROCESSENTRY32 pe;
5438 HANDLE h = INVALID_HANDLE_VALUE;
5439 DWORD pid = GetProcessId(process);
5440
5441 if (pid != 0)
5442 {
5443 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5444 if (h != INVALID_HANDLE_VALUE)
5445 {
5446 pe.dwSize = sizeof(PROCESSENTRY32);
5447 if (!Process32First(h, &pe))
5448 goto theend;
5449
5450 do
5451 {
5452 if (pe.th32ParentProcessID == pid)
5453 {
5454 HANDLE ph = OpenProcess(
5455 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5456 if (ph != NULL)
5457 {
5458 terminate_all(ph, code);
5459 CloseHandle(ph);
5460 }
5461 }
5462 } while (Process32Next(h, &pe));
5463
5464 CloseHandle(h);
5465 }
5466 }
5467
5468theend:
5469 return TerminateProcess(process, code);
5470}
5471
5472/*
5473 * Send a (deadly) signal to "job".
5474 * Return FAIL if it didn't work.
5475 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005476 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005477mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005478{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005479 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005480
Bram Moolenaar923d9262016-02-25 20:56:01 +01005481 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005482 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005483 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005484 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005485 {
5486 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5487 job->jv_channel->ch_killing = TRUE;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005488 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005489 }
Bram Moolenaarfb630902016-10-29 14:55:00 +02005490 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005491 }
5492
5493 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5494 return FAIL;
5495 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005496 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5497 job->jv_proc_info.dwProcessId)
5498 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005499 FreeConsole();
5500 return ret;
5501}
5502
5503/*
5504 * Clear the data related to "job".
5505 */
5506 void
5507mch_clear_job(job_T *job)
5508{
5509 if (job->jv_status != JOB_FAILED)
5510 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005511 if (job->jv_job_object != NULL)
5512 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005513 CloseHandle(job->jv_proc_info.hProcess);
5514 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005515}
5516#endif
5517
Bram Moolenaar071d4272004-06-13 20:20:40 +00005518
Bram Moolenaar4f974752019-02-17 17:44:42 +01005519#ifndef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005520
5521/*
5522 * Start termcap mode
5523 */
5524 static void
5525termcap_mode_start(void)
5526{
5527 DWORD cmodein;
5528
5529 if (g_fTermcapMode)
5530 return;
5531
5532 SaveConsoleBuffer(&g_cbNonTermcap);
5533
5534 if (g_cbTermcap.IsValid)
5535 {
5536 /*
5537 * We've been in termcap mode before. Restore certain screen
5538 * characteristics, including the buffer size and the window
5539 * size. Since we will be redrawing the screen, we don't need
5540 * to restore the actual contents of the buffer.
5541 */
5542 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005543 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005544 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5545 Rows = g_cbTermcap.Info.dwSize.Y;
5546 Columns = g_cbTermcap.Info.dwSize.X;
5547 }
5548 else
5549 {
5550 /*
5551 * This is our first time entering termcap mode. Clear the console
5552 * screen buffer, and resize the buffer to match the current window
5553 * size. We will use this as the size of our editing environment.
5554 */
5555 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005556 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005557 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5558 }
5559
5560#ifdef FEAT_TITLE
5561 resettitle();
5562#endif
5563
5564 GetConsoleMode(g_hConIn, &cmodein);
5565#ifdef FEAT_MOUSE
5566 if (g_fMouseActive)
5567 cmodein |= ENABLE_MOUSE_INPUT;
5568 else
5569 cmodein &= ~ENABLE_MOUSE_INPUT;
5570#endif
5571 cmodein |= ENABLE_WINDOW_INPUT;
5572 SetConsoleMode(g_hConIn, cmodein);
5573
5574 redraw_later_clear();
5575 g_fTermcapMode = TRUE;
5576}
5577
5578
5579/*
5580 * End termcap mode
5581 */
5582 static void
5583termcap_mode_end(void)
5584{
5585 DWORD cmodein;
5586 ConsoleBuffer *cb;
5587 COORD coord;
5588 DWORD dwDummy;
5589
5590 if (!g_fTermcapMode)
5591 return;
5592
5593 SaveConsoleBuffer(&g_cbTermcap);
5594
5595 GetConsoleMode(g_hConIn, &cmodein);
5596 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5597 SetConsoleMode(g_hConIn, cmodein);
5598
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005599#ifdef FEAT_RESTORE_ORIG_SCREEN
5600 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5601#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005602 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005603#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005604 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005605 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005606 SetConsoleCursorInfo(g_hConOut, &g_cci);
5607
5608 if (p_rs || exiting)
5609 {
5610 /*
5611 * Clear anything that happens to be on the current line.
5612 */
5613 coord.X = 0;
5614 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5615 FillConsoleOutputCharacter(g_hConOut, ' ',
5616 cb->Info.dwSize.X, coord, &dwDummy);
5617 /*
5618 * The following is just for aesthetics. If we are exiting without
5619 * restoring the screen, then we want to have a prompt string
5620 * appear at the bottom line. However, the command interpreter
5621 * seems to always advance the cursor one line before displaying
5622 * the prompt string, which causes the screen to scroll. To
5623 * counter this, move the cursor up one line before exiting.
5624 */
5625 if (exiting && !p_rs)
5626 coord.Y--;
5627 /*
5628 * Position the cursor at the leftmost column of the desired row.
5629 */
5630 SetConsoleCursorPosition(g_hConOut, coord);
5631 }
5632
5633 g_fTermcapMode = FALSE;
5634}
Bram Moolenaar4f974752019-02-17 17:44:42 +01005635#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005636
5637
Bram Moolenaar4f974752019-02-17 17:44:42 +01005638#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005639 void
5640mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005641 char_u *s UNUSED,
5642 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005643{
5644 /* never used */
5645}
5646
5647#else
5648
5649/*
5650 * clear `n' chars, starting from `coord'
5651 */
5652 static void
5653clear_chars(
5654 COORD coord,
5655 DWORD n)
5656{
5657 DWORD dwDummy;
5658
5659 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005660
5661 if (!USE_VTP)
5662 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5663 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005664 {
5665 set_console_color_rgb();
5666 gotoxy(coord.X + 1, coord.Y + 1);
5667 vtp_printf("\033[%dX", n);
5668 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005669}
5670
5671
5672/*
5673 * Clear the screen
5674 */
5675 static void
5676clear_screen(void)
5677{
5678 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005679
5680 if (!USE_VTP)
5681 clear_chars(g_coord, Rows * Columns);
5682 else
5683 {
5684 set_console_color_rgb();
5685 gotoxy(1, 1);
5686 vtp_printf("\033[2J");
5687 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005688}
5689
5690
5691/*
5692 * Clear to end of display
5693 */
5694 static void
5695clear_to_end_of_display(void)
5696{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005697 COORD save = g_coord;
5698
5699 if (!USE_VTP)
5700 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005701 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005702 else
5703 {
5704 set_console_color_rgb();
5705 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5706 vtp_printf("\033[0J");
5707
5708 gotoxy(save.X + 1, save.Y + 1);
5709 g_coord = save;
5710 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005711}
5712
5713
5714/*
5715 * Clear to end of line
5716 */
5717 static void
5718clear_to_end_of_line(void)
5719{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005720 COORD save = g_coord;
5721
5722 if (!USE_VTP)
5723 clear_chars(g_coord, Columns - g_coord.X);
5724 else
5725 {
5726 set_console_color_rgb();
5727 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5728 vtp_printf("\033[0K");
5729
5730 gotoxy(save.X + 1, save.Y + 1);
5731 g_coord = save;
5732 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005733}
5734
5735
5736/*
5737 * Scroll the scroll region up by `cLines' lines
5738 */
5739 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005740scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005741{
5742 COORD oldcoord = g_coord;
5743
5744 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5745 delete_lines(cLines);
5746
5747 g_coord = oldcoord;
5748}
5749
5750
5751/*
5752 * Set the scroll region
5753 */
5754 static void
5755set_scroll_region(
5756 unsigned left,
5757 unsigned top,
5758 unsigned right,
5759 unsigned bottom)
5760{
5761 if (left >= right
5762 || top >= bottom
5763 || right > (unsigned) Columns - 1
5764 || bottom > (unsigned) Rows - 1)
5765 return;
5766
5767 g_srScrollRegion.Left = left;
5768 g_srScrollRegion.Top = top;
5769 g_srScrollRegion.Right = right;
5770 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005771}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005772
Bram Moolenaar6982f422019-02-16 16:48:01 +01005773 static void
5774set_scroll_region_tb(
5775 unsigned top,
5776 unsigned bottom)
5777{
5778 if (top >= bottom || bottom > (unsigned)Rows - 1)
5779 return;
5780
5781 g_srScrollRegion.Top = top;
5782 g_srScrollRegion.Bottom = bottom;
5783}
5784
5785 static void
5786set_scroll_region_lr(
5787 unsigned left,
5788 unsigned right)
5789{
5790 if (left >= right || right > (unsigned)Columns - 1)
5791 return;
5792
5793 g_srScrollRegion.Left = left;
5794 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005795}
5796
5797
5798/*
5799 * Insert `cLines' lines at the current cursor position
5800 */
5801 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005802insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005803{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005804 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005805 COORD dest;
5806 CHAR_INFO fill;
5807
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005808 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5809
Bram Moolenaar6982f422019-02-16 16:48:01 +01005810 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005811 dest.Y = g_coord.Y + cLines;
5812
Bram Moolenaar6982f422019-02-16 16:48:01 +01005813 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005814 source.Top = g_coord.Y;
5815 source.Right = g_srScrollRegion.Right;
5816 source.Bottom = g_srScrollRegion.Bottom - cLines;
5817
Bram Moolenaar6982f422019-02-16 16:48:01 +01005818 clip.Left = g_srScrollRegion.Left;
5819 clip.Top = g_coord.Y;
5820 clip.Right = g_srScrollRegion.Right;
5821 clip.Bottom = g_srScrollRegion.Bottom;
5822
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005823 fill.Char.AsciiChar = ' ';
5824 if (!USE_VTP)
5825 fill.Attributes = g_attrCurrent;
5826 else
5827 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005828
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005829 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005830
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005831 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5832
Bram Moolenaar6982f422019-02-16 16:48:01 +01005833 // Here we have to deal with a win32 console flake: If the scroll
5834 // region looks like abc and we scroll c to a and fill with d we get
5835 // cbd... if we scroll block c one line at a time to a, we get cdd...
5836 // vim expects cdd consistently... So we have to deal with that
5837 // here... (this also occurs scrolling the same way in the other
5838 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005839
5840 if (source.Bottom < dest.Y)
5841 {
5842 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005843 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005844
Bram Moolenaar6982f422019-02-16 16:48:01 +01005845 coord.X = source.Left;
5846 for (i = clip.Top; i < dest.Y; ++i)
5847 {
5848 coord.Y = i;
5849 clear_chars(coord, source.Right - source.Left + 1);
5850 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005851 }
5852}
5853
5854
5855/*
5856 * Delete `cLines' lines at the current cursor position
5857 */
5858 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005859delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005860{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005861 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005862 COORD dest;
5863 CHAR_INFO fill;
5864 int nb;
5865
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005866 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5867
Bram Moolenaar6982f422019-02-16 16:48:01 +01005868 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005869 dest.Y = g_coord.Y;
5870
Bram Moolenaar6982f422019-02-16 16:48:01 +01005871 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005872 source.Top = g_coord.Y + cLines;
5873 source.Right = g_srScrollRegion.Right;
5874 source.Bottom = g_srScrollRegion.Bottom;
5875
Bram Moolenaar6982f422019-02-16 16:48:01 +01005876 clip.Left = g_srScrollRegion.Left;
5877 clip.Top = g_coord.Y;
5878 clip.Right = g_srScrollRegion.Right;
5879 clip.Bottom = g_srScrollRegion.Bottom;
5880
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005881 fill.Char.AsciiChar = ' ';
5882 if (!USE_VTP)
5883 fill.Attributes = g_attrCurrent;
5884 else
5885 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005886
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005887 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005888
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005889 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5890
Bram Moolenaar6982f422019-02-16 16:48:01 +01005891 // Here we have to deal with a win32 console flake; See insert_lines()
5892 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005893
5894 nb = dest.Y + (source.Bottom - source.Top) + 1;
5895
5896 if (nb < source.Top)
5897 {
5898 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005899 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005900
Bram Moolenaar6982f422019-02-16 16:48:01 +01005901 coord.X = source.Left;
5902 for (i = nb; i < clip.Bottom; ++i)
5903 {
5904 coord.Y = i;
5905 clear_chars(coord, source.Right - source.Left + 1);
5906 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005907 }
5908}
5909
5910
5911/*
5912 * Set the cursor position
5913 */
5914 static void
5915gotoxy(
5916 unsigned x,
5917 unsigned y)
5918{
5919 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5920 return;
5921
5922 /* external cursor coords are 1-based; internal are 0-based */
5923 g_coord.X = x - 1;
5924 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005925
5926 if (!USE_VTP)
5927 SetConsoleCursorPosition(g_hConOut, g_coord);
5928 else
5929 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005930}
5931
5932
5933/*
5934 * Set the current text attribute = (foreground | background)
5935 * See ../doc/os_win32.txt for the numbers.
5936 */
5937 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005938textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005939{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005940 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005941
5942 SetConsoleTextAttribute(g_hConOut, wAttr);
5943}
5944
5945
5946 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005947textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005948{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005949 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005950
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005951 if (!USE_VTP)
5952 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5953 else
5954 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005955}
5956
5957
5958 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005959textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005960{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005961 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005962
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005963 if (!USE_VTP)
5964 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5965 else
5966 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005967}
5968
5969
5970/*
5971 * restore the default text attribute (whatever we started with)
5972 */
5973 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005974normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005975{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005976 if (!USE_VTP)
5977 textattr(g_attrDefault);
5978 else
5979 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005980}
5981
5982
5983static WORD g_attrPreStandout = 0;
5984
5985/*
5986 * Make the text standout, by brightening it
5987 */
5988 static void
5989standout(void)
5990{
5991 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005992
Bram Moolenaar071d4272004-06-13 20:20:40 +00005993 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5994}
5995
5996
5997/*
5998 * Turn off standout mode
5999 */
6000 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006001standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006002{
6003 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006004 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006005
6006 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006007}
6008
6009
6010/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006011 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006012 */
6013 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006014mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006015{
6016 char_u *p;
6017 int n;
6018
6019 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6020 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006021 if (
6022#ifdef FEAT_TERMGUICOLORS
6023 !p_tgc &&
6024#endif
6025 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006026 {
6027 p = T_ME + 2;
6028 n = getdigits(&p);
6029 if (*p == 'm' && n > 0)
6030 {
6031 cterm_normal_fg_color = (n & 0xf) + 1;
6032 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6033 }
6034 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006035#ifdef FEAT_TERMGUICOLORS
6036 cterm_normal_fg_gui_color = INVALCOLOR;
6037 cterm_normal_bg_gui_color = INVALCOLOR;
6038#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006039}
6040
6041
6042/*
6043 * visual bell: flash the screen
6044 */
6045 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006046visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006047{
6048 COORD coordOrigin = {0, 0};
6049 WORD attrFlash = ~g_attrCurrent & 0xff;
6050
6051 DWORD dwDummy;
6052 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
6053
6054 if (oldattrs == NULL)
6055 return;
6056 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6057 coordOrigin, &dwDummy);
6058 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6059 coordOrigin, &dwDummy);
6060
6061 Sleep(15); /* wait for 15 msec */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006062 if (!USE_VTP)
6063 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006064 coordOrigin, &dwDummy);
6065 vim_free(oldattrs);
6066}
6067
6068
6069/*
6070 * Make the cursor visible or invisible
6071 */
6072 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006073cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006074{
6075 s_cursor_visible = fVisible;
6076#ifdef MCH_CURSOR_SHAPE
6077 mch_update_cursor();
6078#endif
6079}
6080
6081
6082/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006083 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006084 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006085 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006086 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006087write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006088 char_u *pchBuf,
6089 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006090{
6091 COORD coord = g_coord;
6092 DWORD written;
6093
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006094 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6095 {
6096 static WCHAR *unicodebuf = NULL;
6097 static int unibuflen = 0;
6098 int length;
6099 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006100
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006101 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
6102 if (unicodebuf == NULL || length > unibuflen)
6103 {
6104 vim_free(unicodebuf);
6105 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
6106 unibuflen = length;
6107 }
6108 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
6109 unicodebuf, unibuflen);
6110
6111 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006112
6113 if (!USE_VTP)
6114 {
6115 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6116 coord, &written);
6117 /* When writing fails or didn't write a single character, pretend one
6118 * character was written, otherwise we get stuck. */
6119 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
6120 coord, &cchwritten) == 0
Bram Moolenaar78d21da2019-02-17 15:00:52 +01006121 || cchwritten == 0 || cchwritten == (DWORD)-1)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006122 cchwritten = 1;
6123 }
6124 else
6125 {
6126 if (WriteConsoleW(g_hConOut, unicodebuf, length, &cchwritten,
6127 NULL) == 0 || cchwritten == 0)
6128 cchwritten = 1;
6129 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006130
6131 if (cchwritten == length)
6132 {
6133 written = cbToWrite;
6134 g_coord.X += (SHORT)cells;
6135 }
6136 else
6137 {
6138 char_u *p = pchBuf;
6139 for (n = 0; n < cchwritten; n++)
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006140 MB_CPTR_ADV(p);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006141 written = p - pchBuf;
6142 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
6143 }
6144 }
6145 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006146 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006147 if (!USE_VTP)
6148 {
6149 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
6150 coord, &written);
6151 /* When writing fails or didn't write a single character, pretend one
6152 * character was written, otherwise we get stuck. */
6153 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
6154 coord, &written) == 0
Bram Moolenaar78d21da2019-02-17 15:00:52 +01006155 || written == 0 || written == (DWORD)-1)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006156 written = 1;
6157 }
6158 else
6159 {
6160 if (WriteConsole(g_hConOut, (LPCSTR)pchBuf, cbToWrite, &written,
6161 NULL) == 0 || written == 0)
6162 written = 1;
6163 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006164
6165 g_coord.X += (SHORT) written;
6166 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006167
6168 while (g_coord.X > g_srScrollRegion.Right)
6169 {
6170 g_coord.X -= (SHORT) Columns;
6171 if (g_coord.Y < g_srScrollRegion.Bottom)
6172 g_coord.Y++;
6173 }
6174
6175 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6176
6177 return written;
6178}
6179
6180
6181/*
6182 * mch_write(): write the output buffer to the screen, translating ESC
6183 * sequences into calls to console output routines.
6184 */
6185 void
6186mch_write(
6187 char_u *s,
6188 int len)
6189{
6190 s[len] = NUL;
6191
6192 if (!term_console)
6193 {
6194 write(1, s, (unsigned)len);
6195 return;
6196 }
6197
6198 /* translate ESC | sequences into faked bios calls */
6199 while (len--)
6200 {
6201 /* optimization: use one single write_chars for runs of text,
6202 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006203 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006204
6205 if (p_wd)
6206 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006207 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006208 if (prefix != 0)
6209 prefix = 1;
6210 }
6211
6212 if (prefix != 0)
6213 {
6214 DWORD nWritten;
6215
6216 nWritten = write_chars(s, prefix);
6217#ifdef MCH_WRITE_DUMP
6218 if (fdDump)
6219 {
6220 fputc('>', fdDump);
6221 fwrite(s, sizeof(char_u), nWritten, fdDump);
6222 fputs("<\n", fdDump);
6223 }
6224#endif
6225 len -= (nWritten - 1);
6226 s += nWritten;
6227 }
6228 else if (s[0] == '\n')
6229 {
6230 /* \n, newline: go to the beginning of the next line or scroll */
6231 if (g_coord.Y == g_srScrollRegion.Bottom)
6232 {
6233 scroll(1);
6234 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6235 }
6236 else
6237 {
6238 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6239 }
6240#ifdef MCH_WRITE_DUMP
6241 if (fdDump)
6242 fputs("\\n\n", fdDump);
6243#endif
6244 s++;
6245 }
6246 else if (s[0] == '\r')
6247 {
6248 /* \r, carriage return: go to beginning of line */
6249 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
6250#ifdef MCH_WRITE_DUMP
6251 if (fdDump)
6252 fputs("\\r\n", fdDump);
6253#endif
6254 s++;
6255 }
6256 else if (s[0] == '\b')
6257 {
6258 /* \b, backspace: move cursor one position left */
6259 if (g_coord.X > g_srScrollRegion.Left)
6260 g_coord.X--;
6261 else if (g_coord.Y > g_srScrollRegion.Top)
6262 {
6263 g_coord.X = g_srScrollRegion.Right;
6264 g_coord.Y--;
6265 }
6266 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6267#ifdef MCH_WRITE_DUMP
6268 if (fdDump)
6269 fputs("\\b\n", fdDump);
6270#endif
6271 s++;
6272 }
6273 else if (s[0] == '\a')
6274 {
6275 /* \a, bell */
6276 MessageBeep(0xFFFFFFFF);
6277#ifdef MCH_WRITE_DUMP
6278 if (fdDump)
6279 fputs("\\a\n", fdDump);
6280#endif
6281 s++;
6282 }
6283 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6284 {
6285#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006286 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006287#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006288 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006289 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006290
6291 switch (s[2])
6292 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006293 case '0': case '1': case '2': case '3': case '4':
6294 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006295 p = s + 1;
6296 do
6297 {
6298 ++p;
6299 args[argc] = getdigits(&p);
6300 argc += (argc < 15) ? 1 : 0;
6301 if (p > s + len)
6302 break;
6303 } while (*p == ';');
6304
Bram Moolenaar071d4272004-06-13 20:20:40 +00006305 if (p > s + len)
6306 break;
6307
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006308 arg1 = args[0];
6309 arg2 = args[1];
6310 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006311 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006312 if (argc == 1 && args[0] == 0)
6313 normvideo();
6314 else if (argc == 1)
6315 {
6316 if (USE_VTP)
6317 textcolor((WORD) arg1);
6318 else
6319 textattr((WORD) arg1);
6320 }
6321 else if (USE_VTP)
6322 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006323 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006324 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006325 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006326 gotoxy(arg2, arg1);
6327 }
6328 else if (argc == 2 && *p == 'r')
6329 {
6330 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6331 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006332 else if (argc == 2 && *p == 'R')
6333 {
6334 set_scroll_region_tb(arg1, arg2);
6335 }
6336 else if (argc == 2 && *p == 'V')
6337 {
6338 set_scroll_region_lr(arg1, arg2);
6339 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006340 else if (argc == 1 && *p == 'A')
6341 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006342 gotoxy(g_coord.X + 1,
6343 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6344 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006345 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006346 {
6347 textbackground((WORD) arg1);
6348 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006349 else if (argc == 1 && *p == 'C')
6350 {
6351 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6352 g_coord.Y + 1);
6353 }
6354 else if (argc == 1 && *p == 'f')
6355 {
6356 textcolor((WORD) arg1);
6357 }
6358 else if (argc == 1 && *p == 'H')
6359 {
6360 gotoxy(1, arg1);
6361 }
6362 else if (argc == 1 && *p == 'L')
6363 {
6364 insert_lines(arg1);
6365 }
6366 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006367 {
6368 delete_lines(arg1);
6369 }
6370
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006371 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006372 s = p + 1;
6373 break;
6374
Bram Moolenaar071d4272004-06-13 20:20:40 +00006375 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006376 gotoxy(g_coord.X + 1,
6377 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6378 goto got3;
6379
6380 case 'B':
6381 visual_bell();
6382 goto got3;
6383
6384 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006385 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6386 g_coord.Y + 1);
6387 goto got3;
6388
6389 case 'E':
6390 termcap_mode_end();
6391 goto got3;
6392
6393 case 'F':
6394 standout();
6395 goto got3;
6396
6397 case 'f':
6398 standend();
6399 goto got3;
6400
6401 case 'H':
6402 gotoxy(1, 1);
6403 goto got3;
6404
6405 case 'j':
6406 clear_to_end_of_display();
6407 goto got3;
6408
6409 case 'J':
6410 clear_screen();
6411 goto got3;
6412
6413 case 'K':
6414 clear_to_end_of_line();
6415 goto got3;
6416
6417 case 'L':
6418 insert_lines(1);
6419 goto got3;
6420
6421 case 'M':
6422 delete_lines(1);
6423 goto got3;
6424
6425 case 'S':
6426 termcap_mode_start();
6427 goto got3;
6428
6429 case 'V':
6430 cursor_visible(TRUE);
6431 goto got3;
6432
6433 case 'v':
6434 cursor_visible(FALSE);
6435 goto got3;
6436
6437 got3:
6438 s += 3;
6439 len -= 2;
6440 }
6441
6442#ifdef MCH_WRITE_DUMP
6443 if (fdDump)
6444 {
6445 fputs("ESC | ", fdDump);
6446 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6447 fputc('\n', fdDump);
6448 }
6449#endif
6450 }
6451 else
6452 {
6453 /* Write a single character */
6454 DWORD nWritten;
6455
6456 nWritten = write_chars(s, 1);
6457#ifdef MCH_WRITE_DUMP
6458 if (fdDump)
6459 {
6460 fputc('>', fdDump);
6461 fwrite(s, sizeof(char_u), nWritten, fdDump);
6462 fputs("<\n", fdDump);
6463 }
6464#endif
6465
6466 len -= (nWritten - 1);
6467 s += nWritten;
6468 }
6469 }
6470
6471#ifdef MCH_WRITE_DUMP
6472 if (fdDump)
6473 fflush(fdDump);
6474#endif
6475}
6476
Bram Moolenaar4f974752019-02-17 17:44:42 +01006477#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006478
6479
6480/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006481 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006482 */
6483 void
6484mch_delay(
6485 long msec,
Bram Moolenaar1266d672017-02-01 13:43:36 +01006486 int ignoreinput UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006487{
Bram Moolenaar4f974752019-02-17 17:44:42 +01006488#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006489 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006490#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006491 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006492# ifdef FEAT_MZSCHEME
6493 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6494 {
6495 int towait = p_mzq;
6496
6497 /* if msec is large enough, wait by portions in p_mzq */
6498 while (msec > 0)
6499 {
6500 mzvim_check_threads();
6501 if (msec < towait)
6502 towait = msec;
6503 Sleep(towait);
6504 msec -= towait;
6505 }
6506 }
6507 else
6508# endif
6509 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006510 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006511 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006512#endif
6513}
6514
6515
6516/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006517 * This version of remove is not scared by a readonly (backup) file.
6518 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006519 * Return 0 for success, -1 for failure.
6520 */
6521 int
6522mch_remove(char_u *name)
6523{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006524 WCHAR *wn = NULL;
6525 int n;
6526
Bram Moolenaar203258c2016-01-17 22:15:16 +01006527 /*
6528 * On Windows, deleting a directory's symbolic link is done by
6529 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6530 */
6531 if (mch_isdir(name) && mch_is_symbolic_link(name))
6532 return mch_rmdir(name);
6533
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006534 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6535
Bram Moolenaar071d4272004-06-13 20:20:40 +00006536 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6537 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006538 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006539 if (wn != NULL)
6540 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006541 n = DeleteFileW(wn) ? 0 : -1;
6542 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006543 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006544 }
6545 }
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006546 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006547}
6548
6549
6550/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006551 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006552 */
6553 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006554mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006555{
Bram Moolenaar4f974752019-02-17 17:44:42 +01006556#ifndef FEAT_GUI_MSWIN /* never used */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006557 if (g_fCtrlCPressed || g_fCBrkPressed)
6558 {
Bram Moolenaar9698ad72017-08-12 14:52:15 +02006559 ctrl_break_was_pressed = g_fCBrkPressed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006560 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6561 got_int = TRUE;
6562 }
6563#endif
6564}
6565
Bram Moolenaaree273972016-01-02 21:11:51 +01006566/* physical RAM to leave for the OS */
6567#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006568
6569/*
6570 * How much main memory in KiB that can be used by VIM.
6571 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006572 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006573mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006574{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006575 MEMORYSTATUSEX ms;
6576
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006577 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6578 * what fits in 32 bits. But it's not always available. */
6579 ms.dwLength = sizeof(MEMORYSTATUSEX);
6580 GlobalMemoryStatusEx(&ms);
6581 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006582 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006583 /* Process address space fits in physical RAM, use all of it. */
6584 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006585 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006586 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006587 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006588 /* Catch old NT box or perverse hardware setup. */
6589 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006590 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006591 /* Use physical RAM less reserve for OS + data. */
6592 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006593}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006594
Bram Moolenaar071d4272004-06-13 20:20:40 +00006595/*
6596 * Same code as below, but with wide functions and no comments.
6597 * Return 0 for success, non-zero for failure.
6598 */
6599 int
6600mch_wrename(WCHAR *wold, WCHAR *wnew)
6601{
6602 WCHAR *p;
6603 int i;
6604 WCHAR szTempFile[_MAX_PATH + 1];
6605 WCHAR szNewPath[_MAX_PATH + 1];
6606 HANDLE hf;
6607
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006608 p = wold;
6609 for (i = 0; wold[i] != NUL; ++i)
6610 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6611 && wold[i + 1] != 0)
6612 p = wold + i + 1;
6613 if ((int)(wold + i - p) < 8 || p[6] != '~')
6614 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006615
6616 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6617 return -1;
6618 *p = NUL;
6619
6620 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6621 return -2;
6622
6623 if (!DeleteFileW(szTempFile))
6624 return -3;
6625
6626 if (!MoveFileW(wold, szTempFile))
6627 return -4;
6628
6629 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6630 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6631 return -5;
6632 if (!CloseHandle(hf))
6633 return -6;
6634
6635 if (!MoveFileW(szTempFile, wnew))
6636 {
6637 (void)MoveFileW(szTempFile, wold);
6638 return -7;
6639 }
6640
6641 DeleteFileW(szTempFile);
6642
6643 if (!DeleteFileW(wold))
6644 return -8;
6645
6646 return 0;
6647}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006648
6649
6650/*
6651 * mch_rename() works around a bug in rename (aka MoveFile) in
6652 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6653 * file whose short file name is "FOO.BAR" (its long file name will
6654 * be correct: "foo.bar~"). Because a file can be accessed by
6655 * either its SFN or its LFN, "foo.bar" has effectively been
6656 * renamed to "foo.bar", which is not at all what was wanted. This
6657 * seems to happen only when renaming files with three-character
6658 * extensions by appending a suffix that does not include ".".
6659 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6660 *
6661 * There is another problem, which isn't really a bug but isn't right either:
6662 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6663 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6664 * service pack 6. Doesn't seem to happen on Windows 98.
6665 *
6666 * Like rename(), returns 0 upon success, non-zero upon failure.
6667 * Should probably set errno appropriately when errors occur.
6668 */
6669 int
6670mch_rename(
6671 const char *pszOldFile,
6672 const char *pszNewFile)
6673{
6674 char szTempFile[_MAX_PATH+1];
6675 char szNewPath[_MAX_PATH+1];
6676 char *pszFilePart;
6677 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006678 WCHAR *wold = NULL;
6679 WCHAR *wnew = NULL;
6680 int retval = -1;
6681
6682 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6683 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006684 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6685 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006686 if (wold != NULL && wnew != NULL)
6687 retval = mch_wrename(wold, wnew);
6688 vim_free(wold);
6689 vim_free(wnew);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006690 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006691 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006692
6693 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006694 * No need to play tricks unless the file name contains a "~" as the
6695 * seventh character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006696 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006697 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6698 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6699 return rename(pszOldFile, pszNewFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006700
6701 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6702 * a directory, no error is returned and pszFilePart will be NULL. */
6703 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6704 || pszFilePart == NULL)
6705 return -1;
6706 *pszFilePart = NUL;
6707
6708 /* Get (and create) a unique temporary file name in directory of new file */
6709 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6710 return -2;
6711
6712 /* blow the temp file away */
6713 if (!DeleteFile(szTempFile))
6714 return -3;
6715
6716 /* rename old file to the temp file */
6717 if (!MoveFile(pszOldFile, szTempFile))
6718 return -4;
6719
6720 /* now create an empty file called pszOldFile; this prevents the operating
6721 * system using pszOldFile as an alias (SFN) if we're renaming within the
6722 * same directory. For example, we're editing a file called
6723 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6724 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6725 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006726 * cause all sorts of problems later in buf_write(). So, we create an
6727 * empty file called filena~1.txt and the system will have to find some
6728 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006729 */
6730 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6731 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6732 return -5;
6733 if (!CloseHandle(hf))
6734 return -6;
6735
6736 /* rename the temp file to the new file */
6737 if (!MoveFile(szTempFile, pszNewFile))
6738 {
6739 /* Renaming failed. Rename the file back to its old name, so that it
6740 * looks like nothing happened. */
6741 (void)MoveFile(szTempFile, pszOldFile);
6742
6743 return -7;
6744 }
6745
6746 /* Seems to be left around on Novell filesystems */
6747 DeleteFile(szTempFile);
6748
6749 /* finally, remove the empty old file */
6750 if (!DeleteFile(pszOldFile))
6751 return -8;
6752
6753 return 0; /* success */
6754}
6755
6756/*
6757 * Get the default shell for the current hardware platform
6758 */
6759 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006760default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006761{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006762 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006763}
6764
6765/*
6766 * mch_access() extends access() to do more detailed check on network drives.
6767 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6768 */
6769 int
6770mch_access(char *n, int p)
6771{
6772 HANDLE hFile;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006773 int retval = -1; /* default: fail */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006774 WCHAR *wn = NULL;
6775
6776 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006777 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006778
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006779 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006780 {
6781 char TempName[_MAX_PATH + 16] = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006782 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006783
6784 if (p & R_OK)
6785 {
6786 /* Read check is performed by seeing if we can do a find file on
6787 * the directory for any file. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006788 if (wn != NULL)
6789 {
6790 int i;
6791 WIN32_FIND_DATAW d;
6792
6793 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6794 TempNameW[i] = wn[i];
6795 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6796 TempNameW[i++] = '\\';
6797 TempNameW[i++] = '*';
6798 TempNameW[i++] = 0;
6799
6800 hFile = FindFirstFileW(TempNameW, &d);
6801 if (hFile == INVALID_HANDLE_VALUE)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006802 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006803 else
6804 (void)FindClose(hFile);
6805 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006806 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006807 {
6808 char *pch;
6809 WIN32_FIND_DATA d;
6810
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006811 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006812 pch = TempName + STRLEN(TempName) - 1;
6813 if (*pch != '\\' && *pch != '/')
6814 *++pch = '\\';
6815 *++pch = '*';
6816 *++pch = NUL;
6817
6818 hFile = FindFirstFile(TempName, &d);
6819 if (hFile == INVALID_HANDLE_VALUE)
6820 goto getout;
6821 (void)FindClose(hFile);
6822 }
6823 }
6824
6825 if (p & W_OK)
6826 {
6827 /* Trying to create a temporary file in the directory should catch
6828 * directories on read-only network shares. However, in
6829 * directories whose ACL allows writes but denies deletes will end
6830 * up keeping the temporary file :-(. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006831 if (wn != NULL)
6832 {
6833 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006834 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006835 else
6836 DeleteFileW(TempNameW);
6837 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006838 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006839 {
6840 if (!GetTempFileName(n, "VIM", 0, TempName))
6841 goto getout;
6842 mch_remove((char_u *)TempName);
6843 }
6844 }
6845 }
6846 else
6847 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02006848 // Don't consider a file read-only if another process has opened it.
6849 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
6850
Bram Moolenaar071d4272004-06-13 20:20:40 +00006851 /* Trying to open the file for the required access does ACL, read-only
6852 * network share, and file attribute checks. */
Bram Moolenaar5aa98962018-05-06 17:09:38 +02006853 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
6854 | ((p & R_OK) ? GENERIC_READ : 0);
6855
Bram Moolenaar071d4272004-06-13 20:20:40 +00006856 if (wn != NULL)
Bram Moolenaar5aa98962018-05-06 17:09:38 +02006857 hFile = CreateFileW(wn, access_mode, share_mode,
6858 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006859 else
Bram Moolenaar5aa98962018-05-06 17:09:38 +02006860 hFile = CreateFile(n, access_mode, share_mode,
6861 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006862 if (hFile == INVALID_HANDLE_VALUE)
6863 goto getout;
6864 CloseHandle(hFile);
6865 }
6866
6867 retval = 0; /* success */
6868getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00006869 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006870 return retval;
6871}
6872
Bram Moolenaar071d4272004-06-13 20:20:40 +00006873/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006874 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006875 */
6876 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006877mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006878{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006879 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
Bram Moolenaara12a1612019-01-24 16:39:02 +01006880#ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006881 WCHAR *wn;
6882 int f;
6883
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006884 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006885 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006886 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006887 if (wn != NULL)
6888 {
6889 f = _wopen(wn, flags, mode);
6890 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006891 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006892 }
6893 }
Bram Moolenaara12a1612019-01-24 16:39:02 +01006894#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006895
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006896 /* open() can open a file which name is longer than _MAX_PATH bytes
6897 * and shorter than _MAX_PATH characters successfully, but sometimes it
6898 * causes unexpected error in another part. We make it an error explicitly
6899 * here. */
6900 if (strlen(name) >= _MAX_PATH)
6901 return -1;
6902
Bram Moolenaar071d4272004-06-13 20:20:40 +00006903 return open(name, flags, mode);
6904}
6905
6906/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006907 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006908 */
6909 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006910mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006911{
6912 WCHAR *wn, *wm;
6913 FILE *f = NULL;
6914
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006915 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006916 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01006917#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006918 /* Work around an annoying assertion in the Microsoft debug CRT
6919 * when mode's text/binary setting doesn't match _get_fmode(). */
6920 char newMode = mode[strlen(mode) - 1];
6921 int oldMode = 0;
6922
6923 _get_fmode(&oldMode);
6924 if (newMode == 't')
6925 _set_fmode(_O_TEXT);
6926 else if (newMode == 'b')
6927 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01006928#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006929 wn = enc_to_utf16((char_u *)name, NULL);
6930 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006931 if (wn != NULL && wm != NULL)
6932 f = _wfopen(wn, wm);
6933 vim_free(wn);
6934 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006935
Bram Moolenaara12a1612019-01-24 16:39:02 +01006936#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006937 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01006938#endif
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006939 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006940 }
6941
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006942 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6943 * and shorter than _MAX_PATH characters successfully, but sometimes it
6944 * causes unexpected error in another part. We make it an error explicitly
6945 * here. */
6946 if (strlen(name) >= _MAX_PATH)
6947 return NULL;
6948
Bram Moolenaar071d4272004-06-13 20:20:40 +00006949 return fopen(name, mode);
6950}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006951
Bram Moolenaar071d4272004-06-13 20:20:40 +00006952/*
6953 * SUB STREAM (aka info stream) handling:
6954 *
6955 * NTFS can have sub streams for each file. Normal contents of file is
6956 * stored in the main stream, and extra contents (author information and
6957 * title and so on) can be stored in sub stream. After Windows 2000, user
6958 * can access and store those informations in sub streams via explorer's
6959 * property menuitem in right click menu. Those informations in sub streams
6960 * were lost when copying only the main stream. So we have to copy sub
6961 * streams.
6962 *
6963 * Incomplete explanation:
6964 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6965 * More useful info and an example:
6966 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6967 */
6968
6969/*
6970 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6971 * and write to stream "substream" of file "to".
6972 * Errors are ignored.
6973 */
6974 static void
6975copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6976{
6977 HANDLE hTo;
6978 WCHAR *to_name;
6979
6980 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6981 wcscpy(to_name, to);
6982 wcscat(to_name, substream);
6983
6984 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6985 FILE_ATTRIBUTE_NORMAL, NULL);
6986 if (hTo != INVALID_HANDLE_VALUE)
6987 {
6988 long done;
6989 DWORD todo;
6990 DWORD readcnt, written;
6991 char buf[4096];
6992
6993 /* Copy block of bytes at a time. Abort when something goes wrong. */
6994 for (done = 0; done < len; done += written)
6995 {
6996 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006997 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6998 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006999 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7000 FALSE, FALSE, context)
7001 || readcnt != todo
7002 || !WriteFile(hTo, buf, todo, &written, NULL)
7003 || written != todo)
7004 break;
7005 }
7006 CloseHandle(hTo);
7007 }
7008
7009 free(to_name);
7010}
7011
7012/*
7013 * Copy info streams from file "from" to file "to".
7014 */
7015 static void
7016copy_infostreams(char_u *from, char_u *to)
7017{
7018 WCHAR *fromw;
7019 WCHAR *tow;
7020 HANDLE sh;
7021 WIN32_STREAM_ID sid;
7022 int headersize;
7023 WCHAR streamname[_MAX_PATH];
7024 DWORD readcount;
7025 void *context = NULL;
7026 DWORD lo, hi;
7027 int len;
7028
7029 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007030 fromw = enc_to_utf16(from, NULL);
7031 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007032 if (fromw != NULL && tow != NULL)
7033 {
7034 /* Open the file for reading. */
7035 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7036 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7037 if (sh != INVALID_HANDLE_VALUE)
7038 {
7039 /* Use BackupRead() to find the info streams. Repeat until we
7040 * have done them all.*/
7041 for (;;)
7042 {
7043 /* Get the header to find the length of the stream name. If
7044 * the "readcount" is zero we have done all info streams. */
7045 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007046 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007047 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7048 &readcount, FALSE, FALSE, &context)
7049 || readcount == 0)
7050 break;
7051
7052 /* We only deal with streams that have a name. The normal
7053 * file data appears to be without a name, even though docs
7054 * suggest it is called "::$DATA". */
7055 if (sid.dwStreamNameSize > 0)
7056 {
7057 /* Read the stream name. */
7058 if (!BackupRead(sh, (LPBYTE)streamname,
7059 sid.dwStreamNameSize,
7060 &readcount, FALSE, FALSE, &context))
7061 break;
7062
7063 /* Copy an info stream with a name ":anything:$DATA".
7064 * Skip "::$DATA", it has no stream name (examples suggest
7065 * it might be used for the normal file contents).
7066 * Note that BackupRead() counts bytes, but the name is in
7067 * wide characters. */
7068 len = readcount / sizeof(WCHAR);
7069 streamname[len] = 0;
7070 if (len > 7 && wcsicmp(streamname + len - 6,
7071 L":$DATA") == 0)
7072 {
7073 streamname[len - 6] = 0;
7074 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007075 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007076 }
7077 }
7078
7079 /* Advance to the next stream. We might try seeking too far,
7080 * but BackupSeek() doesn't skip over stream borders, thus
7081 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007082 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007083 &lo, &hi, &context);
7084 }
7085
7086 /* Clear the context. */
7087 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7088
7089 CloseHandle(sh);
7090 }
7091 }
7092 vim_free(fromw);
7093 vim_free(tow);
7094}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007095
7096/*
7097 * Copy file attributes from file "from" to file "to".
7098 * For Windows NT and later we copy info streams.
7099 * Always returns zero, errors are ignored.
7100 */
7101 int
7102mch_copy_file_attribute(char_u *from, char_u *to)
7103{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007104 /* File streams only work on Windows NT and later. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007105 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007106 return 0;
7107}
7108
7109#if defined(MYRESETSTKOFLW) || defined(PROTO)
7110/*
7111 * Recreate a destroyed stack guard page in win32.
7112 * Written by Benjamin Peterson.
7113 */
7114
7115/* These magic numbers are from the MS header files */
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007116# define MIN_STACK_WINNT 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00007117
7118/*
7119 * This function does the same thing as _resetstkoflw(), which is only
7120 * available in DevStudio .net and later.
7121 * Returns 0 for failure, 1 for success.
7122 */
7123 int
7124myresetstkoflw(void)
7125{
7126 BYTE *pStackPtr;
7127 BYTE *pGuardPage;
7128 BYTE *pStackBase;
7129 BYTE *pLowestPossiblePage;
7130 MEMORY_BASIC_INFORMATION mbi;
7131 SYSTEM_INFO si;
7132 DWORD nPageSize;
7133 DWORD dummy;
7134
Bram Moolenaar071d4272004-06-13 20:20:40 +00007135 /* We need to know the system page size. */
7136 GetSystemInfo(&si);
7137 nPageSize = si.dwPageSize;
7138
7139 /* ...and the current stack pointer */
7140 pStackPtr = (BYTE*)_alloca(1);
7141
7142 /* ...and the base of the stack. */
7143 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
7144 return 0;
7145 pStackBase = (BYTE*)mbi.AllocationBase;
7146
7147 /* ...and the page thats min_stack_req pages away from stack base; this is
7148 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007149 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007150
Bram Moolenaar071d4272004-06-13 20:20:40 +00007151 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007152 /* We want the first committed page in the stack Start at the stack
7153 * base and move forward through memory until we find a committed block.
7154 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007155 BYTE *pBlock = pStackBase;
7156
Bram Moolenaara466c992005-07-09 21:03:22 +00007157 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007158 {
7159 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
7160 return 0;
7161
7162 pBlock += mbi.RegionSize;
7163
7164 if (mbi.State & MEM_COMMIT)
7165 break;
7166 }
7167
7168 /* mbi now describes the first committed block in the stack. */
7169 if (mbi.Protect & PAGE_GUARD)
7170 return 1;
7171
7172 /* decide where the guard page should start */
7173 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
7174 pGuardPage = pLowestPossiblePage;
7175 else
7176 pGuardPage = (BYTE*)mbi.BaseAddress;
7177
7178 /* allocate the guard page */
7179 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
7180 return 0;
7181
7182 /* apply the guard attribute to the page */
7183 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
7184 &dummy))
7185 return 0;
7186 }
7187
7188 return 1;
7189}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007190#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007191
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007192
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007193/*
7194 * The command line arguments in UCS2
7195 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007196static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007197static LPWSTR *ArglistW = NULL;
7198static int global_argc = 0;
7199static char **global_argv;
7200
7201static int used_file_argc = 0; /* last argument in global_argv[] used
7202 for the argument list. */
7203static int *used_file_indexes = NULL; /* indexes in global_argv[] for
7204 command line arguments added to
7205 the argument list */
7206static int used_file_count = 0; /* nr of entries in used_file_indexes */
7207static int used_file_literal = FALSE; /* take file names literally */
7208static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007209static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007210static int used_alist_count = 0;
7211
7212
7213/*
7214 * Get the command line arguments. Unicode version.
7215 * Returns argc. Zero when something fails.
7216 */
7217 int
7218get_cmd_argsW(char ***argvp)
7219{
7220 char **argv = NULL;
7221 int argc = 0;
7222 int i;
7223
Bram Moolenaar14993322014-09-09 12:25:33 +02007224 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007225 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7226 if (ArglistW != NULL)
7227 {
7228 argv = malloc((nArgsW + 1) * sizeof(char *));
7229 if (argv != NULL)
7230 {
7231 argc = nArgsW;
7232 argv[argc] = NULL;
7233 for (i = 0; i < argc; ++i)
7234 {
7235 int len;
7236
7237 /* Convert each Unicode argument to the current codepage. */
7238 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007239 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007240 (LPSTR *)&argv[i], &len, 0, 0);
7241 if (argv[i] == NULL)
7242 {
7243 /* Out of memory, clear everything. */
7244 while (i > 0)
7245 free(argv[--i]);
7246 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007247 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007248 argc = 0;
7249 }
7250 }
7251 }
7252 }
7253
7254 global_argc = argc;
7255 global_argv = argv;
7256 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007257 {
7258 if (used_file_indexes != NULL)
7259 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007260 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007261 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007262
7263 if (argvp != NULL)
7264 *argvp = argv;
7265 return argc;
7266}
7267
7268 void
7269free_cmd_argsW(void)
7270{
7271 if (ArglistW != NULL)
7272 {
7273 GlobalFree(ArglistW);
7274 ArglistW = NULL;
7275 }
7276}
7277
7278/*
7279 * Remember "name" is an argument that was added to the argument list.
7280 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7281 * is called.
7282 */
7283 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007284used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007285{
7286 int i;
7287
7288 if (used_file_indexes == NULL)
7289 return;
7290 for (i = used_file_argc + 1; i < global_argc; ++i)
7291 if (STRCMP(global_argv[i], name) == 0)
7292 {
7293 used_file_argc = i;
7294 used_file_indexes[used_file_count++] = i;
7295 break;
7296 }
7297 used_file_literal = literal;
7298 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007299 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007300}
7301
7302/*
7303 * Remember the length of the argument list as it was. If it changes then we
7304 * leave it alone when 'encoding' is set.
7305 */
7306 void
7307set_alist_count(void)
7308{
7309 used_alist_count = GARGCOUNT;
7310}
7311
7312/*
7313 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7314 * has been changed while starting up. Use the UCS-2 command line arguments
7315 * and convert them to 'encoding'.
7316 */
7317 void
7318fix_arg_enc(void)
7319{
7320 int i;
7321 int idx;
7322 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007323 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007324
7325 /* Safety checks:
7326 * - if argument count differs between the wide and non-wide argument
7327 * list, something must be wrong.
7328 * - the file name arguments must have been located.
7329 * - the length of the argument list wasn't changed by the user.
7330 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007331 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007332 || ArglistW == NULL
7333 || used_file_indexes == NULL
7334 || used_file_count == 0
7335 || used_alist_count != GARGCOUNT)
7336 return;
7337
Bram Moolenaar86b68352004-12-27 21:59:20 +00007338 /* Remember the buffer numbers for the arguments. */
7339 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7340 if (fnum_list == NULL)
7341 return; /* out of memory */
7342 for (i = 0; i < GARGCOUNT; ++i)
7343 fnum_list[i] = GARGLIST[i].ae_fnum;
7344
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007345 /* Clear the argument list. Make room for the new arguments. */
7346 alist_clear(&global_alist);
7347 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007348 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007349
7350 for (i = 0; i < used_file_count; ++i)
7351 {
7352 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007353 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007354 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007355 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007356 int literal = used_file_literal;
7357
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007358# ifdef FEAT_DIFF
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007359 /* When using diff mode may need to concatenate file name to
7360 * directory name. Just like it's done in main(). */
7361 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7362 && !mch_isdir(alist_name(&GARGLIST[0])))
7363 {
7364 char_u *r;
7365
7366 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7367 if (r != NULL)
7368 {
7369 vim_free(str);
7370 str = r;
7371 }
7372 }
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007373# endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007374 /* Re-use the old buffer by renaming it. When not using literal
7375 * names it's done by alist_expand() below. */
7376 if (used_file_literal)
7377 buf_set_name(fnum_list[i], str);
7378
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007379 /* Check backtick literal. backtick literal is already expanded in
7380 * main.c, so this part add str as literal. */
7381 if (literal == FALSE)
7382 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007383 size_t len = STRLEN(str);
7384
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007385 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7386 literal = TRUE;
7387 }
7388 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007389 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007390 }
7391
7392 if (!used_file_literal)
7393 {
7394 /* Now expand wildcards in the arguments. */
7395 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7396 * filename characters but are excluded from 'isfname' to make
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007397 * "gf" work on a file name in parenthesis (e.g.: see vim.h).
7398 * Also, unset wildignore to not be influenced by this option.
7399 * The arguments specified in command-line should be kept even if
7400 * encoding options were changed. */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007401 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007402 do_cmdline_cmd((char_u *)":let SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007403 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007404 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007405 do_cmdline_cmd((char_u *)":let &wig = SaVe_WIG|unlet SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007406 }
7407
7408 /* If wildcard expansion failed, we are editing the first file of the
7409 * arglist and there is no file name: Edit the first argument now. */
7410 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7411 {
7412 do_cmdline_cmd((char_u *)":rewind");
7413 if (GARGCOUNT == 1 && used_file_full_path)
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007414 (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007415 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007416
7417 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007418}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007419
7420 int
7421mch_setenv(char *var, char *value, int x)
7422{
7423 char_u *envbuf;
7424
7425 envbuf = alloc((unsigned)(STRLEN(var) + STRLEN(value) + 2));
7426 if (envbuf == NULL)
7427 return -1;
7428
7429 sprintf((char *)envbuf, "%s=%s", var, value);
7430
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007431 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
7432 {
7433 WCHAR *p = enc_to_utf16(envbuf, NULL);
7434
7435 vim_free(envbuf);
7436 if (p == NULL)
7437 return -1;
7438 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007439#ifdef libintl_wputenv
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007440 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007441#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007442 /* Unlike Un*x systems, we can free the string for _wputenv(). */
7443 vim_free(p);
7444 }
7445 else
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007446 {
7447 _putenv((char *)envbuf);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007448#ifdef libintl_putenv
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007449 libintl_putenv((char *)envbuf);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007450#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007451 /* Unlike Un*x systems, we can free the string for _putenv(). */
7452 vim_free(envbuf);
7453 }
7454
7455 return 0;
7456}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007457
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007458/*
7459 * Support for 256 colors and 24-bit colors was added in Windows 10
7460 * version 1703 (Creators update).
7461 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007462#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7463
7464/*
7465 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007466 * version 1809 (October 2018 update). However, that version is unstable.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007467 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007468#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
7469#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007470
7471 static void
7472vtp_flag_init(void)
7473{
7474 DWORD ver = get_build_number();
Bram Moolenaar4f974752019-02-17 17:44:42 +01007475#ifndef FEAT_GUI_MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007476 DWORD mode;
7477 HANDLE out;
7478
7479 out = GetStdHandle(STD_OUTPUT_HANDLE);
7480
7481 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7482 GetConsoleMode(out, &mode);
7483 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7484 if (SetConsoleMode(out, mode) == 0)
7485 vtp_working = 0;
7486#endif
7487
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007488 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007489 conpty_working = 1;
7490 if (ver >= CONPTY_STABLE_BUILD)
7491 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007492
7493}
7494
Bram Moolenaar4f974752019-02-17 17:44:42 +01007495#if !defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007496
7497 static void
7498vtp_init(void)
7499{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007500 HMODULE hKerneldll;
7501 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007502# ifdef FEAT_TERMGUICOLORS
7503 COLORREF fg, bg;
7504# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007505
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007506 /* Use functions supported from Vista */
7507 hKerneldll = GetModuleHandle("kernel32.dll");
7508 if (hKerneldll != NULL)
7509 {
7510 pGetConsoleScreenBufferInfoEx =
7511 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7512 hKerneldll, "GetConsoleScreenBufferInfoEx");
7513 pSetConsoleScreenBufferInfoEx =
7514 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7515 hKerneldll, "SetConsoleScreenBufferInfoEx");
7516 if (pGetConsoleScreenBufferInfoEx != NULL
7517 && pSetConsoleScreenBufferInfoEx != NULL)
7518 has_csbiex = TRUE;
7519 }
7520
7521 csbi.cbSize = sizeof(csbi);
7522 if (has_csbiex)
7523 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007524 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7525 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
7526
7527# ifdef FEAT_TERMGUICOLORS
7528 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7529 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7530 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7531 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7532 default_console_color_bg = bg;
7533 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007534# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007535
7536 set_console_color_rgb();
7537}
7538
7539 static void
7540vtp_exit(void)
7541{
7542 reset_console_color_rgb();
7543}
7544
7545 static int
7546vtp_printf(
7547 char *format,
7548 ...)
7549{
7550 char_u buf[100];
7551 va_list list;
7552 DWORD result;
7553
7554 va_start(list, format);
7555 vim_vsnprintf((char *)buf, 100, (char *)format, list);
7556 va_end(list);
7557 WriteConsoleA(g_hConOut, buf, (DWORD)STRLEN(buf), &result, NULL);
7558 return (int)result;
7559}
7560
7561 static void
7562vtp_sgr_bulk(
7563 int arg)
7564{
7565 int args[1];
7566
7567 args[0] = arg;
7568 vtp_sgr_bulks(1, args);
7569}
7570
7571 static void
7572vtp_sgr_bulks(
7573 int argc,
7574 int *args
7575)
7576{
7577 /* 2('\033[') + 4('255.') * 16 + NUL */
7578 char_u buf[2 + (4 * 16) + 1];
7579 char_u *p;
7580 int i;
7581
7582 p = buf;
7583 *p++ = '\033';
7584 *p++ = '[';
7585
7586 for (i = 0; i < argc; ++i)
7587 {
7588 p += vim_snprintf((char *)p, 4, "%d", args[i] & 0xff);
7589 *p++ = ';';
7590 }
7591 p--;
7592 *p++ = 'm';
7593 *p = NUL;
7594 vtp_printf((char *)buf);
7595}
7596
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007597# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007598 static int
7599ctermtoxterm(
7600 int cterm)
7601{
Bram Moolenaar9894e392018-05-05 14:29:06 +02007602 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007603
7604 cterm_color2rgb(cterm, &r, &g, &b, &idx);
7605 return (((int)r << 16) | ((int)g << 8) | (int)b);
7606}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007607# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007608
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007609 static void
7610set_console_color_rgb(void)
7611{
7612# ifdef FEAT_TERMGUICOLORS
7613 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7614 int id;
7615 guicolor_T fg = INVALCOLOR;
7616 guicolor_T bg = INVALCOLOR;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007617 int ctermfg;
7618 int ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007619
7620 if (!USE_VTP)
7621 return;
7622
7623 id = syn_name2id((char_u *)"Normal");
Bram Moolenaard5a58862019-03-07 06:40:27 +01007624 if (id > 0 && p_tgc)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007625 syn_id2colors(id, &fg, &bg);
7626 if (fg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007627 {
7628 ctermfg = -1;
7629 if (id > 0)
7630 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007631 fg = ctermfg != -1 ? ctermtoxterm(ctermfg) : default_console_color_fg;
7632 cterm_normal_fg_gui_color = fg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007633 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007634 if (bg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007635 {
7636 ctermbg = -1;
7637 if (id > 0)
7638 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007639 bg = ctermbg != -1 ? ctermtoxterm(ctermbg) : default_console_color_bg;
7640 cterm_normal_bg_gui_color = bg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007641 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007642 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7643 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7644
7645 csbi.cbSize = sizeof(csbi);
7646 if (has_csbiex)
7647 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7648
7649 csbi.cbSize = sizeof(csbi);
7650 csbi.srWindow.Right += 1;
7651 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007652 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
7653 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007654 if (has_csbiex)
7655 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7656# endif
7657}
7658
7659 static void
7660reset_console_color_rgb(void)
7661{
7662# ifdef FEAT_TERMGUICOLORS
7663 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7664
7665 csbi.cbSize = sizeof(csbi);
7666 if (has_csbiex)
7667 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7668
7669 csbi.cbSize = sizeof(csbi);
7670 csbi.srWindow.Right += 1;
7671 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007672 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
7673 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007674 if (has_csbiex)
7675 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7676# endif
7677}
7678
7679 void
7680control_console_color_rgb(void)
7681{
7682 if (USE_VTP)
7683 set_console_color_rgb();
7684 else
7685 reset_console_color_rgb();
7686}
7687
7688 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007689use_vtp(void)
7690{
7691 return USE_VTP;
7692}
7693
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007694 int
7695is_term_win32(void)
7696{
7697 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
7698}
7699
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007700 int
7701has_vtp_working(void)
7702{
7703 return vtp_working;
7704}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007705
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01007706#endif
7707
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007708 int
7709has_conpty_working(void)
7710{
7711 return conpty_working;
7712}
7713
7714 int
7715is_conpty_stable(void)
7716{
7717 return conpty_stable;
7718}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01007719
Bram Moolenaar4f974752019-02-17 17:44:42 +01007720#if !defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01007721 void
7722resize_console_buf(void)
7723{
7724 CONSOLE_SCREEN_BUFFER_INFO csbi;
7725 COORD coord;
7726 SMALL_RECT newsize;
7727
7728 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
7729 {
7730 coord.X = SRWIDTH(csbi.srWindow);
7731 coord.Y = SRHEIGHT(csbi.srWindow);
7732 SetConsoleScreenBufferSize(g_hConOut, coord);
7733
7734 newsize.Left = 0;
7735 newsize.Top = 0;
7736 newsize.Right = coord.X - 1;
7737 newsize.Bottom = coord.Y - 1;
7738 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
7739
7740 SetConsoleScreenBufferSize(g_hConOut, coord);
7741 }
7742}
7743#endif