blob: fe729d4de20d3eabbf089b4e05fd92876e239f88 [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))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002227 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002228 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2229 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002230 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002231
2232 return TRUE;
2233}
2234
2235/*
2236 * FitConsoleWindow()
2237 * Description:
2238 * Checks if the console window will fit within given buffer dimensions.
2239 * Also, if requested, will shrink the window to fit.
2240 * Returns:
2241 * TRUE on success
2242 */
2243 static BOOL
2244FitConsoleWindow(
2245 COORD dwBufferSize,
2246 BOOL WantAdjust)
2247{
2248 CONSOLE_SCREEN_BUFFER_INFO csbi;
2249 COORD dwWindowSize;
2250 BOOL NeedAdjust = FALSE;
2251
2252 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2253 {
2254 /*
2255 * A buffer resize will fail if the current console window does
2256 * not lie completely within that buffer. To avoid this, we might
2257 * have to move and possibly shrink the window.
2258 */
2259 if (csbi.srWindow.Right >= dwBufferSize.X)
2260 {
2261 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2262 if (dwWindowSize.X > dwBufferSize.X)
2263 dwWindowSize.X = dwBufferSize.X;
2264 csbi.srWindow.Right = dwBufferSize.X - 1;
2265 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2266 NeedAdjust = TRUE;
2267 }
2268 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2269 {
2270 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2271 if (dwWindowSize.Y > dwBufferSize.Y)
2272 dwWindowSize.Y = dwBufferSize.Y;
2273 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2274 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2275 NeedAdjust = TRUE;
2276 }
2277 if (NeedAdjust && WantAdjust)
2278 {
2279 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2280 return FALSE;
2281 }
2282 return TRUE;
2283 }
2284
2285 return FALSE;
2286}
2287
2288typedef struct ConsoleBufferStruct
2289{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002290 BOOL IsValid;
2291 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002292 PCHAR_INFO Buffer;
2293 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002294 PSMALL_RECT Regions;
2295 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002296} ConsoleBuffer;
2297
2298/*
2299 * SaveConsoleBuffer()
2300 * Description:
2301 * Saves important information about the console buffer, including the
2302 * actual buffer contents. The saved information is suitable for later
2303 * restoration by RestoreConsoleBuffer().
2304 * Returns:
2305 * TRUE if all information was saved; FALSE otherwise
2306 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2307 */
2308 static BOOL
2309SaveConsoleBuffer(
2310 ConsoleBuffer *cb)
2311{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002312 DWORD NumCells;
2313 COORD BufferCoord;
2314 SMALL_RECT ReadRegion;
2315 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002316 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002317
Bram Moolenaar071d4272004-06-13 20:20:40 +00002318 if (cb == NULL)
2319 return FALSE;
2320
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002321 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002322 {
2323 cb->IsValid = FALSE;
2324 return FALSE;
2325 }
2326 cb->IsValid = TRUE;
2327
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002328 /*
2329 * Allocate a buffer large enough to hold the entire console screen
2330 * buffer. If this ConsoleBuffer structure has already been initialized
2331 * with a buffer of the correct size, then just use that one.
2332 */
2333 if (!cb->IsValid || cb->Buffer == NULL ||
2334 cb->BufferSize.X != cb->Info.dwSize.X ||
2335 cb->BufferSize.Y != cb->Info.dwSize.Y)
2336 {
2337 cb->BufferSize.X = cb->Info.dwSize.X;
2338 cb->BufferSize.Y = cb->Info.dwSize.Y;
2339 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2340 vim_free(cb->Buffer);
2341 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2342 if (cb->Buffer == NULL)
2343 return FALSE;
2344 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002345
2346 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002347 * We will now copy the console screen buffer into our buffer.
2348 * ReadConsoleOutput() seems to be limited as far as how much you
2349 * can read at a time. Empirically, this number seems to be about
2350 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2351 * in chunks until it is all copied. The chunks will all have the
2352 * same horizontal characteristics, so initialize them now. The
2353 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002354 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002355 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002356 ReadRegion.Left = 0;
2357 ReadRegion.Right = cb->Info.dwSize.X - 1;
2358 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002359
2360 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2361 if (cb->Regions == NULL || numregions != cb->NumRegions)
2362 {
2363 cb->NumRegions = numregions;
2364 vim_free(cb->Regions);
2365 cb->Regions = (PSMALL_RECT)alloc(cb->NumRegions * sizeof(SMALL_RECT));
2366 if (cb->Regions == NULL)
2367 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002368 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002369 return FALSE;
2370 }
2371 }
2372
2373 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002374 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002375 /*
2376 * Read into position (0, Y) in our buffer.
2377 */
2378 BufferCoord.Y = Y;
2379 /*
2380 * Read the region whose top left corner is (0, Y) and whose bottom
2381 * right corner is (width - 1, Y + Y_incr - 1). This should define
2382 * a region of size width by Y_incr. Don't worry if this region is
2383 * too large for the remaining buffer; it will be cropped.
2384 */
2385 ReadRegion.Top = Y;
2386 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002387 if (!ReadConsoleOutputW(g_hConOut, /* output handle */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002388 cb->Buffer, /* our buffer */
2389 cb->BufferSize, /* dimensions of our buffer */
2390 BufferCoord, /* offset in our buffer */
2391 &ReadRegion)) /* region to save */
2392 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002393 VIM_CLEAR(cb->Buffer);
2394 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002395 return FALSE;
2396 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002397 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002398 }
2399
2400 return TRUE;
2401}
2402
2403/*
2404 * RestoreConsoleBuffer()
2405 * Description:
2406 * Restores important information about the console buffer, including the
2407 * actual buffer contents, if desired. The information to restore is in
2408 * the same format used by SaveConsoleBuffer().
2409 * Returns:
2410 * TRUE on success
2411 */
2412 static BOOL
2413RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002414 ConsoleBuffer *cb,
2415 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002416{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002417 COORD BufferCoord;
2418 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002419 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002420
2421 if (cb == NULL || !cb->IsValid)
2422 return FALSE;
2423
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002424 /*
2425 * Before restoring the buffer contents, clear the current buffer, and
2426 * restore the cursor position and window information. Doing this now
2427 * prevents old buffer contents from "flashing" onto the screen.
2428 */
2429 if (RestoreScreen)
2430 ClearConsoleBuffer(cb->Info.wAttributes);
2431
2432 FitConsoleWindow(cb->Info.dwSize, TRUE);
2433 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2434 return FALSE;
2435 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2436 return FALSE;
2437
2438 if (!RestoreScreen)
2439 {
2440 /*
2441 * No need to restore the screen buffer contents, so we're done.
2442 */
2443 return TRUE;
2444 }
2445
2446 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2447 return FALSE;
2448 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2449 return FALSE;
2450
2451 /*
2452 * Restore the screen buffer contents.
2453 */
2454 if (cb->Buffer != NULL)
2455 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002456 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002457 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002458 BufferCoord.X = cb->Regions[i].Left;
2459 BufferCoord.Y = cb->Regions[i].Top;
2460 WriteRegion = cb->Regions[i];
2461 if (!WriteConsoleOutputW(g_hConOut, /* output handle */
2462 cb->Buffer, /* our buffer */
2463 cb->BufferSize, /* dimensions of our buffer */
2464 BufferCoord, /* offset in our buffer */
2465 &WriteRegion)) /* region to restore */
Bram Moolenaar444fda22017-08-11 20:37:00 +02002466 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002467 }
2468 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002469
2470 return TRUE;
2471}
2472
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002473#define FEAT_RESTORE_ORIG_SCREEN
2474#ifdef FEAT_RESTORE_ORIG_SCREEN
2475static ConsoleBuffer g_cbOrig = { 0 };
2476#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002477static ConsoleBuffer g_cbNonTermcap = { 0 };
2478static ConsoleBuffer g_cbTermcap = { 0 };
2479
2480#ifdef FEAT_TITLE
2481#ifdef __BORLANDC__
2482typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2483#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002484typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002485#endif
2486char g_szOrigTitle[256] = { 0 };
2487HWND g_hWnd = NULL; /* also used in os_mswin.c */
2488static HICON g_hOrigIconSmall = NULL;
2489static HICON g_hOrigIcon = NULL;
2490static HICON g_hVimIcon = NULL;
2491static BOOL g_fCanChangeIcon = FALSE;
2492
2493/* ICON* are not defined in VC++ 4.0 */
2494#ifndef ICON_SMALL
2495#define ICON_SMALL 0
2496#endif
2497#ifndef ICON_BIG
2498#define ICON_BIG 1
2499#endif
2500/*
2501 * GetConsoleIcon()
2502 * Description:
2503 * Attempts to retrieve the small icon and/or the big icon currently in
2504 * use by a given window.
2505 * Returns:
2506 * TRUE on success
2507 */
2508 static BOOL
2509GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002510 HWND hWnd,
2511 HICON *phIconSmall,
2512 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002513{
2514 if (hWnd == NULL)
2515 return FALSE;
2516
2517 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002518 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2519 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002520 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002521 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2522 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002523 return TRUE;
2524}
2525
2526/*
2527 * SetConsoleIcon()
2528 * Description:
2529 * Attempts to change the small icon and/or the big icon currently in
2530 * use by a given window.
2531 * Returns:
2532 * TRUE on success
2533 */
2534 static BOOL
2535SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002536 HWND hWnd,
2537 HICON hIconSmall,
2538 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002539{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002540 if (hWnd == NULL)
2541 return FALSE;
2542
2543 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002544 SendMessage(hWnd, WM_SETICON,
2545 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002546 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002547 SendMessage(hWnd, WM_SETICON,
2548 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002549 return TRUE;
2550}
2551
2552/*
2553 * SaveConsoleTitleAndIcon()
2554 * Description:
2555 * Saves the current console window title in g_szOrigTitle, for later
2556 * restoration. Also, attempts to obtain a handle to the console window,
2557 * and use it to save the small and big icons currently in use by the
2558 * console window. This is not always possible on some versions of Windows;
2559 * nor is it possible when running Vim remotely using Telnet (since the
2560 * console window the user sees is owned by a remote process).
2561 */
2562 static void
2563SaveConsoleTitleAndIcon(void)
2564{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002565 /* Save the original title. */
2566 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2567 return;
2568
2569 /*
2570 * Obtain a handle to the console window using GetConsoleWindow() from
2571 * KERNEL32.DLL; we need to handle in order to change the window icon.
2572 * This function only exists on NT-based Windows, starting with Windows
2573 * 2000. On older operating systems, we can't change the window icon
2574 * anyway.
2575 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002576 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002577 if (g_hWnd == NULL)
2578 return;
2579
2580 /* Save the original console window icon. */
2581 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2582 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2583 return;
2584
2585 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002586 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002587 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002588 if (g_hVimIcon != NULL)
2589 g_fCanChangeIcon = TRUE;
2590}
2591#endif
2592
2593static int g_fWindInitCalled = FALSE;
2594static int g_fTermcapMode = FALSE;
2595static CONSOLE_CURSOR_INFO g_cci;
2596static DWORD g_cmodein = 0;
2597static DWORD g_cmodeout = 0;
2598
2599/*
2600 * non-GUI version of mch_init().
2601 */
2602 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002603mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002604{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002605#ifndef FEAT_RESTORE_ORIG_SCREEN
2606 CONSOLE_SCREEN_BUFFER_INFO csbi;
2607#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002608#ifndef __MINGW32__
2609 extern int _fmode;
2610#endif
2611
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002612 /* Silently handle invalid parameters to CRT functions */
2613 SET_INVALID_PARAM_HANDLER;
2614
Bram Moolenaar071d4272004-06-13 20:20:40 +00002615 /* Let critical errors result in a failure, not in a dialog box. Required
2616 * for the timestamp test to work on removed floppies. */
2617 SetErrorMode(SEM_FAILCRITICALERRORS);
2618
2619 _fmode = O_BINARY; /* we do our own CR-LF translation */
2620 out_flush();
2621
2622 /* Obtain handles for the standard Console I/O devices */
2623 if (read_cmd_fd == 0)
2624 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2625 else
2626 create_conin();
2627 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2628
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002629#ifdef FEAT_RESTORE_ORIG_SCREEN
2630 /* Save the initial console buffer for later restoration */
2631 SaveConsoleBuffer(&g_cbOrig);
2632 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2633#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002634 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002635 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2636 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2637#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002638 if (cterm_normal_fg_color == 0)
2639 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2640 if (cterm_normal_bg_color == 0)
2641 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2642
Bram Moolenaarbdace832019-03-02 10:13:42 +01002643 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002644 g_color_index_fg = g_attrDefault & 0xf;
2645 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2646
Bram Moolenaar071d4272004-06-13 20:20:40 +00002647 /* set termcap codes to current text attributes */
2648 update_tcap(g_attrCurrent);
2649
2650 GetConsoleCursorInfo(g_hConOut, &g_cci);
2651 GetConsoleMode(g_hConIn, &g_cmodein);
2652 GetConsoleMode(g_hConOut, &g_cmodeout);
2653
2654#ifdef FEAT_TITLE
2655 SaveConsoleTitleAndIcon();
2656 /*
2657 * Set both the small and big icons of the console window to Vim's icon.
2658 * Note that Vim presently only has one size of icon (32x32), but it
2659 * automatically gets scaled down to 16x16 when setting the small icon.
2660 */
2661 if (g_fCanChangeIcon)
2662 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2663#endif
2664
2665 ui_get_shellsize();
2666
2667#ifdef MCH_WRITE_DUMP
2668 fdDump = fopen("dump", "wt");
2669
2670 if (fdDump)
2671 {
2672 time_t t;
2673
2674 time(&t);
2675 fputs(ctime(&t), fdDump);
2676 fflush(fdDump);
2677 }
2678#endif
2679
2680 g_fWindInitCalled = TRUE;
2681
2682#ifdef FEAT_MOUSE
2683 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2684#endif
2685
2686#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002687 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002688#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002689
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002690 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002691 vtp_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002692}
2693
2694/*
2695 * non-GUI version of mch_exit().
2696 * Shut down and exit with status `r'
2697 * Careful: mch_exit() may be called before mch_init()!
2698 */
2699 void
2700mch_exit(int r)
2701{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002702 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002703
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002704 vtp_exit();
2705
Bram Moolenaar955f1982017-02-05 15:10:51 +01002706 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002707 if (g_fWindInitCalled)
2708 settmode(TMODE_COOK);
2709
2710 ml_close_all(TRUE); /* remove all memfiles */
2711
2712 if (g_fWindInitCalled)
2713 {
2714#ifdef FEAT_TITLE
Bram Moolenaar40385db2018-08-07 22:31:44 +02002715 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002716 /*
2717 * Restore both the small and big icons of the console window to
2718 * what they were at startup. Don't do this when the window is
2719 * closed, Vim would hang here.
2720 */
2721 if (g_fCanChangeIcon && !g_fForceExit)
2722 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2723#endif
2724
2725#ifdef MCH_WRITE_DUMP
2726 if (fdDump)
2727 {
2728 time_t t;
2729
2730 time(&t);
2731 fputs(ctime(&t), fdDump);
2732 fclose(fdDump);
2733 }
2734 fdDump = NULL;
2735#endif
2736 }
2737
2738 SetConsoleCursorInfo(g_hConOut, &g_cci);
2739 SetConsoleMode(g_hConIn, g_cmodein);
2740 SetConsoleMode(g_hConOut, g_cmodeout);
2741
2742#ifdef DYNAMIC_GETTEXT
2743 dyn_libintl_end();
2744#endif
2745
2746 exit(r);
2747}
Bram Moolenaar4f974752019-02-17 17:44:42 +01002748#endif /* !FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002749
Bram Moolenaar071d4272004-06-13 20:20:40 +00002750/*
2751 * Do we have an interactive window?
2752 */
2753 int
2754mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002755 int argc UNUSED,
2756 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002757{
2758 get_exe_name();
2759
Bram Moolenaar4f974752019-02-17 17:44:42 +01002760#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002761 return OK; /* GUI always has a tty */
2762#else
2763 if (isatty(1))
2764 return OK;
2765 return FAIL;
2766#endif
2767}
2768
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002769/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002770 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002771 * When "len" is > 0, also expand short to long filenames.
2772 */
2773 void
2774fname_case(
2775 char_u *name,
2776 int len)
2777{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002778 int flen;
2779 WCHAR *p;
2780 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002781
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002782 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002783 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002784 return;
2785
2786 slash_adjust(name);
2787
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002788 p = enc_to_utf16(name, NULL);
2789 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002790 return;
2791
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002792 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002793 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002794 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002795
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002796 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002797 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002798 if (len > 0 || flen >= (int)STRLEN(q))
2799 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2800 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002801 }
2802 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002803 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002804}
2805
2806
2807/*
2808 * Insert user name in s[len].
2809 */
2810 int
2811mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002812 char_u *s,
2813 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002814{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002815 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002816 DWORD cch = sizeof szUserName;
2817
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002818 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2819 {
2820 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2821 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2822
2823 if (GetUserNameW(wszUserName, &wcch))
2824 {
2825 char_u *p = utf16_to_enc(wszUserName, NULL);
2826
2827 if (p != NULL)
2828 {
2829 vim_strncpy(s, p, len - 1);
2830 vim_free(p);
2831 return OK;
2832 }
2833 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002834 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002835 if (GetUserName(szUserName, &cch))
2836 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002837 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002838 return OK;
2839 }
2840 s[0] = NUL;
2841 return FAIL;
2842}
2843
2844
2845/*
2846 * Insert host name in s[len].
2847 */
2848 void
2849mch_get_host_name(
2850 char_u *s,
2851 int len)
2852{
2853 DWORD cch = len;
2854
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002855 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2856 {
2857 WCHAR wszHostName[256 + 1];
2858 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2859
2860 if (GetComputerNameW(wszHostName, &wcch))
2861 {
2862 char_u *p = utf16_to_enc(wszHostName, NULL);
2863
2864 if (p != NULL)
2865 {
2866 vim_strncpy(s, p, len - 1);
2867 vim_free(p);
2868 return;
2869 }
2870 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002871 }
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002872 if (!GetComputerName((LPSTR)s, &cch))
2873 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002874}
2875
2876
2877/*
2878 * return process ID
2879 */
2880 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002881mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002882{
2883 return (long)GetCurrentProcessId();
2884}
2885
2886
2887/*
2888 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2889 * Return OK for success, FAIL for failure.
2890 */
2891 int
2892mch_dirname(
2893 char_u *buf,
2894 int len)
2895{
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002896 char_u abuf[_MAX_PATH + 1];
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02002897 DWORD lfnlen;
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002898
Bram Moolenaar071d4272004-06-13 20:20:40 +00002899 /*
2900 * Originally this was:
2901 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2902 * But the Win32s known bug list says that getcwd() doesn't work
2903 * so use the Win32 system call instead. <Negri>
2904 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002905 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2906 {
2907 WCHAR wbuf[_MAX_PATH + 1];
2908
2909 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2910 {
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002911 WCHAR wcbuf[_MAX_PATH + 1];
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02002912 char_u *p = NULL;
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002913
2914 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02002915 {
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002916 p = utf16_to_enc(wcbuf, NULL);
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02002917 if (STRLEN(p) >= (size_t)len)
2918 {
2919 // long path name is too long, fall back to short one
2920 vim_free(p);
2921 p = NULL;
2922 }
2923 }
2924 if (p == NULL)
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002925 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002926
2927 if (p != NULL)
2928 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002929 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002930 vim_free(p);
2931 return OK;
2932 }
2933 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002934 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002935 }
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002936 if (GetCurrentDirectory(len, (LPSTR)buf) == 0)
2937 return FAIL;
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02002938 lfnlen = GetLongPathNameA((LPCSTR)buf, (LPSTR)abuf, _MAX_PATH);
2939 if (lfnlen == 0 || lfnlen >= (DWORD)len)
2940 // Failed to get long path name or it's too long: fall back to the
2941 // short path name.
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002942 return OK;
2943
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02002944 STRCPY(buf, abuf);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002945 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002946}
2947
2948/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01002949 * Get file permissions for "name".
2950 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002951 */
2952 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002953mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002954{
Bram Moolenaar8767f522016-07-01 17:17:39 +02002955 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01002956 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002957
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002958 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01002959 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002960}
2961
2962
2963/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002964 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002965 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002966 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002967 */
2968 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002969mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002970{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002971 long n = -1;
2972
Bram Moolenaar071d4272004-06-13 20:20:40 +00002973 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2974 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002975 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002976
2977 if (p != NULL)
2978 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002979 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002980 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002981 if (n == -1)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002982 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002983 }
2984 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002985 if (n == -1)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002986 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002987 if (n == -1)
2988 return FAIL;
2989
2990 win32_set_archive(name);
2991
2992 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002993}
2994
2995/*
2996 * Set hidden flag for "name".
2997 */
2998 void
2999mch_hide(char_u *name)
3000{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003001 int attrs = win32_getattrs(name);
3002 if (attrs == -1)
3003 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003004
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003005 attrs |= FILE_ATTRIBUTE_HIDDEN;
3006 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003007}
3008
3009/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003010 * Return TRUE if file "name" exists and is hidden.
3011 */
3012 int
3013mch_ishidden(char_u *name)
3014{
3015 int f = win32_getattrs(name);
3016
3017 if (f == -1)
3018 return FALSE; /* file does not exist at all */
3019
3020 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3021}
3022
3023/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003024 * return TRUE if "name" is a directory
3025 * return FALSE if "name" is not a directory or upon error
3026 */
3027 int
3028mch_isdir(char_u *name)
3029{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003030 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003031
3032 if (f == -1)
3033 return FALSE; /* file does not exist at all */
3034
3035 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3036}
3037
3038/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003039 * return TRUE if "name" is a directory, NOT a symlink to a directory
3040 * return FALSE if "name" is not a directory
3041 * return FALSE for error
3042 */
3043 int
3044mch_isrealdir(char_u *name)
3045{
3046 return mch_isdir(name) && !mch_is_symbolic_link(name);
3047}
3048
3049/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003050 * Create directory "name".
3051 * Return 0 on success, -1 on error.
3052 */
3053 int
3054mch_mkdir(char_u *name)
3055{
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003056 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3057 {
3058 WCHAR *p;
3059 int retval;
3060
3061 p = enc_to_utf16(name, NULL);
3062 if (p == NULL)
3063 return -1;
3064 retval = _wmkdir(p);
3065 vim_free(p);
3066 return retval;
3067 }
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003068 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003069}
3070
3071/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003072 * Delete directory "name".
3073 * Return 0 on success, -1 on error.
3074 */
3075 int
3076mch_rmdir(char_u *name)
3077{
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003078 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3079 {
3080 WCHAR *p;
3081 int retval;
3082
3083 p = enc_to_utf16(name, NULL);
3084 if (p == NULL)
3085 return -1;
3086 retval = _wrmdir(p);
3087 vim_free(p);
3088 return retval;
3089 }
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003090 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003091}
3092
3093/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003094 * Return TRUE if file "fname" has more than one link.
3095 */
3096 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003097mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003098{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003099 BY_HANDLE_FILE_INFORMATION info;
3100
3101 return win32_fileinfo(fname, &info) == FILEINFO_OK
3102 && info.nNumberOfLinks > 1;
3103}
3104
3105/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003106 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003107 */
3108 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003109mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003110{
3111 HANDLE hFind;
3112 int res = FALSE;
3113 WIN32_FIND_DATAA findDataA;
3114 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003115 WCHAR *wn = NULL;
3116 WIN32_FIND_DATAW findDataW;
3117
3118 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003119 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003120 if (wn != NULL)
3121 {
3122 hFind = FindFirstFileW(wn, &findDataW);
3123 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003124 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003125 {
3126 fileFlags = findDataW.dwFileAttributes;
3127 reparseTag = findDataW.dwReserved0;
3128 }
3129 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003130 else
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003131 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003132 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003133 if (hFind != INVALID_HANDLE_VALUE)
3134 {
3135 fileFlags = findDataA.dwFileAttributes;
3136 reparseTag = findDataA.dwReserved0;
3137 }
3138 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003139
3140 if (hFind != INVALID_HANDLE_VALUE)
3141 FindClose(hFind);
3142
3143 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003144 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3145 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003146 res = TRUE;
3147
3148 return res;
3149}
3150
3151/*
3152 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3153 * link.
3154 */
3155 int
3156mch_is_linked(char_u *fname)
3157{
3158 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3159 return TRUE;
3160 return FALSE;
3161}
3162
3163/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003164 * Get the by-handle-file-information for "fname".
3165 * Returns FILEINFO_OK when OK.
3166 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3167 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3168 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3169 */
3170 int
3171win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3172{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003173 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003174 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003175 WCHAR *wn = NULL;
3176
3177 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003178 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003179 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003180 if (wn == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003181 return FILEINFO_ENC_FAIL;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003182 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003183 if (wn != NULL)
3184 {
3185 hFile = CreateFileW(wn, /* file name */
3186 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003187 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003188 NULL, /* security descriptor */
3189 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003190 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003191 NULL); /* handle to template file */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003192 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003193 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003194 else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003195 hFile = CreateFile((LPCSTR)fname, /* file name */
3196 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003197 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003198 NULL, /* security descriptor */
3199 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003200 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003201 NULL); /* handle to template file */
3202
3203 if (hFile != INVALID_HANDLE_VALUE)
3204 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003205 if (GetFileInformationByHandle(hFile, info) != 0)
3206 res = FILEINFO_OK;
3207 else
3208 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003209 CloseHandle(hFile);
3210 }
3211
Bram Moolenaar03f48552006-02-28 23:52:23 +00003212 return res;
3213}
3214
3215/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003216 * get file attributes for `name'
3217 * -1 : error
3218 * else FILE_ATTRIBUTE_* defined in winnt.h
3219 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003220 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003221win32_getattrs(char_u *name)
3222{
3223 int attr;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003224 WCHAR *p = NULL;
3225
3226 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3227 p = enc_to_utf16(name, NULL);
3228
3229 if (p != NULL)
3230 {
3231 attr = GetFileAttributesW(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003232 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003233 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003234 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003235 attr = GetFileAttributes((char *)name);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003236
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003237 return attr;
3238}
3239
3240/*
3241 * set file attributes for `name' to `attrs'
3242 *
3243 * return -1 for failure, 0 otherwise
3244 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003245 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003246win32_setattrs(char_u *name, int attrs)
3247{
3248 int res;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003249 WCHAR *p = NULL;
3250
3251 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3252 p = enc_to_utf16(name, NULL);
3253
3254 if (p != NULL)
3255 {
3256 res = SetFileAttributesW(p, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003257 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003258 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003259 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003260 res = SetFileAttributes((char *)name, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003261
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003262 return res ? 0 : -1;
3263}
3264
3265/*
3266 * Set archive flag for "name".
3267 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003268 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003269win32_set_archive(char_u *name)
3270{
3271 int attrs = win32_getattrs(name);
3272 if (attrs == -1)
3273 return -1;
3274
3275 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3276 return win32_setattrs(name, attrs);
3277}
3278
3279/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003280 * Return TRUE if file or directory "name" is writable (not readonly).
3281 * Strange semantics of Win32: a readonly directory is writable, but you can't
3282 * delete a file. Let's say this means it is writable.
3283 */
3284 int
3285mch_writable(char_u *name)
3286{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003287 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003288
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003289 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3290 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003291}
3292
Bram Moolenaar071d4272004-06-13 20:20:40 +00003293/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003294 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003295 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003296 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3297 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003298 */
3299 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003300mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003301{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003302 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003303 int len = (int)STRLEN(name);
Bram Moolenaar82956662018-10-06 15:18:45 +02003304 char_u *p, *saved;
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003305
3306 if (len >= _MAX_PATH) /* safety check */
3307 return FALSE;
3308
Bram Moolenaar82956662018-10-06 15:18:45 +02003309 /* Ty using the name directly when a Unix-shell like 'shell'. */
3310 if (strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaar43663192017-03-05 14:29:12 +01003311 if (executable_exists((char *)name, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003312 return TRUE;
3313
3314 /*
3315 * Loop over all extensions in $PATHEXT.
3316 */
Bram Moolenaar82956662018-10-06 15:18:45 +02003317 p = mch_getenv("PATHEXT");
3318 if (p == NULL)
3319 p = (char_u *)".com;.exe;.bat;.cmd";
3320 saved = vim_strsave(p);
3321 if (saved == NULL)
3322 return FALSE;
3323 p = saved;
3324 while (*p)
3325 {
3326 char_u *tmp = vim_strchr(p, ';');
3327
3328 if (tmp != NULL)
3329 *tmp = NUL;
3330 if (_stricoll((char *)name + len - STRLEN(p), (char *)p) == 0
3331 && executable_exists((char *)name, path, use_path))
3332 {
3333 vim_free(saved);
3334 return TRUE;
3335 }
3336 if (tmp == NULL)
3337 break;
3338 p = tmp + 1;
3339 }
3340 vim_free(saved);
3341
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003342 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003343 p = mch_getenv("PATHEXT");
3344 if (p == NULL)
3345 p = (char_u *)".com;.exe;.bat;.cmd";
3346 while (*p)
3347 {
3348 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3349 {
3350 /* A single "." means no extension is added. */
3351 buf[len] = NUL;
3352 ++p;
3353 if (*p)
3354 ++p;
3355 }
3356 else
3357 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaar43663192017-03-05 14:29:12 +01003358 if (executable_exists((char *)buf, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003359 return TRUE;
3360 }
3361 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003362}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003363
3364/*
3365 * Check what "name" is:
3366 * NODE_NORMAL: file or directory (or doesn't exist)
3367 * NODE_WRITABLE: writable device, socket, fifo, etc.
3368 * NODE_OTHER: non-writable things
3369 */
3370 int
3371mch_nodetype(char_u *name)
3372{
3373 HANDLE hFile;
3374 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003375 WCHAR *wn = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003376
Bram Moolenaar043545e2006-10-10 16:44:07 +00003377 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3378 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3379 * here. */
3380 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3381 return NODE_WRITABLE;
3382
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003383 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003384 wn = enc_to_utf16(name, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003385
3386 if (wn != NULL)
3387 {
3388 hFile = CreateFileW(wn, /* file name */
3389 GENERIC_WRITE, /* access mode */
3390 0, /* share mode */
3391 NULL, /* security descriptor */
3392 OPEN_EXISTING, /* creation disposition */
3393 0, /* file attributes */
3394 NULL); /* handle to template file */
3395 vim_free(wn);
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003396 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003397 else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003398 hFile = CreateFile((LPCSTR)name, /* file name */
3399 GENERIC_WRITE, /* access mode */
3400 0, /* share mode */
3401 NULL, /* security descriptor */
3402 OPEN_EXISTING, /* creation disposition */
3403 0, /* file attributes */
3404 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003405
3406 if (hFile == INVALID_HANDLE_VALUE)
3407 return NODE_NORMAL;
3408
3409 type = GetFileType(hFile);
3410 CloseHandle(hFile);
3411 if (type == FILE_TYPE_CHAR)
3412 return NODE_WRITABLE;
3413 if (type == FILE_TYPE_DISK)
3414 return NODE_NORMAL;
3415 return NODE_OTHER;
3416}
3417
3418#ifdef HAVE_ACL
3419struct my_acl
3420{
3421 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3422 PSID pSidOwner;
3423 PSID pSidGroup;
3424 PACL pDacl;
3425 PACL pSacl;
3426};
3427#endif
3428
3429/*
3430 * Return a pointer to the ACL of file "fname" in allocated memory.
3431 * Return NULL if the ACL is not available for whatever reason.
3432 */
3433 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003434mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003435{
3436#ifndef HAVE_ACL
3437 return (vim_acl_T)NULL;
3438#else
3439 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003440 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003441
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003442 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3443 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003444 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003445 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003446
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003447 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3448 wn = enc_to_utf16(fname, NULL);
3449 if (wn != NULL)
3450 {
3451 /* Try to retrieve the entire security descriptor. */
3452 err = GetNamedSecurityInfoW(
3453 wn, // Abstract filename
3454 SE_FILE_OBJECT, // File Object
3455 OWNER_SECURITY_INFORMATION |
3456 GROUP_SECURITY_INFORMATION |
3457 DACL_SECURITY_INFORMATION |
3458 SACL_SECURITY_INFORMATION,
3459 &p->pSidOwner, // Ownership information.
3460 &p->pSidGroup, // Group membership.
3461 &p->pDacl, // Discretionary information.
3462 &p->pSacl, // For auditing purposes.
3463 &p->pSecurityDescriptor);
3464 if (err == ERROR_ACCESS_DENIED ||
3465 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003466 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003467 /* Retrieve only DACL. */
3468 (void)GetNamedSecurityInfoW(
3469 wn,
3470 SE_FILE_OBJECT,
3471 DACL_SECURITY_INFORMATION,
3472 NULL,
3473 NULL,
3474 &p->pDacl,
3475 NULL,
3476 &p->pSecurityDescriptor);
Bram Moolenaar27515922013-06-29 15:36:26 +02003477 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003478 if (p->pSecurityDescriptor == NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003479 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003480 mch_free_acl((vim_acl_T)p);
3481 p = NULL;
3482 }
3483 vim_free(wn);
3484 }
3485 else
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003486 {
3487 /* Try to retrieve the entire security descriptor. */
3488 err = GetNamedSecurityInfo(
3489 (LPSTR)fname, // Abstract filename
3490 SE_FILE_OBJECT, // File Object
3491 OWNER_SECURITY_INFORMATION |
3492 GROUP_SECURITY_INFORMATION |
3493 DACL_SECURITY_INFORMATION |
3494 SACL_SECURITY_INFORMATION,
3495 &p->pSidOwner, // Ownership information.
3496 &p->pSidGroup, // Group membership.
3497 &p->pDacl, // Discretionary information.
3498 &p->pSacl, // For auditing purposes.
3499 &p->pSecurityDescriptor);
3500 if (err == ERROR_ACCESS_DENIED ||
3501 err == ERROR_PRIVILEGE_NOT_HELD)
3502 {
3503 /* Retrieve only DACL. */
3504 (void)GetNamedSecurityInfo(
3505 (LPSTR)fname,
3506 SE_FILE_OBJECT,
3507 DACL_SECURITY_INFORMATION,
3508 NULL,
3509 NULL,
3510 &p->pDacl,
3511 NULL,
3512 &p->pSecurityDescriptor);
3513 }
3514 if (p->pSecurityDescriptor == NULL)
3515 {
3516 mch_free_acl((vim_acl_T)p);
3517 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003518 }
3519 }
3520 }
3521
3522 return (vim_acl_T)p;
3523#endif
3524}
3525
Bram Moolenaar27515922013-06-29 15:36:26 +02003526#ifdef HAVE_ACL
3527/*
3528 * Check if "acl" contains inherited ACE.
3529 */
3530 static BOOL
3531is_acl_inherited(PACL acl)
3532{
3533 DWORD i;
3534 ACL_SIZE_INFORMATION acl_info;
3535 PACCESS_ALLOWED_ACE ace;
3536
3537 acl_info.AceCount = 0;
3538 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3539 for (i = 0; i < acl_info.AceCount; i++)
3540 {
3541 GetAce(acl, i, (LPVOID *)&ace);
3542 if (ace->Header.AceFlags & INHERITED_ACE)
3543 return TRUE;
3544 }
3545 return FALSE;
3546}
3547#endif
3548
Bram Moolenaar071d4272004-06-13 20:20:40 +00003549/*
3550 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3551 * Errors are ignored.
3552 * This must only be called with "acl" equal to what mch_get_acl() returned.
3553 */
3554 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003555mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003556{
3557#ifdef HAVE_ACL
3558 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003559 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003560
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003561 if (p != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003562 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003563 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003564
3565 /* Set security flags */
3566 if (p->pSidOwner)
3567 sec_info |= OWNER_SECURITY_INFORMATION;
3568 if (p->pSidGroup)
3569 sec_info |= GROUP_SECURITY_INFORMATION;
3570 if (p->pDacl)
3571 {
3572 sec_info |= DACL_SECURITY_INFORMATION;
3573 /* Do not inherit its parent's DACL.
3574 * If the DACL is inherited, Cygwin permissions would be changed.
3575 */
3576 if (!is_acl_inherited(p->pDacl))
3577 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3578 }
3579 if (p->pSacl)
3580 sec_info |= SACL_SECURITY_INFORMATION;
3581
Bram Moolenaar27515922013-06-29 15:36:26 +02003582 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3583 wn = enc_to_utf16(fname, NULL);
3584 if (wn != NULL)
3585 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003586 (void)SetNamedSecurityInfoW(
Bram Moolenaar27515922013-06-29 15:36:26 +02003587 wn, // Abstract filename
3588 SE_FILE_OBJECT, // File Object
3589 sec_info,
3590 p->pSidOwner, // Ownership information.
3591 p->pSidGroup, // Group membership.
3592 p->pDacl, // Discretionary information.
3593 p->pSacl // For auditing purposes.
3594 );
3595 vim_free(wn);
3596 }
3597 else
Bram Moolenaar27515922013-06-29 15:36:26 +02003598 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003599 (void)SetNamedSecurityInfo(
Bram Moolenaar27515922013-06-29 15:36:26 +02003600 (LPSTR)fname, // Abstract filename
3601 SE_FILE_OBJECT, // File Object
3602 sec_info,
3603 p->pSidOwner, // Ownership information.
3604 p->pSidGroup, // Group membership.
3605 p->pDacl, // Discretionary information.
3606 p->pSacl // For auditing purposes.
3607 );
3608 }
3609 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003610#endif
3611}
3612
3613 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003614mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003615{
3616#ifdef HAVE_ACL
3617 struct my_acl *p = (struct my_acl *)acl;
3618
3619 if (p != NULL)
3620 {
3621 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3622 vim_free(p);
3623 }
3624#endif
3625}
3626
Bram Moolenaar4f974752019-02-17 17:44:42 +01003627#ifndef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003628
3629/*
3630 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3631 */
3632 static BOOL WINAPI
3633handler_routine(
3634 DWORD dwCtrlType)
3635{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003636 INPUT_RECORD ir;
3637 DWORD out;
3638
Bram Moolenaar071d4272004-06-13 20:20:40 +00003639 switch (dwCtrlType)
3640 {
3641 case CTRL_C_EVENT:
3642 if (ctrl_c_interrupts)
3643 g_fCtrlCPressed = TRUE;
3644 return TRUE;
3645
3646 case CTRL_BREAK_EVENT:
3647 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003648 ctrl_break_was_pressed = TRUE;
3649 /* ReadConsoleInput is blocking, send a key event to continue. */
3650 ir.EventType = KEY_EVENT;
3651 ir.Event.KeyEvent.bKeyDown = TRUE;
3652 ir.Event.KeyEvent.wRepeatCount = 1;
3653 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3654 ir.Event.KeyEvent.wVirtualScanCode = 0;
3655 ir.Event.KeyEvent.dwControlKeyState = 0;
3656 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3657 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003658 return TRUE;
3659
3660 /* fatal events: shut down gracefully */
3661 case CTRL_CLOSE_EVENT:
3662 case CTRL_LOGOFF_EVENT:
3663 case CTRL_SHUTDOWN_EVENT:
3664 windgoto((int)Rows - 1, 0);
3665 g_fForceExit = TRUE;
3666
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003667 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003668 (dwCtrlType == CTRL_CLOSE_EVENT
3669 ? _("close")
3670 : dwCtrlType == CTRL_LOGOFF_EVENT
3671 ? _("logoff")
3672 : _("shutdown")));
3673#ifdef DEBUG
3674 OutputDebugString(IObuff);
3675#endif
3676
3677 preserve_exit(); /* output IObuff, preserve files and exit */
3678
3679 return TRUE; /* not reached */
3680
3681 default:
3682 return FALSE;
3683 }
3684}
3685
3686
3687/*
3688 * set the tty in (raw) ? "raw" : "cooked" mode
3689 */
3690 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003691mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003692{
3693 DWORD cmodein;
3694 DWORD cmodeout;
3695 BOOL bEnableHandler;
3696
3697 GetConsoleMode(g_hConIn, &cmodein);
3698 GetConsoleMode(g_hConOut, &cmodeout);
3699 if (tmode == TMODE_RAW)
3700 {
3701 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3702 ENABLE_ECHO_INPUT);
3703#ifdef FEAT_MOUSE
3704 if (g_fMouseActive)
3705 cmodein |= ENABLE_MOUSE_INPUT;
3706#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003707 cmodeout &= ~(
3708#ifdef FEAT_TERMGUICOLORS
3709 /* Do not turn off the ENABLE_PROCESSRD_OUTPUT flag when using
3710 * VTP. */
3711 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
3712#else
3713 ENABLE_PROCESSED_OUTPUT |
3714#endif
3715 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003716 bEnableHandler = TRUE;
3717 }
3718 else /* cooked */
3719 {
3720 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3721 ENABLE_ECHO_INPUT);
3722 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3723 bEnableHandler = FALSE;
3724 }
3725 SetConsoleMode(g_hConIn, cmodein);
3726 SetConsoleMode(g_hConOut, cmodeout);
3727 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3728
3729#ifdef MCH_WRITE_DUMP
3730 if (fdDump)
3731 {
3732 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3733 tmode == TMODE_RAW ? "raw" :
3734 tmode == TMODE_COOK ? "cooked" : "normal",
3735 cmodein, cmodeout);
3736 fflush(fdDump);
3737 }
3738#endif
3739}
3740
3741
3742/*
3743 * Get the size of the current window in `Rows' and `Columns'
3744 * Return OK when size could be determined, FAIL otherwise.
3745 */
3746 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003747mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003748{
3749 CONSOLE_SCREEN_BUFFER_INFO csbi;
3750
3751 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3752 {
3753 /*
3754 * For some reason, we are trying to get the screen dimensions
3755 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3756 * variables are really intended to mean the size of Vim screen
3757 * while in termcap mode.
3758 */
3759 Rows = g_cbTermcap.Info.dwSize.Y;
3760 Columns = g_cbTermcap.Info.dwSize.X;
3761 }
3762 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3763 {
3764 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3765 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3766 }
3767 else
3768 {
3769 Rows = 25;
3770 Columns = 80;
3771 }
3772 return OK;
3773}
3774
3775/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003776 * Resize console buffer to 'COORD'
3777 */
3778 static void
3779ResizeConBuf(
3780 HANDLE hConsole,
3781 COORD coordScreen)
3782{
3783 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3784 {
3785#ifdef MCH_WRITE_DUMP
3786 if (fdDump)
3787 {
3788 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3789 GetLastError());
3790 fflush(fdDump);
3791 }
3792#endif
3793 }
3794}
3795
3796/*
3797 * Resize console window size to 'srWindowRect'
3798 */
3799 static void
3800ResizeWindow(
3801 HANDLE hConsole,
3802 SMALL_RECT srWindowRect)
3803{
3804 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
3805 {
3806#ifdef MCH_WRITE_DUMP
3807 if (fdDump)
3808 {
3809 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3810 GetLastError());
3811 fflush(fdDump);
3812 }
3813#endif
3814 }
3815}
3816
3817/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003818 * Set a console window to `xSize' * `ySize'
3819 */
3820 static void
3821ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003822 HANDLE hConsole,
3823 int xSize,
3824 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003825{
3826 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3827 SMALL_RECT srWindowRect; /* hold the new console size */
3828 COORD coordScreen;
Bram Moolenaar2551c032018-08-23 22:38:31 +02003829 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003830
3831#ifdef MCH_WRITE_DUMP
3832 if (fdDump)
3833 {
3834 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3835 fflush(fdDump);
3836 }
3837#endif
3838
3839 /* get the largest size we can size the console window to */
3840 coordScreen = GetLargestConsoleWindowSize(hConsole);
3841
3842 /* define the new console window size and scroll position */
3843 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3844 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3845 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3846
3847 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3848 {
3849 int sx, sy;
3850
3851 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3852 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3853 if (sy < ySize || sx < xSize)
3854 {
3855 /*
3856 * Increasing number of lines/columns, do buffer first.
3857 * Use the maximal size in x and y direction.
3858 */
3859 if (sy < ySize)
3860 coordScreen.Y = ySize;
3861 else
3862 coordScreen.Y = sy;
3863 if (sx < xSize)
3864 coordScreen.X = xSize;
3865 else
3866 coordScreen.X = sx;
3867 SetConsoleScreenBufferSize(hConsole, coordScreen);
3868 }
3869 }
3870
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003871 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003872 coordScreen.X = xSize;
3873 coordScreen.Y = ySize;
3874
Bram Moolenaar2551c032018-08-23 22:38:31 +02003875 // In the new console call API, only the first time in reverse order
3876 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003877 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003878 ResizeWindow(hConsole, srWindowRect);
3879 ResizeConBuf(hConsole, coordScreen);
3880 }
3881 else
3882 {
3883 ResizeConBuf(hConsole, coordScreen);
3884 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02003885 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003886 }
3887}
3888
3889
3890/*
3891 * Set the console window to `Rows' * `Columns'
3892 */
3893 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003894mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003895{
3896 COORD coordScreen;
3897
3898 /* Don't change window size while still starting up */
3899 if (suppress_winsize != 0)
3900 {
3901 suppress_winsize = 2;
3902 return;
3903 }
3904
3905 if (term_console)
3906 {
3907 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3908
3909 /* Clamp Rows and Columns to reasonable values */
3910 if (Rows > coordScreen.Y)
3911 Rows = coordScreen.Y;
3912 if (Columns > coordScreen.X)
3913 Columns = coordScreen.X;
3914
3915 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3916 }
3917}
3918
3919/*
3920 * Rows and/or Columns has changed.
3921 */
3922 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003923mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003924{
3925 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3926}
3927
3928
3929/*
3930 * Called when started up, to set the winsize that was delayed.
3931 */
3932 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003933mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003934{
3935 if (suppress_winsize == 2)
3936 {
3937 suppress_winsize = 0;
3938 mch_set_shellsize();
3939 shell_resized();
3940 }
3941 suppress_winsize = 0;
3942}
Bram Moolenaar4f974752019-02-17 17:44:42 +01003943#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003944
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003945 static BOOL
3946vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003947 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003948 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01003949 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003950 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003951 PROCESS_INFORMATION *pi,
3952 LPVOID *env,
3953 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003954{
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003955 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3956 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003957 BOOL ret;
3958 WCHAR *wcmd, *wcwd = NULL;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003959
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003960 wcmd = enc_to_utf16((char_u *)cmd, NULL);
3961 if (wcmd == NULL)
3962 goto fallback;
3963 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003964 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003965 wcwd = enc_to_utf16((char_u *)cwd, NULL);
3966 if (wcwd == NULL)
3967 {
3968 vim_free(wcmd);
3969 goto fallback;
3970 }
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003971 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003972
3973 ret = CreateProcessW(
3974 NULL, /* Executable name */
3975 wcmd, /* Command to execute */
3976 NULL, /* Process security attributes */
3977 NULL, /* Thread security attributes */
3978 inherit_handles, /* Inherit handles */
3979 flags, /* Creation flags */
3980 env, /* Environment */
3981 wcwd, /* Current directory */
3982 (LPSTARTUPINFOW)si, /* Startup information */
3983 pi); /* Process information */
3984 vim_free(wcmd);
Bram Moolenaarbdace832019-03-02 10:13:42 +01003985 vim_free(wcwd);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003986 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003987 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003988fallback:
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003989 return CreateProcess(
3990 NULL, /* Executable name */
3991 cmd, /* Command to execute */
3992 NULL, /* Process security attributes */
3993 NULL, /* Thread security attributes */
3994 inherit_handles, /* Inherit handles */
3995 flags, /* Creation flags */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003996 env, /* Environment */
3997 cwd, /* Current directory */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003998 si, /* Startup information */
3999 pi); /* Process information */
4000}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004001
4002
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004003 static HINSTANCE
4004vim_shell_execute(
4005 char *cmd,
4006 INT n_show_cmd)
4007{
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004008 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4009 {
4010 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
4011 if (wcmd != NULL)
4012 {
4013 HINSTANCE ret;
4014 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4015 vim_free(wcmd);
4016 return ret;
4017 }
4018 }
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004019 return ShellExecute(NULL, NULL, cmd, NULL, NULL, n_show_cmd);
4020}
4021
4022
Bram Moolenaar4f974752019-02-17 17:44:42 +01004023#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004024
4025/*
4026 * Specialised version of system() for Win32 GUI mode.
4027 * This version proceeds as follows:
4028 * 1. Create a console window for use by the subprocess
4029 * 2. Run the subprocess (it gets the allocated console by default)
4030 * 3. Wait for the subprocess to terminate and get its exit code
4031 * 4. Prompt the user to press a key to close the console window
4032 */
4033 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004034mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004035{
4036 STARTUPINFO si;
4037 PROCESS_INFORMATION pi;
4038 DWORD ret = 0;
4039 HWND hwnd = GetFocus();
4040
4041 si.cb = sizeof(si);
4042 si.lpReserved = NULL;
4043 si.lpDesktop = NULL;
4044 si.lpTitle = NULL;
4045 si.dwFlags = STARTF_USESHOWWINDOW;
4046 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004047 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004048 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004049 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004050 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004051 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004052 else
4053 si.wShowWindow = SW_SHOWNORMAL;
4054 si.cbReserved2 = 0;
4055 si.lpReserved2 = NULL;
4056
Bram Moolenaar071d4272004-06-13 20:20:40 +00004057 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004058 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004059 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4060 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004061
4062 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004063 {
4064#ifdef FEAT_GUI
4065 int delay = 1;
4066
4067 /* Keep updating the window while waiting for the shell to finish. */
4068 for (;;)
4069 {
4070 MSG msg;
4071
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004072 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004073 {
4074 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004075 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004076 delay = 1;
4077 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004078 }
4079 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4080 break;
4081
4082 /* We start waiting for a very short time and then increase it, so
4083 * that we respond quickly when the process is quick, and don't
4084 * consume too much overhead when it's slow. */
4085 if (delay < 50)
4086 delay += 10;
4087 }
4088#else
4089 WaitForSingleObject(pi.hProcess, INFINITE);
4090#endif
4091
4092 /* Get the command exit code */
4093 GetExitCodeProcess(pi.hProcess, &ret);
4094 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004095
4096 /* Close the handles to the subprocess, so that it goes away */
4097 CloseHandle(pi.hThread);
4098 CloseHandle(pi.hProcess);
4099
4100 /* Try to get input focus back. Doesn't always work though. */
4101 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4102
4103 return ret;
4104}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004105
4106/*
4107 * Thread launched by the gui to send the current buffer data to the
4108 * process. This way avoid to hang up vim totally if the children
4109 * process take a long time to process the lines.
4110 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004111 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004112sub_process_writer(LPVOID param)
4113{
4114 HANDLE g_hChildStd_IN_Wr = param;
4115 linenr_T lnum = curbuf->b_op_start.lnum;
4116 DWORD len = 0;
4117 DWORD l;
4118 char_u *lp = ml_get(lnum);
4119 char_u *s;
4120 int written = 0;
4121
4122 for (;;)
4123 {
4124 l = (DWORD)STRLEN(lp + written);
4125 if (l == 0)
4126 len = 0;
4127 else if (lp[written] == NL)
4128 {
4129 /* NL -> NUL translation */
4130 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4131 }
4132 else
4133 {
4134 s = vim_strchr(lp + written, NL);
4135 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4136 s == NULL ? l : (DWORD)(s - (lp + written)),
4137 &len, NULL);
4138 }
4139 if (len == (int)l)
4140 {
4141 /* Finished a line, add a NL, unless this line should not have
4142 * one. */
4143 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004144 || (!curbuf->b_p_bin
4145 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004146 || (lnum != curbuf->b_no_eol_lnum
4147 && (lnum != curbuf->b_ml.ml_line_count
4148 || curbuf->b_p_eol)))
4149 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004150 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4151 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004152 }
4153
4154 ++lnum;
4155 if (lnum > curbuf->b_op_end.lnum)
4156 break;
4157
4158 lp = ml_get(lnum);
4159 written = 0;
4160 }
4161 else if (len > 0)
4162 written += len;
4163 }
4164
4165 /* finished all the lines, close pipe */
4166 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004167 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004168}
4169
4170
4171# define BUFLEN 100 /* length for buffer, stolen from unix version */
4172
4173/*
4174 * This function read from the children's stdout and write the
4175 * data on screen or in the buffer accordingly.
4176 */
4177 static void
4178dump_pipe(int options,
4179 HANDLE g_hChildStd_OUT_Rd,
4180 garray_T *ga,
4181 char_u buffer[],
4182 DWORD *buffer_off)
4183{
4184 DWORD availableBytes = 0;
4185 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004186 int ret;
4187 DWORD len;
4188 DWORD toRead;
4189 int repeatCount;
4190
4191 /* we query the pipe to see if there is any data to read
4192 * to avoid to perform a blocking read */
4193 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4194 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004195 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004196 NULL, /* number of read bytes */
4197 &availableBytes, /* available bytes total */
4198 NULL); /* byteLeft */
4199
4200 repeatCount = 0;
4201 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004202 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004203 {
4204 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004205 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004206 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004207 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004208
4209 /* If we haven't read anything, there is a problem */
4210 if (len == 0)
4211 break;
4212
4213 availableBytes -= len;
4214
4215 if (options & SHELL_READ)
4216 {
4217 /* Do NUL -> NL translation, append NL separated
4218 * lines to the current buffer. */
4219 for (i = 0; i < len; ++i)
4220 {
4221 if (buffer[i] == NL)
4222 append_ga_line(ga);
4223 else if (buffer[i] == NUL)
4224 ga_append(ga, NL);
4225 else
4226 ga_append(ga, buffer[i]);
4227 }
4228 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004229 else if (has_mbyte)
4230 {
4231 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004232 int c;
4233 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004234
4235 len += *buffer_off;
4236 buffer[len] = NUL;
4237
4238 /* Check if the last character in buffer[] is
4239 * incomplete, keep these bytes for the next
4240 * round. */
4241 for (p = buffer; p < buffer + len; p += l)
4242 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004243 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004244 if (l == 0)
4245 l = 1; /* NUL byte? */
4246 else if (MB_BYTE2LEN(*p) != l)
4247 break;
4248 }
4249 if (p == buffer) /* no complete character */
4250 {
4251 /* avoid getting stuck at an illegal byte */
4252 if (len >= 12)
4253 ++p;
4254 else
4255 {
4256 *buffer_off = len;
4257 return;
4258 }
4259 }
4260 c = *p;
4261 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004262 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004263 if (p < buffer + len)
4264 {
4265 *p = c;
4266 *buffer_off = (DWORD)((buffer + len) - p);
4267 mch_memmove(buffer, p, *buffer_off);
4268 return;
4269 }
4270 *buffer_off = 0;
4271 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004272 else
4273 {
4274 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004275 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004276 }
4277
4278 windgoto(msg_row, msg_col);
4279 cursor_on();
4280 out_flush();
4281 }
4282}
4283
4284/*
4285 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4286 * for communication and doesn't open any new window.
4287 */
4288 static int
4289mch_system_piped(char *cmd, int options)
4290{
4291 STARTUPINFO si;
4292 PROCESS_INFORMATION pi;
4293 DWORD ret = 0;
4294
4295 HANDLE g_hChildStd_IN_Rd = NULL;
4296 HANDLE g_hChildStd_IN_Wr = NULL;
4297 HANDLE g_hChildStd_OUT_Rd = NULL;
4298 HANDLE g_hChildStd_OUT_Wr = NULL;
4299
4300 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4301 DWORD len;
4302
4303 /* buffer used to receive keys */
4304 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4305 int ta_len = 0; /* valid bytes in ta_buf[] */
4306
4307 DWORD i;
4308 int c;
4309 int noread_cnt = 0;
4310 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004311 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004312 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004313 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004314
4315 SECURITY_ATTRIBUTES saAttr;
4316
4317 /* Set the bInheritHandle flag so pipe handles are inherited. */
4318 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4319 saAttr.bInheritHandle = TRUE;
4320 saAttr.lpSecurityDescriptor = NULL;
4321
4322 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4323 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004324 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004325 /* Create a pipe for the child process's STDIN. */
4326 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4327 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004328 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004329 {
4330 CloseHandle(g_hChildStd_IN_Rd);
4331 CloseHandle(g_hChildStd_IN_Wr);
4332 CloseHandle(g_hChildStd_OUT_Rd);
4333 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004334 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004335 }
4336
4337 si.cb = sizeof(si);
4338 si.lpReserved = NULL;
4339 si.lpDesktop = NULL;
4340 si.lpTitle = NULL;
4341 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4342
4343 /* set-up our file redirection */
4344 si.hStdError = g_hChildStd_OUT_Wr;
4345 si.hStdOutput = g_hChildStd_OUT_Wr;
4346 si.hStdInput = g_hChildStd_IN_Rd;
4347 si.wShowWindow = SW_HIDE;
4348 si.cbReserved2 = 0;
4349 si.lpReserved2 = NULL;
4350
4351 if (options & SHELL_READ)
4352 ga_init2(&ga, 1, BUFLEN);
4353
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004354 if (cmd != NULL)
4355 {
4356 p = (char *)vim_strsave((char_u *)cmd);
4357 if (p != NULL)
4358 unescape_shellxquote((char_u *)p, p_sxe);
4359 else
4360 p = cmd;
4361 }
4362
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004363 /* Now, run the command.
4364 * About "Inherit handles" being TRUE: this command can be litigious,
4365 * handle inheritance was deactivated for pending temp file, but, if we
4366 * deactivate it, the pipes don't work for some reason. */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004367 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4368 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004369
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004370 if (p != cmd)
4371 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004372
4373 /* Close our unused side of the pipes */
4374 CloseHandle(g_hChildStd_IN_Rd);
4375 CloseHandle(g_hChildStd_OUT_Wr);
4376
4377 if (options & SHELL_WRITE)
4378 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004379 HANDLE thread = (HANDLE)
4380 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004381 0, /* default stack size */
4382 sub_process_writer, /* function to be executed */
4383 g_hChildStd_IN_Wr, /* parameter */
4384 0, /* creation flag, start immediately */
4385 NULL); /* we don't care about thread id */
4386 CloseHandle(thread);
4387 g_hChildStd_IN_Wr = NULL;
4388 }
4389
4390 /* Keep updating the window while waiting for the shell to finish. */
4391 for (;;)
4392 {
4393 MSG msg;
4394
Bram Moolenaar175d0702013-12-11 18:36:33 +01004395 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004396 {
4397 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004398 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004399 }
4400
4401 /* write pipe information in the window */
4402 if ((options & (SHELL_READ|SHELL_WRITE))
4403# ifdef FEAT_GUI
4404 || gui.in_use
4405# endif
4406 )
4407 {
4408 len = 0;
4409 if (!(options & SHELL_EXPAND)
4410 && ((options &
4411 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4412 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4413# ifdef FEAT_GUI
4414 || gui.in_use
4415# endif
4416 )
4417 && (ta_len > 0 || noread_cnt > 4))
4418 {
4419 if (ta_len == 0)
4420 {
4421 /* Get extra characters when we don't have any. Reset the
4422 * counter and timer. */
4423 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004424 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4425 }
4426 if (ta_len > 0 || len > 0)
4427 {
4428 /*
4429 * For pipes: Check for CTRL-C: send interrupt signal to
4430 * child. Check for CTRL-D: EOF, close pipe to child.
4431 */
4432 if (len == 1 && cmd != NULL)
4433 {
4434 if (ta_buf[ta_len] == Ctrl_C)
4435 {
4436 /* Learn what exit code is expected, for
4437 * now put 9 as SIGKILL */
4438 TerminateProcess(pi.hProcess, 9);
4439 }
4440 if (ta_buf[ta_len] == Ctrl_D)
4441 {
4442 CloseHandle(g_hChildStd_IN_Wr);
4443 g_hChildStd_IN_Wr = NULL;
4444 }
4445 }
4446
4447 /* replace K_BS by <BS> and K_DEL by <DEL> */
4448 for (i = ta_len; i < ta_len + len; ++i)
4449 {
4450 if (ta_buf[i] == CSI && len - i > 2)
4451 {
4452 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4453 if (c == K_DEL || c == K_KDEL || c == K_BS)
4454 {
4455 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4456 (size_t)(len - i - 2));
4457 if (c == K_DEL || c == K_KDEL)
4458 ta_buf[i] = DEL;
4459 else
4460 ta_buf[i] = Ctrl_H;
4461 len -= 2;
4462 }
4463 }
4464 else if (ta_buf[i] == '\r')
4465 ta_buf[i] = '\n';
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004466 if (has_mbyte)
4467 i += (*mb_ptr2len_len)(ta_buf + i,
4468 ta_len + len - i) - 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004469 }
4470
4471 /*
4472 * For pipes: echo the typed characters. For a pty this
4473 * does not seem to work.
4474 */
4475 for (i = ta_len; i < ta_len + len; ++i)
4476 {
4477 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4478 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004479 else if (has_mbyte)
4480 {
4481 int l = (*mb_ptr2len)(ta_buf + i);
4482
4483 msg_outtrans_len(ta_buf + i, l);
4484 i += l - 1;
4485 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004486 else
4487 msg_outtrans_len(ta_buf + i, 1);
4488 }
4489 windgoto(msg_row, msg_col);
4490 out_flush();
4491
4492 ta_len += len;
4493
4494 /*
4495 * Write the characters to the child, unless EOF has been
4496 * typed for pipes. Write one character at a time, to
4497 * avoid losing too much typeahead. When writing buffer
4498 * lines, drop the typed characters (only check for
4499 * CTRL-C).
4500 */
4501 if (options & SHELL_WRITE)
4502 ta_len = 0;
4503 else if (g_hChildStd_IN_Wr != NULL)
4504 {
4505 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4506 1, &len, NULL);
4507 // if we are typing in, we want to keep things reactive
4508 delay = 1;
4509 if (len > 0)
4510 {
4511 ta_len -= len;
4512 mch_memmove(ta_buf, ta_buf + len, ta_len);
4513 }
4514 }
4515 }
4516 }
4517 }
4518
4519 if (ta_len)
4520 ui_inchar_undo(ta_buf, ta_len);
4521
4522 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4523 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004524 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004525 break;
4526 }
4527
4528 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004529 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004530
4531 /* We start waiting for a very short time and then increase it, so
4532 * that we respond quickly when the process is quick, and don't
4533 * consume too much overhead when it's slow. */
4534 if (delay < 50)
4535 delay += 10;
4536 }
4537
4538 /* Close the pipe */
4539 CloseHandle(g_hChildStd_OUT_Rd);
4540 if (g_hChildStd_IN_Wr != NULL)
4541 CloseHandle(g_hChildStd_IN_Wr);
4542
4543 WaitForSingleObject(pi.hProcess, INFINITE);
4544
4545 /* Get the command exit code */
4546 GetExitCodeProcess(pi.hProcess, &ret);
4547
4548 if (options & SHELL_READ)
4549 {
4550 if (ga.ga_len > 0)
4551 {
4552 append_ga_line(&ga);
4553 /* remember that the NL was missing */
4554 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4555 }
4556 else
4557 curbuf->b_no_eol_lnum = 0;
4558 ga_clear(&ga);
4559 }
4560
4561 /* Close the handles to the subprocess, so that it goes away */
4562 CloseHandle(pi.hThread);
4563 CloseHandle(pi.hProcess);
4564
4565 return ret;
4566}
4567
4568 static int
4569mch_system(char *cmd, int options)
4570{
4571 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004572 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004573 return mch_system_piped(cmd, options);
4574 else
4575 return mch_system_classic(cmd, options);
4576}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004577#else
4578
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004579 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004580mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004581{
4582 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4583 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004584 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004585 if (wcmd != NULL)
4586 {
4587 int ret = _wsystem(wcmd);
4588 vim_free(wcmd);
4589 return ret;
4590 }
4591 }
4592 return system(cmd);
4593}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004594
4595#endif
4596
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004597#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4598/*
4599 * Use a terminal window to run a shell command in.
4600 */
4601 static int
4602mch_call_shell_terminal(
4603 char_u *cmd,
4604 int options UNUSED) /* SHELL_*, see vim.h */
4605{
4606 jobopt_T opt;
4607 char_u *newcmd = NULL;
4608 typval_T argvar[2];
4609 long_u cmdlen;
4610 int retval = -1;
4611 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004612 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004613 aco_save_T aco;
4614 oparg_T oa; /* operator arguments */
4615
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004616 if (cmd == NULL)
4617 cmdlen = STRLEN(p_sh) + 1;
4618 else
4619 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004620 newcmd = lalloc(cmdlen, TRUE);
4621 if (newcmd == NULL)
4622 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004623 if (cmd == NULL)
4624 {
4625 STRCPY(newcmd, p_sh);
4626 ch_log(NULL, "starting terminal to run a shell");
4627 }
4628 else
4629 {
4630 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4631 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4632 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004633
4634 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004635
4636 argvar[0].v_type = VAR_STRING;
4637 argvar[0].vval.v_string = newcmd;
4638 argvar[1].v_type = VAR_UNKNOWN;
4639 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004640 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004641 {
4642 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004643 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004644 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004645
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004646 job = term_getjob(buf->b_term);
4647 ++job->jv_refcount;
4648
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004649 /* Find a window to make "buf" curbuf. */
4650 aucmd_prepbuf(&aco, buf);
4651
4652 clear_oparg(&oa);
4653 while (term_use_loop())
4654 {
4655 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4656 {
4657 /* If terminal_loop() returns OK we got a key that is handled
4658 * in Normal model. We don't do redrawing anyway. */
4659 if (terminal_loop(TRUE) == OK)
4660 normal_cmd(&oa, TRUE);
4661 }
4662 else
4663 normal_cmd(&oa, TRUE);
4664 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004665 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004666 ch_log(NULL, "system command finished");
4667
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004668 job_unref(job);
4669
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004670 /* restore curwin/curbuf and a few other things */
4671 aucmd_restbuf(&aco);
4672
4673 wait_return(TRUE);
4674 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4675
4676 vim_free(newcmd);
4677 return retval;
4678}
4679#endif
4680
Bram Moolenaar071d4272004-06-13 20:20:40 +00004681/*
4682 * Either execute a command by calling the shell or start a new shell
4683 */
4684 int
4685mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004686 char_u *cmd,
4687 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004688{
4689 int x = 0;
4690 int tmode = cur_tmode;
4691#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004692 char szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004693 int did_set_title = FALSE;
4694
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004695 /* Change the title to reflect that we are in a subshell. */
4696 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4697 {
4698 WCHAR szShellTitle[512];
4699
4700 if (GetConsoleTitleW(szShellTitle,
4701 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4702 {
4703 if (cmd == NULL)
4704 wcscat(szShellTitle, L" :sh");
4705 else
4706 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004707 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004708
4709 if (wn != NULL)
4710 {
4711 wcscat(szShellTitle, L" - !");
4712 if ((wcslen(szShellTitle) + wcslen(wn) <
4713 sizeof(szShellTitle)/sizeof(WCHAR)))
4714 wcscat(szShellTitle, wn);
4715 SetConsoleTitleW(szShellTitle);
4716 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004717 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004718 }
4719 }
4720 }
4721 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004722 if (!did_set_title)
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004723 /* Change the title to reflect that we are in a subshell. */
4724 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004725 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004726 if (cmd == NULL)
4727 strcat(szShellTitle, " :sh");
4728 else
4729 {
4730 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004731 if ((strlen(szShellTitle) + strlen((char *)cmd)
4732 < sizeof(szShellTitle)))
4733 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004734 }
4735 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004736 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004737#endif
4738
4739 out_flush();
4740
4741#ifdef MCH_WRITE_DUMP
4742 if (fdDump)
4743 {
4744 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4745 fflush(fdDump);
4746 }
4747#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004748#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4749 /* TODO: make the terminal window work with input or output redirected. */
4750 if (vim_strchr(p_go, GO_TERMINAL) != NULL
4751 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4752 {
4753 /* Use a terminal window to run the command in. */
4754 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004755# ifdef FEAT_TITLE
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004756 resettitle();
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004757# endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004758 return x;
4759 }
4760#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004761
4762 /*
4763 * Catch all deadly signals while running the external command, because a
4764 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4765 */
4766 signal(SIGINT, SIG_IGN);
4767#if defined(__GNUC__) && !defined(__MINGW32__)
4768 signal(SIGKILL, SIG_IGN);
4769#else
4770 signal(SIGBREAK, SIG_IGN);
4771#endif
4772 signal(SIGILL, SIG_IGN);
4773 signal(SIGFPE, SIG_IGN);
4774 signal(SIGSEGV, SIG_IGN);
4775 signal(SIGTERM, SIG_IGN);
4776 signal(SIGABRT, SIG_IGN);
4777
4778 if (options & SHELL_COOKED)
4779 settmode(TMODE_COOK); /* set to normal mode */
4780
4781 if (cmd == NULL)
4782 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004783 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004784 }
4785 else
4786 {
4787 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004788 char_u *newcmd = NULL;
4789 char_u *cmdbase = cmd;
4790 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004791
4792 /* Skip a leading ", ( and "(. */
4793 if (*cmdbase == '"' )
4794 ++cmdbase;
4795 if (*cmdbase == '(')
4796 ++cmdbase;
4797
Bram Moolenaar1c465442017-03-12 20:10:05 +01004798 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004799 {
4800 STARTUPINFO si;
4801 PROCESS_INFORMATION pi;
4802 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004803 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004804 char_u *p;
4805
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004806 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004807 si.cb = sizeof(si);
4808 si.lpReserved = NULL;
4809 si.lpDesktop = NULL;
4810 si.lpTitle = NULL;
4811 si.dwFlags = 0;
4812 si.cbReserved2 = 0;
4813 si.lpReserved2 = NULL;
4814
4815 cmdbase = skipwhite(cmdbase + 5);
4816 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004817 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004818 {
4819 cmdbase = skipwhite(cmdbase + 4);
4820 si.dwFlags = STARTF_USESHOWWINDOW;
4821 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004822 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004823 }
4824 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004825 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004826 {
4827 cmdbase = skipwhite(cmdbase + 2);
4828 flags = CREATE_NO_WINDOW;
4829 si.dwFlags = STARTF_USESTDHANDLES;
4830 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004831 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004832 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004833 NULL, // Security att.
4834 OPEN_EXISTING, // Open flags
4835 FILE_ATTRIBUTE_NORMAL, // File att.
4836 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004837 si.hStdOutput = si.hStdInput;
4838 si.hStdError = si.hStdInput;
4839 }
4840
4841 /* Remove a trailing ", ) and )" if they have a match
4842 * at the start of the command. */
4843 if (cmdbase > cmd)
4844 {
4845 p = cmdbase + STRLEN(cmdbase);
4846 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4847 *--p = NUL;
4848 if (p > cmdbase && p[-1] == ')'
4849 && (*cmd =='(' || cmd[1] == '('))
4850 *--p = NUL;
4851 }
4852
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004853 newcmd = cmdbase;
4854 unescape_shellxquote(cmdbase, p_sxe);
4855
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004856 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004857 * If creating new console, arguments are passed to the
4858 * 'cmd.exe' as-is. If it's not, arguments are not treated
4859 * correctly for current 'cmd.exe'. So unescape characters in
4860 * shellxescape except '|' for avoiding to be treated as
4861 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004862 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004863 if (flags != CREATE_NEW_CONSOLE)
4864 {
4865 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004866 char_u *cmd_shell = mch_getenv("COMSPEC");
4867
4868 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004869 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004870
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004871 subcmd = vim_strsave_escaped_ext(cmdbase,
4872 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004873 if (subcmd != NULL)
4874 {
4875 /* make "cmd.exe /c arguments" */
4876 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004877 newcmd = lalloc(cmdlen, TRUE);
4878 if (newcmd != NULL)
4879 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004880 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004881 else
4882 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004883 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004884 }
4885 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004886
4887 /*
4888 * Now, start the command as a process, so that it doesn't
4889 * inherit our handles which causes unpleasant dangling swap
4890 * files if we exit before the spawned process
4891 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004892 if (vim_create_process((char *)newcmd, FALSE, flags,
4893 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004894 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004895 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4896 > (HINSTANCE)32)
4897 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004898 else
4899 {
4900 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01004901#ifdef FEAT_GUI_MSWIN
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004902 emsg(_("E371: Command not found"));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004903#endif
4904 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004905
4906 if (newcmd != cmdbase)
4907 vim_free(newcmd);
4908
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004909 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004910 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004911 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004912 CloseHandle(si.hStdInput);
4913 }
4914 /* Close the handles to the subprocess, so that it goes away */
4915 CloseHandle(pi.hThread);
4916 CloseHandle(pi.hProcess);
4917 }
4918 else
4919 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004920 cmdlen = (
Bram Moolenaar4f974752019-02-17 17:44:42 +01004921#ifdef FEAT_GUI_MSWIN
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004922 (!p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004923#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004924 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4925
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004926 newcmd = lalloc(cmdlen, TRUE);
4927 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004928 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01004929#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004930 if (need_vimrun_warning)
4931 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01004932 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
4933 "External commands will not pause after completion.\n"
4934 "See :help win32-vimrun for more information.");
4935 char *title = _("Vim Warning");
Bram Moolenaar63e43442016-11-19 17:28:44 +01004936 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4937 {
4938 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
4939 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
4940
4941 if (wmsg != NULL && wtitle != NULL)
4942 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
4943 vim_free(wmsg);
4944 vim_free(wtitle);
4945 }
4946 else
Bram Moolenaar63e43442016-11-19 17:28:44 +01004947 MessageBox(NULL, msg, title, MB_ICONWARNING);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004948 need_vimrun_warning = FALSE;
4949 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004950 if (!s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004951 /* Use vimrun to execute the command. It opens a console
4952 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004953 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004954 vimrun_path,
4955 (msg_silent != 0 || (options & SHELL_DOOUT))
4956 ? "-s " : "",
4957 p_sh, p_shcf, cmd);
4958 else
4959#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004960 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004961 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004962 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004963 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004964 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004965 }
4966 }
4967
4968 if (tmode == TMODE_RAW)
4969 settmode(TMODE_RAW); /* set to raw mode */
4970
4971 /* Print the return value, unless "vimrun" was used. */
4972 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01004973#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004974 && ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004975#endif
4976 )
4977 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004978 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004979 msg_putchar('\n');
4980 }
4981#ifdef FEAT_TITLE
4982 resettitle();
4983#endif
4984
4985 signal(SIGINT, SIG_DFL);
4986#if defined(__GNUC__) && !defined(__MINGW32__)
4987 signal(SIGKILL, SIG_DFL);
4988#else
4989 signal(SIGBREAK, SIG_DFL);
4990#endif
4991 signal(SIGILL, SIG_DFL);
4992 signal(SIGFPE, SIG_DFL);
4993 signal(SIGSEGV, SIG_DFL);
4994 signal(SIGTERM, SIG_DFL);
4995 signal(SIGABRT, SIG_DFL);
4996
4997 return x;
4998}
4999
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005000#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005001 static HANDLE
5002job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005003 char_u *fname,
5004 DWORD dwDesiredAccess,
5005 DWORD dwShareMode,
5006 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5007 DWORD dwCreationDisposition,
5008 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005009{
5010 HANDLE h;
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005011 WCHAR *wn = NULL;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005012
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005013 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5014 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005015 wn = enc_to_utf16(fname, NULL);
5016 if (wn != NULL)
5017 {
5018 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5019 lpSecurityAttributes, dwCreationDisposition,
5020 dwFlagsAndAttributes, NULL);
5021 vim_free(wn);
5022 }
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005023 }
5024 if (wn == NULL)
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005025 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
5026 lpSecurityAttributes, dwCreationDisposition,
5027 dwFlagsAndAttributes, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005028 return h;
5029}
5030
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005031/*
5032 * Turn the dictionary "env" into a NUL separated list that can be used as the
5033 * environment argument of vim_create_process().
5034 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005035 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005036win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005037{
5038 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005039 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005040 LPVOID base = GetEnvironmentStringsW();
5041
5042 /* for last \0 */
5043 if (ga_grow(gap, 1) == FAIL)
5044 return;
5045
5046 if (base)
5047 {
5048 WCHAR *p = (WCHAR*) base;
5049
5050 /* for last \0 */
5051 if (ga_grow(gap, 1) == FAIL)
5052 return;
5053
5054 while (*p != 0 || *(p + 1) != 0)
5055 {
5056 if (ga_grow(gap, 1) == OK)
5057 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5058 p++;
5059 }
5060 FreeEnvironmentStrings(base);
5061 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5062 }
5063
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005064 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005065 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005066 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005067 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005068 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005069 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005070 typval_T *item = &dict_lookup(hi)->di_tv;
5071 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005072 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005073 --todo;
5074 if (wkey != NULL && wval != NULL)
5075 {
5076 size_t n;
5077 size_t lkey = wcslen(wkey);
5078 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005079
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005080 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5081 continue;
5082 for (n = 0; n < lkey; n++)
5083 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5084 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5085 for (n = 0; n < lval; n++)
5086 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5087 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5088 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005089 vim_free(wkey);
5090 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005091 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005092 }
5093 }
5094
Bram Moolenaar493359e2018-06-12 20:25:52 +02005095# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005096 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005097# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005098 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005099 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005100# endif
5101# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005102 char_u *version = get_vim_var_str(VV_VERSION);
5103 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005104# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005105 // size of "VIM_SERVERNAME=" and value,
5106 // plus "VIM_TERMINAL=" and value,
5107 // plus two terminating NULs
5108 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005109# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005110 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005111# endif
5112# ifdef FEAT_TERMINAL
5113 + 13 + version_len + 2
5114# endif
5115 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005116
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005117 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005118 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005119# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005120 for (n = 0; n < 15; n++)
5121 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5122 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005123 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005124 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5125 (WCHAR)servername[n];
5126 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005127# endif
5128# ifdef FEAT_TERMINAL
5129 if (is_terminal)
5130 {
5131 for (n = 0; n < 13; n++)
5132 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5133 (WCHAR)"VIM_TERMINAL="[n];
5134 for (n = 0; n < version_len; n++)
5135 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5136 (WCHAR)version[n];
5137 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5138 }
5139# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005140 }
5141 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005142# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005143}
5144
Bram Moolenaarb091f302019-01-19 14:37:00 +01005145/*
5146 * Create a pair of pipes.
5147 * Return TRUE for success, FALSE for failure.
5148 */
5149 static BOOL
5150create_pipe_pair(HANDLE handles[2])
5151{
5152 static LONG s;
5153 char name[64];
5154 SECURITY_ATTRIBUTES sa;
5155
5156 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5157 GetCurrentProcessId(),
5158 InterlockedIncrement(&s));
5159
5160 // Create named pipe. Max size of named pipe is 65535.
5161 handles[1] = CreateNamedPipe(
5162 name,
5163 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5164 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005165 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005166
5167 if (handles[1] == INVALID_HANDLE_VALUE)
5168 return FALSE;
5169
5170 sa.nLength = sizeof(sa);
5171 sa.bInheritHandle = TRUE;
5172 sa.lpSecurityDescriptor = NULL;
5173
5174 handles[0] = CreateFile(name,
5175 FILE_GENERIC_READ,
5176 FILE_SHARE_READ, &sa,
5177 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5178
5179 if (handles[0] == INVALID_HANDLE_VALUE)
5180 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005181 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005182 return FALSE;
5183 }
5184
5185 return TRUE;
5186}
5187
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005188 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005189mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005190{
5191 STARTUPINFO si;
5192 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005193 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005194 SECURITY_ATTRIBUTES saAttr;
5195 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005196 HANDLE ifd[2];
5197 HANDLE ofd[2];
5198 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005199 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005200
5201 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5202 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5203 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5204 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5205 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5206 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5207 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5208
5209 if (use_out_for_err && use_null_for_out)
5210 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005211
5212 ifd[0] = INVALID_HANDLE_VALUE;
5213 ifd[1] = INVALID_HANDLE_VALUE;
5214 ofd[0] = INVALID_HANDLE_VALUE;
5215 ofd[1] = INVALID_HANDLE_VALUE;
5216 efd[0] = INVALID_HANDLE_VALUE;
5217 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005218 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005219
Bram Moolenaar14207f42016-10-27 21:13:10 +02005220 jo = CreateJobObject(NULL, NULL);
5221 if (jo == NULL)
5222 {
5223 job->jv_status = JOB_FAILED;
5224 goto failed;
5225 }
5226
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005227 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005228 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005229
Bram Moolenaar76467df2016-02-12 19:30:26 +01005230 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005231 ZeroMemory(&si, sizeof(si));
5232 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005233 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005234 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005235
Bram Moolenaard8070362016-02-15 21:56:54 +01005236 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5237 saAttr.bInheritHandle = TRUE;
5238 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005239
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005240 if (use_file_for_in)
5241 {
5242 char_u *fname = options->jo_io_name[PART_IN];
5243
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005244 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5245 FILE_SHARE_READ | FILE_SHARE_WRITE,
5246 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5247 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005248 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005249 semsg(_(e_notopen), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005250 goto failed;
5251 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005252 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005253 else if (!use_null_for_in
5254 && (!create_pipe_pair(ifd)
5255 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005256 goto failed;
5257
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005258 if (use_file_for_out)
5259 {
5260 char_u *fname = options->jo_io_name[PART_OUT];
5261
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005262 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5263 FILE_SHARE_READ | FILE_SHARE_WRITE,
5264 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5265 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005266 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005267 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005268 goto failed;
5269 }
5270 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005271 else if (!use_null_for_out &&
5272 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005273 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005274 goto failed;
5275
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005276 if (use_file_for_err)
5277 {
5278 char_u *fname = options->jo_io_name[PART_ERR];
5279
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005280 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5281 FILE_SHARE_READ | FILE_SHARE_WRITE,
5282 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5283 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005284 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005285 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005286 goto failed;
5287 }
5288 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005289 else if (!use_out_for_err && !use_null_for_err &&
5290 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005291 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005292 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005293
Bram Moolenaard8070362016-02-15 21:56:54 +01005294 si.dwFlags |= STARTF_USESTDHANDLES;
5295 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005296 si.hStdOutput = ofd[1];
5297 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5298
5299 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5300 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005301 if (options->jo_set & JO_CHANNEL)
5302 {
5303 channel = options->jo_channel;
5304 if (channel != NULL)
5305 ++channel->ch_refcount;
5306 }
5307 else
5308 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005309 if (channel == NULL)
5310 goto failed;
5311 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005312
5313 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005314 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005315 CREATE_DEFAULT_ERROR_MODE |
5316 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005317 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005318 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005319 &si, &pi,
5320 ga.ga_data,
5321 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005322 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005323 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005324 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005325 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005326 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005327
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005328 ga_clear(&ga);
5329
Bram Moolenaar14207f42016-10-27 21:13:10 +02005330 if (!AssignProcessToJobObject(jo, pi.hProcess))
5331 {
5332 /* if failing, switch the way to terminate
5333 * process with TerminateProcess. */
5334 CloseHandle(jo);
5335 jo = NULL;
5336 }
5337 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005338 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005339 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005340 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005341 job->jv_status = JOB_STARTED;
5342
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005343 CloseHandle(ifd[0]);
5344 CloseHandle(ofd[1]);
5345 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005346 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005347
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005348 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005349 if (channel != NULL)
5350 {
5351 channel_set_pipes(channel,
5352 use_file_for_in || use_null_for_in
5353 ? INVALID_FD : (sock_T)ifd[1],
5354 use_file_for_out || use_null_for_out
5355 ? INVALID_FD : (sock_T)ofd[0],
5356 use_out_for_err || use_file_for_err || use_null_for_err
5357 ? INVALID_FD : (sock_T)efd[0]);
5358 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005359 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005360 return;
5361
5362failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005363 CloseHandle(ifd[0]);
5364 CloseHandle(ofd[0]);
5365 CloseHandle(efd[0]);
5366 CloseHandle(ifd[1]);
5367 CloseHandle(ofd[1]);
5368 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005369 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005370 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005371}
5372
5373 char *
5374mch_job_status(job_T *job)
5375{
5376 DWORD dwExitCode = 0;
5377
Bram Moolenaar76467df2016-02-12 19:30:26 +01005378 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5379 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005380 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005381 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005382 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005383 {
5384 ch_log(job->jv_channel, "Job ended");
5385 job->jv_status = JOB_ENDED;
5386 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005387 return "dead";
5388 }
5389 return "run";
5390}
5391
Bram Moolenaar97792de2016-10-15 18:36:49 +02005392 job_T *
5393mch_detect_ended_job(job_T *job_list)
5394{
5395 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5396 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5397 job_T *job = job_list;
5398
5399 while (job != NULL)
5400 {
5401 DWORD n;
5402 DWORD result;
5403
5404 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5405 && job != NULL; job = job->jv_next)
5406 {
5407 if (job->jv_status == JOB_STARTED)
5408 {
5409 jobHandles[n] = job->jv_proc_info.hProcess;
5410 jobArray[n] = job;
5411 ++n;
5412 }
5413 }
5414 if (n == 0)
5415 continue;
5416 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5417 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5418 {
5419 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5420
5421 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5422 return wait_job;
5423 }
5424 }
5425 return NULL;
5426}
5427
Bram Moolenaarfb630902016-10-29 14:55:00 +02005428 static BOOL
5429terminate_all(HANDLE process, int code)
5430{
5431 PROCESSENTRY32 pe;
5432 HANDLE h = INVALID_HANDLE_VALUE;
5433 DWORD pid = GetProcessId(process);
5434
5435 if (pid != 0)
5436 {
5437 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5438 if (h != INVALID_HANDLE_VALUE)
5439 {
5440 pe.dwSize = sizeof(PROCESSENTRY32);
5441 if (!Process32First(h, &pe))
5442 goto theend;
5443
5444 do
5445 {
5446 if (pe.th32ParentProcessID == pid)
5447 {
5448 HANDLE ph = OpenProcess(
5449 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5450 if (ph != NULL)
5451 {
5452 terminate_all(ph, code);
5453 CloseHandle(ph);
5454 }
5455 }
5456 } while (Process32Next(h, &pe));
5457
5458 CloseHandle(h);
5459 }
5460 }
5461
5462theend:
5463 return TerminateProcess(process, code);
5464}
5465
5466/*
5467 * Send a (deadly) signal to "job".
5468 * Return FAIL if it didn't work.
5469 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005470 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005471mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005472{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005473 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005474
Bram Moolenaar923d9262016-02-25 20:56:01 +01005475 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005476 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005477 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005478 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005479 {
5480 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5481 job->jv_channel->ch_killing = TRUE;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005482 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005483 }
Bram Moolenaarfb630902016-10-29 14:55:00 +02005484 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005485 }
5486
5487 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5488 return FAIL;
5489 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005490 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5491 job->jv_proc_info.dwProcessId)
5492 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005493 FreeConsole();
5494 return ret;
5495}
5496
5497/*
5498 * Clear the data related to "job".
5499 */
5500 void
5501mch_clear_job(job_T *job)
5502{
5503 if (job->jv_status != JOB_FAILED)
5504 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005505 if (job->jv_job_object != NULL)
5506 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005507 CloseHandle(job->jv_proc_info.hProcess);
5508 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005509}
5510#endif
5511
Bram Moolenaar071d4272004-06-13 20:20:40 +00005512
Bram Moolenaar4f974752019-02-17 17:44:42 +01005513#ifndef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005514
5515/*
5516 * Start termcap mode
5517 */
5518 static void
5519termcap_mode_start(void)
5520{
5521 DWORD cmodein;
5522
5523 if (g_fTermcapMode)
5524 return;
5525
5526 SaveConsoleBuffer(&g_cbNonTermcap);
5527
5528 if (g_cbTermcap.IsValid)
5529 {
5530 /*
5531 * We've been in termcap mode before. Restore certain screen
5532 * characteristics, including the buffer size and the window
5533 * size. Since we will be redrawing the screen, we don't need
5534 * to restore the actual contents of the buffer.
5535 */
5536 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005537 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005538 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5539 Rows = g_cbTermcap.Info.dwSize.Y;
5540 Columns = g_cbTermcap.Info.dwSize.X;
5541 }
5542 else
5543 {
5544 /*
5545 * This is our first time entering termcap mode. Clear the console
5546 * screen buffer, and resize the buffer to match the current window
5547 * size. We will use this as the size of our editing environment.
5548 */
5549 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005550 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005551 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5552 }
5553
5554#ifdef FEAT_TITLE
5555 resettitle();
5556#endif
5557
5558 GetConsoleMode(g_hConIn, &cmodein);
5559#ifdef FEAT_MOUSE
5560 if (g_fMouseActive)
5561 cmodein |= ENABLE_MOUSE_INPUT;
5562 else
5563 cmodein &= ~ENABLE_MOUSE_INPUT;
5564#endif
5565 cmodein |= ENABLE_WINDOW_INPUT;
5566 SetConsoleMode(g_hConIn, cmodein);
5567
5568 redraw_later_clear();
5569 g_fTermcapMode = TRUE;
5570}
5571
5572
5573/*
5574 * End termcap mode
5575 */
5576 static void
5577termcap_mode_end(void)
5578{
5579 DWORD cmodein;
5580 ConsoleBuffer *cb;
5581 COORD coord;
5582 DWORD dwDummy;
5583
5584 if (!g_fTermcapMode)
5585 return;
5586
5587 SaveConsoleBuffer(&g_cbTermcap);
5588
5589 GetConsoleMode(g_hConIn, &cmodein);
5590 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5591 SetConsoleMode(g_hConIn, cmodein);
5592
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005593#ifdef FEAT_RESTORE_ORIG_SCREEN
5594 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5595#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005596 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005597#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005598 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005599 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005600 SetConsoleCursorInfo(g_hConOut, &g_cci);
5601
5602 if (p_rs || exiting)
5603 {
5604 /*
5605 * Clear anything that happens to be on the current line.
5606 */
5607 coord.X = 0;
5608 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5609 FillConsoleOutputCharacter(g_hConOut, ' ',
5610 cb->Info.dwSize.X, coord, &dwDummy);
5611 /*
5612 * The following is just for aesthetics. If we are exiting without
5613 * restoring the screen, then we want to have a prompt string
5614 * appear at the bottom line. However, the command interpreter
5615 * seems to always advance the cursor one line before displaying
5616 * the prompt string, which causes the screen to scroll. To
5617 * counter this, move the cursor up one line before exiting.
5618 */
5619 if (exiting && !p_rs)
5620 coord.Y--;
5621 /*
5622 * Position the cursor at the leftmost column of the desired row.
5623 */
5624 SetConsoleCursorPosition(g_hConOut, coord);
5625 }
5626
5627 g_fTermcapMode = FALSE;
5628}
Bram Moolenaar4f974752019-02-17 17:44:42 +01005629#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005630
5631
Bram Moolenaar4f974752019-02-17 17:44:42 +01005632#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005633 void
5634mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005635 char_u *s UNUSED,
5636 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005637{
5638 /* never used */
5639}
5640
5641#else
5642
5643/*
5644 * clear `n' chars, starting from `coord'
5645 */
5646 static void
5647clear_chars(
5648 COORD coord,
5649 DWORD n)
5650{
5651 DWORD dwDummy;
5652
5653 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005654
5655 if (!USE_VTP)
5656 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5657 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005658 {
5659 set_console_color_rgb();
5660 gotoxy(coord.X + 1, coord.Y + 1);
5661 vtp_printf("\033[%dX", n);
5662 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005663}
5664
5665
5666/*
5667 * Clear the screen
5668 */
5669 static void
5670clear_screen(void)
5671{
5672 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005673
5674 if (!USE_VTP)
5675 clear_chars(g_coord, Rows * Columns);
5676 else
5677 {
5678 set_console_color_rgb();
5679 gotoxy(1, 1);
5680 vtp_printf("\033[2J");
5681 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005682}
5683
5684
5685/*
5686 * Clear to end of display
5687 */
5688 static void
5689clear_to_end_of_display(void)
5690{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005691 COORD save = g_coord;
5692
5693 if (!USE_VTP)
5694 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005695 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005696 else
5697 {
5698 set_console_color_rgb();
5699 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5700 vtp_printf("\033[0J");
5701
5702 gotoxy(save.X + 1, save.Y + 1);
5703 g_coord = save;
5704 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005705}
5706
5707
5708/*
5709 * Clear to end of line
5710 */
5711 static void
5712clear_to_end_of_line(void)
5713{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005714 COORD save = g_coord;
5715
5716 if (!USE_VTP)
5717 clear_chars(g_coord, Columns - g_coord.X);
5718 else
5719 {
5720 set_console_color_rgb();
5721 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5722 vtp_printf("\033[0K");
5723
5724 gotoxy(save.X + 1, save.Y + 1);
5725 g_coord = save;
5726 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005727}
5728
5729
5730/*
5731 * Scroll the scroll region up by `cLines' lines
5732 */
5733 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005734scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005735{
5736 COORD oldcoord = g_coord;
5737
5738 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5739 delete_lines(cLines);
5740
5741 g_coord = oldcoord;
5742}
5743
5744
5745/*
5746 * Set the scroll region
5747 */
5748 static void
5749set_scroll_region(
5750 unsigned left,
5751 unsigned top,
5752 unsigned right,
5753 unsigned bottom)
5754{
5755 if (left >= right
5756 || top >= bottom
5757 || right > (unsigned) Columns - 1
5758 || bottom > (unsigned) Rows - 1)
5759 return;
5760
5761 g_srScrollRegion.Left = left;
5762 g_srScrollRegion.Top = top;
5763 g_srScrollRegion.Right = right;
5764 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005765}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005766
Bram Moolenaar6982f422019-02-16 16:48:01 +01005767 static void
5768set_scroll_region_tb(
5769 unsigned top,
5770 unsigned bottom)
5771{
5772 if (top >= bottom || bottom > (unsigned)Rows - 1)
5773 return;
5774
5775 g_srScrollRegion.Top = top;
5776 g_srScrollRegion.Bottom = bottom;
5777}
5778
5779 static void
5780set_scroll_region_lr(
5781 unsigned left,
5782 unsigned right)
5783{
5784 if (left >= right || right > (unsigned)Columns - 1)
5785 return;
5786
5787 g_srScrollRegion.Left = left;
5788 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005789}
5790
5791
5792/*
5793 * Insert `cLines' lines at the current cursor position
5794 */
5795 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005796insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005797{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005798 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005799 COORD dest;
5800 CHAR_INFO fill;
5801
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005802 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5803
Bram Moolenaar6982f422019-02-16 16:48:01 +01005804 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005805 dest.Y = g_coord.Y + cLines;
5806
Bram Moolenaar6982f422019-02-16 16:48:01 +01005807 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005808 source.Top = g_coord.Y;
5809 source.Right = g_srScrollRegion.Right;
5810 source.Bottom = g_srScrollRegion.Bottom - cLines;
5811
Bram Moolenaar6982f422019-02-16 16:48:01 +01005812 clip.Left = g_srScrollRegion.Left;
5813 clip.Top = g_coord.Y;
5814 clip.Right = g_srScrollRegion.Right;
5815 clip.Bottom = g_srScrollRegion.Bottom;
5816
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005817 fill.Char.AsciiChar = ' ';
5818 if (!USE_VTP)
5819 fill.Attributes = g_attrCurrent;
5820 else
5821 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005822
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005823 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005824
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005825 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5826
Bram Moolenaar6982f422019-02-16 16:48:01 +01005827 // Here we have to deal with a win32 console flake: If the scroll
5828 // region looks like abc and we scroll c to a and fill with d we get
5829 // cbd... if we scroll block c one line at a time to a, we get cdd...
5830 // vim expects cdd consistently... So we have to deal with that
5831 // here... (this also occurs scrolling the same way in the other
5832 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005833
5834 if (source.Bottom < dest.Y)
5835 {
5836 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005837 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005838
Bram Moolenaar6982f422019-02-16 16:48:01 +01005839 coord.X = source.Left;
5840 for (i = clip.Top; i < dest.Y; ++i)
5841 {
5842 coord.Y = i;
5843 clear_chars(coord, source.Right - source.Left + 1);
5844 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005845 }
5846}
5847
5848
5849/*
5850 * Delete `cLines' lines at the current cursor position
5851 */
5852 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005853delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005854{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005855 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005856 COORD dest;
5857 CHAR_INFO fill;
5858 int nb;
5859
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005860 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5861
Bram Moolenaar6982f422019-02-16 16:48:01 +01005862 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005863 dest.Y = g_coord.Y;
5864
Bram Moolenaar6982f422019-02-16 16:48:01 +01005865 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005866 source.Top = g_coord.Y + cLines;
5867 source.Right = g_srScrollRegion.Right;
5868 source.Bottom = g_srScrollRegion.Bottom;
5869
Bram Moolenaar6982f422019-02-16 16:48:01 +01005870 clip.Left = g_srScrollRegion.Left;
5871 clip.Top = g_coord.Y;
5872 clip.Right = g_srScrollRegion.Right;
5873 clip.Bottom = g_srScrollRegion.Bottom;
5874
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005875 fill.Char.AsciiChar = ' ';
5876 if (!USE_VTP)
5877 fill.Attributes = g_attrCurrent;
5878 else
5879 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005880
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005881 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005882
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005883 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5884
Bram Moolenaar6982f422019-02-16 16:48:01 +01005885 // Here we have to deal with a win32 console flake; See insert_lines()
5886 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005887
5888 nb = dest.Y + (source.Bottom - source.Top) + 1;
5889
5890 if (nb < source.Top)
5891 {
5892 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005893 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005894
Bram Moolenaar6982f422019-02-16 16:48:01 +01005895 coord.X = source.Left;
5896 for (i = nb; i < clip.Bottom; ++i)
5897 {
5898 coord.Y = i;
5899 clear_chars(coord, source.Right - source.Left + 1);
5900 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005901 }
5902}
5903
5904
5905/*
5906 * Set the cursor position
5907 */
5908 static void
5909gotoxy(
5910 unsigned x,
5911 unsigned y)
5912{
5913 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5914 return;
5915
5916 /* external cursor coords are 1-based; internal are 0-based */
5917 g_coord.X = x - 1;
5918 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005919
5920 if (!USE_VTP)
5921 SetConsoleCursorPosition(g_hConOut, g_coord);
5922 else
5923 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005924}
5925
5926
5927/*
5928 * Set the current text attribute = (foreground | background)
5929 * See ../doc/os_win32.txt for the numbers.
5930 */
5931 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005932textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005933{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005934 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005935
5936 SetConsoleTextAttribute(g_hConOut, wAttr);
5937}
5938
5939
5940 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005941textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005942{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005943 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005944
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005945 if (!USE_VTP)
5946 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5947 else
5948 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005949}
5950
5951
5952 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005953textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005954{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005955 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005956
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005957 if (!USE_VTP)
5958 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5959 else
5960 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005961}
5962
5963
5964/*
5965 * restore the default text attribute (whatever we started with)
5966 */
5967 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005968normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005969{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005970 if (!USE_VTP)
5971 textattr(g_attrDefault);
5972 else
5973 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005974}
5975
5976
5977static WORD g_attrPreStandout = 0;
5978
5979/*
5980 * Make the text standout, by brightening it
5981 */
5982 static void
5983standout(void)
5984{
5985 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005986
Bram Moolenaar071d4272004-06-13 20:20:40 +00005987 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5988}
5989
5990
5991/*
5992 * Turn off standout mode
5993 */
5994 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005995standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005996{
5997 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005998 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005999
6000 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006001}
6002
6003
6004/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006005 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006006 */
6007 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006008mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006009{
6010 char_u *p;
6011 int n;
6012
6013 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6014 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006015 if (
6016#ifdef FEAT_TERMGUICOLORS
6017 !p_tgc &&
6018#endif
6019 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006020 {
6021 p = T_ME + 2;
6022 n = getdigits(&p);
6023 if (*p == 'm' && n > 0)
6024 {
6025 cterm_normal_fg_color = (n & 0xf) + 1;
6026 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6027 }
6028 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006029#ifdef FEAT_TERMGUICOLORS
6030 cterm_normal_fg_gui_color = INVALCOLOR;
6031 cterm_normal_bg_gui_color = INVALCOLOR;
6032#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006033}
6034
6035
6036/*
6037 * visual bell: flash the screen
6038 */
6039 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006040visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006041{
6042 COORD coordOrigin = {0, 0};
6043 WORD attrFlash = ~g_attrCurrent & 0xff;
6044
6045 DWORD dwDummy;
6046 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
6047
6048 if (oldattrs == NULL)
6049 return;
6050 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6051 coordOrigin, &dwDummy);
6052 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6053 coordOrigin, &dwDummy);
6054
6055 Sleep(15); /* wait for 15 msec */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006056 if (!USE_VTP)
6057 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006058 coordOrigin, &dwDummy);
6059 vim_free(oldattrs);
6060}
6061
6062
6063/*
6064 * Make the cursor visible or invisible
6065 */
6066 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006067cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006068{
6069 s_cursor_visible = fVisible;
6070#ifdef MCH_CURSOR_SHAPE
6071 mch_update_cursor();
6072#endif
6073}
6074
6075
6076/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006077 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006078 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006079 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006080 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006081write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006082 char_u *pchBuf,
6083 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006084{
6085 COORD coord = g_coord;
6086 DWORD written;
6087
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006088 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6089 {
6090 static WCHAR *unicodebuf = NULL;
6091 static int unibuflen = 0;
6092 int length;
6093 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006094
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006095 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
6096 if (unicodebuf == NULL || length > unibuflen)
6097 {
6098 vim_free(unicodebuf);
6099 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
6100 unibuflen = length;
6101 }
6102 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
6103 unicodebuf, unibuflen);
6104
6105 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006106
6107 if (!USE_VTP)
6108 {
6109 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6110 coord, &written);
6111 /* When writing fails or didn't write a single character, pretend one
6112 * character was written, otherwise we get stuck. */
6113 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
6114 coord, &cchwritten) == 0
Bram Moolenaar78d21da2019-02-17 15:00:52 +01006115 || cchwritten == 0 || cchwritten == (DWORD)-1)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006116 cchwritten = 1;
6117 }
6118 else
6119 {
6120 if (WriteConsoleW(g_hConOut, unicodebuf, length, &cchwritten,
6121 NULL) == 0 || cchwritten == 0)
6122 cchwritten = 1;
6123 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006124
6125 if (cchwritten == length)
6126 {
6127 written = cbToWrite;
6128 g_coord.X += (SHORT)cells;
6129 }
6130 else
6131 {
6132 char_u *p = pchBuf;
6133 for (n = 0; n < cchwritten; n++)
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006134 MB_CPTR_ADV(p);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006135 written = p - pchBuf;
6136 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
6137 }
6138 }
6139 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006140 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006141 if (!USE_VTP)
6142 {
6143 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
6144 coord, &written);
6145 /* When writing fails or didn't write a single character, pretend one
6146 * character was written, otherwise we get stuck. */
6147 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
6148 coord, &written) == 0
Bram Moolenaar78d21da2019-02-17 15:00:52 +01006149 || written == 0 || written == (DWORD)-1)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006150 written = 1;
6151 }
6152 else
6153 {
6154 if (WriteConsole(g_hConOut, (LPCSTR)pchBuf, cbToWrite, &written,
6155 NULL) == 0 || written == 0)
6156 written = 1;
6157 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006158
6159 g_coord.X += (SHORT) written;
6160 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006161
6162 while (g_coord.X > g_srScrollRegion.Right)
6163 {
6164 g_coord.X -= (SHORT) Columns;
6165 if (g_coord.Y < g_srScrollRegion.Bottom)
6166 g_coord.Y++;
6167 }
6168
6169 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6170
6171 return written;
6172}
6173
6174
6175/*
6176 * mch_write(): write the output buffer to the screen, translating ESC
6177 * sequences into calls to console output routines.
6178 */
6179 void
6180mch_write(
6181 char_u *s,
6182 int len)
6183{
6184 s[len] = NUL;
6185
6186 if (!term_console)
6187 {
6188 write(1, s, (unsigned)len);
6189 return;
6190 }
6191
6192 /* translate ESC | sequences into faked bios calls */
6193 while (len--)
6194 {
6195 /* optimization: use one single write_chars for runs of text,
6196 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006197 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006198
6199 if (p_wd)
6200 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006201 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006202 if (prefix != 0)
6203 prefix = 1;
6204 }
6205
6206 if (prefix != 0)
6207 {
6208 DWORD nWritten;
6209
6210 nWritten = write_chars(s, prefix);
6211#ifdef MCH_WRITE_DUMP
6212 if (fdDump)
6213 {
6214 fputc('>', fdDump);
6215 fwrite(s, sizeof(char_u), nWritten, fdDump);
6216 fputs("<\n", fdDump);
6217 }
6218#endif
6219 len -= (nWritten - 1);
6220 s += nWritten;
6221 }
6222 else if (s[0] == '\n')
6223 {
6224 /* \n, newline: go to the beginning of the next line or scroll */
6225 if (g_coord.Y == g_srScrollRegion.Bottom)
6226 {
6227 scroll(1);
6228 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6229 }
6230 else
6231 {
6232 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6233 }
6234#ifdef MCH_WRITE_DUMP
6235 if (fdDump)
6236 fputs("\\n\n", fdDump);
6237#endif
6238 s++;
6239 }
6240 else if (s[0] == '\r')
6241 {
6242 /* \r, carriage return: go to beginning of line */
6243 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
6244#ifdef MCH_WRITE_DUMP
6245 if (fdDump)
6246 fputs("\\r\n", fdDump);
6247#endif
6248 s++;
6249 }
6250 else if (s[0] == '\b')
6251 {
6252 /* \b, backspace: move cursor one position left */
6253 if (g_coord.X > g_srScrollRegion.Left)
6254 g_coord.X--;
6255 else if (g_coord.Y > g_srScrollRegion.Top)
6256 {
6257 g_coord.X = g_srScrollRegion.Right;
6258 g_coord.Y--;
6259 }
6260 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6261#ifdef MCH_WRITE_DUMP
6262 if (fdDump)
6263 fputs("\\b\n", fdDump);
6264#endif
6265 s++;
6266 }
6267 else if (s[0] == '\a')
6268 {
6269 /* \a, bell */
6270 MessageBeep(0xFFFFFFFF);
6271#ifdef MCH_WRITE_DUMP
6272 if (fdDump)
6273 fputs("\\a\n", fdDump);
6274#endif
6275 s++;
6276 }
6277 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6278 {
6279#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006280 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006281#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006282 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006283 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006284
6285 switch (s[2])
6286 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006287 case '0': case '1': case '2': case '3': case '4':
6288 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006289 p = s + 1;
6290 do
6291 {
6292 ++p;
6293 args[argc] = getdigits(&p);
6294 argc += (argc < 15) ? 1 : 0;
6295 if (p > s + len)
6296 break;
6297 } while (*p == ';');
6298
Bram Moolenaar071d4272004-06-13 20:20:40 +00006299 if (p > s + len)
6300 break;
6301
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006302 arg1 = args[0];
6303 arg2 = args[1];
6304 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006305 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006306 if (argc == 1 && args[0] == 0)
6307 normvideo();
6308 else if (argc == 1)
6309 {
6310 if (USE_VTP)
6311 textcolor((WORD) arg1);
6312 else
6313 textattr((WORD) arg1);
6314 }
6315 else if (USE_VTP)
6316 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006317 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006318 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006319 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006320 gotoxy(arg2, arg1);
6321 }
6322 else if (argc == 2 && *p == 'r')
6323 {
6324 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6325 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006326 else if (argc == 2 && *p == 'R')
6327 {
6328 set_scroll_region_tb(arg1, arg2);
6329 }
6330 else if (argc == 2 && *p == 'V')
6331 {
6332 set_scroll_region_lr(arg1, arg2);
6333 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006334 else if (argc == 1 && *p == 'A')
6335 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006336 gotoxy(g_coord.X + 1,
6337 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6338 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006339 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006340 {
6341 textbackground((WORD) arg1);
6342 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006343 else if (argc == 1 && *p == 'C')
6344 {
6345 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6346 g_coord.Y + 1);
6347 }
6348 else if (argc == 1 && *p == 'f')
6349 {
6350 textcolor((WORD) arg1);
6351 }
6352 else if (argc == 1 && *p == 'H')
6353 {
6354 gotoxy(1, arg1);
6355 }
6356 else if (argc == 1 && *p == 'L')
6357 {
6358 insert_lines(arg1);
6359 }
6360 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006361 {
6362 delete_lines(arg1);
6363 }
6364
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006365 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006366 s = p + 1;
6367 break;
6368
Bram Moolenaar071d4272004-06-13 20:20:40 +00006369 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006370 gotoxy(g_coord.X + 1,
6371 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6372 goto got3;
6373
6374 case 'B':
6375 visual_bell();
6376 goto got3;
6377
6378 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006379 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6380 g_coord.Y + 1);
6381 goto got3;
6382
6383 case 'E':
6384 termcap_mode_end();
6385 goto got3;
6386
6387 case 'F':
6388 standout();
6389 goto got3;
6390
6391 case 'f':
6392 standend();
6393 goto got3;
6394
6395 case 'H':
6396 gotoxy(1, 1);
6397 goto got3;
6398
6399 case 'j':
6400 clear_to_end_of_display();
6401 goto got3;
6402
6403 case 'J':
6404 clear_screen();
6405 goto got3;
6406
6407 case 'K':
6408 clear_to_end_of_line();
6409 goto got3;
6410
6411 case 'L':
6412 insert_lines(1);
6413 goto got3;
6414
6415 case 'M':
6416 delete_lines(1);
6417 goto got3;
6418
6419 case 'S':
6420 termcap_mode_start();
6421 goto got3;
6422
6423 case 'V':
6424 cursor_visible(TRUE);
6425 goto got3;
6426
6427 case 'v':
6428 cursor_visible(FALSE);
6429 goto got3;
6430
6431 got3:
6432 s += 3;
6433 len -= 2;
6434 }
6435
6436#ifdef MCH_WRITE_DUMP
6437 if (fdDump)
6438 {
6439 fputs("ESC | ", fdDump);
6440 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6441 fputc('\n', fdDump);
6442 }
6443#endif
6444 }
6445 else
6446 {
6447 /* Write a single character */
6448 DWORD nWritten;
6449
6450 nWritten = write_chars(s, 1);
6451#ifdef MCH_WRITE_DUMP
6452 if (fdDump)
6453 {
6454 fputc('>', fdDump);
6455 fwrite(s, sizeof(char_u), nWritten, fdDump);
6456 fputs("<\n", fdDump);
6457 }
6458#endif
6459
6460 len -= (nWritten - 1);
6461 s += nWritten;
6462 }
6463 }
6464
6465#ifdef MCH_WRITE_DUMP
6466 if (fdDump)
6467 fflush(fdDump);
6468#endif
6469}
6470
Bram Moolenaar4f974752019-02-17 17:44:42 +01006471#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006472
6473
6474/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006475 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006476 */
6477 void
6478mch_delay(
6479 long msec,
Bram Moolenaar1266d672017-02-01 13:43:36 +01006480 int ignoreinput UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006481{
Bram Moolenaar4f974752019-02-17 17:44:42 +01006482#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006483 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006484#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006485 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006486# ifdef FEAT_MZSCHEME
6487 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6488 {
6489 int towait = p_mzq;
6490
6491 /* if msec is large enough, wait by portions in p_mzq */
6492 while (msec > 0)
6493 {
6494 mzvim_check_threads();
6495 if (msec < towait)
6496 towait = msec;
6497 Sleep(towait);
6498 msec -= towait;
6499 }
6500 }
6501 else
6502# endif
6503 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006504 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006505 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006506#endif
6507}
6508
6509
6510/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006511 * This version of remove is not scared by a readonly (backup) file.
6512 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006513 * Return 0 for success, -1 for failure.
6514 */
6515 int
6516mch_remove(char_u *name)
6517{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006518 WCHAR *wn = NULL;
6519 int n;
6520
Bram Moolenaar203258c2016-01-17 22:15:16 +01006521 /*
6522 * On Windows, deleting a directory's symbolic link is done by
6523 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6524 */
6525 if (mch_isdir(name) && mch_is_symbolic_link(name))
6526 return mch_rmdir(name);
6527
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006528 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6529
Bram Moolenaar071d4272004-06-13 20:20:40 +00006530 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6531 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006532 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006533 if (wn != NULL)
6534 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006535 n = DeleteFileW(wn) ? 0 : -1;
6536 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006537 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006538 }
6539 }
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006540 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006541}
6542
6543
6544/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006545 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006546 */
6547 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006548mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006549{
Bram Moolenaar4f974752019-02-17 17:44:42 +01006550#ifndef FEAT_GUI_MSWIN /* never used */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006551 if (g_fCtrlCPressed || g_fCBrkPressed)
6552 {
Bram Moolenaar9698ad72017-08-12 14:52:15 +02006553 ctrl_break_was_pressed = g_fCBrkPressed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006554 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6555 got_int = TRUE;
6556 }
6557#endif
6558}
6559
Bram Moolenaaree273972016-01-02 21:11:51 +01006560/* physical RAM to leave for the OS */
6561#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006562
6563/*
6564 * How much main memory in KiB that can be used by VIM.
6565 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006566 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006567mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006568{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006569 MEMORYSTATUSEX ms;
6570
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006571 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6572 * what fits in 32 bits. But it's not always available. */
6573 ms.dwLength = sizeof(MEMORYSTATUSEX);
6574 GlobalMemoryStatusEx(&ms);
6575 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006576 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006577 /* Process address space fits in physical RAM, use all of it. */
6578 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006579 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006580 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006581 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006582 /* Catch old NT box or perverse hardware setup. */
6583 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006584 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006585 /* Use physical RAM less reserve for OS + data. */
6586 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006587}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006588
Bram Moolenaar071d4272004-06-13 20:20:40 +00006589/*
6590 * Same code as below, but with wide functions and no comments.
6591 * Return 0 for success, non-zero for failure.
6592 */
6593 int
6594mch_wrename(WCHAR *wold, WCHAR *wnew)
6595{
6596 WCHAR *p;
6597 int i;
6598 WCHAR szTempFile[_MAX_PATH + 1];
6599 WCHAR szNewPath[_MAX_PATH + 1];
6600 HANDLE hf;
6601
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006602 p = wold;
6603 for (i = 0; wold[i] != NUL; ++i)
6604 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6605 && wold[i + 1] != 0)
6606 p = wold + i + 1;
6607 if ((int)(wold + i - p) < 8 || p[6] != '~')
6608 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006609
6610 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6611 return -1;
6612 *p = NUL;
6613
6614 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6615 return -2;
6616
6617 if (!DeleteFileW(szTempFile))
6618 return -3;
6619
6620 if (!MoveFileW(wold, szTempFile))
6621 return -4;
6622
6623 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6624 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6625 return -5;
6626 if (!CloseHandle(hf))
6627 return -6;
6628
6629 if (!MoveFileW(szTempFile, wnew))
6630 {
6631 (void)MoveFileW(szTempFile, wold);
6632 return -7;
6633 }
6634
6635 DeleteFileW(szTempFile);
6636
6637 if (!DeleteFileW(wold))
6638 return -8;
6639
6640 return 0;
6641}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006642
6643
6644/*
6645 * mch_rename() works around a bug in rename (aka MoveFile) in
6646 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6647 * file whose short file name is "FOO.BAR" (its long file name will
6648 * be correct: "foo.bar~"). Because a file can be accessed by
6649 * either its SFN or its LFN, "foo.bar" has effectively been
6650 * renamed to "foo.bar", which is not at all what was wanted. This
6651 * seems to happen only when renaming files with three-character
6652 * extensions by appending a suffix that does not include ".".
6653 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6654 *
6655 * There is another problem, which isn't really a bug but isn't right either:
6656 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6657 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6658 * service pack 6. Doesn't seem to happen on Windows 98.
6659 *
6660 * Like rename(), returns 0 upon success, non-zero upon failure.
6661 * Should probably set errno appropriately when errors occur.
6662 */
6663 int
6664mch_rename(
6665 const char *pszOldFile,
6666 const char *pszNewFile)
6667{
6668 char szTempFile[_MAX_PATH+1];
6669 char szNewPath[_MAX_PATH+1];
6670 char *pszFilePart;
6671 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006672 WCHAR *wold = NULL;
6673 WCHAR *wnew = NULL;
6674 int retval = -1;
6675
6676 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6677 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006678 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6679 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006680 if (wold != NULL && wnew != NULL)
6681 retval = mch_wrename(wold, wnew);
6682 vim_free(wold);
6683 vim_free(wnew);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006684 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006685 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006686
6687 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006688 * No need to play tricks unless the file name contains a "~" as the
6689 * seventh character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006690 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006691 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6692 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6693 return rename(pszOldFile, pszNewFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006694
6695 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6696 * a directory, no error is returned and pszFilePart will be NULL. */
6697 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6698 || pszFilePart == NULL)
6699 return -1;
6700 *pszFilePart = NUL;
6701
6702 /* Get (and create) a unique temporary file name in directory of new file */
6703 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6704 return -2;
6705
6706 /* blow the temp file away */
6707 if (!DeleteFile(szTempFile))
6708 return -3;
6709
6710 /* rename old file to the temp file */
6711 if (!MoveFile(pszOldFile, szTempFile))
6712 return -4;
6713
6714 /* now create an empty file called pszOldFile; this prevents the operating
6715 * system using pszOldFile as an alias (SFN) if we're renaming within the
6716 * same directory. For example, we're editing a file called
6717 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6718 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6719 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006720 * cause all sorts of problems later in buf_write(). So, we create an
6721 * empty file called filena~1.txt and the system will have to find some
6722 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006723 */
6724 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6725 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6726 return -5;
6727 if (!CloseHandle(hf))
6728 return -6;
6729
6730 /* rename the temp file to the new file */
6731 if (!MoveFile(szTempFile, pszNewFile))
6732 {
6733 /* Renaming failed. Rename the file back to its old name, so that it
6734 * looks like nothing happened. */
6735 (void)MoveFile(szTempFile, pszOldFile);
6736
6737 return -7;
6738 }
6739
6740 /* Seems to be left around on Novell filesystems */
6741 DeleteFile(szTempFile);
6742
6743 /* finally, remove the empty old file */
6744 if (!DeleteFile(pszOldFile))
6745 return -8;
6746
6747 return 0; /* success */
6748}
6749
6750/*
6751 * Get the default shell for the current hardware platform
6752 */
6753 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006754default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006755{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006756 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006757}
6758
6759/*
6760 * mch_access() extends access() to do more detailed check on network drives.
6761 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6762 */
6763 int
6764mch_access(char *n, int p)
6765{
6766 HANDLE hFile;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006767 int retval = -1; /* default: fail */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006768 WCHAR *wn = NULL;
6769
6770 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006771 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006772
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006773 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006774 {
6775 char TempName[_MAX_PATH + 16] = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006776 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006777
6778 if (p & R_OK)
6779 {
6780 /* Read check is performed by seeing if we can do a find file on
6781 * the directory for any file. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006782 if (wn != NULL)
6783 {
6784 int i;
6785 WIN32_FIND_DATAW d;
6786
6787 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6788 TempNameW[i] = wn[i];
6789 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6790 TempNameW[i++] = '\\';
6791 TempNameW[i++] = '*';
6792 TempNameW[i++] = 0;
6793
6794 hFile = FindFirstFileW(TempNameW, &d);
6795 if (hFile == INVALID_HANDLE_VALUE)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006796 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006797 else
6798 (void)FindClose(hFile);
6799 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006800 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006801 {
6802 char *pch;
6803 WIN32_FIND_DATA d;
6804
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006805 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006806 pch = TempName + STRLEN(TempName) - 1;
6807 if (*pch != '\\' && *pch != '/')
6808 *++pch = '\\';
6809 *++pch = '*';
6810 *++pch = NUL;
6811
6812 hFile = FindFirstFile(TempName, &d);
6813 if (hFile == INVALID_HANDLE_VALUE)
6814 goto getout;
6815 (void)FindClose(hFile);
6816 }
6817 }
6818
6819 if (p & W_OK)
6820 {
6821 /* Trying to create a temporary file in the directory should catch
6822 * directories on read-only network shares. However, in
6823 * directories whose ACL allows writes but denies deletes will end
6824 * up keeping the temporary file :-(. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006825 if (wn != NULL)
6826 {
6827 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006828 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006829 else
6830 DeleteFileW(TempNameW);
6831 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006832 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006833 {
6834 if (!GetTempFileName(n, "VIM", 0, TempName))
6835 goto getout;
6836 mch_remove((char_u *)TempName);
6837 }
6838 }
6839 }
6840 else
6841 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02006842 // Don't consider a file read-only if another process has opened it.
6843 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
6844
Bram Moolenaar071d4272004-06-13 20:20:40 +00006845 /* Trying to open the file for the required access does ACL, read-only
6846 * network share, and file attribute checks. */
Bram Moolenaar5aa98962018-05-06 17:09:38 +02006847 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
6848 | ((p & R_OK) ? GENERIC_READ : 0);
6849
Bram Moolenaar071d4272004-06-13 20:20:40 +00006850 if (wn != NULL)
Bram Moolenaar5aa98962018-05-06 17:09:38 +02006851 hFile = CreateFileW(wn, access_mode, share_mode,
6852 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006853 else
Bram Moolenaar5aa98962018-05-06 17:09:38 +02006854 hFile = CreateFile(n, access_mode, share_mode,
6855 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006856 if (hFile == INVALID_HANDLE_VALUE)
6857 goto getout;
6858 CloseHandle(hFile);
6859 }
6860
6861 retval = 0; /* success */
6862getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00006863 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006864 return retval;
6865}
6866
Bram Moolenaar071d4272004-06-13 20:20:40 +00006867/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006868 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006869 */
6870 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006871mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006872{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006873 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
Bram Moolenaara12a1612019-01-24 16:39:02 +01006874#ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006875 WCHAR *wn;
6876 int f;
6877
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006878 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006879 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006880 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006881 if (wn != NULL)
6882 {
6883 f = _wopen(wn, flags, mode);
6884 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006885 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006886 }
6887 }
Bram Moolenaara12a1612019-01-24 16:39:02 +01006888#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006889
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006890 /* open() can open a file which name is longer than _MAX_PATH bytes
6891 * and shorter than _MAX_PATH characters successfully, but sometimes it
6892 * causes unexpected error in another part. We make it an error explicitly
6893 * here. */
6894 if (strlen(name) >= _MAX_PATH)
6895 return -1;
6896
Bram Moolenaar071d4272004-06-13 20:20:40 +00006897 return open(name, flags, mode);
6898}
6899
6900/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006901 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006902 */
6903 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006904mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006905{
6906 WCHAR *wn, *wm;
6907 FILE *f = NULL;
6908
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006909 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006910 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01006911#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006912 /* Work around an annoying assertion in the Microsoft debug CRT
6913 * when mode's text/binary setting doesn't match _get_fmode(). */
6914 char newMode = mode[strlen(mode) - 1];
6915 int oldMode = 0;
6916
6917 _get_fmode(&oldMode);
6918 if (newMode == 't')
6919 _set_fmode(_O_TEXT);
6920 else if (newMode == 'b')
6921 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01006922#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006923 wn = enc_to_utf16((char_u *)name, NULL);
6924 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006925 if (wn != NULL && wm != NULL)
6926 f = _wfopen(wn, wm);
6927 vim_free(wn);
6928 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006929
Bram Moolenaara12a1612019-01-24 16:39:02 +01006930#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006931 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01006932#endif
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006933 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006934 }
6935
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006936 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6937 * and shorter than _MAX_PATH characters successfully, but sometimes it
6938 * causes unexpected error in another part. We make it an error explicitly
6939 * here. */
6940 if (strlen(name) >= _MAX_PATH)
6941 return NULL;
6942
Bram Moolenaar071d4272004-06-13 20:20:40 +00006943 return fopen(name, mode);
6944}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006945
Bram Moolenaar071d4272004-06-13 20:20:40 +00006946/*
6947 * SUB STREAM (aka info stream) handling:
6948 *
6949 * NTFS can have sub streams for each file. Normal contents of file is
6950 * stored in the main stream, and extra contents (author information and
6951 * title and so on) can be stored in sub stream. After Windows 2000, user
6952 * can access and store those informations in sub streams via explorer's
6953 * property menuitem in right click menu. Those informations in sub streams
6954 * were lost when copying only the main stream. So we have to copy sub
6955 * streams.
6956 *
6957 * Incomplete explanation:
6958 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6959 * More useful info and an example:
6960 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6961 */
6962
6963/*
6964 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6965 * and write to stream "substream" of file "to".
6966 * Errors are ignored.
6967 */
6968 static void
6969copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6970{
6971 HANDLE hTo;
6972 WCHAR *to_name;
6973
6974 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6975 wcscpy(to_name, to);
6976 wcscat(to_name, substream);
6977
6978 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6979 FILE_ATTRIBUTE_NORMAL, NULL);
6980 if (hTo != INVALID_HANDLE_VALUE)
6981 {
6982 long done;
6983 DWORD todo;
6984 DWORD readcnt, written;
6985 char buf[4096];
6986
6987 /* Copy block of bytes at a time. Abort when something goes wrong. */
6988 for (done = 0; done < len; done += written)
6989 {
6990 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006991 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6992 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006993 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6994 FALSE, FALSE, context)
6995 || readcnt != todo
6996 || !WriteFile(hTo, buf, todo, &written, NULL)
6997 || written != todo)
6998 break;
6999 }
7000 CloseHandle(hTo);
7001 }
7002
7003 free(to_name);
7004}
7005
7006/*
7007 * Copy info streams from file "from" to file "to".
7008 */
7009 static void
7010copy_infostreams(char_u *from, char_u *to)
7011{
7012 WCHAR *fromw;
7013 WCHAR *tow;
7014 HANDLE sh;
7015 WIN32_STREAM_ID sid;
7016 int headersize;
7017 WCHAR streamname[_MAX_PATH];
7018 DWORD readcount;
7019 void *context = NULL;
7020 DWORD lo, hi;
7021 int len;
7022
7023 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007024 fromw = enc_to_utf16(from, NULL);
7025 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007026 if (fromw != NULL && tow != NULL)
7027 {
7028 /* Open the file for reading. */
7029 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7030 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7031 if (sh != INVALID_HANDLE_VALUE)
7032 {
7033 /* Use BackupRead() to find the info streams. Repeat until we
7034 * have done them all.*/
7035 for (;;)
7036 {
7037 /* Get the header to find the length of the stream name. If
7038 * the "readcount" is zero we have done all info streams. */
7039 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007040 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007041 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7042 &readcount, FALSE, FALSE, &context)
7043 || readcount == 0)
7044 break;
7045
7046 /* We only deal with streams that have a name. The normal
7047 * file data appears to be without a name, even though docs
7048 * suggest it is called "::$DATA". */
7049 if (sid.dwStreamNameSize > 0)
7050 {
7051 /* Read the stream name. */
7052 if (!BackupRead(sh, (LPBYTE)streamname,
7053 sid.dwStreamNameSize,
7054 &readcount, FALSE, FALSE, &context))
7055 break;
7056
7057 /* Copy an info stream with a name ":anything:$DATA".
7058 * Skip "::$DATA", it has no stream name (examples suggest
7059 * it might be used for the normal file contents).
7060 * Note that BackupRead() counts bytes, but the name is in
7061 * wide characters. */
7062 len = readcount / sizeof(WCHAR);
7063 streamname[len] = 0;
7064 if (len > 7 && wcsicmp(streamname + len - 6,
7065 L":$DATA") == 0)
7066 {
7067 streamname[len - 6] = 0;
7068 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007069 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007070 }
7071 }
7072
7073 /* Advance to the next stream. We might try seeking too far,
7074 * but BackupSeek() doesn't skip over stream borders, thus
7075 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007076 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007077 &lo, &hi, &context);
7078 }
7079
7080 /* Clear the context. */
7081 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7082
7083 CloseHandle(sh);
7084 }
7085 }
7086 vim_free(fromw);
7087 vim_free(tow);
7088}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007089
7090/*
7091 * Copy file attributes from file "from" to file "to".
7092 * For Windows NT and later we copy info streams.
7093 * Always returns zero, errors are ignored.
7094 */
7095 int
7096mch_copy_file_attribute(char_u *from, char_u *to)
7097{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007098 /* File streams only work on Windows NT and later. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007099 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007100 return 0;
7101}
7102
7103#if defined(MYRESETSTKOFLW) || defined(PROTO)
7104/*
7105 * Recreate a destroyed stack guard page in win32.
7106 * Written by Benjamin Peterson.
7107 */
7108
7109/* These magic numbers are from the MS header files */
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007110# define MIN_STACK_WINNT 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00007111
7112/*
7113 * This function does the same thing as _resetstkoflw(), which is only
7114 * available in DevStudio .net and later.
7115 * Returns 0 for failure, 1 for success.
7116 */
7117 int
7118myresetstkoflw(void)
7119{
7120 BYTE *pStackPtr;
7121 BYTE *pGuardPage;
7122 BYTE *pStackBase;
7123 BYTE *pLowestPossiblePage;
7124 MEMORY_BASIC_INFORMATION mbi;
7125 SYSTEM_INFO si;
7126 DWORD nPageSize;
7127 DWORD dummy;
7128
Bram Moolenaar071d4272004-06-13 20:20:40 +00007129 /* We need to know the system page size. */
7130 GetSystemInfo(&si);
7131 nPageSize = si.dwPageSize;
7132
7133 /* ...and the current stack pointer */
7134 pStackPtr = (BYTE*)_alloca(1);
7135
7136 /* ...and the base of the stack. */
7137 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
7138 return 0;
7139 pStackBase = (BYTE*)mbi.AllocationBase;
7140
7141 /* ...and the page thats min_stack_req pages away from stack base; this is
7142 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007143 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007144
Bram Moolenaar071d4272004-06-13 20:20:40 +00007145 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007146 /* We want the first committed page in the stack Start at the stack
7147 * base and move forward through memory until we find a committed block.
7148 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007149 BYTE *pBlock = pStackBase;
7150
Bram Moolenaara466c992005-07-09 21:03:22 +00007151 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007152 {
7153 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
7154 return 0;
7155
7156 pBlock += mbi.RegionSize;
7157
7158 if (mbi.State & MEM_COMMIT)
7159 break;
7160 }
7161
7162 /* mbi now describes the first committed block in the stack. */
7163 if (mbi.Protect & PAGE_GUARD)
7164 return 1;
7165
7166 /* decide where the guard page should start */
7167 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
7168 pGuardPage = pLowestPossiblePage;
7169 else
7170 pGuardPage = (BYTE*)mbi.BaseAddress;
7171
7172 /* allocate the guard page */
7173 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
7174 return 0;
7175
7176 /* apply the guard attribute to the page */
7177 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
7178 &dummy))
7179 return 0;
7180 }
7181
7182 return 1;
7183}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007184#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007185
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007186
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007187/*
7188 * The command line arguments in UCS2
7189 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007190static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007191static LPWSTR *ArglistW = NULL;
7192static int global_argc = 0;
7193static char **global_argv;
7194
7195static int used_file_argc = 0; /* last argument in global_argv[] used
7196 for the argument list. */
7197static int *used_file_indexes = NULL; /* indexes in global_argv[] for
7198 command line arguments added to
7199 the argument list */
7200static int used_file_count = 0; /* nr of entries in used_file_indexes */
7201static int used_file_literal = FALSE; /* take file names literally */
7202static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007203static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007204static int used_alist_count = 0;
7205
7206
7207/*
7208 * Get the command line arguments. Unicode version.
7209 * Returns argc. Zero when something fails.
7210 */
7211 int
7212get_cmd_argsW(char ***argvp)
7213{
7214 char **argv = NULL;
7215 int argc = 0;
7216 int i;
7217
Bram Moolenaar14993322014-09-09 12:25:33 +02007218 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007219 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7220 if (ArglistW != NULL)
7221 {
7222 argv = malloc((nArgsW + 1) * sizeof(char *));
7223 if (argv != NULL)
7224 {
7225 argc = nArgsW;
7226 argv[argc] = NULL;
7227 for (i = 0; i < argc; ++i)
7228 {
7229 int len;
7230
7231 /* Convert each Unicode argument to the current codepage. */
7232 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007233 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007234 (LPSTR *)&argv[i], &len, 0, 0);
7235 if (argv[i] == NULL)
7236 {
7237 /* Out of memory, clear everything. */
7238 while (i > 0)
7239 free(argv[--i]);
7240 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007241 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007242 argc = 0;
7243 }
7244 }
7245 }
7246 }
7247
7248 global_argc = argc;
7249 global_argv = argv;
7250 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007251 {
7252 if (used_file_indexes != NULL)
7253 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007254 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007255 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007256
7257 if (argvp != NULL)
7258 *argvp = argv;
7259 return argc;
7260}
7261
7262 void
7263free_cmd_argsW(void)
7264{
7265 if (ArglistW != NULL)
7266 {
7267 GlobalFree(ArglistW);
7268 ArglistW = NULL;
7269 }
7270}
7271
7272/*
7273 * Remember "name" is an argument that was added to the argument list.
7274 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7275 * is called.
7276 */
7277 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007278used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007279{
7280 int i;
7281
7282 if (used_file_indexes == NULL)
7283 return;
7284 for (i = used_file_argc + 1; i < global_argc; ++i)
7285 if (STRCMP(global_argv[i], name) == 0)
7286 {
7287 used_file_argc = i;
7288 used_file_indexes[used_file_count++] = i;
7289 break;
7290 }
7291 used_file_literal = literal;
7292 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007293 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007294}
7295
7296/*
7297 * Remember the length of the argument list as it was. If it changes then we
7298 * leave it alone when 'encoding' is set.
7299 */
7300 void
7301set_alist_count(void)
7302{
7303 used_alist_count = GARGCOUNT;
7304}
7305
7306/*
7307 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7308 * has been changed while starting up. Use the UCS-2 command line arguments
7309 * and convert them to 'encoding'.
7310 */
7311 void
7312fix_arg_enc(void)
7313{
7314 int i;
7315 int idx;
7316 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007317 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007318
7319 /* Safety checks:
7320 * - if argument count differs between the wide and non-wide argument
7321 * list, something must be wrong.
7322 * - the file name arguments must have been located.
7323 * - the length of the argument list wasn't changed by the user.
7324 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007325 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007326 || ArglistW == NULL
7327 || used_file_indexes == NULL
7328 || used_file_count == 0
7329 || used_alist_count != GARGCOUNT)
7330 return;
7331
Bram Moolenaar86b68352004-12-27 21:59:20 +00007332 /* Remember the buffer numbers for the arguments. */
7333 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7334 if (fnum_list == NULL)
7335 return; /* out of memory */
7336 for (i = 0; i < GARGCOUNT; ++i)
7337 fnum_list[i] = GARGLIST[i].ae_fnum;
7338
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007339 /* Clear the argument list. Make room for the new arguments. */
7340 alist_clear(&global_alist);
7341 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007342 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007343
7344 for (i = 0; i < used_file_count; ++i)
7345 {
7346 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007347 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007348 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007349 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007350 int literal = used_file_literal;
7351
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007352# ifdef FEAT_DIFF
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007353 /* When using diff mode may need to concatenate file name to
7354 * directory name. Just like it's done in main(). */
7355 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7356 && !mch_isdir(alist_name(&GARGLIST[0])))
7357 {
7358 char_u *r;
7359
7360 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7361 if (r != NULL)
7362 {
7363 vim_free(str);
7364 str = r;
7365 }
7366 }
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007367# endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007368 /* Re-use the old buffer by renaming it. When not using literal
7369 * names it's done by alist_expand() below. */
7370 if (used_file_literal)
7371 buf_set_name(fnum_list[i], str);
7372
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007373 /* Check backtick literal. backtick literal is already expanded in
7374 * main.c, so this part add str as literal. */
7375 if (literal == FALSE)
7376 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007377 size_t len = STRLEN(str);
7378
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007379 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7380 literal = TRUE;
7381 }
7382 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007383 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007384 }
7385
7386 if (!used_file_literal)
7387 {
7388 /* Now expand wildcards in the arguments. */
7389 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7390 * filename characters but are excluded from 'isfname' to make
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007391 * "gf" work on a file name in parenthesis (e.g.: see vim.h).
7392 * Also, unset wildignore to not be influenced by this option.
7393 * The arguments specified in command-line should be kept even if
7394 * encoding options were changed. */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007395 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007396 do_cmdline_cmd((char_u *)":let SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007397 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007398 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007399 do_cmdline_cmd((char_u *)":let &wig = SaVe_WIG|unlet SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007400 }
7401
7402 /* If wildcard expansion failed, we are editing the first file of the
7403 * arglist and there is no file name: Edit the first argument now. */
7404 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7405 {
7406 do_cmdline_cmd((char_u *)":rewind");
7407 if (GARGCOUNT == 1 && used_file_full_path)
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007408 (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007409 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007410
7411 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007412}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007413
7414 int
7415mch_setenv(char *var, char *value, int x)
7416{
7417 char_u *envbuf;
7418
7419 envbuf = alloc((unsigned)(STRLEN(var) + STRLEN(value) + 2));
7420 if (envbuf == NULL)
7421 return -1;
7422
7423 sprintf((char *)envbuf, "%s=%s", var, value);
7424
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007425 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
7426 {
7427 WCHAR *p = enc_to_utf16(envbuf, NULL);
7428
7429 vim_free(envbuf);
7430 if (p == NULL)
7431 return -1;
7432 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007433#ifdef libintl_wputenv
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007434 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007435#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007436 /* Unlike Un*x systems, we can free the string for _wputenv(). */
7437 vim_free(p);
7438 }
7439 else
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007440 {
7441 _putenv((char *)envbuf);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007442#ifdef libintl_putenv
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007443 libintl_putenv((char *)envbuf);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007444#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007445 /* Unlike Un*x systems, we can free the string for _putenv(). */
7446 vim_free(envbuf);
7447 }
7448
7449 return 0;
7450}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007451
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007452/*
7453 * Support for 256 colors and 24-bit colors was added in Windows 10
7454 * version 1703 (Creators update).
7455 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007456#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7457
7458/*
7459 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007460 * version 1809 (October 2018 update). However, that version is unstable.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007461 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007462#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
7463#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007464
7465 static void
7466vtp_flag_init(void)
7467{
7468 DWORD ver = get_build_number();
Bram Moolenaar4f974752019-02-17 17:44:42 +01007469#ifndef FEAT_GUI_MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007470 DWORD mode;
7471 HANDLE out;
7472
7473 out = GetStdHandle(STD_OUTPUT_HANDLE);
7474
7475 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7476 GetConsoleMode(out, &mode);
7477 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7478 if (SetConsoleMode(out, mode) == 0)
7479 vtp_working = 0;
7480#endif
7481
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007482 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007483 conpty_working = 1;
7484 if (ver >= CONPTY_STABLE_BUILD)
7485 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007486
7487}
7488
Bram Moolenaar4f974752019-02-17 17:44:42 +01007489#if !defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007490
7491 static void
7492vtp_init(void)
7493{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007494 HMODULE hKerneldll;
7495 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007496# ifdef FEAT_TERMGUICOLORS
7497 COLORREF fg, bg;
7498# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007499
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007500 /* Use functions supported from Vista */
7501 hKerneldll = GetModuleHandle("kernel32.dll");
7502 if (hKerneldll != NULL)
7503 {
7504 pGetConsoleScreenBufferInfoEx =
7505 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7506 hKerneldll, "GetConsoleScreenBufferInfoEx");
7507 pSetConsoleScreenBufferInfoEx =
7508 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7509 hKerneldll, "SetConsoleScreenBufferInfoEx");
7510 if (pGetConsoleScreenBufferInfoEx != NULL
7511 && pSetConsoleScreenBufferInfoEx != NULL)
7512 has_csbiex = TRUE;
7513 }
7514
7515 csbi.cbSize = sizeof(csbi);
7516 if (has_csbiex)
7517 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007518 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7519 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
7520
7521# ifdef FEAT_TERMGUICOLORS
7522 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7523 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7524 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7525 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7526 default_console_color_bg = bg;
7527 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007528# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007529
7530 set_console_color_rgb();
7531}
7532
7533 static void
7534vtp_exit(void)
7535{
7536 reset_console_color_rgb();
7537}
7538
7539 static int
7540vtp_printf(
7541 char *format,
7542 ...)
7543{
7544 char_u buf[100];
7545 va_list list;
7546 DWORD result;
7547
7548 va_start(list, format);
7549 vim_vsnprintf((char *)buf, 100, (char *)format, list);
7550 va_end(list);
7551 WriteConsoleA(g_hConOut, buf, (DWORD)STRLEN(buf), &result, NULL);
7552 return (int)result;
7553}
7554
7555 static void
7556vtp_sgr_bulk(
7557 int arg)
7558{
7559 int args[1];
7560
7561 args[0] = arg;
7562 vtp_sgr_bulks(1, args);
7563}
7564
7565 static void
7566vtp_sgr_bulks(
7567 int argc,
7568 int *args
7569)
7570{
7571 /* 2('\033[') + 4('255.') * 16 + NUL */
7572 char_u buf[2 + (4 * 16) + 1];
7573 char_u *p;
7574 int i;
7575
7576 p = buf;
7577 *p++ = '\033';
7578 *p++ = '[';
7579
7580 for (i = 0; i < argc; ++i)
7581 {
7582 p += vim_snprintf((char *)p, 4, "%d", args[i] & 0xff);
7583 *p++ = ';';
7584 }
7585 p--;
7586 *p++ = 'm';
7587 *p = NUL;
7588 vtp_printf((char *)buf);
7589}
7590
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007591# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007592 static int
7593ctermtoxterm(
7594 int cterm)
7595{
Bram Moolenaar9894e392018-05-05 14:29:06 +02007596 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007597
7598 cterm_color2rgb(cterm, &r, &g, &b, &idx);
7599 return (((int)r << 16) | ((int)g << 8) | (int)b);
7600}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007601# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007602
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007603 static void
7604set_console_color_rgb(void)
7605{
7606# ifdef FEAT_TERMGUICOLORS
7607 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7608 int id;
7609 guicolor_T fg = INVALCOLOR;
7610 guicolor_T bg = INVALCOLOR;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007611 int ctermfg;
7612 int ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007613
7614 if (!USE_VTP)
7615 return;
7616
7617 id = syn_name2id((char_u *)"Normal");
Bram Moolenaard5a58862019-03-07 06:40:27 +01007618 if (id > 0 && p_tgc)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007619 syn_id2colors(id, &fg, &bg);
7620 if (fg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007621 {
7622 ctermfg = -1;
7623 if (id > 0)
7624 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007625 fg = ctermfg != -1 ? ctermtoxterm(ctermfg) : default_console_color_fg;
7626 cterm_normal_fg_gui_color = fg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007627 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007628 if (bg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007629 {
7630 ctermbg = -1;
7631 if (id > 0)
7632 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007633 bg = ctermbg != -1 ? ctermtoxterm(ctermbg) : default_console_color_bg;
7634 cterm_normal_bg_gui_color = bg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007635 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007636 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7637 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7638
7639 csbi.cbSize = sizeof(csbi);
7640 if (has_csbiex)
7641 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7642
7643 csbi.cbSize = sizeof(csbi);
7644 csbi.srWindow.Right += 1;
7645 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007646 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
7647 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007648 if (has_csbiex)
7649 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7650# endif
7651}
7652
7653 static void
7654reset_console_color_rgb(void)
7655{
7656# ifdef FEAT_TERMGUICOLORS
7657 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7658
7659 csbi.cbSize = sizeof(csbi);
7660 if (has_csbiex)
7661 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7662
7663 csbi.cbSize = sizeof(csbi);
7664 csbi.srWindow.Right += 1;
7665 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007666 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
7667 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007668 if (has_csbiex)
7669 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7670# endif
7671}
7672
7673 void
7674control_console_color_rgb(void)
7675{
7676 if (USE_VTP)
7677 set_console_color_rgb();
7678 else
7679 reset_console_color_rgb();
7680}
7681
7682 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007683use_vtp(void)
7684{
7685 return USE_VTP;
7686}
7687
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007688 int
7689is_term_win32(void)
7690{
7691 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
7692}
7693
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007694 int
7695has_vtp_working(void)
7696{
7697 return vtp_working;
7698}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007699
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01007700#endif
7701
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007702 int
7703has_conpty_working(void)
7704{
7705 return conpty_working;
7706}
7707
7708 int
7709is_conpty_stable(void)
7710{
7711 return conpty_stable;
7712}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01007713
Bram Moolenaar4f974752019-02-17 17:44:42 +01007714#if !defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01007715 void
7716resize_console_buf(void)
7717{
7718 CONSOLE_SCREEN_BUFFER_INFO csbi;
7719 COORD coord;
7720 SMALL_RECT newsize;
7721
7722 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
7723 {
7724 coord.X = SRWIDTH(csbi.srWindow);
7725 coord.Y = SRHEIGHT(csbi.srWindow);
7726 SetConsoleScreenBufferSize(g_hConOut, coord);
7727
7728 newsize.Left = 0;
7729 newsize.Top = 0;
7730 newsize.Right = coord.X - 1;
7731 newsize.Bottom = coord.Y - 1;
7732 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
7733
7734 SetConsoleScreenBufferSize(g_hConOut, coord);
7735 }
7736}
7737#endif