blob: 876a7a409ac6ee99e7067b8301e17f58b6429cad [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
12 * Used for both the console version and the Win32 GUI. A lot of code is for
Bram Moolenaar4f974752019-02-17 17:44:42 +010013 * the console version only, so there is a lot of "#ifndef FEAT_GUI_MSWIN".
Bram Moolenaar071d4272004-06-13 20:20:40 +000014 *
15 * Win32 (Windows NT and Windows 95) system-dependent routines.
16 * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17 * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18 *
19 * George V. Reilly <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
Bram Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010032
33/* cproto fails on missing include files */
34#ifndef PROTO
35# include <process.h>
36#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000037
38#undef chdir
39#ifdef __GNUC__
40# ifndef __MINGW32__
41# include <dirent.h>
42# endif
43#else
44# include <direct.h>
45#endif
46
Bram Moolenaar82881492012-11-20 16:53:39 +010047#ifndef PROTO
Bram Moolenaar4f974752019-02-17 17:44:42 +010048# if defined(FEAT_TITLE) && !defined(FEAT_GUI_MSWIN)
Bram Moolenaar82881492012-11-20 16:53:39 +010049# include <shellapi.h>
50# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000051#endif
52
Bram Moolenaarfb630902016-10-29 14:55:00 +020053#ifdef FEAT_JOB_CHANNEL
54# include <tlhelp32.h>
55#endif
56
Bram Moolenaar071d4272004-06-13 20:20:40 +000057#ifdef __MINGW32__
58# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
59# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
60# endif
61# ifndef RIGHTMOST_BUTTON_PRESSED
62# define RIGHTMOST_BUTTON_PRESSED 0x0002
63# endif
64# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
65# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
66# endif
67# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
68# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
69# endif
70# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
71# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
72# endif
73
74/*
75 * EventFlags
76 */
77# ifndef MOUSE_MOVED
78# define MOUSE_MOVED 0x0001
79# endif
80# ifndef DOUBLE_CLICK
81# define DOUBLE_CLICK 0x0002
82# endif
83#endif
84
85/* Record all output and all keyboard & mouse input */
86/* #define MCH_WRITE_DUMP */
87
88#ifdef MCH_WRITE_DUMP
89FILE* fdDump = NULL;
90#endif
91
92/*
93 * When generating prototypes for Win32 on Unix, these lines make the syntax
94 * errors disappear. They do not need to be correct.
95 */
96#ifdef PROTO
97#define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000098typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000099typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000100typedef int ACCESS_MASK;
101typedef int BOOL;
102typedef int COLORREF;
103typedef int CONSOLE_CURSOR_INFO;
104typedef int COORD;
105typedef int DWORD;
106typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100107typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000108typedef int HDC;
109typedef int HFONT;
110typedef int HICON;
111typedef int HINSTANCE;
112typedef int HWND;
113typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200114typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000115typedef int KEY_EVENT_RECORD;
116typedef int LOGFONT;
117typedef int LPBOOL;
118typedef int LPCTSTR;
119typedef int LPDWORD;
120typedef int LPSTR;
121typedef int LPTSTR;
122typedef int LPVOID;
123typedef int MOUSE_EVENT_RECORD;
124typedef int PACL;
125typedef int PDWORD;
126typedef int PHANDLE;
127typedef int PRINTDLG;
128typedef int PSECURITY_DESCRIPTOR;
129typedef int PSID;
130typedef int SECURITY_INFORMATION;
131typedef int SHORT;
132typedef int SMALL_RECT;
133typedef int TEXTMETRIC;
134typedef int TOKEN_INFORMATION_CLASS;
135typedef int TRUSTEE;
136typedef int WORD;
137typedef int WCHAR;
138typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100139typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200140typedef int SE_OBJECT_TYPE;
141typedef int PSNSECINFO;
142typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100143typedef int STARTUPINFO;
144typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200145typedef int LPSECURITY_ATTRIBUTES;
146# define __stdcall /* empty */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000147#endif
148
Bram Moolenaar071d4272004-06-13 20:20:40 +0000149#if defined(__BORLANDC__)
150/* Strangely Borland uses a non-standard name. */
151# define wcsicmp(a, b) wcscmpi((a), (b))
152#endif
153
Bram Moolenaar4f974752019-02-17 17:44:42 +0100154#ifndef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000155/* Win32 Console handles for input and output */
156static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
157static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
158
159/* Win32 Screen buffer,coordinate,console I/O information */
160static SMALL_RECT g_srScrollRegion;
161static COORD g_coord; /* 0-based, but external coords are 1-based */
162
163/* The attribute of the screen when the editor was started */
164static WORD g_attrDefault = 7; /* lightgray text on black background */
165static WORD g_attrCurrent;
166
167static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
168static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
169static int g_fForceExit = FALSE; /* set when forcefully exiting */
170
Bram Moolenaar071d4272004-06-13 20:20:40 +0000171static void scroll(unsigned cLines);
172static void set_scroll_region(unsigned left, unsigned top,
173 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100174static void set_scroll_region_tb(unsigned top, unsigned bottom);
175static void set_scroll_region_lr(unsigned left, unsigned right);
176static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000177static void delete_lines(unsigned cLines);
178static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000179static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000180static int s_cursor_visible = TRUE;
181static int did_create_conin = FALSE;
182#else
183static int s_dont_use_vimrun = TRUE;
184static int need_vimrun_warning = FALSE;
185static char *vimrun_path = "vimrun ";
186#endif
187
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200188static int win32_getattrs(char_u *name);
189static int win32_setattrs(char_u *name, int attrs);
190static int win32_set_archive(char_u *name);
191
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100192static int conpty_working = 0;
193static int conpty_stable = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100194static void vtp_flag_init();
195
Bram Moolenaar4f974752019-02-17 17:44:42 +0100196#ifndef FEAT_GUI_MSWIN
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100197static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100198static void vtp_init();
199static void vtp_exit();
200static int vtp_printf(char *format, ...);
201static void vtp_sgr_bulk(int arg);
202static void vtp_sgr_bulks(int argc, int *argv);
203
204static guicolor_T save_console_bg_rgb;
205static guicolor_T save_console_fg_rgb;
206
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200207static int g_color_index_bg = 0;
208static int g_color_index_fg = 7;
209
210# ifdef FEAT_TERMGUICOLORS
211static int default_console_color_bg = 0x000000; // black
212static int default_console_color_fg = 0xc0c0c0; // white
213# endif
214
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100215# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200216# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100217# else
218# define USE_VTP 0
219# endif
220
221static void set_console_color_rgb(void);
222static void reset_console_color_rgb(void);
223#endif
224
225/* This flag is newly created from Windows 10 */
226#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
227# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
228#endif
229
Bram Moolenaar4f974752019-02-17 17:44:42 +0100230#ifndef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000231static int suppress_winsize = 1; /* don't fiddle with console */
232#endif
233
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200234static char_u *exe_path = NULL;
235
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100236static BOOL win8_or_later = FALSE;
237
Bram Moolenaar4f974752019-02-17 17:44:42 +0100238#ifndef FEAT_GUI_MSWIN
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100239/* Dynamic loading for portability */
240typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
241{
242 ULONG cbSize;
243 COORD dwSize;
244 COORD dwCursorPosition;
245 WORD wAttributes;
246 SMALL_RECT srWindow;
247 COORD dwMaximumWindowSize;
248 WORD wPopupAttributes;
249 BOOL bFullscreenSupported;
250 COLORREF ColorTable[16];
251} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
252typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
253static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
254typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
255static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
256static BOOL has_csbiex = FALSE;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100257#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100258
259/*
260 * Get version number including build number
261 */
262typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
263# define MAKE_VER(major, minor, build) \
264 (((major) << 24) | ((minor) << 16) | (build))
265
266 static DWORD
267get_build_number(void)
268{
269 OSVERSIONINFOW osver = {sizeof(OSVERSIONINFOW)};
270 HMODULE hNtdll;
271 PfnRtlGetVersion pRtlGetVersion;
272 DWORD ver = MAKE_VER(0, 0, 0);
273
274 hNtdll = GetModuleHandle("ntdll.dll");
275 if (hNtdll != NULL)
276 {
277 pRtlGetVersion =
278 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
279 pRtlGetVersion(&osver);
280 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
281 min(osver.dwMinorVersion, 255),
282 min(osver.dwBuildNumber, 32767));
283 }
284 return ver;
285}
286
Bram Moolenaar4f974752019-02-17 17:44:42 +0100287#ifndef FEAT_GUI_MSWIN
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100288/*
289 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100290 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100291 */
292 static BOOL
293read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100294 HANDLE hInput,
295 INPUT_RECORD *lpBuffer,
296 DWORD nLength,
297 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100298{
299 enum
300 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100301 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100302 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100303 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100304 static DWORD s_dwIndex = 0;
305 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100306 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100307 int head;
308 int tail;
309 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100310
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200311 if (nLength == -2)
312 return (s_dwMax > 0) ? TRUE : FALSE;
313
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100314 if (!win8_or_later)
315 {
316 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200317 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
318 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100319 }
320
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100321 if (s_dwMax == 0)
322 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100323 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200324 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
325 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100326 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100327 s_dwIndex = 0;
328 s_dwMax = dwEvents;
329 if (dwEvents == 0)
330 {
331 *lpEvents = 0;
332 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100333 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100334
335 if (s_dwMax > 1)
336 {
337 head = 0;
338 tail = s_dwMax - 1;
339 while (head != tail)
340 {
341 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
342 && s_irCache[head + 1].EventType
343 == WINDOW_BUFFER_SIZE_EVENT)
344 {
345 /* Remove duplicate event to avoid flicker. */
346 for (i = head; i < tail; ++i)
347 s_irCache[i] = s_irCache[i + 1];
348 --tail;
349 continue;
350 }
351 head++;
352 }
353 s_dwMax = tail + 1;
354 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100355 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100356
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100357 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200358 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100359 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100360 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100361 return TRUE;
362}
363
364/*
365 * Version of PeekConsoleInput() that works with IME.
366 */
367 static BOOL
368peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100369 HANDLE hInput,
370 INPUT_RECORD *lpBuffer,
371 DWORD nLength,
372 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100373{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100374 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100375}
376
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100377# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200378 static DWORD
379msg_wait_for_multiple_objects(
380 DWORD nCount,
381 LPHANDLE pHandles,
382 BOOL fWaitAll,
383 DWORD dwMilliseconds,
384 DWORD dwWakeMask)
385{
386 if (read_console_input(NULL, NULL, -2, NULL))
387 return WAIT_OBJECT_0;
388 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
389 dwMilliseconds, dwWakeMask);
390}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100391# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200392
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100393# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200394 static DWORD
395wait_for_single_object(
396 HANDLE hHandle,
397 DWORD dwMilliseconds)
398{
399 if (read_console_input(NULL, NULL, -2, NULL))
400 return WAIT_OBJECT_0;
401 return WaitForSingleObject(hHandle, dwMilliseconds);
402}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100403# endif
404#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200405
Bram Moolenaar071d4272004-06-13 20:20:40 +0000406 static void
407get_exe_name(void)
408{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100409 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
410 * as the maximum length that works (plus a NUL byte). */
411#define MAX_ENV_PATH_LEN 8192
412 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200413 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000414
415 if (exe_name == NULL)
416 {
417 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100418 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000419 if (*temp != NUL)
420 exe_name = FullName_save((char_u *)temp, FALSE);
421 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000422
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200423 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000424 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200425 exe_path = vim_strnsave(exe_name,
426 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200427 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000428 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200429 /* Append our starting directory to $PATH, so that when doing
430 * "!xxd" it's found in our starting directory. Needed because
431 * SearchPath() also looks there. */
432 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100433 if (p == NULL
434 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200435 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100436 if (p == NULL || *p == NUL)
437 temp[0] = NUL;
438 else
439 {
440 STRCPY(temp, p);
441 STRCAT(temp, ";");
442 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200443 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100444 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200445 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000446 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000447 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000448}
449
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200450/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100451 * Unescape characters in "p" that appear in "escaped".
452 */
453 static void
454unescape_shellxquote(char_u *p, char_u *escaped)
455{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100456 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100457 int n;
458
459 while (*p != NUL)
460 {
461 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
462 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100463 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100464 p += n;
465 l -= n;
466 }
467}
468
469/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200470 * Load library "name".
471 */
472 HINSTANCE
473vimLoadLib(char *name)
474{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200475 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200476
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200477 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
478 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200479 if (exe_path == NULL)
480 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200481 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200482 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200483 WCHAR old_dirw[MAXPATHL];
484
485 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
486 {
487 /* Change directory to where the executable is, both to make
488 * sure we find a .dll there and to avoid looking for a .dll
489 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100490 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200491 dll = LoadLibrary(name);
492 SetCurrentDirectoryW(old_dirw);
493 return dll;
494 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200495 }
496 return dll;
497}
498
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100499#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
500/*
501 * Get related information about 'funcname' which is imported by 'hInst'.
502 * If 'info' is 0, return the function address.
503 * If 'info' is 1, return the module name which the function is imported from.
504 */
505 static void *
506get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
507{
508 PBYTE pImage = (PBYTE)hInst;
509 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
510 PIMAGE_NT_HEADERS pPE;
511 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
512 PIMAGE_THUNK_DATA pIAT; /* Import Address Table */
513 PIMAGE_THUNK_DATA pINT; /* Import Name Table */
514 PIMAGE_IMPORT_BY_NAME pImpName;
515
516 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
517 return NULL;
518 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
519 if (pPE->Signature != IMAGE_NT_SIGNATURE)
520 return NULL;
521 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
522 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
523 .VirtualAddress);
524 for (; pImpDesc->FirstThunk; ++pImpDesc)
525 {
526 if (!pImpDesc->OriginalFirstThunk)
527 continue;
528 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
529 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
530 for (; pIAT->u1.Function; ++pIAT, ++pINT)
531 {
532 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
533 continue;
534 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
535 + (UINT_PTR)(pINT->u1.AddressOfData));
536 if (strcmp((char *)pImpName->Name, funcname) == 0)
537 {
538 switch (info)
539 {
540 case 0:
541 return (void *)pIAT->u1.Function;
542 case 1:
543 return (void *)(pImage + pImpDesc->Name);
544 default:
545 return NULL;
546 }
547 }
548 }
549 }
550 return NULL;
551}
552
553/*
554 * Get the module handle which 'funcname' in 'hInst' is imported from.
555 */
556 HINSTANCE
557find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
558{
559 char *modulename;
560
561 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
562 if (modulename != NULL)
563 return GetModuleHandleA(modulename);
564 return NULL;
565}
566
567/*
568 * Get the address of 'funcname' which is imported by 'hInst' DLL.
569 */
570 void *
571get_dll_import_func(HINSTANCE hInst, const char *funcname)
572{
573 return get_imported_func_info(hInst, funcname, 0);
574}
575#endif
576
Bram Moolenaar071d4272004-06-13 20:20:40 +0000577#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
578# ifndef GETTEXT_DLL
579# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200580# define GETTEXT_DLL_ALT1 "libintl-8.dll"
581# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000582# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200583/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000584static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200585static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000586static char *null_libintl_textdomain(const char *);
587static char *null_libintl_bindtextdomain(const char *, const char *);
588static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100589static int null_libintl_putenv(const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100590static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000591
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200592static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000593char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200594char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
595 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000596char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
597char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000598 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000599char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
600 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100601int (*dyn_libintl_putenv)(const char *) = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100602int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000603
604 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100605dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000606{
607 int i;
608 static struct
609 {
610 char *name;
611 FARPROC *ptr;
612 } libintl_entry[] =
613 {
614 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200615 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000616 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
617 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
618 {NULL, NULL}
619 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100620 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000621
Bram Moolenaar7554c542018-10-06 15:03:15 +0200622 // No need to initialize twice.
623 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000624 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200625 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100626 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar7554c542018-10-06 15:03:15 +0200627#ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100628 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200629 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
630#endif
631#ifdef GETTEXT_DLL_ALT2
632 if (!hLibintlDLL)
633 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100634#endif
635 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000636 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200637 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000638 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200639 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100640 semsg(_(e_loadlib), GETTEXT_DLL);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200641 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000642 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200643 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000644 }
645 for (i = 0; libintl_entry[i].name != NULL
646 && libintl_entry[i].ptr != NULL; ++i)
647 {
648 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
649 libintl_entry[i].name)) == NULL)
650 {
651 dyn_libintl_end();
652 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000653 {
654 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100655 semsg(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000656 verbose_leave();
657 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000658 return 0;
659 }
660 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000661
662 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000663 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000664 "bind_textdomain_codeset");
665 if (dyn_libintl_bind_textdomain_codeset == NULL)
666 dyn_libintl_bind_textdomain_codeset =
667 null_libintl_bind_textdomain_codeset;
668
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100669 /* _putenv() function for the libintl.dll is optional. */
670 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
671 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100672 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100673 dyn_libintl_putenv = (void *)GetProcAddress(hmsvcrt, "_putenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100674 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
675 }
676 if (dyn_libintl_putenv == NULL || dyn_libintl_putenv == _putenv)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100677 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100678 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
679 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100680
Bram Moolenaar071d4272004-06-13 20:20:40 +0000681 return 1;
682}
683
684 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100685dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000686{
687 if (hLibintlDLL)
688 FreeLibrary(hLibintlDLL);
689 hLibintlDLL = NULL;
690 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200691 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000692 dyn_libintl_textdomain = null_libintl_textdomain;
693 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000694 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100695 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100696 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000697}
698
699 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000700null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000701{
702 return (char*)msgid;
703}
704
705 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200706null_libintl_ngettext(
707 const char *msgid,
708 const char *msgid_plural,
709 unsigned long n)
710{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200711 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200712}
713
Bram Moolenaaree695f72016-08-03 22:08:45 +0200714 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100715null_libintl_bindtextdomain(
716 const char *domainname UNUSED,
717 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000718{
719 return NULL;
720}
721
722 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100723null_libintl_bind_textdomain_codeset(
724 const char *domainname UNUSED,
725 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000726{
727 return NULL;
728}
729
730 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100731null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000732{
733 return NULL;
734}
735
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200736 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100737null_libintl_putenv(const char *envstring UNUSED)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100738{
739 return 0;
740}
741
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200742 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100743null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100744{
745 return 0;
746}
747
Bram Moolenaar071d4272004-06-13 20:20:40 +0000748#endif /* DYNAMIC_GETTEXT */
749
750/* This symbol is not defined in older versions of the SDK or Visual C++ */
751
752#ifndef VER_PLATFORM_WIN32_WINDOWS
753# define VER_PLATFORM_WIN32_WINDOWS 1
754#endif
755
756DWORD g_PlatformId;
757
758#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100759# ifndef PROTO
760# include <aclapi.h>
761# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200762# ifndef PROTECTED_DACL_SECURITY_INFORMATION
763# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
764# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000765#endif
766
Bram Moolenaar27515922013-06-29 15:36:26 +0200767#ifdef HAVE_ACL
768/*
769 * Enables or disables the specified privilege.
770 */
771 static BOOL
772win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
773{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100774 BOOL bResult;
775 LUID luid;
776 HANDLE hToken;
777 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200778
779 if (!OpenProcessToken(GetCurrentProcess(),
780 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
781 return FALSE;
782
783 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
784 {
785 CloseHandle(hToken);
786 return FALSE;
787 }
788
Bram Moolenaar45500912014-07-09 20:51:07 +0200789 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200790 tokenPrivileges.Privileges[0].Luid = luid;
791 tokenPrivileges.Privileges[0].Attributes = bEnable ?
792 SE_PRIVILEGE_ENABLED : 0;
793
794 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
795 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
796
797 CloseHandle(hToken);
798
799 return bResult && GetLastError() == ERROR_SUCCESS;
800}
801#endif
802
Bram Moolenaar071d4272004-06-13 20:20:40 +0000803/*
804 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
805 * VER_PLATFORM_WIN32_WINDOWS (Win95).
806 */
807 void
808PlatformId(void)
809{
810 static int done = FALSE;
811
812 if (!done)
813 {
814 OSVERSIONINFO ovi;
815
816 ovi.dwOSVersionInfoSize = sizeof(ovi);
817 GetVersionEx(&ovi);
818
819 g_PlatformId = ovi.dwPlatformId;
820
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100821 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
822 || ovi.dwMajorVersion > 6)
823 win8_or_later = TRUE;
824
Bram Moolenaar071d4272004-06-13 20:20:40 +0000825#ifdef HAVE_ACL
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200826 /* Enable privilege for getting or setting SACLs. */
827 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000828#endif
829 done = TRUE;
830 }
831}
832
Bram Moolenaar4f974752019-02-17 17:44:42 +0100833#ifndef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000834
835#define SHIFT (SHIFT_PRESSED)
836#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
837#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
838#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
839
840
841/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
842 * We map function keys to their ANSI terminal equivalents, as produced
843 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
844 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
845 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
846 * combinations of function/arrow/etc keys.
847 */
848
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000849static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000850{
851 WORD wVirtKey;
852 BOOL fAnsiKey;
853 int chAlone;
854 int chShift;
855 int chCtrl;
856 int chAlt;
857} VirtKeyMap[] =
858{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200859// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000860 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
861
862 { VK_F1, TRUE, ';', 'T', '^', 'h', },
863 { VK_F2, TRUE, '<', 'U', '_', 'i', },
864 { VK_F3, TRUE, '=', 'V', '`', 'j', },
865 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
866 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
867 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
868 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
869 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
870 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
871 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200872 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
873 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000874
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200875 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
876 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
877 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
878 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
879 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
880 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
881 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
882 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
883 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
884 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000885
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200886 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000887
888#if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200889 // Most people don't have F13-F20, but what the hell...
890 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
891 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
892 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
893 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
894 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
895 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
896 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
897 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000898#endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200899 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
900 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
901 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
902 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000903
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200904 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
905 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
906 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
907 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
908 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
909 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
910 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
911 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
912 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
913 // Sorry, out of number space! <negri>
914 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
915
Bram Moolenaar071d4272004-06-13 20:20:40 +0000916};
917
918
919#ifdef _MSC_VER
920// The ToAscii bug destroys several registers. Need to turn off optimization
921// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000922# pragma warning(push)
923# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000924# pragma optimize("", off)
925#endif
926
927#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200928# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000929#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200930# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000931#endif
932
933/* The return code indicates key code size. */
934 static int
935#ifdef __BORLANDC__
936 __stdcall
937#endif
938win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000939 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000940{
941 UINT uMods = pker->dwControlKeyState;
942 static int s_iIsDead = 0;
943 static WORD awAnsiCode[2];
944 static BYTE abKeystate[256];
945
946
947 if (s_iIsDead == 2)
948 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200949 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000950 s_iIsDead = 0;
951 return 1;
952 }
953
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200954 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000955 return 1;
956
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200957 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000958
Bram Moolenaar071d4272004-06-13 20:20:40 +0000959 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200960 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000961
962 if (uMods & SHIFT_PRESSED)
963 abKeystate[VK_SHIFT] = 0x80;
964 if (uMods & CAPSLOCK_ON)
965 abKeystate[VK_CAPITAL] = 1;
966
967 if ((uMods & ALT_GR) == ALT_GR)
968 {
969 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
970 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
971 }
972
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200973 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
974 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000975
976 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200977 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000978
979 return s_iIsDead;
980}
981
982#ifdef _MSC_VER
983/* MUST switch optimization on again here, otherwise a call to
984 * decode_key_event() may crash (e.g. when hitting caps-lock) */
985# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000986# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000987
988# if (_MSC_VER < 1100)
989/* MUST turn off global optimisation for this next function, or
990 * pressing ctrl-minus in insert mode crashes Vim when built with
991 * VC4.1. -- negri. */
992# pragma optimize("g", off)
993# endif
994#endif
995
996static BOOL g_fJustGotFocus = FALSE;
997
998/*
999 * Decode a KEY_EVENT into one or two keystrokes
1000 */
1001 static BOOL
1002decode_key_event(
1003 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001004 WCHAR *pch,
1005 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001006 int *pmodifiers,
1007 BOOL fDoPost)
1008{
1009 int i;
1010 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1011
1012 *pch = *pch2 = NUL;
1013 g_fJustGotFocus = FALSE;
1014
1015 /* ignore key up events */
1016 if (!pker->bKeyDown)
1017 return FALSE;
1018
1019 /* ignore some keystrokes */
1020 switch (pker->wVirtualKeyCode)
1021 {
1022 /* modifiers */
1023 case VK_SHIFT:
1024 case VK_CONTROL:
1025 case VK_MENU: /* Alt key */
1026 return FALSE;
1027
1028 default:
1029 break;
1030 }
1031
1032 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001033 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001034 {
1035 /* Ctrl-6 is Ctrl-^ */
1036 if (pker->wVirtualKeyCode == '6')
1037 {
1038 *pch = Ctrl_HAT;
1039 return TRUE;
1040 }
1041 /* Ctrl-2 is Ctrl-@ */
1042 else if (pker->wVirtualKeyCode == '2')
1043 {
1044 *pch = NUL;
1045 return TRUE;
1046 }
1047 /* Ctrl-- is Ctrl-_ */
1048 else if (pker->wVirtualKeyCode == 0xBD)
1049 {
1050 *pch = Ctrl__;
1051 return TRUE;
1052 }
1053 }
1054
1055 /* Shift-TAB */
1056 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1057 {
1058 *pch = K_NUL;
1059 *pch2 = '\017';
1060 return TRUE;
1061 }
1062
1063 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1064 {
1065 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1066 {
1067 if (nModifs == 0)
1068 *pch = VirtKeyMap[i].chAlone;
1069 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1070 *pch = VirtKeyMap[i].chShift;
1071 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1072 *pch = VirtKeyMap[i].chCtrl;
1073 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1074 *pch = VirtKeyMap[i].chAlt;
1075
1076 if (*pch != 0)
1077 {
1078 if (VirtKeyMap[i].fAnsiKey)
1079 {
1080 *pch2 = *pch;
1081 *pch = K_NUL;
1082 }
1083
1084 return TRUE;
1085 }
1086 }
1087 }
1088
1089 i = win32_kbd_patch_key(pker);
1090
1091 if (i < 0)
1092 *pch = NUL;
1093 else
1094 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001095 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001096
1097 if (pmodifiers != NULL)
1098 {
1099 /* Pass on the ALT key as a modifier, but only when not combined
1100 * with CTRL (which is ALTGR). */
1101 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1102 *pmodifiers |= MOD_MASK_ALT;
1103
1104 /* Pass on SHIFT only for special keys, because we don't know when
1105 * it's already included with the character. */
1106 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1107 *pmodifiers |= MOD_MASK_SHIFT;
1108
1109 /* Pass on CTRL only for non-special keys, because we don't know
1110 * when it's already included with the character. And not when
1111 * combined with ALT (which is ALTGR). */
1112 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1113 && *pch >= 0x20 && *pch < 0x80)
1114 *pmodifiers |= MOD_MASK_CTRL;
1115 }
1116 }
1117
1118 return (*pch != NUL);
1119}
1120
1121#ifdef _MSC_VER
1122# pragma optimize("", on)
1123#endif
1124
Bram Moolenaar4f974752019-02-17 17:44:42 +01001125#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001126
1127
1128#ifdef FEAT_MOUSE
1129
1130/*
1131 * For the GUI the mouse handling is in gui_w32.c.
1132 */
Bram Moolenaar4f974752019-02-17 17:44:42 +01001133# ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001134 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001135mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001136{
1137}
1138# else
1139static int g_fMouseAvail = FALSE; /* mouse present */
1140static int g_fMouseActive = FALSE; /* mouse enabled */
1141static int g_nMouseClick = -1; /* mouse status */
1142static int g_xMouse; /* mouse x coordinate */
1143static int g_yMouse; /* mouse y coordinate */
1144
1145/*
1146 * Enable or disable mouse input
1147 */
1148 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001149mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001150{
1151 DWORD cmodein;
1152
1153 if (!g_fMouseAvail)
1154 return;
1155
1156 g_fMouseActive = on;
1157 GetConsoleMode(g_hConIn, &cmodein);
1158
1159 if (g_fMouseActive)
1160 cmodein |= ENABLE_MOUSE_INPUT;
1161 else
1162 cmodein &= ~ENABLE_MOUSE_INPUT;
1163
1164 SetConsoleMode(g_hConIn, cmodein);
1165}
1166
Bram Moolenaar157d8132018-03-06 17:09:20 +01001167
1168#if defined(FEAT_BEVAL_TERM) || defined(PROTO)
1169/*
1170 * Called when 'balloonevalterm' changed.
1171 */
1172 void
1173mch_bevalterm_changed(void)
1174{
1175 mch_setmouse(g_fMouseActive);
1176}
1177#endif
1178
Bram Moolenaar071d4272004-06-13 20:20:40 +00001179/*
1180 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1181 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1182 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1183 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1184 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1185 * and we return the mouse position in g_xMouse and g_yMouse.
1186 *
1187 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1188 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1189 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1190 *
1191 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1192 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1193 *
1194 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1195 * moves, even if it stays within the same character cell. We ignore
1196 * all MOUSE_MOVED messages if the position hasn't really changed, and
1197 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1198 * we're only interested in MOUSE_DRAG).
1199 *
1200 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1201 * 2-button mouses by pressing the left & right buttons simultaneously.
1202 * In practice, it's almost impossible to click both at the same time,
1203 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1204 * in such cases, if the user is clicking quickly.
1205 */
1206 static BOOL
1207decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001208 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001209{
1210 static int s_nOldButton = -1;
1211 static int s_nOldMouseClick = -1;
1212 static int s_xOldMouse = -1;
1213 static int s_yOldMouse = -1;
1214 static linenr_T s_old_topline = 0;
1215#ifdef FEAT_DIFF
1216 static int s_old_topfill = 0;
1217#endif
1218 static int s_cClicks = 1;
1219 static BOOL s_fReleased = TRUE;
1220 static DWORD s_dwLastClickTime = 0;
1221 static BOOL s_fNextIsMiddle = FALSE;
1222
1223 static DWORD cButtons = 0; /* number of buttons supported */
1224
1225 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1226 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1227 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1228 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1229
1230 int nButton;
1231
1232 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1233 cButtons = 2;
1234
1235 if (!g_fMouseAvail || !g_fMouseActive)
1236 {
1237 g_nMouseClick = -1;
1238 return FALSE;
1239 }
1240
1241 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1242 if (g_fJustGotFocus)
1243 {
1244 g_fJustGotFocus = FALSE;
1245 return FALSE;
1246 }
1247
1248 /* unprocessed mouse click? */
1249 if (g_nMouseClick != -1)
1250 return TRUE;
1251
1252 nButton = -1;
1253 g_xMouse = pmer->dwMousePosition.X;
1254 g_yMouse = pmer->dwMousePosition.Y;
1255
1256 if (pmer->dwEventFlags == MOUSE_MOVED)
1257 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001258 /* Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
Bram Moolenaar071d4272004-06-13 20:20:40 +00001259 * events even when the mouse moves only within a char cell.) */
1260 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1261 return FALSE;
1262 }
1263
1264 /* If no buttons are pressed... */
1265 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1266 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001267 nButton = MOUSE_RELEASE;
1268
Bram Moolenaar071d4272004-06-13 20:20:40 +00001269 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1270 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001271 {
1272#ifdef FEAT_BEVAL_TERM
1273 /* do return mouse move events when we want them */
1274 if (p_bevalterm)
1275 nButton = MOUSE_DRAG;
1276 else
1277#endif
1278 return FALSE;
1279 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001280
Bram Moolenaar071d4272004-06-13 20:20:40 +00001281 s_fReleased = TRUE;
1282 }
1283 else /* one or more buttons pressed */
1284 {
1285 /* on a 2-button mouse, hold down left and right buttons
1286 * simultaneously to get MIDDLE. */
1287
1288 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1289 {
1290 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1291
1292 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001293 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001294 if (dwLR == LEFT || dwLR == RIGHT)
1295 {
1296 for (;;)
1297 {
1298 /* wait a short time for next input event */
1299 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1300 != WAIT_OBJECT_0)
1301 break;
1302 else
1303 {
1304 DWORD cRecords = 0;
1305 INPUT_RECORD ir;
1306 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1307
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001308 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001309
1310 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1311 || !(pmer2->dwButtonState & LEFT_RIGHT))
1312 break;
1313 else
1314 {
1315 if (pmer2->dwEventFlags != MOUSE_MOVED)
1316 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001317 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001318
1319 return decode_mouse_event(pmer2);
1320 }
1321 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1322 s_yOldMouse == pmer2->dwMousePosition.Y)
1323 {
1324 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001325 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001326
1327 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001328 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001329
1330 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1331 break;
1332 }
1333 else
1334 break;
1335 }
1336 }
1337 }
1338 }
1339 }
1340
1341 if (s_fNextIsMiddle)
1342 {
1343 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1344 ? MOUSE_DRAG : MOUSE_MIDDLE;
1345 s_fNextIsMiddle = FALSE;
1346 }
1347 else if (cButtons == 2 &&
1348 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1349 {
1350 nButton = MOUSE_MIDDLE;
1351
1352 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1353 {
1354 s_fNextIsMiddle = TRUE;
1355 nButton = MOUSE_RELEASE;
1356 }
1357 }
1358 else if ((pmer->dwButtonState & LEFT) == LEFT)
1359 nButton = MOUSE_LEFT;
1360 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1361 nButton = MOUSE_MIDDLE;
1362 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1363 nButton = MOUSE_RIGHT;
1364
1365 if (! s_fReleased && ! s_fNextIsMiddle
1366 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1367 return FALSE;
1368
1369 s_fReleased = s_fNextIsMiddle;
1370 }
1371
1372 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1373 {
1374 /* button pressed or released, without mouse moving */
1375 if (nButton != -1 && nButton != MOUSE_RELEASE)
1376 {
1377 DWORD dwCurrentTime = GetTickCount();
1378
1379 if (s_xOldMouse != g_xMouse
1380 || s_yOldMouse != g_yMouse
1381 || s_nOldButton != nButton
1382 || s_old_topline != curwin->w_topline
1383#ifdef FEAT_DIFF
1384 || s_old_topfill != curwin->w_topfill
1385#endif
1386 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1387 {
1388 s_cClicks = 1;
1389 }
1390 else if (++s_cClicks > 4)
1391 {
1392 s_cClicks = 1;
1393 }
1394
1395 s_dwLastClickTime = dwCurrentTime;
1396 }
1397 }
1398 else if (pmer->dwEventFlags == MOUSE_MOVED)
1399 {
1400 if (nButton != -1 && nButton != MOUSE_RELEASE)
1401 nButton = MOUSE_DRAG;
1402
1403 s_cClicks = 1;
1404 }
1405
1406 if (nButton == -1)
1407 return FALSE;
1408
1409 if (nButton != MOUSE_RELEASE)
1410 s_nOldButton = nButton;
1411
1412 g_nMouseClick = nButton;
1413
1414 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1415 g_nMouseClick |= MOUSE_SHIFT;
1416 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1417 g_nMouseClick |= MOUSE_CTRL;
1418 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1419 g_nMouseClick |= MOUSE_ALT;
1420
1421 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1422 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1423
1424 /* only pass on interesting (i.e., different) mouse events */
1425 if (s_xOldMouse == g_xMouse
1426 && s_yOldMouse == g_yMouse
1427 && s_nOldMouseClick == g_nMouseClick)
1428 {
1429 g_nMouseClick = -1;
1430 return FALSE;
1431 }
1432
1433 s_xOldMouse = g_xMouse;
1434 s_yOldMouse = g_yMouse;
1435 s_old_topline = curwin->w_topline;
1436#ifdef FEAT_DIFF
1437 s_old_topfill = curwin->w_topfill;
1438#endif
1439 s_nOldMouseClick = g_nMouseClick;
1440
1441 return TRUE;
1442}
1443
Bram Moolenaar4f974752019-02-17 17:44:42 +01001444# endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001445#endif /* FEAT_MOUSE */
1446
1447
1448#ifdef MCH_CURSOR_SHAPE
1449/*
1450 * Set the shape of the cursor.
1451 * 'thickness' can be from 1 (thin) to 99 (block)
1452 */
1453 static void
1454mch_set_cursor_shape(int thickness)
1455{
1456 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1457 ConsoleCursorInfo.dwSize = thickness;
1458 ConsoleCursorInfo.bVisible = s_cursor_visible;
1459
1460 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1461 if (s_cursor_visible)
1462 SetConsoleCursorPosition(g_hConOut, g_coord);
1463}
1464
1465 void
1466mch_update_cursor(void)
1467{
1468 int idx;
1469 int thickness;
1470
1471 /*
1472 * How the cursor is drawn depends on the current mode.
1473 */
1474 idx = get_shape_idx(FALSE);
1475
1476 if (shape_table[idx].shape == SHAPE_BLOCK)
1477 thickness = 99; /* 100 doesn't work on W95 */
1478 else
1479 thickness = shape_table[idx].percentage;
1480 mch_set_cursor_shape(thickness);
1481}
1482#endif
1483
Bram Moolenaar4f974752019-02-17 17:44:42 +01001484#ifndef FEAT_GUI_MSWIN /* this isn't used for the GUI */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001485/*
1486 * Handle FOCUS_EVENT.
1487 */
1488 static void
1489handle_focus_event(INPUT_RECORD ir)
1490{
1491 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1492 ui_focus_change((int)g_fJustGotFocus);
1493}
1494
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001495static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1496
Bram Moolenaar071d4272004-06-13 20:20:40 +00001497/*
1498 * Wait until console input from keyboard or mouse is available,
1499 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001500 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001501 * Return TRUE if something is available FALSE if not.
1502 */
1503 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001504WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001505{
1506 DWORD dwNow = 0, dwEndTime = 0;
1507 INPUT_RECORD ir;
1508 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001509 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001510#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001511 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001512#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001513
1514 if (msec > 0)
1515 /* Wait until the specified time has elapsed. */
1516 dwEndTime = GetTickCount() + msec;
1517 else if (msec < 0)
1518 /* Wait forever. */
1519 dwEndTime = INFINITE;
1520
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001521 // We need to loop until the end of the time period, because
1522 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001523 for (;;)
1524 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001525 // Only process messages when waiting.
1526 if (msec != 0)
1527 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001528#ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001529 parse_queued_messages();
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001530#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001531#ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001532 mzvim_check_threads();
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001533#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001534#ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001535 serverProcessPendingMessages();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001536#endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001537 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001538
Bram Moolenaar071d4272004-06-13 20:20:40 +00001539 if (0
1540#ifdef FEAT_MOUSE
1541 || g_nMouseClick != -1
1542#endif
1543#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001544 || (!ignore_input && input_available())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001545#endif
1546 )
1547 return TRUE;
1548
1549 if (msec > 0)
1550 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001551 /* If the specified wait time has passed, return. Beware that
1552 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001553 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001554 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001555 break;
1556 }
1557 if (msec != 0)
1558 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001559 DWORD dwWaitTime = dwEndTime - dwNow;
1560
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001561#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001562 /* Check channel while waiting for input. */
Bram Moolenaar9186a272016-02-23 19:34:01 +01001563 if (dwWaitTime > 100)
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001564 {
Bram Moolenaar9186a272016-02-23 19:34:01 +01001565 dwWaitTime = 100;
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001566 /* If there is readahead then parse_queued_messages() timed out
1567 * and we should call it again soon. */
1568 if (channel_any_readahead())
1569 dwWaitTime = 10;
1570 }
Bram Moolenaar9186a272016-02-23 19:34:01 +01001571#endif
Bram Moolenaarc3719bd2017-11-18 22:13:31 +01001572#ifdef FEAT_BEVAL_GUI
Bram Moolenaar59716a22017-03-01 20:32:44 +01001573 if (p_beval && dwWaitTime > 100)
1574 /* The 'balloonexpr' may indirectly invoke a callback while
1575 * waiting for a character, need to check often. */
1576 dwWaitTime = 100;
1577#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001578#ifdef FEAT_MZSCHEME
1579 if (mzthreads_allowed() && p_mzq > 0
1580 && (msec < 0 || (long)dwWaitTime > p_mzq))
1581 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1582#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001583#ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001584 // When waiting very briefly don't trigger timers.
1585 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001586 {
1587 long due_time;
1588
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001589 // Trigger timers and then get the time in msec until the next
1590 // one is due. Wait up to that time.
1591 due_time = check_due_timer();
1592 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001593 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001594 // timer may have used feedkeys().
1595 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001596 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001597 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1598 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001599 }
1600#endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001601 if (
Bram Moolenaar071d4272004-06-13 20:20:40 +00001602#ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001603 // Wait for either an event on the console input or a
1604 // message in the client-server window.
1605 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1606 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607#else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001608 wait_for_single_object(g_hConIn, dwWaitTime)
1609 != WAIT_OBJECT_0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001610#endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001611 )
1612 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001613 }
1614
1615 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001616 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001617
1618#ifdef FEAT_MBYTE_IME
1619 if (State & CMDLINE && msg_row == Rows - 1)
1620 {
1621 CONSOLE_SCREEN_BUFFER_INFO csbi;
1622
1623 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1624 {
1625 if (csbi.dwCursorPosition.Y != msg_row)
1626 {
1627 /* The screen is now messed up, must redraw the
1628 * command line and later all the windows. */
1629 redraw_all_later(CLEAR);
1630 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1631 redrawcmd();
1632 }
1633 }
1634 }
1635#endif
1636
1637 if (cRecords > 0)
1638 {
1639 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1640 {
1641#ifdef FEAT_MBYTE_IME
1642 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1643 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001644 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001645 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1646 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001647 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001648 continue;
1649 }
1650#endif
1651 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1652 NULL, FALSE))
1653 return TRUE;
1654 }
1655
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001656 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001657
1658 if (ir.EventType == FOCUS_EVENT)
1659 handle_focus_event(ir);
1660 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001661 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001662 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1663
1664 // Only call shell_resized() when the size actually change to
1665 // avoid the screen is cleard.
1666 if (dwSize.X != Columns || dwSize.Y != Rows)
1667 {
1668 CONSOLE_SCREEN_BUFFER_INFO csbi;
1669 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
1670 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
1671 ResizeConBuf(g_hConOut, dwSize);
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001672 shell_resized();
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001673 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001674 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001675#ifdef FEAT_MOUSE
1676 else if (ir.EventType == MOUSE_EVENT
1677 && decode_mouse_event(&ir.Event.MouseEvent))
1678 return TRUE;
1679#endif
1680 }
1681 else if (msec == 0)
1682 break;
1683 }
1684
1685#ifdef FEAT_CLIENTSERVER
1686 /* Something might have been received while we were waiting. */
1687 if (input_available())
1688 return TRUE;
1689#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001690
Bram Moolenaar071d4272004-06-13 20:20:40 +00001691 return FALSE;
1692}
1693
1694#ifndef FEAT_GUI_MSWIN
1695/*
1696 * return non-zero if a character is available
1697 */
1698 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001699mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001700{
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001701 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001702}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001703
1704# if defined(FEAT_TERMINAL) || defined(PROTO)
1705/*
1706 * Check for any pending input or messages.
1707 */
1708 int
1709mch_check_messages(void)
1710{
1711 return WaitForChar(0L, TRUE);
1712}
1713# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001714#endif
1715
1716/*
1717 * Create the console input. Used when reading stdin doesn't work.
1718 */
1719 static void
1720create_conin(void)
1721{
1722 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1723 FILE_SHARE_READ|FILE_SHARE_WRITE,
1724 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001725 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001726 did_create_conin = TRUE;
1727}
1728
1729/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001730 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001731 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001732 static WCHAR
1733tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001734{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001735 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001736
1737 for (;;)
1738 {
1739 INPUT_RECORD ir;
1740 DWORD cRecords = 0;
1741
1742#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001743 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001744 if (input_available())
1745 return 0;
1746# ifdef FEAT_MOUSE
1747 if (g_nMouseClick != -1)
1748 return 0;
1749# endif
1750#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001751 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001752 {
1753 if (did_create_conin)
1754 read_error_exit();
1755 create_conin();
1756 continue;
1757 }
1758
1759 if (ir.EventType == KEY_EVENT)
1760 {
1761 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1762 pmodifiers, TRUE))
1763 return ch;
1764 }
1765 else if (ir.EventType == FOCUS_EVENT)
1766 handle_focus_event(ir);
1767 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1768 shell_resized();
1769#ifdef FEAT_MOUSE
1770 else if (ir.EventType == MOUSE_EVENT)
1771 {
1772 if (decode_mouse_event(&ir.Event.MouseEvent))
1773 return 0;
1774 }
1775#endif
1776 }
1777}
Bram Moolenaar4f974752019-02-17 17:44:42 +01001778#endif /* !FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001779
1780
1781/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001782 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001783 * Get one or more characters from the keyboard or the mouse.
1784 * If time == 0, do not wait for characters.
1785 * If time == n, wait a short time for characters.
1786 * If time == -1, wait forever for characters.
1787 * Returns the number of characters read into buf.
1788 */
1789 int
1790mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001791 char_u *buf UNUSED,
1792 int maxlen UNUSED,
1793 long time UNUSED,
1794 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001795{
Bram Moolenaar4f974752019-02-17 17:44:42 +01001796#ifndef FEAT_GUI_MSWIN /* this isn't used for the GUI */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001797
1798 int len;
1799 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001800#define TYPEAHEADLEN 20
1801 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1802 static int typeaheadlen = 0;
1803
1804 /* First use any typeahead that was kept because "buf" was too small. */
1805 if (typeaheadlen > 0)
1806 goto theend;
1807
Bram Moolenaar071d4272004-06-13 20:20:40 +00001808 if (time >= 0)
1809 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001810 if (!WaitForChar(time, FALSE)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001811 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001812 }
1813 else /* time == -1, wait forever */
1814 {
1815 mch_set_winsize_now(); /* Allow winsize changes from now on */
1816
Bram Moolenaar3918c952005-03-15 22:34:55 +00001817 /*
1818 * If there is no character available within 2 seconds (default)
1819 * write the autoscript file to disk. Or cause the CursorHold event
1820 * to be triggered.
1821 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001822 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001823 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001824 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001825 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001826 buf[0] = K_SPECIAL;
1827 buf[1] = KS_EXTRA;
1828 buf[2] = (int)KE_CURSORHOLD;
1829 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001830 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001831 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001832 }
1833 }
1834
1835 /*
1836 * Try to read as many characters as there are, until the buffer is full.
1837 */
1838
1839 /* we will get at least one key. Get more if they are available. */
1840 g_fCBrkPressed = FALSE;
1841
1842#ifdef MCH_WRITE_DUMP
1843 if (fdDump)
1844 fputc('[', fdDump);
1845#endif
1846
1847 /* Keep looping until there is something in the typeahead buffer and more
1848 * to get and still room in the buffer (up to two bytes for a char and
1849 * three bytes for a modifier). */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001850 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001851 && typeaheadlen + 5 <= TYPEAHEADLEN)
1852 {
1853 if (typebuf_changed(tb_change_cnt))
1854 {
1855 /* "buf" may be invalid now if a client put something in the
1856 * typeahead buffer and "buf" is in the typeahead buffer. */
1857 typeaheadlen = 0;
1858 break;
1859 }
1860#ifdef FEAT_MOUSE
1861 if (g_nMouseClick != -1)
1862 {
1863# ifdef MCH_WRITE_DUMP
1864 if (fdDump)
1865 fprintf(fdDump, "{%02x @ %d, %d}",
1866 g_nMouseClick, g_xMouse, g_yMouse);
1867# endif
1868 typeahead[typeaheadlen++] = ESC + 128;
1869 typeahead[typeaheadlen++] = 'M';
1870 typeahead[typeaheadlen++] = g_nMouseClick;
1871 typeahead[typeaheadlen++] = g_xMouse + '!';
1872 typeahead[typeaheadlen++] = g_yMouse + '!';
1873 g_nMouseClick = -1;
1874 }
1875 else
1876#endif
1877 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001878 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001879 int modifiers = 0;
1880
1881 c = tgetch(&modifiers, &ch2);
1882
1883 if (typebuf_changed(tb_change_cnt))
1884 {
1885 /* "buf" may be invalid now if a client put something in the
1886 * typeahead buffer and "buf" is in the typeahead buffer. */
1887 typeaheadlen = 0;
1888 break;
1889 }
1890
1891 if (c == Ctrl_C && ctrl_c_interrupts)
1892 {
1893#if defined(FEAT_CLIENTSERVER)
1894 trash_input_buf();
1895#endif
1896 got_int = TRUE;
1897 }
1898
1899#ifdef FEAT_MOUSE
1900 if (g_nMouseClick == -1)
1901#endif
1902 {
1903 int n = 1;
1904
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001905 if (ch2 == NUL)
1906 {
1907 int i;
1908 char_u *p;
1909 WCHAR ch[2];
1910
1911 ch[0] = c;
1912 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1913 {
1914 ch[1] = tgetch(&modifiers, &ch2);
1915 n++;
1916 }
1917 p = utf16_to_enc(ch, &n);
1918 if (p != NULL)
1919 {
1920 for (i = 0; i < n; i++)
1921 typeahead[typeaheadlen + i] = p[i];
1922 vim_free(p);
1923 }
1924 }
1925 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001926 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001927 if (ch2 != NUL)
1928 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001929 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001930 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001931 switch (ch2)
1932 {
1933 case (WCHAR)'\324': // SHIFT+Insert
1934 case (WCHAR)'\325': // CTRL+Insert
1935 case (WCHAR)'\327': // SHIFT+Delete
1936 case (WCHAR)'\330': // CTRL+Delete
1937 typeahead[typeaheadlen + n] = (char_u)ch2;
1938 n++;
1939 break;
1940
1941 default:
1942 typeahead[typeaheadlen + n] = 3;
1943 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1944 n += 2;
1945 break;
1946 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001947 }
1948 else
1949 {
1950 typeahead[typeaheadlen + n] = 3;
1951 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1952 n += 2;
1953 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001954 }
1955
Bram Moolenaar071d4272004-06-13 20:20:40 +00001956 /* Use the ALT key to set the 8th bit of the character
1957 * when it's one byte, the 8th bit isn't set yet and not
1958 * using a double-byte encoding (would become a lead
1959 * byte). */
1960 if ((modifiers & MOD_MASK_ALT)
1961 && n == 1
1962 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001963 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00001964 )
1965 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001966 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1967 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001968 modifiers &= ~MOD_MASK_ALT;
1969 }
1970
1971 if (modifiers != 0)
1972 {
1973 /* Prepend modifiers to the character. */
1974 mch_memmove(typeahead + typeaheadlen + 3,
1975 typeahead + typeaheadlen, n);
1976 typeahead[typeaheadlen++] = K_SPECIAL;
1977 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1978 typeahead[typeaheadlen++] = modifiers;
1979 }
1980
1981 typeaheadlen += n;
1982
1983#ifdef MCH_WRITE_DUMP
1984 if (fdDump)
1985 fputc(c, fdDump);
1986#endif
1987 }
1988 }
1989 }
1990
1991#ifdef MCH_WRITE_DUMP
1992 if (fdDump)
1993 {
1994 fputs("]\n", fdDump);
1995 fflush(fdDump);
1996 }
1997#endif
1998
Bram Moolenaar071d4272004-06-13 20:20:40 +00001999theend:
2000 /* Move typeahead to "buf", as much as fits. */
2001 len = 0;
2002 while (len < maxlen && typeaheadlen > 0)
2003 {
2004 buf[len++] = typeahead[0];
2005 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2006 }
2007 return len;
2008
Bram Moolenaar4f974752019-02-17 17:44:42 +01002009#else /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002010 return 0;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002011#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002012}
2013
Bram Moolenaar82881492012-11-20 16:53:39 +01002014#ifndef PROTO
2015# ifndef __MINGW32__
2016# include <shellapi.h> /* required for FindExecutable() */
2017# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002018#endif
2019
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002020/*
Bram Moolenaar43663192017-03-05 14:29:12 +01002021 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2022 * If "use_path" is FALSE: Return TRUE if "name" exists.
2023 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2024 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002025 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002026 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002027 static int
Bram Moolenaar43663192017-03-05 14:29:12 +01002028executable_exists(char *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002029{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002030 char *dum;
2031 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002032 char *curpath, *newpath;
2033 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002034
Bram Moolenaar43663192017-03-05 14:29:12 +01002035 if (!use_path)
2036 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002037 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01002038 {
2039 if (path != NULL)
Bram Moolenaar066029e2017-03-05 15:19:32 +01002040 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002041 if (mch_isFullName((char_u *)name))
Bram Moolenaar066029e2017-03-05 15:19:32 +01002042 *path = vim_strsave((char_u *)name);
2043 else
2044 *path = FullName_save((char_u *)name, FALSE);
2045 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002046 return TRUE;
2047 }
2048 return FALSE;
2049 }
2050
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002051 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002052 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002053 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002054 WCHAR fnamew[_MAX_PATH];
2055 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002056 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002057
2058 if (p != NULL)
2059 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002060 wcurpath = _wgetenv(L"PATH");
2061 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
2062 * sizeof(WCHAR));
2063 if (wnewpath == NULL)
2064 return FALSE;
2065 wcscpy(wnewpath, L".;");
2066 wcscat(wnewpath, wcurpath);
2067 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
2068 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002069 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002070 if (n == 0)
2071 return FALSE;
2072 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
2073 return FALSE;
2074 if (path != NULL)
2075 *path = utf16_to_enc(fnamew, NULL);
2076 return TRUE;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002077 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002078 }
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002079
2080 curpath = getenv("PATH");
2081 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
2082 if (newpath == NULL)
2083 return FALSE;
2084 STRCPY(newpath, ".;");
2085 STRCAT(newpath, curpath);
2086 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
2087 vim_free(newpath);
2088 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002089 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002090 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002091 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002092 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002093 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002094 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002095}
2096
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002097#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2098 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002099/*
2100 * Bad parameter handler.
2101 *
2102 * Certain MS CRT functions will intentionally crash when passed invalid
2103 * parameters to highlight possible security holes. Setting this function as
2104 * the bad parameter handler will prevent the crash.
2105 *
2106 * In debug builds the parameters contain CRT information that might help track
2107 * down the source of a problem, but in non-debug builds the arguments are all
2108 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2109 * worth allowing these to make debugging of issues easier.
2110 */
2111 static void
2112bad_param_handler(const wchar_t *expression,
2113 const wchar_t *function,
2114 const wchar_t *file,
2115 unsigned int line,
2116 uintptr_t pReserved)
2117{
2118}
2119
2120# define SET_INVALID_PARAM_HANDLER \
2121 ((void)_set_invalid_parameter_handler(bad_param_handler))
2122#else
2123# define SET_INVALID_PARAM_HANDLER
2124#endif
2125
Bram Moolenaar4f974752019-02-17 17:44:42 +01002126#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002127
2128/*
2129 * GUI version of mch_init().
2130 */
2131 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002132mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002133{
2134#ifndef __MINGW32__
2135 extern int _fmode;
2136#endif
2137
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002138 /* Silently handle invalid parameters to CRT functions */
2139 SET_INVALID_PARAM_HANDLER;
2140
Bram Moolenaar071d4272004-06-13 20:20:40 +00002141 /* Let critical errors result in a failure, not in a dialog box. Required
2142 * for the timestamp test to work on removed floppies. */
2143 SetErrorMode(SEM_FAILCRITICALERRORS);
2144
2145 _fmode = O_BINARY; /* we do our own CR-LF translation */
2146
2147 /* Specify window size. Is there a place to get the default from? */
2148 Rows = 25;
2149 Columns = 80;
2150
2151 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002152 {
2153 char_u vimrun_location[_MAX_PATH + 4];
2154
2155 /* First try in same directory as gvim.exe */
2156 STRCPY(vimrun_location, exe_name);
2157 STRCPY(gettail(vimrun_location), "vimrun.exe");
2158 if (mch_getperm(vimrun_location) >= 0)
2159 {
2160 if (*skiptowhite(vimrun_location) != NUL)
2161 {
2162 /* Enclose path with white space in double quotes. */
2163 mch_memmove(vimrun_location + 1, vimrun_location,
2164 STRLEN(vimrun_location) + 1);
2165 *vimrun_location = '"';
2166 STRCPY(gettail(vimrun_location), "vimrun\" ");
2167 }
2168 else
2169 STRCPY(gettail(vimrun_location), "vimrun ");
2170
2171 vimrun_path = (char *)vim_strsave(vimrun_location);
2172 s_dont_use_vimrun = FALSE;
2173 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002174 else if (executable_exists("vimrun.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002175 s_dont_use_vimrun = FALSE;
2176
2177 /* Don't give the warning for a missing vimrun.exe right now, but only
2178 * when vimrun was supposed to be used. Don't bother people that do
2179 * not need vimrun.exe. */
2180 if (s_dont_use_vimrun)
2181 need_vimrun_warning = TRUE;
2182 }
2183
2184 /*
2185 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2186 * Otherwise the default "findstr /n" is used.
2187 */
Bram Moolenaar43663192017-03-05 14:29:12 +01002188 if (!executable_exists("findstr.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002189 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2190
2191#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002192 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002193#endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002194
2195 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002196}
2197
2198
Bram Moolenaar4f974752019-02-17 17:44:42 +01002199#else /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002200
2201#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2202#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2203
2204/*
2205 * ClearConsoleBuffer()
2206 * Description:
2207 * Clears the entire contents of the console screen buffer, using the
2208 * specified attribute.
2209 * Returns:
2210 * TRUE on success
2211 */
2212 static BOOL
2213ClearConsoleBuffer(WORD wAttribute)
2214{
2215 CONSOLE_SCREEN_BUFFER_INFO csbi;
2216 COORD coord;
2217 DWORD NumCells, dummy;
2218
2219 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2220 return FALSE;
2221
2222 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2223 coord.X = 0;
2224 coord.Y = 0;
2225 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2226 coord, &dummy))
2227 {
2228 return FALSE;
2229 }
2230 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2231 coord, &dummy))
2232 {
2233 return FALSE;
2234 }
2235
2236 return TRUE;
2237}
2238
2239/*
2240 * FitConsoleWindow()
2241 * Description:
2242 * Checks if the console window will fit within given buffer dimensions.
2243 * Also, if requested, will shrink the window to fit.
2244 * Returns:
2245 * TRUE on success
2246 */
2247 static BOOL
2248FitConsoleWindow(
2249 COORD dwBufferSize,
2250 BOOL WantAdjust)
2251{
2252 CONSOLE_SCREEN_BUFFER_INFO csbi;
2253 COORD dwWindowSize;
2254 BOOL NeedAdjust = FALSE;
2255
2256 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2257 {
2258 /*
2259 * A buffer resize will fail if the current console window does
2260 * not lie completely within that buffer. To avoid this, we might
2261 * have to move and possibly shrink the window.
2262 */
2263 if (csbi.srWindow.Right >= dwBufferSize.X)
2264 {
2265 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2266 if (dwWindowSize.X > dwBufferSize.X)
2267 dwWindowSize.X = dwBufferSize.X;
2268 csbi.srWindow.Right = dwBufferSize.X - 1;
2269 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2270 NeedAdjust = TRUE;
2271 }
2272 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2273 {
2274 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2275 if (dwWindowSize.Y > dwBufferSize.Y)
2276 dwWindowSize.Y = dwBufferSize.Y;
2277 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2278 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2279 NeedAdjust = TRUE;
2280 }
2281 if (NeedAdjust && WantAdjust)
2282 {
2283 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2284 return FALSE;
2285 }
2286 return TRUE;
2287 }
2288
2289 return FALSE;
2290}
2291
2292typedef struct ConsoleBufferStruct
2293{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002294 BOOL IsValid;
2295 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002296 PCHAR_INFO Buffer;
2297 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002298 PSMALL_RECT Regions;
2299 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002300} ConsoleBuffer;
2301
2302/*
2303 * SaveConsoleBuffer()
2304 * Description:
2305 * Saves important information about the console buffer, including the
2306 * actual buffer contents. The saved information is suitable for later
2307 * restoration by RestoreConsoleBuffer().
2308 * Returns:
2309 * TRUE if all information was saved; FALSE otherwise
2310 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2311 */
2312 static BOOL
2313SaveConsoleBuffer(
2314 ConsoleBuffer *cb)
2315{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002316 DWORD NumCells;
2317 COORD BufferCoord;
2318 SMALL_RECT ReadRegion;
2319 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002320 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002321
Bram Moolenaar071d4272004-06-13 20:20:40 +00002322 if (cb == NULL)
2323 return FALSE;
2324
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002325 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002326 {
2327 cb->IsValid = FALSE;
2328 return FALSE;
2329 }
2330 cb->IsValid = TRUE;
2331
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002332 /*
2333 * Allocate a buffer large enough to hold the entire console screen
2334 * buffer. If this ConsoleBuffer structure has already been initialized
2335 * with a buffer of the correct size, then just use that one.
2336 */
2337 if (!cb->IsValid || cb->Buffer == NULL ||
2338 cb->BufferSize.X != cb->Info.dwSize.X ||
2339 cb->BufferSize.Y != cb->Info.dwSize.Y)
2340 {
2341 cb->BufferSize.X = cb->Info.dwSize.X;
2342 cb->BufferSize.Y = cb->Info.dwSize.Y;
2343 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2344 vim_free(cb->Buffer);
2345 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2346 if (cb->Buffer == NULL)
2347 return FALSE;
2348 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002349
2350 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002351 * We will now copy the console screen buffer into our buffer.
2352 * ReadConsoleOutput() seems to be limited as far as how much you
2353 * can read at a time. Empirically, this number seems to be about
2354 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2355 * in chunks until it is all copied. The chunks will all have the
2356 * same horizontal characteristics, so initialize them now. The
2357 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002358 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002359 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002360 ReadRegion.Left = 0;
2361 ReadRegion.Right = cb->Info.dwSize.X - 1;
2362 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002363
2364 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2365 if (cb->Regions == NULL || numregions != cb->NumRegions)
2366 {
2367 cb->NumRegions = numregions;
2368 vim_free(cb->Regions);
2369 cb->Regions = (PSMALL_RECT)alloc(cb->NumRegions * sizeof(SMALL_RECT));
2370 if (cb->Regions == NULL)
2371 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002372 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002373 return FALSE;
2374 }
2375 }
2376
2377 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002378 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002379 /*
2380 * Read into position (0, Y) in our buffer.
2381 */
2382 BufferCoord.Y = Y;
2383 /*
2384 * Read the region whose top left corner is (0, Y) and whose bottom
2385 * right corner is (width - 1, Y + Y_incr - 1). This should define
2386 * a region of size width by Y_incr. Don't worry if this region is
2387 * too large for the remaining buffer; it will be cropped.
2388 */
2389 ReadRegion.Top = Y;
2390 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002391 if (!ReadConsoleOutputW(g_hConOut, /* output handle */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002392 cb->Buffer, /* our buffer */
2393 cb->BufferSize, /* dimensions of our buffer */
2394 BufferCoord, /* offset in our buffer */
2395 &ReadRegion)) /* region to save */
2396 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002397 VIM_CLEAR(cb->Buffer);
2398 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002399 return FALSE;
2400 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002401 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002402 }
2403
2404 return TRUE;
2405}
2406
2407/*
2408 * RestoreConsoleBuffer()
2409 * Description:
2410 * Restores important information about the console buffer, including the
2411 * actual buffer contents, if desired. The information to restore is in
2412 * the same format used by SaveConsoleBuffer().
2413 * Returns:
2414 * TRUE on success
2415 */
2416 static BOOL
2417RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002418 ConsoleBuffer *cb,
2419 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002420{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002421 COORD BufferCoord;
2422 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002423 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002424
2425 if (cb == NULL || !cb->IsValid)
2426 return FALSE;
2427
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002428 /*
2429 * Before restoring the buffer contents, clear the current buffer, and
2430 * restore the cursor position and window information. Doing this now
2431 * prevents old buffer contents from "flashing" onto the screen.
2432 */
2433 if (RestoreScreen)
2434 ClearConsoleBuffer(cb->Info.wAttributes);
2435
2436 FitConsoleWindow(cb->Info.dwSize, TRUE);
2437 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2438 return FALSE;
2439 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2440 return FALSE;
2441
2442 if (!RestoreScreen)
2443 {
2444 /*
2445 * No need to restore the screen buffer contents, so we're done.
2446 */
2447 return TRUE;
2448 }
2449
2450 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2451 return FALSE;
2452 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2453 return FALSE;
2454
2455 /*
2456 * Restore the screen buffer contents.
2457 */
2458 if (cb->Buffer != NULL)
2459 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002460 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002461 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002462 BufferCoord.X = cb->Regions[i].Left;
2463 BufferCoord.Y = cb->Regions[i].Top;
2464 WriteRegion = cb->Regions[i];
2465 if (!WriteConsoleOutputW(g_hConOut, /* output handle */
2466 cb->Buffer, /* our buffer */
2467 cb->BufferSize, /* dimensions of our buffer */
2468 BufferCoord, /* offset in our buffer */
2469 &WriteRegion)) /* region to restore */
2470 {
2471 return FALSE;
2472 }
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002473 }
2474 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002475
2476 return TRUE;
2477}
2478
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002479#define FEAT_RESTORE_ORIG_SCREEN
2480#ifdef FEAT_RESTORE_ORIG_SCREEN
2481static ConsoleBuffer g_cbOrig = { 0 };
2482#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002483static ConsoleBuffer g_cbNonTermcap = { 0 };
2484static ConsoleBuffer g_cbTermcap = { 0 };
2485
2486#ifdef FEAT_TITLE
2487#ifdef __BORLANDC__
2488typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2489#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002490typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002491#endif
2492char g_szOrigTitle[256] = { 0 };
2493HWND g_hWnd = NULL; /* also used in os_mswin.c */
2494static HICON g_hOrigIconSmall = NULL;
2495static HICON g_hOrigIcon = NULL;
2496static HICON g_hVimIcon = NULL;
2497static BOOL g_fCanChangeIcon = FALSE;
2498
2499/* ICON* are not defined in VC++ 4.0 */
2500#ifndef ICON_SMALL
2501#define ICON_SMALL 0
2502#endif
2503#ifndef ICON_BIG
2504#define ICON_BIG 1
2505#endif
2506/*
2507 * GetConsoleIcon()
2508 * Description:
2509 * Attempts to retrieve the small icon and/or the big icon currently in
2510 * use by a given window.
2511 * Returns:
2512 * TRUE on success
2513 */
2514 static BOOL
2515GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002516 HWND hWnd,
2517 HICON *phIconSmall,
2518 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519{
2520 if (hWnd == NULL)
2521 return FALSE;
2522
2523 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002524 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2525 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002526 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002527 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2528 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002529 return TRUE;
2530}
2531
2532/*
2533 * SetConsoleIcon()
2534 * Description:
2535 * Attempts to change the small icon and/or the big icon currently in
2536 * use by a given window.
2537 * Returns:
2538 * TRUE on success
2539 */
2540 static BOOL
2541SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002542 HWND hWnd,
2543 HICON hIconSmall,
2544 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002545{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002546 if (hWnd == NULL)
2547 return FALSE;
2548
2549 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002550 SendMessage(hWnd, WM_SETICON,
2551 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002552 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002553 SendMessage(hWnd, WM_SETICON,
2554 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002555 return TRUE;
2556}
2557
2558/*
2559 * SaveConsoleTitleAndIcon()
2560 * Description:
2561 * Saves the current console window title in g_szOrigTitle, for later
2562 * restoration. Also, attempts to obtain a handle to the console window,
2563 * and use it to save the small and big icons currently in use by the
2564 * console window. This is not always possible on some versions of Windows;
2565 * nor is it possible when running Vim remotely using Telnet (since the
2566 * console window the user sees is owned by a remote process).
2567 */
2568 static void
2569SaveConsoleTitleAndIcon(void)
2570{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002571 /* Save the original title. */
2572 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2573 return;
2574
2575 /*
2576 * Obtain a handle to the console window using GetConsoleWindow() from
2577 * KERNEL32.DLL; we need to handle in order to change the window icon.
2578 * This function only exists on NT-based Windows, starting with Windows
2579 * 2000. On older operating systems, we can't change the window icon
2580 * anyway.
2581 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002582 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002583 if (g_hWnd == NULL)
2584 return;
2585
2586 /* Save the original console window icon. */
2587 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2588 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2589 return;
2590
2591 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002592 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002593 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002594 if (g_hVimIcon != NULL)
2595 g_fCanChangeIcon = TRUE;
2596}
2597#endif
2598
2599static int g_fWindInitCalled = FALSE;
2600static int g_fTermcapMode = FALSE;
2601static CONSOLE_CURSOR_INFO g_cci;
2602static DWORD g_cmodein = 0;
2603static DWORD g_cmodeout = 0;
2604
2605/*
2606 * non-GUI version of mch_init().
2607 */
2608 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002609mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002610{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002611#ifndef FEAT_RESTORE_ORIG_SCREEN
2612 CONSOLE_SCREEN_BUFFER_INFO csbi;
2613#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002614#ifndef __MINGW32__
2615 extern int _fmode;
2616#endif
2617
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002618 /* Silently handle invalid parameters to CRT functions */
2619 SET_INVALID_PARAM_HANDLER;
2620
Bram Moolenaar071d4272004-06-13 20:20:40 +00002621 /* Let critical errors result in a failure, not in a dialog box. Required
2622 * for the timestamp test to work on removed floppies. */
2623 SetErrorMode(SEM_FAILCRITICALERRORS);
2624
2625 _fmode = O_BINARY; /* we do our own CR-LF translation */
2626 out_flush();
2627
2628 /* Obtain handles for the standard Console I/O devices */
2629 if (read_cmd_fd == 0)
2630 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2631 else
2632 create_conin();
2633 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2634
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002635#ifdef FEAT_RESTORE_ORIG_SCREEN
2636 /* Save the initial console buffer for later restoration */
2637 SaveConsoleBuffer(&g_cbOrig);
2638 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2639#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002640 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002641 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2642 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2643#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002644 if (cterm_normal_fg_color == 0)
2645 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2646 if (cterm_normal_bg_color == 0)
2647 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2648
Bram Moolenaarbdace832019-03-02 10:13:42 +01002649 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002650 g_color_index_fg = g_attrDefault & 0xf;
2651 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2652
Bram Moolenaar071d4272004-06-13 20:20:40 +00002653 /* set termcap codes to current text attributes */
2654 update_tcap(g_attrCurrent);
2655
2656 GetConsoleCursorInfo(g_hConOut, &g_cci);
2657 GetConsoleMode(g_hConIn, &g_cmodein);
2658 GetConsoleMode(g_hConOut, &g_cmodeout);
2659
2660#ifdef FEAT_TITLE
2661 SaveConsoleTitleAndIcon();
2662 /*
2663 * Set both the small and big icons of the console window to Vim's icon.
2664 * Note that Vim presently only has one size of icon (32x32), but it
2665 * automatically gets scaled down to 16x16 when setting the small icon.
2666 */
2667 if (g_fCanChangeIcon)
2668 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2669#endif
2670
2671 ui_get_shellsize();
2672
2673#ifdef MCH_WRITE_DUMP
2674 fdDump = fopen("dump", "wt");
2675
2676 if (fdDump)
2677 {
2678 time_t t;
2679
2680 time(&t);
2681 fputs(ctime(&t), fdDump);
2682 fflush(fdDump);
2683 }
2684#endif
2685
2686 g_fWindInitCalled = TRUE;
2687
2688#ifdef FEAT_MOUSE
2689 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2690#endif
2691
2692#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002693 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002694#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002695
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002696 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002697 vtp_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002698}
2699
2700/*
2701 * non-GUI version of mch_exit().
2702 * Shut down and exit with status `r'
2703 * Careful: mch_exit() may be called before mch_init()!
2704 */
2705 void
2706mch_exit(int r)
2707{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002708 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002709
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002710 vtp_exit();
2711
Bram Moolenaar955f1982017-02-05 15:10:51 +01002712 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002713 if (g_fWindInitCalled)
2714 settmode(TMODE_COOK);
2715
2716 ml_close_all(TRUE); /* remove all memfiles */
2717
2718 if (g_fWindInitCalled)
2719 {
2720#ifdef FEAT_TITLE
Bram Moolenaar40385db2018-08-07 22:31:44 +02002721 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002722 /*
2723 * Restore both the small and big icons of the console window to
2724 * what they were at startup. Don't do this when the window is
2725 * closed, Vim would hang here.
2726 */
2727 if (g_fCanChangeIcon && !g_fForceExit)
2728 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2729#endif
2730
2731#ifdef MCH_WRITE_DUMP
2732 if (fdDump)
2733 {
2734 time_t t;
2735
2736 time(&t);
2737 fputs(ctime(&t), fdDump);
2738 fclose(fdDump);
2739 }
2740 fdDump = NULL;
2741#endif
2742 }
2743
2744 SetConsoleCursorInfo(g_hConOut, &g_cci);
2745 SetConsoleMode(g_hConIn, g_cmodein);
2746 SetConsoleMode(g_hConOut, g_cmodeout);
2747
2748#ifdef DYNAMIC_GETTEXT
2749 dyn_libintl_end();
2750#endif
2751
2752 exit(r);
2753}
Bram Moolenaar4f974752019-02-17 17:44:42 +01002754#endif /* !FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002755
Bram Moolenaar071d4272004-06-13 20:20:40 +00002756/*
2757 * Do we have an interactive window?
2758 */
2759 int
2760mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002761 int argc UNUSED,
2762 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002763{
2764 get_exe_name();
2765
Bram Moolenaar4f974752019-02-17 17:44:42 +01002766#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002767 return OK; /* GUI always has a tty */
2768#else
2769 if (isatty(1))
2770 return OK;
2771 return FAIL;
2772#endif
2773}
2774
2775
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002776/*
2777 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2778 * if it already exists. When "len" is > 0, also expand short to long
2779 * filenames.
2780 * Return FAIL if wide functions are not available, OK otherwise.
2781 * NOTE: much of this is identical to fname_case(), keep in sync!
2782 */
2783 static int
2784fname_casew(
2785 WCHAR *name,
2786 int len)
2787{
2788 WCHAR szTrueName[_MAX_PATH + 2];
2789 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2790 WCHAR *ptrue, *ptruePrev;
2791 WCHAR *porig, *porigPrev;
2792 int flen;
2793 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002794 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002795 int c;
2796 int slen;
2797
2798 flen = (int)wcslen(name);
2799 if (flen > _MAX_PATH)
2800 return OK;
2801
2802 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2803
2804 /* Build the new name in szTrueName[] one component at a time. */
2805 porig = name;
2806 ptrue = szTrueName;
2807
2808 if (iswalpha(porig[0]) && porig[1] == L':')
2809 {
2810 /* copy leading drive letter */
2811 *ptrue++ = *porig++;
2812 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002813 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002814 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002815
2816 while (*porig != NUL)
2817 {
2818 /* copy \ characters */
2819 while (*porig == psepc)
2820 *ptrue++ = *porig++;
2821
2822 ptruePrev = ptrue;
2823 porigPrev = porig;
2824 while (*porig != NUL && *porig != psepc)
2825 {
2826 *ptrue++ = *porig++;
2827 }
2828 *ptrue = NUL;
2829
2830 /* To avoid a slow failure append "\*" when searching a directory,
2831 * server or network share. */
2832 wcscpy(szTrueNameTemp, szTrueName);
2833 slen = (int)wcslen(szTrueNameTemp);
2834 if (*porig == psepc && slen + 2 < _MAX_PATH)
2835 wcscpy(szTrueNameTemp + slen, L"\\*");
2836
2837 /* Skip "", "." and "..". */
2838 if (ptrue > ptruePrev
2839 && (ptruePrev[0] != L'.'
2840 || (ptruePrev[1] != NUL
2841 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2842 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2843 != INVALID_HANDLE_VALUE)
2844 {
2845 c = *porig;
2846 *porig = NUL;
2847
2848 /* Only use the match when it's the same name (ignoring case) or
2849 * expansion is allowed and there is a match with the short name
2850 * and there is enough room. */
2851 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2852 || (len > 0
2853 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2854 && (int)(ptruePrev - szTrueName)
2855 + (int)wcslen(fb.cFileName) < len)))
2856 {
2857 wcscpy(ptruePrev, fb.cFileName);
2858
2859 /* Look for exact match and prefer it if found. Must be a
2860 * long name, otherwise there would be only one match. */
2861 while (FindNextFileW(hFind, &fb))
2862 {
2863 if (*fb.cAlternateFileName != NUL
2864 && (wcscoll(porigPrev, fb.cFileName) == 0
2865 || (len > 0
2866 && (_wcsicoll(porigPrev,
2867 fb.cAlternateFileName) == 0
2868 && (int)(ptruePrev - szTrueName)
2869 + (int)wcslen(fb.cFileName) < len))))
2870 {
2871 wcscpy(ptruePrev, fb.cFileName);
2872 break;
2873 }
2874 }
2875 }
2876 FindClose(hFind);
2877 *porig = c;
2878 ptrue = ptruePrev + wcslen(ptruePrev);
2879 }
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002880 }
2881
2882 wcscpy(name, szTrueName);
2883 return OK;
2884}
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002885
Bram Moolenaar071d4272004-06-13 20:20:40 +00002886/*
2887 * fname_case(): Set the case of the file name, if it already exists.
2888 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002889 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002890 */
2891 void
2892fname_case(
2893 char_u *name,
2894 int len)
2895{
2896 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002897 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002898 char *ptrue, *ptruePrev;
2899 char *porig, *porigPrev;
2900 int flen;
2901 WIN32_FIND_DATA fb;
2902 HANDLE hFind;
2903 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002904 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002905
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002906 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002907 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002908 return;
2909
2910 slash_adjust(name);
2911
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002912 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2913 {
2914 WCHAR *p = enc_to_utf16(name, NULL);
2915
2916 if (p != NULL)
2917 {
2918 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002919 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002920
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002921 wcsncpy(buf, p, _MAX_PATH);
2922 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002923 vim_free(p);
2924
2925 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2926 {
2927 q = utf16_to_enc(buf, NULL);
2928 if (q != NULL)
2929 {
2930 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2931 vim_free(q);
2932 return;
2933 }
2934 }
2935 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002936 return;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002937 }
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002938
2939 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2940 * So we should check this after calling wide function. */
2941 if (flen > _MAX_PATH)
2942 return;
2943
Bram Moolenaar071d4272004-06-13 20:20:40 +00002944 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002945 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002946 ptrue = szTrueName;
2947
2948 if (isalpha(porig[0]) && porig[1] == ':')
2949 {
2950 /* copy leading drive letter */
2951 *ptrue++ = *porig++;
2952 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002953 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002954 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002955
2956 while (*porig != NUL)
2957 {
2958 /* copy \ characters */
2959 while (*porig == psepc)
2960 *ptrue++ = *porig++;
2961
2962 ptruePrev = ptrue;
2963 porigPrev = porig;
2964 while (*porig != NUL && *porig != psepc)
2965 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002966 int l;
2967
2968 if (enc_dbcs)
2969 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002970 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002971 while (--l >= 0)
2972 *ptrue++ = *porig++;
2973 }
2974 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002975 *ptrue++ = *porig++;
2976 }
2977 *ptrue = NUL;
2978
Bram Moolenaar464c9252010-10-13 20:37:41 +02002979 /* To avoid a slow failure append "\*" when searching a directory,
2980 * server or network share. */
2981 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002982 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002983 if (*porig == psepc && slen + 2 < _MAX_PATH)
2984 STRCPY(szTrueNameTemp + slen, "\\*");
2985
Bram Moolenaar071d4272004-06-13 20:20:40 +00002986 /* Skip "", "." and "..". */
2987 if (ptrue > ptruePrev
2988 && (ptruePrev[0] != '.'
2989 || (ptruePrev[1] != NUL
2990 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002991 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002992 != INVALID_HANDLE_VALUE)
2993 {
2994 c = *porig;
2995 *porig = NUL;
2996
2997 /* Only use the match when it's the same name (ignoring case) or
2998 * expansion is allowed and there is a match with the short name
2999 * and there is enough room. */
3000 if (_stricoll(porigPrev, fb.cFileName) == 0
3001 || (len > 0
3002 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
3003 && (int)(ptruePrev - szTrueName)
3004 + (int)strlen(fb.cFileName) < len)))
3005 {
3006 STRCPY(ptruePrev, fb.cFileName);
3007
3008 /* Look for exact match and prefer it if found. Must be a
3009 * long name, otherwise there would be only one match. */
3010 while (FindNextFile(hFind, &fb))
3011 {
3012 if (*fb.cAlternateFileName != NUL
3013 && (strcoll(porigPrev, fb.cFileName) == 0
3014 || (len > 0
3015 && (_stricoll(porigPrev,
3016 fb.cAlternateFileName) == 0
3017 && (int)(ptruePrev - szTrueName)
3018 + (int)strlen(fb.cFileName) < len))))
3019 {
3020 STRCPY(ptruePrev, fb.cFileName);
3021 break;
3022 }
3023 }
3024 }
3025 FindClose(hFind);
3026 *porig = c;
3027 ptrue = ptruePrev + strlen(ptruePrev);
3028 }
3029 }
3030
3031 STRCPY(name, szTrueName);
3032}
3033
3034
3035/*
3036 * Insert user name in s[len].
3037 */
3038 int
3039mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003040 char_u *s,
3041 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003042{
Bram Moolenaar41a09032007-10-01 18:34:34 +00003043 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003044 DWORD cch = sizeof szUserName;
3045
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003046 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3047 {
3048 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
3049 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
3050
3051 if (GetUserNameW(wszUserName, &wcch))
3052 {
3053 char_u *p = utf16_to_enc(wszUserName, NULL);
3054
3055 if (p != NULL)
3056 {
3057 vim_strncpy(s, p, len - 1);
3058 vim_free(p);
3059 return OK;
3060 }
3061 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003062 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003063 if (GetUserName(szUserName, &cch))
3064 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003065 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003066 return OK;
3067 }
3068 s[0] = NUL;
3069 return FAIL;
3070}
3071
3072
3073/*
3074 * Insert host name in s[len].
3075 */
3076 void
3077mch_get_host_name(
3078 char_u *s,
3079 int len)
3080{
3081 DWORD cch = len;
3082
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003083 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3084 {
3085 WCHAR wszHostName[256 + 1];
3086 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
3087
3088 if (GetComputerNameW(wszHostName, &wcch))
3089 {
3090 char_u *p = utf16_to_enc(wszHostName, NULL);
3091
3092 if (p != NULL)
3093 {
3094 vim_strncpy(s, p, len - 1);
3095 vim_free(p);
3096 return;
3097 }
3098 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003099 }
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003100 if (!GetComputerName((LPSTR)s, &cch))
3101 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003102}
3103
3104
3105/*
3106 * return process ID
3107 */
3108 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003109mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003110{
3111 return (long)GetCurrentProcessId();
3112}
3113
3114
3115/*
3116 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3117 * Return OK for success, FAIL for failure.
3118 */
3119 int
3120mch_dirname(
3121 char_u *buf,
3122 int len)
3123{
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003124 char_u abuf[_MAX_PATH + 1];
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003125 DWORD lfnlen;
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003126
Bram Moolenaar071d4272004-06-13 20:20:40 +00003127 /*
3128 * Originally this was:
3129 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3130 * But the Win32s known bug list says that getcwd() doesn't work
3131 * so use the Win32 system call instead. <Negri>
3132 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003133 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3134 {
3135 WCHAR wbuf[_MAX_PATH + 1];
3136
3137 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3138 {
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003139 WCHAR wcbuf[_MAX_PATH + 1];
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003140 char_u *p = NULL;
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003141
3142 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003143 {
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003144 p = utf16_to_enc(wcbuf, NULL);
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003145 if (STRLEN(p) >= (size_t)len)
3146 {
3147 // long path name is too long, fall back to short one
3148 vim_free(p);
3149 p = NULL;
3150 }
3151 }
3152 if (p == NULL)
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003153 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003154
3155 if (p != NULL)
3156 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003157 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003158 vim_free(p);
3159 return OK;
3160 }
3161 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003162 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003163 }
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003164 if (GetCurrentDirectory(len, (LPSTR)buf) == 0)
3165 return FAIL;
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003166 lfnlen = GetLongPathNameA((LPCSTR)buf, (LPSTR)abuf, _MAX_PATH);
3167 if (lfnlen == 0 || lfnlen >= (DWORD)len)
3168 // Failed to get long path name or it's too long: fall back to the
3169 // short path name.
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003170 return OK;
3171
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003172 STRCPY(buf, abuf);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003173 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003174}
3175
3176/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003177 * Get file permissions for "name".
3178 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003179 */
3180 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003181mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003182{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003183 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003184 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003185
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003186 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003187 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003188}
3189
3190
3191/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003192 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003193 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003194 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003195 */
3196 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003197mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003198{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003199 long n = -1;
3200
Bram Moolenaar071d4272004-06-13 20:20:40 +00003201 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3202 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003203 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003204
3205 if (p != NULL)
3206 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003207 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003208 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003209 if (n == -1)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003210 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003211 }
3212 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003213 if (n == -1)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003214 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003215 if (n == -1)
3216 return FAIL;
3217
3218 win32_set_archive(name);
3219
3220 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003221}
3222
3223/*
3224 * Set hidden flag for "name".
3225 */
3226 void
3227mch_hide(char_u *name)
3228{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003229 int attrs = win32_getattrs(name);
3230 if (attrs == -1)
3231 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003232
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003233 attrs |= FILE_ATTRIBUTE_HIDDEN;
3234 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003235}
3236
3237/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003238 * Return TRUE if file "name" exists and is hidden.
3239 */
3240 int
3241mch_ishidden(char_u *name)
3242{
3243 int f = win32_getattrs(name);
3244
3245 if (f == -1)
3246 return FALSE; /* file does not exist at all */
3247
3248 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3249}
3250
3251/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003252 * return TRUE if "name" is a directory
3253 * return FALSE if "name" is not a directory or upon error
3254 */
3255 int
3256mch_isdir(char_u *name)
3257{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003258 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003259
3260 if (f == -1)
3261 return FALSE; /* file does not exist at all */
3262
3263 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3264}
3265
3266/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003267 * return TRUE if "name" is a directory, NOT a symlink to a directory
3268 * return FALSE if "name" is not a directory
3269 * return FALSE for error
3270 */
3271 int
3272mch_isrealdir(char_u *name)
3273{
3274 return mch_isdir(name) && !mch_is_symbolic_link(name);
3275}
3276
3277/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003278 * Create directory "name".
3279 * Return 0 on success, -1 on error.
3280 */
3281 int
3282mch_mkdir(char_u *name)
3283{
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003284 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3285 {
3286 WCHAR *p;
3287 int retval;
3288
3289 p = enc_to_utf16(name, NULL);
3290 if (p == NULL)
3291 return -1;
3292 retval = _wmkdir(p);
3293 vim_free(p);
3294 return retval;
3295 }
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003296 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003297}
3298
3299/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003300 * Delete directory "name".
3301 * Return 0 on success, -1 on error.
3302 */
3303 int
3304mch_rmdir(char_u *name)
3305{
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003306 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3307 {
3308 WCHAR *p;
3309 int retval;
3310
3311 p = enc_to_utf16(name, NULL);
3312 if (p == NULL)
3313 return -1;
3314 retval = _wrmdir(p);
3315 vim_free(p);
3316 return retval;
3317 }
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003318 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003319}
3320
3321/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003322 * Return TRUE if file "fname" has more than one link.
3323 */
3324 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003325mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003326{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003327 BY_HANDLE_FILE_INFORMATION info;
3328
3329 return win32_fileinfo(fname, &info) == FILEINFO_OK
3330 && info.nNumberOfLinks > 1;
3331}
3332
3333/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003334 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003335 */
3336 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003337mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003338{
3339 HANDLE hFind;
3340 int res = FALSE;
3341 WIN32_FIND_DATAA findDataA;
3342 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003343 WCHAR *wn = NULL;
3344 WIN32_FIND_DATAW findDataW;
3345
3346 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003347 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003348 if (wn != NULL)
3349 {
3350 hFind = FindFirstFileW(wn, &findDataW);
3351 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003352 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003353 {
3354 fileFlags = findDataW.dwFileAttributes;
3355 reparseTag = findDataW.dwReserved0;
3356 }
3357 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003358 else
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003359 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003360 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003361 if (hFind != INVALID_HANDLE_VALUE)
3362 {
3363 fileFlags = findDataA.dwFileAttributes;
3364 reparseTag = findDataA.dwReserved0;
3365 }
3366 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003367
3368 if (hFind != INVALID_HANDLE_VALUE)
3369 FindClose(hFind);
3370
3371 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003372 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3373 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003374 res = TRUE;
3375
3376 return res;
3377}
3378
3379/*
3380 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3381 * link.
3382 */
3383 int
3384mch_is_linked(char_u *fname)
3385{
3386 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3387 return TRUE;
3388 return FALSE;
3389}
3390
3391/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003392 * Get the by-handle-file-information for "fname".
3393 * Returns FILEINFO_OK when OK.
3394 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3395 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3396 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3397 */
3398 int
3399win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3400{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003401 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003402 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003403 WCHAR *wn = NULL;
3404
3405 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003406 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003407 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003408 if (wn == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003409 return FILEINFO_ENC_FAIL;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003410 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003411 if (wn != NULL)
3412 {
3413 hFile = CreateFileW(wn, /* file name */
3414 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003415 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003416 NULL, /* security descriptor */
3417 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003418 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003419 NULL); /* handle to template file */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003420 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003421 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003422 else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003423 hFile = CreateFile((LPCSTR)fname, /* file name */
3424 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003425 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003426 NULL, /* security descriptor */
3427 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003428 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003429 NULL); /* handle to template file */
3430
3431 if (hFile != INVALID_HANDLE_VALUE)
3432 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003433 if (GetFileInformationByHandle(hFile, info) != 0)
3434 res = FILEINFO_OK;
3435 else
3436 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003437 CloseHandle(hFile);
3438 }
3439
Bram Moolenaar03f48552006-02-28 23:52:23 +00003440 return res;
3441}
3442
3443/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003444 * get file attributes for `name'
3445 * -1 : error
3446 * else FILE_ATTRIBUTE_* defined in winnt.h
3447 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003448 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003449win32_getattrs(char_u *name)
3450{
3451 int attr;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003452 WCHAR *p = NULL;
3453
3454 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3455 p = enc_to_utf16(name, NULL);
3456
3457 if (p != NULL)
3458 {
3459 attr = GetFileAttributesW(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003460 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003461 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003462 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003463 attr = GetFileAttributes((char *)name);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003464
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003465 return attr;
3466}
3467
3468/*
3469 * set file attributes for `name' to `attrs'
3470 *
3471 * return -1 for failure, 0 otherwise
3472 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003473 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003474win32_setattrs(char_u *name, int attrs)
3475{
3476 int res;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003477 WCHAR *p = NULL;
3478
3479 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3480 p = enc_to_utf16(name, NULL);
3481
3482 if (p != NULL)
3483 {
3484 res = SetFileAttributesW(p, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003485 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003486 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003487 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003488 res = SetFileAttributes((char *)name, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003489
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003490 return res ? 0 : -1;
3491}
3492
3493/*
3494 * Set archive flag for "name".
3495 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003496 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003497win32_set_archive(char_u *name)
3498{
3499 int attrs = win32_getattrs(name);
3500 if (attrs == -1)
3501 return -1;
3502
3503 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3504 return win32_setattrs(name, attrs);
3505}
3506
3507/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003508 * Return TRUE if file or directory "name" is writable (not readonly).
3509 * Strange semantics of Win32: a readonly directory is writable, but you can't
3510 * delete a file. Let's say this means it is writable.
3511 */
3512 int
3513mch_writable(char_u *name)
3514{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003515 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003516
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003517 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3518 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003519}
3520
Bram Moolenaar071d4272004-06-13 20:20:40 +00003521/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003522 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003523 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003524 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3525 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003526 */
3527 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003528mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003529{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003530 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003531 int len = (int)STRLEN(name);
Bram Moolenaar82956662018-10-06 15:18:45 +02003532 char_u *p, *saved;
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003533
3534 if (len >= _MAX_PATH) /* safety check */
3535 return FALSE;
3536
Bram Moolenaar82956662018-10-06 15:18:45 +02003537 /* Ty using the name directly when a Unix-shell like 'shell'. */
3538 if (strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaar43663192017-03-05 14:29:12 +01003539 if (executable_exists((char *)name, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003540 return TRUE;
3541
3542 /*
3543 * Loop over all extensions in $PATHEXT.
3544 */
Bram Moolenaar82956662018-10-06 15:18:45 +02003545 p = mch_getenv("PATHEXT");
3546 if (p == NULL)
3547 p = (char_u *)".com;.exe;.bat;.cmd";
3548 saved = vim_strsave(p);
3549 if (saved == NULL)
3550 return FALSE;
3551 p = saved;
3552 while (*p)
3553 {
3554 char_u *tmp = vim_strchr(p, ';');
3555
3556 if (tmp != NULL)
3557 *tmp = NUL;
3558 if (_stricoll((char *)name + len - STRLEN(p), (char *)p) == 0
3559 && executable_exists((char *)name, path, use_path))
3560 {
3561 vim_free(saved);
3562 return TRUE;
3563 }
3564 if (tmp == NULL)
3565 break;
3566 p = tmp + 1;
3567 }
3568 vim_free(saved);
3569
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003570 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003571 p = mch_getenv("PATHEXT");
3572 if (p == NULL)
3573 p = (char_u *)".com;.exe;.bat;.cmd";
3574 while (*p)
3575 {
3576 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3577 {
3578 /* A single "." means no extension is added. */
3579 buf[len] = NUL;
3580 ++p;
3581 if (*p)
3582 ++p;
3583 }
3584 else
3585 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaar43663192017-03-05 14:29:12 +01003586 if (executable_exists((char *)buf, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003587 return TRUE;
3588 }
3589 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003590}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003591
3592/*
3593 * Check what "name" is:
3594 * NODE_NORMAL: file or directory (or doesn't exist)
3595 * NODE_WRITABLE: writable device, socket, fifo, etc.
3596 * NODE_OTHER: non-writable things
3597 */
3598 int
3599mch_nodetype(char_u *name)
3600{
3601 HANDLE hFile;
3602 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003603 WCHAR *wn = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003604
Bram Moolenaar043545e2006-10-10 16:44:07 +00003605 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3606 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3607 * here. */
3608 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3609 return NODE_WRITABLE;
3610
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003611 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003612 wn = enc_to_utf16(name, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003613
3614 if (wn != NULL)
3615 {
3616 hFile = CreateFileW(wn, /* file name */
3617 GENERIC_WRITE, /* access mode */
3618 0, /* share mode */
3619 NULL, /* security descriptor */
3620 OPEN_EXISTING, /* creation disposition */
3621 0, /* file attributes */
3622 NULL); /* handle to template file */
3623 vim_free(wn);
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003624 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003625 else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003626 hFile = CreateFile((LPCSTR)name, /* file name */
3627 GENERIC_WRITE, /* access mode */
3628 0, /* share mode */
3629 NULL, /* security descriptor */
3630 OPEN_EXISTING, /* creation disposition */
3631 0, /* file attributes */
3632 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003633
3634 if (hFile == INVALID_HANDLE_VALUE)
3635 return NODE_NORMAL;
3636
3637 type = GetFileType(hFile);
3638 CloseHandle(hFile);
3639 if (type == FILE_TYPE_CHAR)
3640 return NODE_WRITABLE;
3641 if (type == FILE_TYPE_DISK)
3642 return NODE_NORMAL;
3643 return NODE_OTHER;
3644}
3645
3646#ifdef HAVE_ACL
3647struct my_acl
3648{
3649 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3650 PSID pSidOwner;
3651 PSID pSidGroup;
3652 PACL pDacl;
3653 PACL pSacl;
3654};
3655#endif
3656
3657/*
3658 * Return a pointer to the ACL of file "fname" in allocated memory.
3659 * Return NULL if the ACL is not available for whatever reason.
3660 */
3661 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003662mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003663{
3664#ifndef HAVE_ACL
3665 return (vim_acl_T)NULL;
3666#else
3667 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003668 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003669
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003670 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3671 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003672 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003673 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003674
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003675 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3676 wn = enc_to_utf16(fname, NULL);
3677 if (wn != NULL)
3678 {
3679 /* Try to retrieve the entire security descriptor. */
3680 err = GetNamedSecurityInfoW(
3681 wn, // Abstract filename
3682 SE_FILE_OBJECT, // File Object
3683 OWNER_SECURITY_INFORMATION |
3684 GROUP_SECURITY_INFORMATION |
3685 DACL_SECURITY_INFORMATION |
3686 SACL_SECURITY_INFORMATION,
3687 &p->pSidOwner, // Ownership information.
3688 &p->pSidGroup, // Group membership.
3689 &p->pDacl, // Discretionary information.
3690 &p->pSacl, // For auditing purposes.
3691 &p->pSecurityDescriptor);
3692 if (err == ERROR_ACCESS_DENIED ||
3693 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003694 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003695 /* Retrieve only DACL. */
3696 (void)GetNamedSecurityInfoW(
3697 wn,
3698 SE_FILE_OBJECT,
3699 DACL_SECURITY_INFORMATION,
3700 NULL,
3701 NULL,
3702 &p->pDacl,
3703 NULL,
3704 &p->pSecurityDescriptor);
Bram Moolenaar27515922013-06-29 15:36:26 +02003705 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003706 if (p->pSecurityDescriptor == NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003707 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003708 mch_free_acl((vim_acl_T)p);
3709 p = NULL;
3710 }
3711 vim_free(wn);
3712 }
3713 else
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003714 {
3715 /* Try to retrieve the entire security descriptor. */
3716 err = GetNamedSecurityInfo(
3717 (LPSTR)fname, // Abstract filename
3718 SE_FILE_OBJECT, // File Object
3719 OWNER_SECURITY_INFORMATION |
3720 GROUP_SECURITY_INFORMATION |
3721 DACL_SECURITY_INFORMATION |
3722 SACL_SECURITY_INFORMATION,
3723 &p->pSidOwner, // Ownership information.
3724 &p->pSidGroup, // Group membership.
3725 &p->pDacl, // Discretionary information.
3726 &p->pSacl, // For auditing purposes.
3727 &p->pSecurityDescriptor);
3728 if (err == ERROR_ACCESS_DENIED ||
3729 err == ERROR_PRIVILEGE_NOT_HELD)
3730 {
3731 /* Retrieve only DACL. */
3732 (void)GetNamedSecurityInfo(
3733 (LPSTR)fname,
3734 SE_FILE_OBJECT,
3735 DACL_SECURITY_INFORMATION,
3736 NULL,
3737 NULL,
3738 &p->pDacl,
3739 NULL,
3740 &p->pSecurityDescriptor);
3741 }
3742 if (p->pSecurityDescriptor == NULL)
3743 {
3744 mch_free_acl((vim_acl_T)p);
3745 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003746 }
3747 }
3748 }
3749
3750 return (vim_acl_T)p;
3751#endif
3752}
3753
Bram Moolenaar27515922013-06-29 15:36:26 +02003754#ifdef HAVE_ACL
3755/*
3756 * Check if "acl" contains inherited ACE.
3757 */
3758 static BOOL
3759is_acl_inherited(PACL acl)
3760{
3761 DWORD i;
3762 ACL_SIZE_INFORMATION acl_info;
3763 PACCESS_ALLOWED_ACE ace;
3764
3765 acl_info.AceCount = 0;
3766 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3767 for (i = 0; i < acl_info.AceCount; i++)
3768 {
3769 GetAce(acl, i, (LPVOID *)&ace);
3770 if (ace->Header.AceFlags & INHERITED_ACE)
3771 return TRUE;
3772 }
3773 return FALSE;
3774}
3775#endif
3776
Bram Moolenaar071d4272004-06-13 20:20:40 +00003777/*
3778 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3779 * Errors are ignored.
3780 * This must only be called with "acl" equal to what mch_get_acl() returned.
3781 */
3782 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003783mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003784{
3785#ifdef HAVE_ACL
3786 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003787 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003788
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003789 if (p != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003790 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003791 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003792
3793 /* Set security flags */
3794 if (p->pSidOwner)
3795 sec_info |= OWNER_SECURITY_INFORMATION;
3796 if (p->pSidGroup)
3797 sec_info |= GROUP_SECURITY_INFORMATION;
3798 if (p->pDacl)
3799 {
3800 sec_info |= DACL_SECURITY_INFORMATION;
3801 /* Do not inherit its parent's DACL.
3802 * If the DACL is inherited, Cygwin permissions would be changed.
3803 */
3804 if (!is_acl_inherited(p->pDacl))
3805 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3806 }
3807 if (p->pSacl)
3808 sec_info |= SACL_SECURITY_INFORMATION;
3809
Bram Moolenaar27515922013-06-29 15:36:26 +02003810 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3811 wn = enc_to_utf16(fname, NULL);
3812 if (wn != NULL)
3813 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003814 (void)SetNamedSecurityInfoW(
Bram Moolenaar27515922013-06-29 15:36:26 +02003815 wn, // Abstract filename
3816 SE_FILE_OBJECT, // File Object
3817 sec_info,
3818 p->pSidOwner, // Ownership information.
3819 p->pSidGroup, // Group membership.
3820 p->pDacl, // Discretionary information.
3821 p->pSacl // For auditing purposes.
3822 );
3823 vim_free(wn);
3824 }
3825 else
Bram Moolenaar27515922013-06-29 15:36:26 +02003826 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003827 (void)SetNamedSecurityInfo(
Bram Moolenaar27515922013-06-29 15:36:26 +02003828 (LPSTR)fname, // Abstract filename
3829 SE_FILE_OBJECT, // File Object
3830 sec_info,
3831 p->pSidOwner, // Ownership information.
3832 p->pSidGroup, // Group membership.
3833 p->pDacl, // Discretionary information.
3834 p->pSacl // For auditing purposes.
3835 );
3836 }
3837 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003838#endif
3839}
3840
3841 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003842mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003843{
3844#ifdef HAVE_ACL
3845 struct my_acl *p = (struct my_acl *)acl;
3846
3847 if (p != NULL)
3848 {
3849 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3850 vim_free(p);
3851 }
3852#endif
3853}
3854
Bram Moolenaar4f974752019-02-17 17:44:42 +01003855#ifndef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003856
3857/*
3858 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3859 */
3860 static BOOL WINAPI
3861handler_routine(
3862 DWORD dwCtrlType)
3863{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003864 INPUT_RECORD ir;
3865 DWORD out;
3866
Bram Moolenaar071d4272004-06-13 20:20:40 +00003867 switch (dwCtrlType)
3868 {
3869 case CTRL_C_EVENT:
3870 if (ctrl_c_interrupts)
3871 g_fCtrlCPressed = TRUE;
3872 return TRUE;
3873
3874 case CTRL_BREAK_EVENT:
3875 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003876 ctrl_break_was_pressed = TRUE;
3877 /* ReadConsoleInput is blocking, send a key event to continue. */
3878 ir.EventType = KEY_EVENT;
3879 ir.Event.KeyEvent.bKeyDown = TRUE;
3880 ir.Event.KeyEvent.wRepeatCount = 1;
3881 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3882 ir.Event.KeyEvent.wVirtualScanCode = 0;
3883 ir.Event.KeyEvent.dwControlKeyState = 0;
3884 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3885 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003886 return TRUE;
3887
3888 /* fatal events: shut down gracefully */
3889 case CTRL_CLOSE_EVENT:
3890 case CTRL_LOGOFF_EVENT:
3891 case CTRL_SHUTDOWN_EVENT:
3892 windgoto((int)Rows - 1, 0);
3893 g_fForceExit = TRUE;
3894
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003895 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003896 (dwCtrlType == CTRL_CLOSE_EVENT
3897 ? _("close")
3898 : dwCtrlType == CTRL_LOGOFF_EVENT
3899 ? _("logoff")
3900 : _("shutdown")));
3901#ifdef DEBUG
3902 OutputDebugString(IObuff);
3903#endif
3904
3905 preserve_exit(); /* output IObuff, preserve files and exit */
3906
3907 return TRUE; /* not reached */
3908
3909 default:
3910 return FALSE;
3911 }
3912}
3913
3914
3915/*
3916 * set the tty in (raw) ? "raw" : "cooked" mode
3917 */
3918 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003919mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003920{
3921 DWORD cmodein;
3922 DWORD cmodeout;
3923 BOOL bEnableHandler;
3924
3925 GetConsoleMode(g_hConIn, &cmodein);
3926 GetConsoleMode(g_hConOut, &cmodeout);
3927 if (tmode == TMODE_RAW)
3928 {
3929 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3930 ENABLE_ECHO_INPUT);
3931#ifdef FEAT_MOUSE
3932 if (g_fMouseActive)
3933 cmodein |= ENABLE_MOUSE_INPUT;
3934#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003935 cmodeout &= ~(
3936#ifdef FEAT_TERMGUICOLORS
3937 /* Do not turn off the ENABLE_PROCESSRD_OUTPUT flag when using
3938 * VTP. */
3939 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
3940#else
3941 ENABLE_PROCESSED_OUTPUT |
3942#endif
3943 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003944 bEnableHandler = TRUE;
3945 }
3946 else /* cooked */
3947 {
3948 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3949 ENABLE_ECHO_INPUT);
3950 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3951 bEnableHandler = FALSE;
3952 }
3953 SetConsoleMode(g_hConIn, cmodein);
3954 SetConsoleMode(g_hConOut, cmodeout);
3955 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3956
3957#ifdef MCH_WRITE_DUMP
3958 if (fdDump)
3959 {
3960 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3961 tmode == TMODE_RAW ? "raw" :
3962 tmode == TMODE_COOK ? "cooked" : "normal",
3963 cmodein, cmodeout);
3964 fflush(fdDump);
3965 }
3966#endif
3967}
3968
3969
3970/*
3971 * Get the size of the current window in `Rows' and `Columns'
3972 * Return OK when size could be determined, FAIL otherwise.
3973 */
3974 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003975mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003976{
3977 CONSOLE_SCREEN_BUFFER_INFO csbi;
3978
3979 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3980 {
3981 /*
3982 * For some reason, we are trying to get the screen dimensions
3983 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3984 * variables are really intended to mean the size of Vim screen
3985 * while in termcap mode.
3986 */
3987 Rows = g_cbTermcap.Info.dwSize.Y;
3988 Columns = g_cbTermcap.Info.dwSize.X;
3989 }
3990 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3991 {
3992 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3993 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3994 }
3995 else
3996 {
3997 Rows = 25;
3998 Columns = 80;
3999 }
4000 return OK;
4001}
4002
4003/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004004 * Resize console buffer to 'COORD'
4005 */
4006 static void
4007ResizeConBuf(
4008 HANDLE hConsole,
4009 COORD coordScreen)
4010{
4011 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4012 {
4013#ifdef MCH_WRITE_DUMP
4014 if (fdDump)
4015 {
4016 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4017 GetLastError());
4018 fflush(fdDump);
4019 }
4020#endif
4021 }
4022}
4023
4024/*
4025 * Resize console window size to 'srWindowRect'
4026 */
4027 static void
4028ResizeWindow(
4029 HANDLE hConsole,
4030 SMALL_RECT srWindowRect)
4031{
4032 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4033 {
4034#ifdef MCH_WRITE_DUMP
4035 if (fdDump)
4036 {
4037 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4038 GetLastError());
4039 fflush(fdDump);
4040 }
4041#endif
4042 }
4043}
4044
4045/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004046 * Set a console window to `xSize' * `ySize'
4047 */
4048 static void
4049ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004050 HANDLE hConsole,
4051 int xSize,
4052 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004053{
4054 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
4055 SMALL_RECT srWindowRect; /* hold the new console size */
4056 COORD coordScreen;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004057 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004058
4059#ifdef MCH_WRITE_DUMP
4060 if (fdDump)
4061 {
4062 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4063 fflush(fdDump);
4064 }
4065#endif
4066
4067 /* get the largest size we can size the console window to */
4068 coordScreen = GetLargestConsoleWindowSize(hConsole);
4069
4070 /* define the new console window size and scroll position */
4071 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4072 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4073 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4074
4075 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4076 {
4077 int sx, sy;
4078
4079 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4080 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4081 if (sy < ySize || sx < xSize)
4082 {
4083 /*
4084 * Increasing number of lines/columns, do buffer first.
4085 * Use the maximal size in x and y direction.
4086 */
4087 if (sy < ySize)
4088 coordScreen.Y = ySize;
4089 else
4090 coordScreen.Y = sy;
4091 if (sx < xSize)
4092 coordScreen.X = xSize;
4093 else
4094 coordScreen.X = sx;
4095 SetConsoleScreenBufferSize(hConsole, coordScreen);
4096 }
4097 }
4098
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004099 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004100 coordScreen.X = xSize;
4101 coordScreen.Y = ySize;
4102
Bram Moolenaar2551c032018-08-23 22:38:31 +02004103 // In the new console call API, only the first time in reverse order
4104 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004105 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004106 ResizeWindow(hConsole, srWindowRect);
4107 ResizeConBuf(hConsole, coordScreen);
4108 }
4109 else
4110 {
4111 ResizeConBuf(hConsole, coordScreen);
4112 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004113 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004114 }
4115}
4116
4117
4118/*
4119 * Set the console window to `Rows' * `Columns'
4120 */
4121 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004122mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004123{
4124 COORD coordScreen;
4125
4126 /* Don't change window size while still starting up */
4127 if (suppress_winsize != 0)
4128 {
4129 suppress_winsize = 2;
4130 return;
4131 }
4132
4133 if (term_console)
4134 {
4135 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4136
4137 /* Clamp Rows and Columns to reasonable values */
4138 if (Rows > coordScreen.Y)
4139 Rows = coordScreen.Y;
4140 if (Columns > coordScreen.X)
4141 Columns = coordScreen.X;
4142
4143 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4144 }
4145}
4146
4147/*
4148 * Rows and/or Columns has changed.
4149 */
4150 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004151mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004152{
4153 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4154}
4155
4156
4157/*
4158 * Called when started up, to set the winsize that was delayed.
4159 */
4160 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004161mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004162{
4163 if (suppress_winsize == 2)
4164 {
4165 suppress_winsize = 0;
4166 mch_set_shellsize();
4167 shell_resized();
4168 }
4169 suppress_winsize = 0;
4170}
Bram Moolenaar4f974752019-02-17 17:44:42 +01004171#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004172
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004173 static BOOL
4174vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004175 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004176 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004177 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004178 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004179 PROCESS_INFORMATION *pi,
4180 LPVOID *env,
4181 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004182{
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004183 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4184 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004185 BOOL ret;
4186 WCHAR *wcmd, *wcwd = NULL;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004187
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004188 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4189 if (wcmd == NULL)
4190 goto fallback;
4191 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004192 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004193 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4194 if (wcwd == NULL)
4195 {
4196 vim_free(wcmd);
4197 goto fallback;
4198 }
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004199 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004200
4201 ret = CreateProcessW(
4202 NULL, /* Executable name */
4203 wcmd, /* Command to execute */
4204 NULL, /* Process security attributes */
4205 NULL, /* Thread security attributes */
4206 inherit_handles, /* Inherit handles */
4207 flags, /* Creation flags */
4208 env, /* Environment */
4209 wcwd, /* Current directory */
4210 (LPSTARTUPINFOW)si, /* Startup information */
4211 pi); /* Process information */
4212 vim_free(wcmd);
Bram Moolenaarbdace832019-03-02 10:13:42 +01004213 vim_free(wcwd);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004214 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004215 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004216fallback:
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004217 return CreateProcess(
4218 NULL, /* Executable name */
4219 cmd, /* Command to execute */
4220 NULL, /* Process security attributes */
4221 NULL, /* Thread security attributes */
4222 inherit_handles, /* Inherit handles */
4223 flags, /* Creation flags */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004224 env, /* Environment */
4225 cwd, /* Current directory */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004226 si, /* Startup information */
4227 pi); /* Process information */
4228}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004229
4230
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004231 static HINSTANCE
4232vim_shell_execute(
4233 char *cmd,
4234 INT n_show_cmd)
4235{
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004236 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4237 {
4238 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
4239 if (wcmd != NULL)
4240 {
4241 HINSTANCE ret;
4242 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4243 vim_free(wcmd);
4244 return ret;
4245 }
4246 }
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004247 return ShellExecute(NULL, NULL, cmd, NULL, NULL, n_show_cmd);
4248}
4249
4250
Bram Moolenaar4f974752019-02-17 17:44:42 +01004251#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004252
4253/*
4254 * Specialised version of system() for Win32 GUI mode.
4255 * This version proceeds as follows:
4256 * 1. Create a console window for use by the subprocess
4257 * 2. Run the subprocess (it gets the allocated console by default)
4258 * 3. Wait for the subprocess to terminate and get its exit code
4259 * 4. Prompt the user to press a key to close the console window
4260 */
4261 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004262mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004263{
4264 STARTUPINFO si;
4265 PROCESS_INFORMATION pi;
4266 DWORD ret = 0;
4267 HWND hwnd = GetFocus();
4268
4269 si.cb = sizeof(si);
4270 si.lpReserved = NULL;
4271 si.lpDesktop = NULL;
4272 si.lpTitle = NULL;
4273 si.dwFlags = STARTF_USESHOWWINDOW;
4274 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004275 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004276 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004277 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004278 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004279 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004280 else
4281 si.wShowWindow = SW_SHOWNORMAL;
4282 si.cbReserved2 = 0;
4283 si.lpReserved2 = NULL;
4284
Bram Moolenaar071d4272004-06-13 20:20:40 +00004285 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004286 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004287 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4288 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004289
4290 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004291 {
4292#ifdef FEAT_GUI
4293 int delay = 1;
4294
4295 /* Keep updating the window while waiting for the shell to finish. */
4296 for (;;)
4297 {
4298 MSG msg;
4299
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004300 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004301 {
4302 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004303 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004304 delay = 1;
4305 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004306 }
4307 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4308 break;
4309
4310 /* We start waiting for a very short time and then increase it, so
4311 * that we respond quickly when the process is quick, and don't
4312 * consume too much overhead when it's slow. */
4313 if (delay < 50)
4314 delay += 10;
4315 }
4316#else
4317 WaitForSingleObject(pi.hProcess, INFINITE);
4318#endif
4319
4320 /* Get the command exit code */
4321 GetExitCodeProcess(pi.hProcess, &ret);
4322 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004323
4324 /* Close the handles to the subprocess, so that it goes away */
4325 CloseHandle(pi.hThread);
4326 CloseHandle(pi.hProcess);
4327
4328 /* Try to get input focus back. Doesn't always work though. */
4329 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4330
4331 return ret;
4332}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004333
4334/*
4335 * Thread launched by the gui to send the current buffer data to the
4336 * process. This way avoid to hang up vim totally if the children
4337 * process take a long time to process the lines.
4338 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004339 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004340sub_process_writer(LPVOID param)
4341{
4342 HANDLE g_hChildStd_IN_Wr = param;
4343 linenr_T lnum = curbuf->b_op_start.lnum;
4344 DWORD len = 0;
4345 DWORD l;
4346 char_u *lp = ml_get(lnum);
4347 char_u *s;
4348 int written = 0;
4349
4350 for (;;)
4351 {
4352 l = (DWORD)STRLEN(lp + written);
4353 if (l == 0)
4354 len = 0;
4355 else if (lp[written] == NL)
4356 {
4357 /* NL -> NUL translation */
4358 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4359 }
4360 else
4361 {
4362 s = vim_strchr(lp + written, NL);
4363 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4364 s == NULL ? l : (DWORD)(s - (lp + written)),
4365 &len, NULL);
4366 }
4367 if (len == (int)l)
4368 {
4369 /* Finished a line, add a NL, unless this line should not have
4370 * one. */
4371 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004372 || (!curbuf->b_p_bin
4373 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004374 || (lnum != curbuf->b_no_eol_lnum
4375 && (lnum != curbuf->b_ml.ml_line_count
4376 || curbuf->b_p_eol)))
4377 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004378 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4379 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004380 }
4381
4382 ++lnum;
4383 if (lnum > curbuf->b_op_end.lnum)
4384 break;
4385
4386 lp = ml_get(lnum);
4387 written = 0;
4388 }
4389 else if (len > 0)
4390 written += len;
4391 }
4392
4393 /* finished all the lines, close pipe */
4394 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004395 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004396}
4397
4398
4399# define BUFLEN 100 /* length for buffer, stolen from unix version */
4400
4401/*
4402 * This function read from the children's stdout and write the
4403 * data on screen or in the buffer accordingly.
4404 */
4405 static void
4406dump_pipe(int options,
4407 HANDLE g_hChildStd_OUT_Rd,
4408 garray_T *ga,
4409 char_u buffer[],
4410 DWORD *buffer_off)
4411{
4412 DWORD availableBytes = 0;
4413 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004414 int ret;
4415 DWORD len;
4416 DWORD toRead;
4417 int repeatCount;
4418
4419 /* we query the pipe to see if there is any data to read
4420 * to avoid to perform a blocking read */
4421 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4422 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004423 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004424 NULL, /* number of read bytes */
4425 &availableBytes, /* available bytes total */
4426 NULL); /* byteLeft */
4427
4428 repeatCount = 0;
4429 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004430 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004431 {
4432 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004433 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004434 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004435 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004436
4437 /* If we haven't read anything, there is a problem */
4438 if (len == 0)
4439 break;
4440
4441 availableBytes -= len;
4442
4443 if (options & SHELL_READ)
4444 {
4445 /* Do NUL -> NL translation, append NL separated
4446 * lines to the current buffer. */
4447 for (i = 0; i < len; ++i)
4448 {
4449 if (buffer[i] == NL)
4450 append_ga_line(ga);
4451 else if (buffer[i] == NUL)
4452 ga_append(ga, NL);
4453 else
4454 ga_append(ga, buffer[i]);
4455 }
4456 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004457 else if (has_mbyte)
4458 {
4459 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004460 int c;
4461 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004462
4463 len += *buffer_off;
4464 buffer[len] = NUL;
4465
4466 /* Check if the last character in buffer[] is
4467 * incomplete, keep these bytes for the next
4468 * round. */
4469 for (p = buffer; p < buffer + len; p += l)
4470 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004471 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004472 if (l == 0)
4473 l = 1; /* NUL byte? */
4474 else if (MB_BYTE2LEN(*p) != l)
4475 break;
4476 }
4477 if (p == buffer) /* no complete character */
4478 {
4479 /* avoid getting stuck at an illegal byte */
4480 if (len >= 12)
4481 ++p;
4482 else
4483 {
4484 *buffer_off = len;
4485 return;
4486 }
4487 }
4488 c = *p;
4489 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004490 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004491 if (p < buffer + len)
4492 {
4493 *p = c;
4494 *buffer_off = (DWORD)((buffer + len) - p);
4495 mch_memmove(buffer, p, *buffer_off);
4496 return;
4497 }
4498 *buffer_off = 0;
4499 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004500 else
4501 {
4502 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004503 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004504 }
4505
4506 windgoto(msg_row, msg_col);
4507 cursor_on();
4508 out_flush();
4509 }
4510}
4511
4512/*
4513 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4514 * for communication and doesn't open any new window.
4515 */
4516 static int
4517mch_system_piped(char *cmd, int options)
4518{
4519 STARTUPINFO si;
4520 PROCESS_INFORMATION pi;
4521 DWORD ret = 0;
4522
4523 HANDLE g_hChildStd_IN_Rd = NULL;
4524 HANDLE g_hChildStd_IN_Wr = NULL;
4525 HANDLE g_hChildStd_OUT_Rd = NULL;
4526 HANDLE g_hChildStd_OUT_Wr = NULL;
4527
4528 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4529 DWORD len;
4530
4531 /* buffer used to receive keys */
4532 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4533 int ta_len = 0; /* valid bytes in ta_buf[] */
4534
4535 DWORD i;
4536 int c;
4537 int noread_cnt = 0;
4538 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004539 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004540 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004541 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004542
4543 SECURITY_ATTRIBUTES saAttr;
4544
4545 /* Set the bInheritHandle flag so pipe handles are inherited. */
4546 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4547 saAttr.bInheritHandle = TRUE;
4548 saAttr.lpSecurityDescriptor = NULL;
4549
4550 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4551 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004552 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004553 /* Create a pipe for the child process's STDIN. */
4554 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4555 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004556 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004557 {
4558 CloseHandle(g_hChildStd_IN_Rd);
4559 CloseHandle(g_hChildStd_IN_Wr);
4560 CloseHandle(g_hChildStd_OUT_Rd);
4561 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004562 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004563 }
4564
4565 si.cb = sizeof(si);
4566 si.lpReserved = NULL;
4567 si.lpDesktop = NULL;
4568 si.lpTitle = NULL;
4569 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4570
4571 /* set-up our file redirection */
4572 si.hStdError = g_hChildStd_OUT_Wr;
4573 si.hStdOutput = g_hChildStd_OUT_Wr;
4574 si.hStdInput = g_hChildStd_IN_Rd;
4575 si.wShowWindow = SW_HIDE;
4576 si.cbReserved2 = 0;
4577 si.lpReserved2 = NULL;
4578
4579 if (options & SHELL_READ)
4580 ga_init2(&ga, 1, BUFLEN);
4581
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004582 if (cmd != NULL)
4583 {
4584 p = (char *)vim_strsave((char_u *)cmd);
4585 if (p != NULL)
4586 unescape_shellxquote((char_u *)p, p_sxe);
4587 else
4588 p = cmd;
4589 }
4590
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004591 /* Now, run the command.
4592 * About "Inherit handles" being TRUE: this command can be litigious,
4593 * handle inheritance was deactivated for pending temp file, but, if we
4594 * deactivate it, the pipes don't work for some reason. */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004595 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4596 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004597
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004598 if (p != cmd)
4599 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004600
4601 /* Close our unused side of the pipes */
4602 CloseHandle(g_hChildStd_IN_Rd);
4603 CloseHandle(g_hChildStd_OUT_Wr);
4604
4605 if (options & SHELL_WRITE)
4606 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004607 HANDLE thread = (HANDLE)
4608 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004609 0, /* default stack size */
4610 sub_process_writer, /* function to be executed */
4611 g_hChildStd_IN_Wr, /* parameter */
4612 0, /* creation flag, start immediately */
4613 NULL); /* we don't care about thread id */
4614 CloseHandle(thread);
4615 g_hChildStd_IN_Wr = NULL;
4616 }
4617
4618 /* Keep updating the window while waiting for the shell to finish. */
4619 for (;;)
4620 {
4621 MSG msg;
4622
Bram Moolenaar175d0702013-12-11 18:36:33 +01004623 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004624 {
4625 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004626 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004627 }
4628
4629 /* write pipe information in the window */
4630 if ((options & (SHELL_READ|SHELL_WRITE))
4631# ifdef FEAT_GUI
4632 || gui.in_use
4633# endif
4634 )
4635 {
4636 len = 0;
4637 if (!(options & SHELL_EXPAND)
4638 && ((options &
4639 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4640 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4641# ifdef FEAT_GUI
4642 || gui.in_use
4643# endif
4644 )
4645 && (ta_len > 0 || noread_cnt > 4))
4646 {
4647 if (ta_len == 0)
4648 {
4649 /* Get extra characters when we don't have any. Reset the
4650 * counter and timer. */
4651 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004652 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4653 }
4654 if (ta_len > 0 || len > 0)
4655 {
4656 /*
4657 * For pipes: Check for CTRL-C: send interrupt signal to
4658 * child. Check for CTRL-D: EOF, close pipe to child.
4659 */
4660 if (len == 1 && cmd != NULL)
4661 {
4662 if (ta_buf[ta_len] == Ctrl_C)
4663 {
4664 /* Learn what exit code is expected, for
4665 * now put 9 as SIGKILL */
4666 TerminateProcess(pi.hProcess, 9);
4667 }
4668 if (ta_buf[ta_len] == Ctrl_D)
4669 {
4670 CloseHandle(g_hChildStd_IN_Wr);
4671 g_hChildStd_IN_Wr = NULL;
4672 }
4673 }
4674
4675 /* replace K_BS by <BS> and K_DEL by <DEL> */
4676 for (i = ta_len; i < ta_len + len; ++i)
4677 {
4678 if (ta_buf[i] == CSI && len - i > 2)
4679 {
4680 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4681 if (c == K_DEL || c == K_KDEL || c == K_BS)
4682 {
4683 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4684 (size_t)(len - i - 2));
4685 if (c == K_DEL || c == K_KDEL)
4686 ta_buf[i] = DEL;
4687 else
4688 ta_buf[i] = Ctrl_H;
4689 len -= 2;
4690 }
4691 }
4692 else if (ta_buf[i] == '\r')
4693 ta_buf[i] = '\n';
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004694 if (has_mbyte)
4695 i += (*mb_ptr2len_len)(ta_buf + i,
4696 ta_len + len - i) - 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004697 }
4698
4699 /*
4700 * For pipes: echo the typed characters. For a pty this
4701 * does not seem to work.
4702 */
4703 for (i = ta_len; i < ta_len + len; ++i)
4704 {
4705 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4706 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004707 else if (has_mbyte)
4708 {
4709 int l = (*mb_ptr2len)(ta_buf + i);
4710
4711 msg_outtrans_len(ta_buf + i, l);
4712 i += l - 1;
4713 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004714 else
4715 msg_outtrans_len(ta_buf + i, 1);
4716 }
4717 windgoto(msg_row, msg_col);
4718 out_flush();
4719
4720 ta_len += len;
4721
4722 /*
4723 * Write the characters to the child, unless EOF has been
4724 * typed for pipes. Write one character at a time, to
4725 * avoid losing too much typeahead. When writing buffer
4726 * lines, drop the typed characters (only check for
4727 * CTRL-C).
4728 */
4729 if (options & SHELL_WRITE)
4730 ta_len = 0;
4731 else if (g_hChildStd_IN_Wr != NULL)
4732 {
4733 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4734 1, &len, NULL);
4735 // if we are typing in, we want to keep things reactive
4736 delay = 1;
4737 if (len > 0)
4738 {
4739 ta_len -= len;
4740 mch_memmove(ta_buf, ta_buf + len, ta_len);
4741 }
4742 }
4743 }
4744 }
4745 }
4746
4747 if (ta_len)
4748 ui_inchar_undo(ta_buf, ta_len);
4749
4750 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4751 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004752 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004753 break;
4754 }
4755
4756 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004757 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004758
4759 /* We start waiting for a very short time and then increase it, so
4760 * that we respond quickly when the process is quick, and don't
4761 * consume too much overhead when it's slow. */
4762 if (delay < 50)
4763 delay += 10;
4764 }
4765
4766 /* Close the pipe */
4767 CloseHandle(g_hChildStd_OUT_Rd);
4768 if (g_hChildStd_IN_Wr != NULL)
4769 CloseHandle(g_hChildStd_IN_Wr);
4770
4771 WaitForSingleObject(pi.hProcess, INFINITE);
4772
4773 /* Get the command exit code */
4774 GetExitCodeProcess(pi.hProcess, &ret);
4775
4776 if (options & SHELL_READ)
4777 {
4778 if (ga.ga_len > 0)
4779 {
4780 append_ga_line(&ga);
4781 /* remember that the NL was missing */
4782 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4783 }
4784 else
4785 curbuf->b_no_eol_lnum = 0;
4786 ga_clear(&ga);
4787 }
4788
4789 /* Close the handles to the subprocess, so that it goes away */
4790 CloseHandle(pi.hThread);
4791 CloseHandle(pi.hProcess);
4792
4793 return ret;
4794}
4795
4796 static int
4797mch_system(char *cmd, int options)
4798{
4799 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004800 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004801 return mch_system_piped(cmd, options);
4802 else
4803 return mch_system_classic(cmd, options);
4804}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004805#else
4806
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004807 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004808mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004809{
4810 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4811 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004812 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004813 if (wcmd != NULL)
4814 {
4815 int ret = _wsystem(wcmd);
4816 vim_free(wcmd);
4817 return ret;
4818 }
4819 }
4820 return system(cmd);
4821}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004822
4823#endif
4824
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004825#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4826/*
4827 * Use a terminal window to run a shell command in.
4828 */
4829 static int
4830mch_call_shell_terminal(
4831 char_u *cmd,
4832 int options UNUSED) /* SHELL_*, see vim.h */
4833{
4834 jobopt_T opt;
4835 char_u *newcmd = NULL;
4836 typval_T argvar[2];
4837 long_u cmdlen;
4838 int retval = -1;
4839 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004840 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004841 aco_save_T aco;
4842 oparg_T oa; /* operator arguments */
4843
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004844 if (cmd == NULL)
4845 cmdlen = STRLEN(p_sh) + 1;
4846 else
4847 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004848 newcmd = lalloc(cmdlen, TRUE);
4849 if (newcmd == NULL)
4850 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004851 if (cmd == NULL)
4852 {
4853 STRCPY(newcmd, p_sh);
4854 ch_log(NULL, "starting terminal to run a shell");
4855 }
4856 else
4857 {
4858 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4859 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4860 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004861
4862 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004863
4864 argvar[0].v_type = VAR_STRING;
4865 argvar[0].vval.v_string = newcmd;
4866 argvar[1].v_type = VAR_UNKNOWN;
4867 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004868 if (buf == NULL)
4869 return 255;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004870
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004871 job = term_getjob(buf->b_term);
4872 ++job->jv_refcount;
4873
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004874 /* Find a window to make "buf" curbuf. */
4875 aucmd_prepbuf(&aco, buf);
4876
4877 clear_oparg(&oa);
4878 while (term_use_loop())
4879 {
4880 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4881 {
4882 /* If terminal_loop() returns OK we got a key that is handled
4883 * in Normal model. We don't do redrawing anyway. */
4884 if (terminal_loop(TRUE) == OK)
4885 normal_cmd(&oa, TRUE);
4886 }
4887 else
4888 normal_cmd(&oa, TRUE);
4889 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004890 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004891 ch_log(NULL, "system command finished");
4892
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004893 job_unref(job);
4894
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004895 /* restore curwin/curbuf and a few other things */
4896 aucmd_restbuf(&aco);
4897
4898 wait_return(TRUE);
4899 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4900
4901 vim_free(newcmd);
4902 return retval;
4903}
4904#endif
4905
Bram Moolenaar071d4272004-06-13 20:20:40 +00004906/*
4907 * Either execute a command by calling the shell or start a new shell
4908 */
4909 int
4910mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004911 char_u *cmd,
4912 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004913{
4914 int x = 0;
4915 int tmode = cur_tmode;
4916#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004917 char szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004918 int did_set_title = FALSE;
4919
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004920 /* Change the title to reflect that we are in a subshell. */
4921 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4922 {
4923 WCHAR szShellTitle[512];
4924
4925 if (GetConsoleTitleW(szShellTitle,
4926 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4927 {
4928 if (cmd == NULL)
4929 wcscat(szShellTitle, L" :sh");
4930 else
4931 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004932 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004933
4934 if (wn != NULL)
4935 {
4936 wcscat(szShellTitle, L" - !");
4937 if ((wcslen(szShellTitle) + wcslen(wn) <
4938 sizeof(szShellTitle)/sizeof(WCHAR)))
4939 wcscat(szShellTitle, wn);
4940 SetConsoleTitleW(szShellTitle);
4941 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004942 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004943 }
4944 }
4945 }
4946 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004947 if (!did_set_title)
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004948 /* Change the title to reflect that we are in a subshell. */
4949 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004950 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004951 if (cmd == NULL)
4952 strcat(szShellTitle, " :sh");
4953 else
4954 {
4955 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004956 if ((strlen(szShellTitle) + strlen((char *)cmd)
4957 < sizeof(szShellTitle)))
4958 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004959 }
4960 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004961 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004962#endif
4963
4964 out_flush();
4965
4966#ifdef MCH_WRITE_DUMP
4967 if (fdDump)
4968 {
4969 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4970 fflush(fdDump);
4971 }
4972#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004973#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4974 /* TODO: make the terminal window work with input or output redirected. */
4975 if (vim_strchr(p_go, GO_TERMINAL) != NULL
4976 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4977 {
4978 /* Use a terminal window to run the command in. */
4979 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004980# ifdef FEAT_TITLE
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004981 resettitle();
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004982# endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004983 return x;
4984 }
4985#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004986
4987 /*
4988 * Catch all deadly signals while running the external command, because a
4989 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4990 */
4991 signal(SIGINT, SIG_IGN);
4992#if defined(__GNUC__) && !defined(__MINGW32__)
4993 signal(SIGKILL, SIG_IGN);
4994#else
4995 signal(SIGBREAK, SIG_IGN);
4996#endif
4997 signal(SIGILL, SIG_IGN);
4998 signal(SIGFPE, SIG_IGN);
4999 signal(SIGSEGV, SIG_IGN);
5000 signal(SIGTERM, SIG_IGN);
5001 signal(SIGABRT, SIG_IGN);
5002
5003 if (options & SHELL_COOKED)
5004 settmode(TMODE_COOK); /* set to normal mode */
5005
5006 if (cmd == NULL)
5007 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005008 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005009 }
5010 else
5011 {
5012 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005013 char_u *newcmd = NULL;
5014 char_u *cmdbase = cmd;
5015 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005016
5017 /* Skip a leading ", ( and "(. */
5018 if (*cmdbase == '"' )
5019 ++cmdbase;
5020 if (*cmdbase == '(')
5021 ++cmdbase;
5022
Bram Moolenaar1c465442017-03-12 20:10:05 +01005023 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005024 {
5025 STARTUPINFO si;
5026 PROCESS_INFORMATION pi;
5027 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005028 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005029 char_u *p;
5030
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005031 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005032 si.cb = sizeof(si);
5033 si.lpReserved = NULL;
5034 si.lpDesktop = NULL;
5035 si.lpTitle = NULL;
5036 si.dwFlags = 0;
5037 si.cbReserved2 = 0;
5038 si.lpReserved2 = NULL;
5039
5040 cmdbase = skipwhite(cmdbase + 5);
5041 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005042 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005043 {
5044 cmdbase = skipwhite(cmdbase + 4);
5045 si.dwFlags = STARTF_USESHOWWINDOW;
5046 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005047 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005048 }
5049 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005050 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005051 {
5052 cmdbase = skipwhite(cmdbase + 2);
5053 flags = CREATE_NO_WINDOW;
5054 si.dwFlags = STARTF_USESTDHANDLES;
5055 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005056 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005057 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005058 NULL, // Security att.
5059 OPEN_EXISTING, // Open flags
5060 FILE_ATTRIBUTE_NORMAL, // File att.
5061 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005062 si.hStdOutput = si.hStdInput;
5063 si.hStdError = si.hStdInput;
5064 }
5065
5066 /* Remove a trailing ", ) and )" if they have a match
5067 * at the start of the command. */
5068 if (cmdbase > cmd)
5069 {
5070 p = cmdbase + STRLEN(cmdbase);
5071 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5072 *--p = NUL;
5073 if (p > cmdbase && p[-1] == ')'
5074 && (*cmd =='(' || cmd[1] == '('))
5075 *--p = NUL;
5076 }
5077
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005078 newcmd = cmdbase;
5079 unescape_shellxquote(cmdbase, p_sxe);
5080
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005081 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005082 * If creating new console, arguments are passed to the
5083 * 'cmd.exe' as-is. If it's not, arguments are not treated
5084 * correctly for current 'cmd.exe'. So unescape characters in
5085 * shellxescape except '|' for avoiding to be treated as
5086 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005087 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005088 if (flags != CREATE_NEW_CONSOLE)
5089 {
5090 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005091 char_u *cmd_shell = mch_getenv("COMSPEC");
5092
5093 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005094 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005095
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005096 subcmd = vim_strsave_escaped_ext(cmdbase,
5097 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005098 if (subcmd != NULL)
5099 {
5100 /* make "cmd.exe /c arguments" */
5101 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005102 newcmd = lalloc(cmdlen, TRUE);
5103 if (newcmd != NULL)
5104 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005105 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005106 else
5107 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005108 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005109 }
5110 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005111
5112 /*
5113 * Now, start the command as a process, so that it doesn't
5114 * inherit our handles which causes unpleasant dangling swap
5115 * files if we exit before the spawned process
5116 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005117 if (vim_create_process((char *)newcmd, FALSE, flags,
5118 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005119 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005120 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5121 > (HINSTANCE)32)
5122 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005123 else
5124 {
5125 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005126#ifdef FEAT_GUI_MSWIN
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005127 emsg(_("E371: Command not found"));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005128#endif
5129 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005130
5131 if (newcmd != cmdbase)
5132 vim_free(newcmd);
5133
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005134 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005135 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005136 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005137 CloseHandle(si.hStdInput);
5138 }
5139 /* Close the handles to the subprocess, so that it goes away */
5140 CloseHandle(pi.hThread);
5141 CloseHandle(pi.hProcess);
5142 }
5143 else
5144 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005145 cmdlen = (
Bram Moolenaar4f974752019-02-17 17:44:42 +01005146#ifdef FEAT_GUI_MSWIN
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005147 (!p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005148#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005149 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
5150
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005151 newcmd = lalloc(cmdlen, TRUE);
5152 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005153 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005154#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005155 if (need_vimrun_warning)
5156 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005157 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5158 "External commands will not pause after completion.\n"
5159 "See :help win32-vimrun for more information.");
5160 char *title = _("Vim Warning");
Bram Moolenaar63e43442016-11-19 17:28:44 +01005161 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5162 {
5163 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5164 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
5165
5166 if (wmsg != NULL && wtitle != NULL)
5167 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5168 vim_free(wmsg);
5169 vim_free(wtitle);
5170 }
5171 else
Bram Moolenaar63e43442016-11-19 17:28:44 +01005172 MessageBox(NULL, msg, title, MB_ICONWARNING);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005173 need_vimrun_warning = FALSE;
5174 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005175 if (!s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005176 /* Use vimrun to execute the command. It opens a console
5177 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005178 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005179 vimrun_path,
5180 (msg_silent != 0 || (options & SHELL_DOOUT))
5181 ? "-s " : "",
5182 p_sh, p_shcf, cmd);
5183 else
5184#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005185 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005186 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005187 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005188 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005189 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005190 }
5191 }
5192
5193 if (tmode == TMODE_RAW)
5194 settmode(TMODE_RAW); /* set to raw mode */
5195
5196 /* Print the return value, unless "vimrun" was used. */
5197 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005198#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005199 && ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005200#endif
5201 )
5202 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005203 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005204 msg_putchar('\n');
5205 }
5206#ifdef FEAT_TITLE
5207 resettitle();
5208#endif
5209
5210 signal(SIGINT, SIG_DFL);
5211#if defined(__GNUC__) && !defined(__MINGW32__)
5212 signal(SIGKILL, SIG_DFL);
5213#else
5214 signal(SIGBREAK, SIG_DFL);
5215#endif
5216 signal(SIGILL, SIG_DFL);
5217 signal(SIGFPE, SIG_DFL);
5218 signal(SIGSEGV, SIG_DFL);
5219 signal(SIGTERM, SIG_DFL);
5220 signal(SIGABRT, SIG_DFL);
5221
5222 return x;
5223}
5224
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005225#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005226 static HANDLE
5227job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005228 char_u *fname,
5229 DWORD dwDesiredAccess,
5230 DWORD dwShareMode,
5231 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5232 DWORD dwCreationDisposition,
5233 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005234{
5235 HANDLE h;
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005236 WCHAR *wn = NULL;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005237
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005238 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5239 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005240 wn = enc_to_utf16(fname, NULL);
5241 if (wn != NULL)
5242 {
5243 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5244 lpSecurityAttributes, dwCreationDisposition,
5245 dwFlagsAndAttributes, NULL);
5246 vim_free(wn);
5247 }
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005248 }
5249 if (wn == NULL)
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005250 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
5251 lpSecurityAttributes, dwCreationDisposition,
5252 dwFlagsAndAttributes, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005253 return h;
5254}
5255
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005256/*
5257 * Turn the dictionary "env" into a NUL separated list that can be used as the
5258 * environment argument of vim_create_process().
5259 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005260 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005261win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005262{
5263 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005264 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005265 LPVOID base = GetEnvironmentStringsW();
5266
5267 /* for last \0 */
5268 if (ga_grow(gap, 1) == FAIL)
5269 return;
5270
5271 if (base)
5272 {
5273 WCHAR *p = (WCHAR*) base;
5274
5275 /* for last \0 */
5276 if (ga_grow(gap, 1) == FAIL)
5277 return;
5278
5279 while (*p != 0 || *(p + 1) != 0)
5280 {
5281 if (ga_grow(gap, 1) == OK)
5282 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5283 p++;
5284 }
5285 FreeEnvironmentStrings(base);
5286 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5287 }
5288
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005289 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005290 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005291 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005292 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005293 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005294 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005295 typval_T *item = &dict_lookup(hi)->di_tv;
5296 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005297 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005298 --todo;
5299 if (wkey != NULL && wval != NULL)
5300 {
5301 size_t n;
5302 size_t lkey = wcslen(wkey);
5303 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005304
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005305 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5306 continue;
5307 for (n = 0; n < lkey; n++)
5308 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5309 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5310 for (n = 0; n < lval; n++)
5311 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5312 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5313 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005314 vim_free(wkey);
5315 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005316 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005317 }
5318 }
5319
Bram Moolenaar493359e2018-06-12 20:25:52 +02005320# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005321 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005322# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005323 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005324 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005325# endif
5326# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005327 char_u *version = get_vim_var_str(VV_VERSION);
5328 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005329# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005330 // size of "VIM_SERVERNAME=" and value,
5331 // plus "VIM_TERMINAL=" and value,
5332 // plus two terminating NULs
5333 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005334# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005335 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005336# endif
5337# ifdef FEAT_TERMINAL
5338 + 13 + version_len + 2
5339# endif
5340 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005341
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005342 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005343 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005344# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005345 for (n = 0; n < 15; n++)
5346 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5347 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005348 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005349 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5350 (WCHAR)servername[n];
5351 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005352# endif
5353# ifdef FEAT_TERMINAL
5354 if (is_terminal)
5355 {
5356 for (n = 0; n < 13; n++)
5357 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5358 (WCHAR)"VIM_TERMINAL="[n];
5359 for (n = 0; n < version_len; n++)
5360 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5361 (WCHAR)version[n];
5362 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5363 }
5364# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005365 }
5366 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005367# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005368}
5369
Bram Moolenaarb091f302019-01-19 14:37:00 +01005370/*
5371 * Create a pair of pipes.
5372 * Return TRUE for success, FALSE for failure.
5373 */
5374 static BOOL
5375create_pipe_pair(HANDLE handles[2])
5376{
5377 static LONG s;
5378 char name[64];
5379 SECURITY_ATTRIBUTES sa;
5380
5381 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5382 GetCurrentProcessId(),
5383 InterlockedIncrement(&s));
5384
5385 // Create named pipe. Max size of named pipe is 65535.
5386 handles[1] = CreateNamedPipe(
5387 name,
5388 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5389 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005390 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005391
5392 if (handles[1] == INVALID_HANDLE_VALUE)
5393 return FALSE;
5394
5395 sa.nLength = sizeof(sa);
5396 sa.bInheritHandle = TRUE;
5397 sa.lpSecurityDescriptor = NULL;
5398
5399 handles[0] = CreateFile(name,
5400 FILE_GENERIC_READ,
5401 FILE_SHARE_READ, &sa,
5402 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5403
5404 if (handles[0] == INVALID_HANDLE_VALUE)
5405 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005406 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005407 return FALSE;
5408 }
5409
5410 return TRUE;
5411}
5412
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005413 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005414mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005415{
5416 STARTUPINFO si;
5417 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005418 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005419 SECURITY_ATTRIBUTES saAttr;
5420 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005421 HANDLE ifd[2];
5422 HANDLE ofd[2];
5423 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005424 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005425
5426 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5427 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5428 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5429 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5430 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5431 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5432 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5433
5434 if (use_out_for_err && use_null_for_out)
5435 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005436
5437 ifd[0] = INVALID_HANDLE_VALUE;
5438 ifd[1] = INVALID_HANDLE_VALUE;
5439 ofd[0] = INVALID_HANDLE_VALUE;
5440 ofd[1] = INVALID_HANDLE_VALUE;
5441 efd[0] = INVALID_HANDLE_VALUE;
5442 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005443 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005444
Bram Moolenaar14207f42016-10-27 21:13:10 +02005445 jo = CreateJobObject(NULL, NULL);
5446 if (jo == NULL)
5447 {
5448 job->jv_status = JOB_FAILED;
5449 goto failed;
5450 }
5451
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005452 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005453 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005454
Bram Moolenaar76467df2016-02-12 19:30:26 +01005455 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005456 ZeroMemory(&si, sizeof(si));
5457 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005458 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005459 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005460
Bram Moolenaard8070362016-02-15 21:56:54 +01005461 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5462 saAttr.bInheritHandle = TRUE;
5463 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005464
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005465 if (use_file_for_in)
5466 {
5467 char_u *fname = options->jo_io_name[PART_IN];
5468
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005469 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5470 FILE_SHARE_READ | FILE_SHARE_WRITE,
5471 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5472 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005473 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005474 semsg(_(e_notopen), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005475 goto failed;
5476 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005477 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005478 else if (!use_null_for_in
5479 && (!create_pipe_pair(ifd)
5480 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005481 goto failed;
5482
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005483 if (use_file_for_out)
5484 {
5485 char_u *fname = options->jo_io_name[PART_OUT];
5486
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005487 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5488 FILE_SHARE_READ | FILE_SHARE_WRITE,
5489 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5490 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005491 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005492 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005493 goto failed;
5494 }
5495 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005496 else if (!use_null_for_out &&
5497 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005498 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005499 goto failed;
5500
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005501 if (use_file_for_err)
5502 {
5503 char_u *fname = options->jo_io_name[PART_ERR];
5504
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005505 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5506 FILE_SHARE_READ | FILE_SHARE_WRITE,
5507 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5508 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005509 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005510 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005511 goto failed;
5512 }
5513 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005514 else if (!use_out_for_err && !use_null_for_err &&
5515 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005516 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005517 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005518
Bram Moolenaard8070362016-02-15 21:56:54 +01005519 si.dwFlags |= STARTF_USESTDHANDLES;
5520 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005521 si.hStdOutput = ofd[1];
5522 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5523
5524 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5525 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005526 if (options->jo_set & JO_CHANNEL)
5527 {
5528 channel = options->jo_channel;
5529 if (channel != NULL)
5530 ++channel->ch_refcount;
5531 }
5532 else
5533 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005534 if (channel == NULL)
5535 goto failed;
5536 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005537
5538 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005539 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005540 CREATE_DEFAULT_ERROR_MODE |
5541 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005542 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005543 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005544 &si, &pi,
5545 ga.ga_data,
5546 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005547 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005548 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005549 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005550 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005551 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005552
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005553 ga_clear(&ga);
5554
Bram Moolenaar14207f42016-10-27 21:13:10 +02005555 if (!AssignProcessToJobObject(jo, pi.hProcess))
5556 {
5557 /* if failing, switch the way to terminate
5558 * process with TerminateProcess. */
5559 CloseHandle(jo);
5560 jo = NULL;
5561 }
5562 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005563 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005564 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005565 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005566 job->jv_status = JOB_STARTED;
5567
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005568 CloseHandle(ifd[0]);
5569 CloseHandle(ofd[1]);
5570 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005571 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005572
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005573 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005574 if (channel != NULL)
5575 {
5576 channel_set_pipes(channel,
5577 use_file_for_in || use_null_for_in
5578 ? INVALID_FD : (sock_T)ifd[1],
5579 use_file_for_out || use_null_for_out
5580 ? INVALID_FD : (sock_T)ofd[0],
5581 use_out_for_err || use_file_for_err || use_null_for_err
5582 ? INVALID_FD : (sock_T)efd[0]);
5583 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005584 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005585 return;
5586
5587failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005588 CloseHandle(ifd[0]);
5589 CloseHandle(ofd[0]);
5590 CloseHandle(efd[0]);
5591 CloseHandle(ifd[1]);
5592 CloseHandle(ofd[1]);
5593 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005594 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005595 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005596}
5597
5598 char *
5599mch_job_status(job_T *job)
5600{
5601 DWORD dwExitCode = 0;
5602
Bram Moolenaar76467df2016-02-12 19:30:26 +01005603 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5604 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005605 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005606 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005607 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005608 {
5609 ch_log(job->jv_channel, "Job ended");
5610 job->jv_status = JOB_ENDED;
5611 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005612 return "dead";
5613 }
5614 return "run";
5615}
5616
Bram Moolenaar97792de2016-10-15 18:36:49 +02005617 job_T *
5618mch_detect_ended_job(job_T *job_list)
5619{
5620 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5621 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5622 job_T *job = job_list;
5623
5624 while (job != NULL)
5625 {
5626 DWORD n;
5627 DWORD result;
5628
5629 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5630 && job != NULL; job = job->jv_next)
5631 {
5632 if (job->jv_status == JOB_STARTED)
5633 {
5634 jobHandles[n] = job->jv_proc_info.hProcess;
5635 jobArray[n] = job;
5636 ++n;
5637 }
5638 }
5639 if (n == 0)
5640 continue;
5641 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5642 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5643 {
5644 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5645
5646 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5647 return wait_job;
5648 }
5649 }
5650 return NULL;
5651}
5652
Bram Moolenaarfb630902016-10-29 14:55:00 +02005653 static BOOL
5654terminate_all(HANDLE process, int code)
5655{
5656 PROCESSENTRY32 pe;
5657 HANDLE h = INVALID_HANDLE_VALUE;
5658 DWORD pid = GetProcessId(process);
5659
5660 if (pid != 0)
5661 {
5662 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5663 if (h != INVALID_HANDLE_VALUE)
5664 {
5665 pe.dwSize = sizeof(PROCESSENTRY32);
5666 if (!Process32First(h, &pe))
5667 goto theend;
5668
5669 do
5670 {
5671 if (pe.th32ParentProcessID == pid)
5672 {
5673 HANDLE ph = OpenProcess(
5674 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5675 if (ph != NULL)
5676 {
5677 terminate_all(ph, code);
5678 CloseHandle(ph);
5679 }
5680 }
5681 } while (Process32Next(h, &pe));
5682
5683 CloseHandle(h);
5684 }
5685 }
5686
5687theend:
5688 return TerminateProcess(process, code);
5689}
5690
5691/*
5692 * Send a (deadly) signal to "job".
5693 * Return FAIL if it didn't work.
5694 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005695 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005696mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005697{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005698 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005699
Bram Moolenaar923d9262016-02-25 20:56:01 +01005700 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005701 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005702 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005703 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005704 {
5705 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5706 job->jv_channel->ch_killing = TRUE;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005707 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005708 }
Bram Moolenaarfb630902016-10-29 14:55:00 +02005709 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005710 }
5711
5712 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5713 return FAIL;
5714 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005715 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5716 job->jv_proc_info.dwProcessId)
5717 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005718 FreeConsole();
5719 return ret;
5720}
5721
5722/*
5723 * Clear the data related to "job".
5724 */
5725 void
5726mch_clear_job(job_T *job)
5727{
5728 if (job->jv_status != JOB_FAILED)
5729 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005730 if (job->jv_job_object != NULL)
5731 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005732 CloseHandle(job->jv_proc_info.hProcess);
5733 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005734}
5735#endif
5736
Bram Moolenaar071d4272004-06-13 20:20:40 +00005737
Bram Moolenaar4f974752019-02-17 17:44:42 +01005738#ifndef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005739
5740/*
5741 * Start termcap mode
5742 */
5743 static void
5744termcap_mode_start(void)
5745{
5746 DWORD cmodein;
5747
5748 if (g_fTermcapMode)
5749 return;
5750
5751 SaveConsoleBuffer(&g_cbNonTermcap);
5752
5753 if (g_cbTermcap.IsValid)
5754 {
5755 /*
5756 * We've been in termcap mode before. Restore certain screen
5757 * characteristics, including the buffer size and the window
5758 * size. Since we will be redrawing the screen, we don't need
5759 * to restore the actual contents of the buffer.
5760 */
5761 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005762 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005763 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5764 Rows = g_cbTermcap.Info.dwSize.Y;
5765 Columns = g_cbTermcap.Info.dwSize.X;
5766 }
5767 else
5768 {
5769 /*
5770 * This is our first time entering termcap mode. Clear the console
5771 * screen buffer, and resize the buffer to match the current window
5772 * size. We will use this as the size of our editing environment.
5773 */
5774 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005775 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005776 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5777 }
5778
5779#ifdef FEAT_TITLE
5780 resettitle();
5781#endif
5782
5783 GetConsoleMode(g_hConIn, &cmodein);
5784#ifdef FEAT_MOUSE
5785 if (g_fMouseActive)
5786 cmodein |= ENABLE_MOUSE_INPUT;
5787 else
5788 cmodein &= ~ENABLE_MOUSE_INPUT;
5789#endif
5790 cmodein |= ENABLE_WINDOW_INPUT;
5791 SetConsoleMode(g_hConIn, cmodein);
5792
5793 redraw_later_clear();
5794 g_fTermcapMode = TRUE;
5795}
5796
5797
5798/*
5799 * End termcap mode
5800 */
5801 static void
5802termcap_mode_end(void)
5803{
5804 DWORD cmodein;
5805 ConsoleBuffer *cb;
5806 COORD coord;
5807 DWORD dwDummy;
5808
5809 if (!g_fTermcapMode)
5810 return;
5811
5812 SaveConsoleBuffer(&g_cbTermcap);
5813
5814 GetConsoleMode(g_hConIn, &cmodein);
5815 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5816 SetConsoleMode(g_hConIn, cmodein);
5817
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005818#ifdef FEAT_RESTORE_ORIG_SCREEN
5819 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5820#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005821 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005822#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005823 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005824 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005825 SetConsoleCursorInfo(g_hConOut, &g_cci);
5826
5827 if (p_rs || exiting)
5828 {
5829 /*
5830 * Clear anything that happens to be on the current line.
5831 */
5832 coord.X = 0;
5833 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5834 FillConsoleOutputCharacter(g_hConOut, ' ',
5835 cb->Info.dwSize.X, coord, &dwDummy);
5836 /*
5837 * The following is just for aesthetics. If we are exiting without
5838 * restoring the screen, then we want to have a prompt string
5839 * appear at the bottom line. However, the command interpreter
5840 * seems to always advance the cursor one line before displaying
5841 * the prompt string, which causes the screen to scroll. To
5842 * counter this, move the cursor up one line before exiting.
5843 */
5844 if (exiting && !p_rs)
5845 coord.Y--;
5846 /*
5847 * Position the cursor at the leftmost column of the desired row.
5848 */
5849 SetConsoleCursorPosition(g_hConOut, coord);
5850 }
5851
5852 g_fTermcapMode = FALSE;
5853}
Bram Moolenaar4f974752019-02-17 17:44:42 +01005854#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005855
5856
Bram Moolenaar4f974752019-02-17 17:44:42 +01005857#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005858 void
5859mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005860 char_u *s UNUSED,
5861 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005862{
5863 /* never used */
5864}
5865
5866#else
5867
5868/*
5869 * clear `n' chars, starting from `coord'
5870 */
5871 static void
5872clear_chars(
5873 COORD coord,
5874 DWORD n)
5875{
5876 DWORD dwDummy;
5877
5878 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005879
5880 if (!USE_VTP)
5881 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5882 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005883 {
5884 set_console_color_rgb();
5885 gotoxy(coord.X + 1, coord.Y + 1);
5886 vtp_printf("\033[%dX", n);
5887 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005888}
5889
5890
5891/*
5892 * Clear the screen
5893 */
5894 static void
5895clear_screen(void)
5896{
5897 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005898
5899 if (!USE_VTP)
5900 clear_chars(g_coord, Rows * Columns);
5901 else
5902 {
5903 set_console_color_rgb();
5904 gotoxy(1, 1);
5905 vtp_printf("\033[2J");
5906 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005907}
5908
5909
5910/*
5911 * Clear to end of display
5912 */
5913 static void
5914clear_to_end_of_display(void)
5915{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005916 COORD save = g_coord;
5917
5918 if (!USE_VTP)
5919 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005920 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005921 else
5922 {
5923 set_console_color_rgb();
5924 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5925 vtp_printf("\033[0J");
5926
5927 gotoxy(save.X + 1, save.Y + 1);
5928 g_coord = save;
5929 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005930}
5931
5932
5933/*
5934 * Clear to end of line
5935 */
5936 static void
5937clear_to_end_of_line(void)
5938{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005939 COORD save = g_coord;
5940
5941 if (!USE_VTP)
5942 clear_chars(g_coord, Columns - g_coord.X);
5943 else
5944 {
5945 set_console_color_rgb();
5946 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5947 vtp_printf("\033[0K");
5948
5949 gotoxy(save.X + 1, save.Y + 1);
5950 g_coord = save;
5951 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005952}
5953
5954
5955/*
5956 * Scroll the scroll region up by `cLines' lines
5957 */
5958 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005959scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005960{
5961 COORD oldcoord = g_coord;
5962
5963 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5964 delete_lines(cLines);
5965
5966 g_coord = oldcoord;
5967}
5968
5969
5970/*
5971 * Set the scroll region
5972 */
5973 static void
5974set_scroll_region(
5975 unsigned left,
5976 unsigned top,
5977 unsigned right,
5978 unsigned bottom)
5979{
5980 if (left >= right
5981 || top >= bottom
5982 || right > (unsigned) Columns - 1
5983 || bottom > (unsigned) Rows - 1)
5984 return;
5985
5986 g_srScrollRegion.Left = left;
5987 g_srScrollRegion.Top = top;
5988 g_srScrollRegion.Right = right;
5989 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005990}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005991
Bram Moolenaar6982f422019-02-16 16:48:01 +01005992 static void
5993set_scroll_region_tb(
5994 unsigned top,
5995 unsigned bottom)
5996{
5997 if (top >= bottom || bottom > (unsigned)Rows - 1)
5998 return;
5999
6000 g_srScrollRegion.Top = top;
6001 g_srScrollRegion.Bottom = bottom;
6002}
6003
6004 static void
6005set_scroll_region_lr(
6006 unsigned left,
6007 unsigned right)
6008{
6009 if (left >= right || right > (unsigned)Columns - 1)
6010 return;
6011
6012 g_srScrollRegion.Left = left;
6013 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006014}
6015
6016
6017/*
6018 * Insert `cLines' lines at the current cursor position
6019 */
6020 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006021insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006022{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006023 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006024 COORD dest;
6025 CHAR_INFO fill;
6026
Bram Moolenaar6982f422019-02-16 16:48:01 +01006027 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006028 dest.Y = g_coord.Y + cLines;
6029
Bram Moolenaar6982f422019-02-16 16:48:01 +01006030 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006031 source.Top = g_coord.Y;
6032 source.Right = g_srScrollRegion.Right;
6033 source.Bottom = g_srScrollRegion.Bottom - cLines;
6034
Bram Moolenaar6982f422019-02-16 16:48:01 +01006035 clip.Left = g_srScrollRegion.Left;
6036 clip.Top = g_coord.Y;
6037 clip.Right = g_srScrollRegion.Right;
6038 clip.Bottom = g_srScrollRegion.Bottom;
6039
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006040 {
6041 fill.Char.AsciiChar = ' ';
Bram Moolenaar21edde82019-02-17 14:10:56 +01006042 if (!USE_VTP)
6043 fill.Attributes = g_attrCurrent;
6044 else
6045 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006046
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006047 set_console_color_rgb();
6048
Bram Moolenaar6982f422019-02-16 16:48:01 +01006049 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006050 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006051 // Here we have to deal with a win32 console flake: If the scroll
6052 // region looks like abc and we scroll c to a and fill with d we get
6053 // cbd... if we scroll block c one line at a time to a, we get cdd...
6054 // vim expects cdd consistently... So we have to deal with that
6055 // here... (this also occurs scrolling the same way in the other
6056 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006057
6058 if (source.Bottom < dest.Y)
6059 {
6060 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006061 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006062
Bram Moolenaar6982f422019-02-16 16:48:01 +01006063 coord.X = source.Left;
6064 for (i = clip.Top; i < dest.Y; ++i)
6065 {
6066 coord.Y = i;
6067 clear_chars(coord, source.Right - source.Left + 1);
6068 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006069 }
6070}
6071
6072
6073/*
6074 * Delete `cLines' lines at the current cursor position
6075 */
6076 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006077delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006078{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006079 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006080 COORD dest;
6081 CHAR_INFO fill;
6082 int nb;
6083
Bram Moolenaar6982f422019-02-16 16:48:01 +01006084 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006085 dest.Y = g_coord.Y;
6086
Bram Moolenaar6982f422019-02-16 16:48:01 +01006087 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006088 source.Top = g_coord.Y + cLines;
6089 source.Right = g_srScrollRegion.Right;
6090 source.Bottom = g_srScrollRegion.Bottom;
6091
Bram Moolenaar6982f422019-02-16 16:48:01 +01006092 clip.Left = g_srScrollRegion.Left;
6093 clip.Top = g_coord.Y;
6094 clip.Right = g_srScrollRegion.Right;
6095 clip.Bottom = g_srScrollRegion.Bottom;
6096
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006097 {
6098 fill.Char.AsciiChar = ' ';
Bram Moolenaar21edde82019-02-17 14:10:56 +01006099 if (!USE_VTP)
6100 fill.Attributes = g_attrCurrent;
6101 else
6102 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006103
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006104 set_console_color_rgb();
6105
Bram Moolenaar6982f422019-02-16 16:48:01 +01006106 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006107 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006108 // Here we have to deal with a win32 console flake; See insert_lines()
6109 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006110
6111 nb = dest.Y + (source.Bottom - source.Top) + 1;
6112
6113 if (nb < source.Top)
6114 {
6115 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006116 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006117
Bram Moolenaar6982f422019-02-16 16:48:01 +01006118 coord.X = source.Left;
6119 for (i = nb; i < clip.Bottom; ++i)
6120 {
6121 coord.Y = i;
6122 clear_chars(coord, source.Right - source.Left + 1);
6123 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006124 }
6125}
6126
6127
6128/*
6129 * Set the cursor position
6130 */
6131 static void
6132gotoxy(
6133 unsigned x,
6134 unsigned y)
6135{
6136 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6137 return;
6138
6139 /* external cursor coords are 1-based; internal are 0-based */
6140 g_coord.X = x - 1;
6141 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006142
6143 if (!USE_VTP)
6144 SetConsoleCursorPosition(g_hConOut, g_coord);
6145 else
6146 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006147}
6148
6149
6150/*
6151 * Set the current text attribute = (foreground | background)
6152 * See ../doc/os_win32.txt for the numbers.
6153 */
6154 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006155textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006156{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006157 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006158
6159 SetConsoleTextAttribute(g_hConOut, wAttr);
6160}
6161
6162
6163 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006164textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006165{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006166 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006167
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006168 if (!USE_VTP)
6169 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6170 else
6171 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006172}
6173
6174
6175 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006176textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006177{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006178 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006179
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006180 if (!USE_VTP)
6181 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6182 else
6183 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006184}
6185
6186
6187/*
6188 * restore the default text attribute (whatever we started with)
6189 */
6190 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006191normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006192{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006193 if (!USE_VTP)
6194 textattr(g_attrDefault);
6195 else
6196 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006197}
6198
6199
6200static WORD g_attrPreStandout = 0;
6201
6202/*
6203 * Make the text standout, by brightening it
6204 */
6205 static void
6206standout(void)
6207{
6208 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006209
Bram Moolenaar071d4272004-06-13 20:20:40 +00006210 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6211}
6212
6213
6214/*
6215 * Turn off standout mode
6216 */
6217 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006218standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006219{
6220 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006221 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006222
6223 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006224}
6225
6226
6227/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006228 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006229 */
6230 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006231mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006232{
6233 char_u *p;
6234 int n;
6235
6236 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6237 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006238 if (
6239#ifdef FEAT_TERMGUICOLORS
6240 !p_tgc &&
6241#endif
6242 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006243 {
6244 p = T_ME + 2;
6245 n = getdigits(&p);
6246 if (*p == 'm' && n > 0)
6247 {
6248 cterm_normal_fg_color = (n & 0xf) + 1;
6249 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6250 }
6251 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006252#ifdef FEAT_TERMGUICOLORS
6253 cterm_normal_fg_gui_color = INVALCOLOR;
6254 cterm_normal_bg_gui_color = INVALCOLOR;
6255#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006256}
6257
6258
6259/*
6260 * visual bell: flash the screen
6261 */
6262 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006263visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006264{
6265 COORD coordOrigin = {0, 0};
6266 WORD attrFlash = ~g_attrCurrent & 0xff;
6267
6268 DWORD dwDummy;
6269 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
6270
6271 if (oldattrs == NULL)
6272 return;
6273 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6274 coordOrigin, &dwDummy);
6275 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6276 coordOrigin, &dwDummy);
6277
6278 Sleep(15); /* wait for 15 msec */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006279 if (!USE_VTP)
6280 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006281 coordOrigin, &dwDummy);
6282 vim_free(oldattrs);
6283}
6284
6285
6286/*
6287 * Make the cursor visible or invisible
6288 */
6289 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006290cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006291{
6292 s_cursor_visible = fVisible;
6293#ifdef MCH_CURSOR_SHAPE
6294 mch_update_cursor();
6295#endif
6296}
6297
6298
6299/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006300 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006301 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006302 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006303 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006304write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006305 char_u *pchBuf,
6306 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006307{
6308 COORD coord = g_coord;
6309 DWORD written;
6310
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006311 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6312 {
6313 static WCHAR *unicodebuf = NULL;
6314 static int unibuflen = 0;
6315 int length;
6316 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006317
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006318 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
6319 if (unicodebuf == NULL || length > unibuflen)
6320 {
6321 vim_free(unicodebuf);
6322 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
6323 unibuflen = length;
6324 }
6325 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
6326 unicodebuf, unibuflen);
6327
6328 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006329
6330 if (!USE_VTP)
6331 {
6332 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6333 coord, &written);
6334 /* When writing fails or didn't write a single character, pretend one
6335 * character was written, otherwise we get stuck. */
6336 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
6337 coord, &cchwritten) == 0
Bram Moolenaar78d21da2019-02-17 15:00:52 +01006338 || cchwritten == 0 || cchwritten == (DWORD)-1)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006339 cchwritten = 1;
6340 }
6341 else
6342 {
6343 if (WriteConsoleW(g_hConOut, unicodebuf, length, &cchwritten,
6344 NULL) == 0 || cchwritten == 0)
6345 cchwritten = 1;
6346 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006347
6348 if (cchwritten == length)
6349 {
6350 written = cbToWrite;
6351 g_coord.X += (SHORT)cells;
6352 }
6353 else
6354 {
6355 char_u *p = pchBuf;
6356 for (n = 0; n < cchwritten; n++)
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006357 MB_CPTR_ADV(p);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006358 written = p - pchBuf;
6359 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
6360 }
6361 }
6362 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006363 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006364 if (!USE_VTP)
6365 {
6366 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
6367 coord, &written);
6368 /* When writing fails or didn't write a single character, pretend one
6369 * character was written, otherwise we get stuck. */
6370 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
6371 coord, &written) == 0
Bram Moolenaar78d21da2019-02-17 15:00:52 +01006372 || written == 0 || written == (DWORD)-1)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006373 written = 1;
6374 }
6375 else
6376 {
6377 if (WriteConsole(g_hConOut, (LPCSTR)pchBuf, cbToWrite, &written,
6378 NULL) == 0 || written == 0)
6379 written = 1;
6380 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006381
6382 g_coord.X += (SHORT) written;
6383 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006384
6385 while (g_coord.X > g_srScrollRegion.Right)
6386 {
6387 g_coord.X -= (SHORT) Columns;
6388 if (g_coord.Y < g_srScrollRegion.Bottom)
6389 g_coord.Y++;
6390 }
6391
6392 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6393
6394 return written;
6395}
6396
6397
6398/*
6399 * mch_write(): write the output buffer to the screen, translating ESC
6400 * sequences into calls to console output routines.
6401 */
6402 void
6403mch_write(
6404 char_u *s,
6405 int len)
6406{
6407 s[len] = NUL;
6408
6409 if (!term_console)
6410 {
6411 write(1, s, (unsigned)len);
6412 return;
6413 }
6414
6415 /* translate ESC | sequences into faked bios calls */
6416 while (len--)
6417 {
6418 /* optimization: use one single write_chars for runs of text,
6419 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006420 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006421
6422 if (p_wd)
6423 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006424 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006425 if (prefix != 0)
6426 prefix = 1;
6427 }
6428
6429 if (prefix != 0)
6430 {
6431 DWORD nWritten;
6432
6433 nWritten = write_chars(s, prefix);
6434#ifdef MCH_WRITE_DUMP
6435 if (fdDump)
6436 {
6437 fputc('>', fdDump);
6438 fwrite(s, sizeof(char_u), nWritten, fdDump);
6439 fputs("<\n", fdDump);
6440 }
6441#endif
6442 len -= (nWritten - 1);
6443 s += nWritten;
6444 }
6445 else if (s[0] == '\n')
6446 {
6447 /* \n, newline: go to the beginning of the next line or scroll */
6448 if (g_coord.Y == g_srScrollRegion.Bottom)
6449 {
6450 scroll(1);
6451 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6452 }
6453 else
6454 {
6455 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6456 }
6457#ifdef MCH_WRITE_DUMP
6458 if (fdDump)
6459 fputs("\\n\n", fdDump);
6460#endif
6461 s++;
6462 }
6463 else if (s[0] == '\r')
6464 {
6465 /* \r, carriage return: go to beginning of line */
6466 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
6467#ifdef MCH_WRITE_DUMP
6468 if (fdDump)
6469 fputs("\\r\n", fdDump);
6470#endif
6471 s++;
6472 }
6473 else if (s[0] == '\b')
6474 {
6475 /* \b, backspace: move cursor one position left */
6476 if (g_coord.X > g_srScrollRegion.Left)
6477 g_coord.X--;
6478 else if (g_coord.Y > g_srScrollRegion.Top)
6479 {
6480 g_coord.X = g_srScrollRegion.Right;
6481 g_coord.Y--;
6482 }
6483 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6484#ifdef MCH_WRITE_DUMP
6485 if (fdDump)
6486 fputs("\\b\n", fdDump);
6487#endif
6488 s++;
6489 }
6490 else if (s[0] == '\a')
6491 {
6492 /* \a, bell */
6493 MessageBeep(0xFFFFFFFF);
6494#ifdef MCH_WRITE_DUMP
6495 if (fdDump)
6496 fputs("\\a\n", fdDump);
6497#endif
6498 s++;
6499 }
6500 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6501 {
6502#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006503 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006504#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006505 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006506 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006507
6508 switch (s[2])
6509 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006510 case '0': case '1': case '2': case '3': case '4':
6511 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006512 p = s + 1;
6513 do
6514 {
6515 ++p;
6516 args[argc] = getdigits(&p);
6517 argc += (argc < 15) ? 1 : 0;
6518 if (p > s + len)
6519 break;
6520 } while (*p == ';');
6521
Bram Moolenaar071d4272004-06-13 20:20:40 +00006522 if (p > s + len)
6523 break;
6524
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006525 arg1 = args[0];
6526 arg2 = args[1];
6527 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006528 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006529 if (argc == 1 && args[0] == 0)
6530 normvideo();
6531 else if (argc == 1)
6532 {
6533 if (USE_VTP)
6534 textcolor((WORD) arg1);
6535 else
6536 textattr((WORD) arg1);
6537 }
6538 else if (USE_VTP)
6539 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006540 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006541 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006542 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006543 gotoxy(arg2, arg1);
6544 }
6545 else if (argc == 2 && *p == 'r')
6546 {
6547 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6548 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006549 else if (argc == 2 && *p == 'R')
6550 {
6551 set_scroll_region_tb(arg1, arg2);
6552 }
6553 else if (argc == 2 && *p == 'V')
6554 {
6555 set_scroll_region_lr(arg1, arg2);
6556 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006557 else if (argc == 1 && *p == 'A')
6558 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006559 gotoxy(g_coord.X + 1,
6560 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6561 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006562 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006563 {
6564 textbackground((WORD) arg1);
6565 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006566 else if (argc == 1 && *p == 'C')
6567 {
6568 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6569 g_coord.Y + 1);
6570 }
6571 else if (argc == 1 && *p == 'f')
6572 {
6573 textcolor((WORD) arg1);
6574 }
6575 else if (argc == 1 && *p == 'H')
6576 {
6577 gotoxy(1, arg1);
6578 }
6579 else if (argc == 1 && *p == 'L')
6580 {
6581 insert_lines(arg1);
6582 }
6583 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006584 {
6585 delete_lines(arg1);
6586 }
6587
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006588 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006589 s = p + 1;
6590 break;
6591
Bram Moolenaar071d4272004-06-13 20:20:40 +00006592 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006593 gotoxy(g_coord.X + 1,
6594 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6595 goto got3;
6596
6597 case 'B':
6598 visual_bell();
6599 goto got3;
6600
6601 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006602 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6603 g_coord.Y + 1);
6604 goto got3;
6605
6606 case 'E':
6607 termcap_mode_end();
6608 goto got3;
6609
6610 case 'F':
6611 standout();
6612 goto got3;
6613
6614 case 'f':
6615 standend();
6616 goto got3;
6617
6618 case 'H':
6619 gotoxy(1, 1);
6620 goto got3;
6621
6622 case 'j':
6623 clear_to_end_of_display();
6624 goto got3;
6625
6626 case 'J':
6627 clear_screen();
6628 goto got3;
6629
6630 case 'K':
6631 clear_to_end_of_line();
6632 goto got3;
6633
6634 case 'L':
6635 insert_lines(1);
6636 goto got3;
6637
6638 case 'M':
6639 delete_lines(1);
6640 goto got3;
6641
6642 case 'S':
6643 termcap_mode_start();
6644 goto got3;
6645
6646 case 'V':
6647 cursor_visible(TRUE);
6648 goto got3;
6649
6650 case 'v':
6651 cursor_visible(FALSE);
6652 goto got3;
6653
6654 got3:
6655 s += 3;
6656 len -= 2;
6657 }
6658
6659#ifdef MCH_WRITE_DUMP
6660 if (fdDump)
6661 {
6662 fputs("ESC | ", fdDump);
6663 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6664 fputc('\n', fdDump);
6665 }
6666#endif
6667 }
6668 else
6669 {
6670 /* Write a single character */
6671 DWORD nWritten;
6672
6673 nWritten = write_chars(s, 1);
6674#ifdef MCH_WRITE_DUMP
6675 if (fdDump)
6676 {
6677 fputc('>', fdDump);
6678 fwrite(s, sizeof(char_u), nWritten, fdDump);
6679 fputs("<\n", fdDump);
6680 }
6681#endif
6682
6683 len -= (nWritten - 1);
6684 s += nWritten;
6685 }
6686 }
6687
6688#ifdef MCH_WRITE_DUMP
6689 if (fdDump)
6690 fflush(fdDump);
6691#endif
6692}
6693
Bram Moolenaar4f974752019-02-17 17:44:42 +01006694#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006695
6696
6697/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006698 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006699 */
6700 void
6701mch_delay(
6702 long msec,
Bram Moolenaar1266d672017-02-01 13:43:36 +01006703 int ignoreinput UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006704{
Bram Moolenaar4f974752019-02-17 17:44:42 +01006705#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006706 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006707#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006708 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006709# ifdef FEAT_MZSCHEME
6710 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6711 {
6712 int towait = p_mzq;
6713
6714 /* if msec is large enough, wait by portions in p_mzq */
6715 while (msec > 0)
6716 {
6717 mzvim_check_threads();
6718 if (msec < towait)
6719 towait = msec;
6720 Sleep(towait);
6721 msec -= towait;
6722 }
6723 }
6724 else
6725# endif
6726 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006727 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006728 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006729#endif
6730}
6731
6732
6733/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006734 * This version of remove is not scared by a readonly (backup) file.
6735 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006736 * Return 0 for success, -1 for failure.
6737 */
6738 int
6739mch_remove(char_u *name)
6740{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006741 WCHAR *wn = NULL;
6742 int n;
6743
Bram Moolenaar203258c2016-01-17 22:15:16 +01006744 /*
6745 * On Windows, deleting a directory's symbolic link is done by
6746 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6747 */
6748 if (mch_isdir(name) && mch_is_symbolic_link(name))
6749 return mch_rmdir(name);
6750
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006751 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6752
Bram Moolenaar071d4272004-06-13 20:20:40 +00006753 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6754 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006755 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006756 if (wn != NULL)
6757 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006758 n = DeleteFileW(wn) ? 0 : -1;
6759 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006760 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006761 }
6762 }
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006763 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006764}
6765
6766
6767/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006768 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006769 */
6770 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006771mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006772{
Bram Moolenaar4f974752019-02-17 17:44:42 +01006773#ifndef FEAT_GUI_MSWIN /* never used */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006774 if (g_fCtrlCPressed || g_fCBrkPressed)
6775 {
Bram Moolenaar9698ad72017-08-12 14:52:15 +02006776 ctrl_break_was_pressed = g_fCBrkPressed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006777 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6778 got_int = TRUE;
6779 }
6780#endif
6781}
6782
Bram Moolenaaree273972016-01-02 21:11:51 +01006783/* physical RAM to leave for the OS */
6784#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006785
6786/*
6787 * How much main memory in KiB that can be used by VIM.
6788 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006789 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006790mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006791{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006792 MEMORYSTATUSEX ms;
6793
Bram Moolenaaree273972016-01-02 21:11:51 +01006794 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006795 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6796 * what fits in 32 bits. But it's not always available. */
6797 ms.dwLength = sizeof(MEMORYSTATUSEX);
6798 GlobalMemoryStatusEx(&ms);
6799 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006800 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006801 /* Process address space fits in physical RAM, use all of it. */
6802 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006803 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006804 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006805 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006806 /* Catch old NT box or perverse hardware setup. */
6807 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006808 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006809 /* Use physical RAM less reserve for OS + data. */
6810 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006811}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006812
Bram Moolenaar071d4272004-06-13 20:20:40 +00006813/*
6814 * Same code as below, but with wide functions and no comments.
6815 * Return 0 for success, non-zero for failure.
6816 */
6817 int
6818mch_wrename(WCHAR *wold, WCHAR *wnew)
6819{
6820 WCHAR *p;
6821 int i;
6822 WCHAR szTempFile[_MAX_PATH + 1];
6823 WCHAR szNewPath[_MAX_PATH + 1];
6824 HANDLE hf;
6825
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006826 p = wold;
6827 for (i = 0; wold[i] != NUL; ++i)
6828 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6829 && wold[i + 1] != 0)
6830 p = wold + i + 1;
6831 if ((int)(wold + i - p) < 8 || p[6] != '~')
6832 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006833
6834 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6835 return -1;
6836 *p = NUL;
6837
6838 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6839 return -2;
6840
6841 if (!DeleteFileW(szTempFile))
6842 return -3;
6843
6844 if (!MoveFileW(wold, szTempFile))
6845 return -4;
6846
6847 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6848 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6849 return -5;
6850 if (!CloseHandle(hf))
6851 return -6;
6852
6853 if (!MoveFileW(szTempFile, wnew))
6854 {
6855 (void)MoveFileW(szTempFile, wold);
6856 return -7;
6857 }
6858
6859 DeleteFileW(szTempFile);
6860
6861 if (!DeleteFileW(wold))
6862 return -8;
6863
6864 return 0;
6865}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006866
6867
6868/*
6869 * mch_rename() works around a bug in rename (aka MoveFile) in
6870 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6871 * file whose short file name is "FOO.BAR" (its long file name will
6872 * be correct: "foo.bar~"). Because a file can be accessed by
6873 * either its SFN or its LFN, "foo.bar" has effectively been
6874 * renamed to "foo.bar", which is not at all what was wanted. This
6875 * seems to happen only when renaming files with three-character
6876 * extensions by appending a suffix that does not include ".".
6877 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6878 *
6879 * There is another problem, which isn't really a bug but isn't right either:
6880 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6881 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6882 * service pack 6. Doesn't seem to happen on Windows 98.
6883 *
6884 * Like rename(), returns 0 upon success, non-zero upon failure.
6885 * Should probably set errno appropriately when errors occur.
6886 */
6887 int
6888mch_rename(
6889 const char *pszOldFile,
6890 const char *pszNewFile)
6891{
6892 char szTempFile[_MAX_PATH+1];
6893 char szNewPath[_MAX_PATH+1];
6894 char *pszFilePart;
6895 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006896 WCHAR *wold = NULL;
6897 WCHAR *wnew = NULL;
6898 int retval = -1;
6899
6900 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6901 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006902 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6903 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006904 if (wold != NULL && wnew != NULL)
6905 retval = mch_wrename(wold, wnew);
6906 vim_free(wold);
6907 vim_free(wnew);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006908 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006909 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006910
6911 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006912 * No need to play tricks unless the file name contains a "~" as the
6913 * seventh character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006914 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006915 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6916 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6917 return rename(pszOldFile, pszNewFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006918
6919 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6920 * a directory, no error is returned and pszFilePart will be NULL. */
6921 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6922 || pszFilePart == NULL)
6923 return -1;
6924 *pszFilePart = NUL;
6925
6926 /* Get (and create) a unique temporary file name in directory of new file */
6927 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6928 return -2;
6929
6930 /* blow the temp file away */
6931 if (!DeleteFile(szTempFile))
6932 return -3;
6933
6934 /* rename old file to the temp file */
6935 if (!MoveFile(pszOldFile, szTempFile))
6936 return -4;
6937
6938 /* now create an empty file called pszOldFile; this prevents the operating
6939 * system using pszOldFile as an alias (SFN) if we're renaming within the
6940 * same directory. For example, we're editing a file called
6941 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6942 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6943 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006944 * cause all sorts of problems later in buf_write(). So, we create an
6945 * empty file called filena~1.txt and the system will have to find some
6946 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006947 */
6948 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6949 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6950 return -5;
6951 if (!CloseHandle(hf))
6952 return -6;
6953
6954 /* rename the temp file to the new file */
6955 if (!MoveFile(szTempFile, pszNewFile))
6956 {
6957 /* Renaming failed. Rename the file back to its old name, so that it
6958 * looks like nothing happened. */
6959 (void)MoveFile(szTempFile, pszOldFile);
6960
6961 return -7;
6962 }
6963
6964 /* Seems to be left around on Novell filesystems */
6965 DeleteFile(szTempFile);
6966
6967 /* finally, remove the empty old file */
6968 if (!DeleteFile(pszOldFile))
6969 return -8;
6970
6971 return 0; /* success */
6972}
6973
6974/*
6975 * Get the default shell for the current hardware platform
6976 */
6977 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006978default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006979{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006980 PlatformId();
6981
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006982 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006983}
6984
6985/*
6986 * mch_access() extends access() to do more detailed check on network drives.
6987 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6988 */
6989 int
6990mch_access(char *n, int p)
6991{
6992 HANDLE hFile;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006993 int retval = -1; /* default: fail */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006994 WCHAR *wn = NULL;
6995
6996 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006997 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006998
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006999 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007000 {
7001 char TempName[_MAX_PATH + 16] = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007002 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007003
7004 if (p & R_OK)
7005 {
7006 /* Read check is performed by seeing if we can do a find file on
7007 * the directory for any file. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007008 if (wn != NULL)
7009 {
7010 int i;
7011 WIN32_FIND_DATAW d;
7012
7013 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7014 TempNameW[i] = wn[i];
7015 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7016 TempNameW[i++] = '\\';
7017 TempNameW[i++] = '*';
7018 TempNameW[i++] = 0;
7019
7020 hFile = FindFirstFileW(TempNameW, &d);
7021 if (hFile == INVALID_HANDLE_VALUE)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007022 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007023 else
7024 (void)FindClose(hFile);
7025 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007026 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007027 {
7028 char *pch;
7029 WIN32_FIND_DATA d;
7030
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007031 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007032 pch = TempName + STRLEN(TempName) - 1;
7033 if (*pch != '\\' && *pch != '/')
7034 *++pch = '\\';
7035 *++pch = '*';
7036 *++pch = NUL;
7037
7038 hFile = FindFirstFile(TempName, &d);
7039 if (hFile == INVALID_HANDLE_VALUE)
7040 goto getout;
7041 (void)FindClose(hFile);
7042 }
7043 }
7044
7045 if (p & W_OK)
7046 {
7047 /* Trying to create a temporary file in the directory should catch
7048 * directories on read-only network shares. However, in
7049 * directories whose ACL allows writes but denies deletes will end
7050 * up keeping the temporary file :-(. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007051 if (wn != NULL)
7052 {
7053 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007054 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007055 else
7056 DeleteFileW(TempNameW);
7057 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007058 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007059 {
7060 if (!GetTempFileName(n, "VIM", 0, TempName))
7061 goto getout;
7062 mch_remove((char_u *)TempName);
7063 }
7064 }
7065 }
7066 else
7067 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007068 // Don't consider a file read-only if another process has opened it.
7069 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7070
Bram Moolenaar071d4272004-06-13 20:20:40 +00007071 /* Trying to open the file for the required access does ACL, read-only
7072 * network share, and file attribute checks. */
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007073 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7074 | ((p & R_OK) ? GENERIC_READ : 0);
7075
Bram Moolenaar071d4272004-06-13 20:20:40 +00007076 if (wn != NULL)
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007077 hFile = CreateFileW(wn, access_mode, share_mode,
7078 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007079 else
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007080 hFile = CreateFile(n, access_mode, share_mode,
7081 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007082 if (hFile == INVALID_HANDLE_VALUE)
7083 goto getout;
7084 CloseHandle(hFile);
7085 }
7086
7087 retval = 0; /* success */
7088getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007089 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007090 return retval;
7091}
7092
Bram Moolenaar071d4272004-06-13 20:20:40 +00007093/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007094 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007095 */
7096 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007097mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007098{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007099 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
Bram Moolenaara12a1612019-01-24 16:39:02 +01007100#ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00007101 WCHAR *wn;
7102 int f;
7103
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007104 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007105 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007106 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007107 if (wn != NULL)
7108 {
7109 f = _wopen(wn, flags, mode);
7110 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007111 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007112 }
7113 }
Bram Moolenaara12a1612019-01-24 16:39:02 +01007114#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007115
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01007116 /* open() can open a file which name is longer than _MAX_PATH bytes
7117 * and shorter than _MAX_PATH characters successfully, but sometimes it
7118 * causes unexpected error in another part. We make it an error explicitly
7119 * here. */
7120 if (strlen(name) >= _MAX_PATH)
7121 return -1;
7122
Bram Moolenaar071d4272004-06-13 20:20:40 +00007123 return open(name, flags, mode);
7124}
7125
7126/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007127 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007128 */
7129 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007130mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007131{
7132 WCHAR *wn, *wm;
7133 FILE *f = NULL;
7134
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007135 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007136 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01007137#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007138 /* Work around an annoying assertion in the Microsoft debug CRT
7139 * when mode's text/binary setting doesn't match _get_fmode(). */
7140 char newMode = mode[strlen(mode) - 1];
7141 int oldMode = 0;
7142
7143 _get_fmode(&oldMode);
7144 if (newMode == 't')
7145 _set_fmode(_O_TEXT);
7146 else if (newMode == 'b')
7147 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007148#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007149 wn = enc_to_utf16((char_u *)name, NULL);
7150 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007151 if (wn != NULL && wm != NULL)
7152 f = _wfopen(wn, wm);
7153 vim_free(wn);
7154 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007155
Bram Moolenaara12a1612019-01-24 16:39:02 +01007156#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007157 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007158#endif
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007159 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007160 }
7161
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01007162 /* fopen() can open a file which name is longer than _MAX_PATH bytes
7163 * and shorter than _MAX_PATH characters successfully, but sometimes it
7164 * causes unexpected error in another part. We make it an error explicitly
7165 * here. */
7166 if (strlen(name) >= _MAX_PATH)
7167 return NULL;
7168
Bram Moolenaar071d4272004-06-13 20:20:40 +00007169 return fopen(name, mode);
7170}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007171
Bram Moolenaar071d4272004-06-13 20:20:40 +00007172/*
7173 * SUB STREAM (aka info stream) handling:
7174 *
7175 * NTFS can have sub streams for each file. Normal contents of file is
7176 * stored in the main stream, and extra contents (author information and
7177 * title and so on) can be stored in sub stream. After Windows 2000, user
7178 * can access and store those informations in sub streams via explorer's
7179 * property menuitem in right click menu. Those informations in sub streams
7180 * were lost when copying only the main stream. So we have to copy sub
7181 * streams.
7182 *
7183 * Incomplete explanation:
7184 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7185 * More useful info and an example:
7186 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7187 */
7188
7189/*
7190 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7191 * and write to stream "substream" of file "to".
7192 * Errors are ignored.
7193 */
7194 static void
7195copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7196{
7197 HANDLE hTo;
7198 WCHAR *to_name;
7199
7200 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7201 wcscpy(to_name, to);
7202 wcscat(to_name, substream);
7203
7204 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7205 FILE_ATTRIBUTE_NORMAL, NULL);
7206 if (hTo != INVALID_HANDLE_VALUE)
7207 {
7208 long done;
7209 DWORD todo;
7210 DWORD readcnt, written;
7211 char buf[4096];
7212
7213 /* Copy block of bytes at a time. Abort when something goes wrong. */
7214 for (done = 0; done < len; done += written)
7215 {
7216 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007217 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7218 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007219 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7220 FALSE, FALSE, context)
7221 || readcnt != todo
7222 || !WriteFile(hTo, buf, todo, &written, NULL)
7223 || written != todo)
7224 break;
7225 }
7226 CloseHandle(hTo);
7227 }
7228
7229 free(to_name);
7230}
7231
7232/*
7233 * Copy info streams from file "from" to file "to".
7234 */
7235 static void
7236copy_infostreams(char_u *from, char_u *to)
7237{
7238 WCHAR *fromw;
7239 WCHAR *tow;
7240 HANDLE sh;
7241 WIN32_STREAM_ID sid;
7242 int headersize;
7243 WCHAR streamname[_MAX_PATH];
7244 DWORD readcount;
7245 void *context = NULL;
7246 DWORD lo, hi;
7247 int len;
7248
7249 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007250 fromw = enc_to_utf16(from, NULL);
7251 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007252 if (fromw != NULL && tow != NULL)
7253 {
7254 /* Open the file for reading. */
7255 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7256 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7257 if (sh != INVALID_HANDLE_VALUE)
7258 {
7259 /* Use BackupRead() to find the info streams. Repeat until we
7260 * have done them all.*/
7261 for (;;)
7262 {
7263 /* Get the header to find the length of the stream name. If
7264 * the "readcount" is zero we have done all info streams. */
7265 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007266 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007267 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7268 &readcount, FALSE, FALSE, &context)
7269 || readcount == 0)
7270 break;
7271
7272 /* We only deal with streams that have a name. The normal
7273 * file data appears to be without a name, even though docs
7274 * suggest it is called "::$DATA". */
7275 if (sid.dwStreamNameSize > 0)
7276 {
7277 /* Read the stream name. */
7278 if (!BackupRead(sh, (LPBYTE)streamname,
7279 sid.dwStreamNameSize,
7280 &readcount, FALSE, FALSE, &context))
7281 break;
7282
7283 /* Copy an info stream with a name ":anything:$DATA".
7284 * Skip "::$DATA", it has no stream name (examples suggest
7285 * it might be used for the normal file contents).
7286 * Note that BackupRead() counts bytes, but the name is in
7287 * wide characters. */
7288 len = readcount / sizeof(WCHAR);
7289 streamname[len] = 0;
7290 if (len > 7 && wcsicmp(streamname + len - 6,
7291 L":$DATA") == 0)
7292 {
7293 streamname[len - 6] = 0;
7294 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007295 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007296 }
7297 }
7298
7299 /* Advance to the next stream. We might try seeking too far,
7300 * but BackupSeek() doesn't skip over stream borders, thus
7301 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007302 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007303 &lo, &hi, &context);
7304 }
7305
7306 /* Clear the context. */
7307 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7308
7309 CloseHandle(sh);
7310 }
7311 }
7312 vim_free(fromw);
7313 vim_free(tow);
7314}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007315
7316/*
7317 * Copy file attributes from file "from" to file "to".
7318 * For Windows NT and later we copy info streams.
7319 * Always returns zero, errors are ignored.
7320 */
7321 int
7322mch_copy_file_attribute(char_u *from, char_u *to)
7323{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007324 /* File streams only work on Windows NT and later. */
7325 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007326 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007327 return 0;
7328}
7329
7330#if defined(MYRESETSTKOFLW) || defined(PROTO)
7331/*
7332 * Recreate a destroyed stack guard page in win32.
7333 * Written by Benjamin Peterson.
7334 */
7335
7336/* These magic numbers are from the MS header files */
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007337# define MIN_STACK_WINNT 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00007338
7339/*
7340 * This function does the same thing as _resetstkoflw(), which is only
7341 * available in DevStudio .net and later.
7342 * Returns 0 for failure, 1 for success.
7343 */
7344 int
7345myresetstkoflw(void)
7346{
7347 BYTE *pStackPtr;
7348 BYTE *pGuardPage;
7349 BYTE *pStackBase;
7350 BYTE *pLowestPossiblePage;
7351 MEMORY_BASIC_INFORMATION mbi;
7352 SYSTEM_INFO si;
7353 DWORD nPageSize;
7354 DWORD dummy;
7355
Bram Moolenaar071d4272004-06-13 20:20:40 +00007356 PlatformId();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007357
7358 /* We need to know the system page size. */
7359 GetSystemInfo(&si);
7360 nPageSize = si.dwPageSize;
7361
7362 /* ...and the current stack pointer */
7363 pStackPtr = (BYTE*)_alloca(1);
7364
7365 /* ...and the base of the stack. */
7366 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
7367 return 0;
7368 pStackBase = (BYTE*)mbi.AllocationBase;
7369
7370 /* ...and the page thats min_stack_req pages away from stack base; this is
7371 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007372 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007373
Bram Moolenaar071d4272004-06-13 20:20:40 +00007374 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007375 /* We want the first committed page in the stack Start at the stack
7376 * base and move forward through memory until we find a committed block.
7377 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007378 BYTE *pBlock = pStackBase;
7379
Bram Moolenaara466c992005-07-09 21:03:22 +00007380 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007381 {
7382 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
7383 return 0;
7384
7385 pBlock += mbi.RegionSize;
7386
7387 if (mbi.State & MEM_COMMIT)
7388 break;
7389 }
7390
7391 /* mbi now describes the first committed block in the stack. */
7392 if (mbi.Protect & PAGE_GUARD)
7393 return 1;
7394
7395 /* decide where the guard page should start */
7396 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
7397 pGuardPage = pLowestPossiblePage;
7398 else
7399 pGuardPage = (BYTE*)mbi.BaseAddress;
7400
7401 /* allocate the guard page */
7402 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
7403 return 0;
7404
7405 /* apply the guard attribute to the page */
7406 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
7407 &dummy))
7408 return 0;
7409 }
7410
7411 return 1;
7412}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007413#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007414
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007415
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007416/*
7417 * The command line arguments in UCS2
7418 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007419static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007420static LPWSTR *ArglistW = NULL;
7421static int global_argc = 0;
7422static char **global_argv;
7423
7424static int used_file_argc = 0; /* last argument in global_argv[] used
7425 for the argument list. */
7426static int *used_file_indexes = NULL; /* indexes in global_argv[] for
7427 command line arguments added to
7428 the argument list */
7429static int used_file_count = 0; /* nr of entries in used_file_indexes */
7430static int used_file_literal = FALSE; /* take file names literally */
7431static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007432static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007433static int used_alist_count = 0;
7434
7435
7436/*
7437 * Get the command line arguments. Unicode version.
7438 * Returns argc. Zero when something fails.
7439 */
7440 int
7441get_cmd_argsW(char ***argvp)
7442{
7443 char **argv = NULL;
7444 int argc = 0;
7445 int i;
7446
Bram Moolenaar14993322014-09-09 12:25:33 +02007447 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007448 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7449 if (ArglistW != NULL)
7450 {
7451 argv = malloc((nArgsW + 1) * sizeof(char *));
7452 if (argv != NULL)
7453 {
7454 argc = nArgsW;
7455 argv[argc] = NULL;
7456 for (i = 0; i < argc; ++i)
7457 {
7458 int len;
7459
7460 /* Convert each Unicode argument to the current codepage. */
7461 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007462 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007463 (LPSTR *)&argv[i], &len, 0, 0);
7464 if (argv[i] == NULL)
7465 {
7466 /* Out of memory, clear everything. */
7467 while (i > 0)
7468 free(argv[--i]);
7469 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007470 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007471 argc = 0;
7472 }
7473 }
7474 }
7475 }
7476
7477 global_argc = argc;
7478 global_argv = argv;
7479 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007480 {
7481 if (used_file_indexes != NULL)
7482 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007483 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007484 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007485
7486 if (argvp != NULL)
7487 *argvp = argv;
7488 return argc;
7489}
7490
7491 void
7492free_cmd_argsW(void)
7493{
7494 if (ArglistW != NULL)
7495 {
7496 GlobalFree(ArglistW);
7497 ArglistW = NULL;
7498 }
7499}
7500
7501/*
7502 * Remember "name" is an argument that was added to the argument list.
7503 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7504 * is called.
7505 */
7506 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007507used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007508{
7509 int i;
7510
7511 if (used_file_indexes == NULL)
7512 return;
7513 for (i = used_file_argc + 1; i < global_argc; ++i)
7514 if (STRCMP(global_argv[i], name) == 0)
7515 {
7516 used_file_argc = i;
7517 used_file_indexes[used_file_count++] = i;
7518 break;
7519 }
7520 used_file_literal = literal;
7521 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007522 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007523}
7524
7525/*
7526 * Remember the length of the argument list as it was. If it changes then we
7527 * leave it alone when 'encoding' is set.
7528 */
7529 void
7530set_alist_count(void)
7531{
7532 used_alist_count = GARGCOUNT;
7533}
7534
7535/*
7536 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7537 * has been changed while starting up. Use the UCS-2 command line arguments
7538 * and convert them to 'encoding'.
7539 */
7540 void
7541fix_arg_enc(void)
7542{
7543 int i;
7544 int idx;
7545 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007546 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007547
7548 /* Safety checks:
7549 * - if argument count differs between the wide and non-wide argument
7550 * list, something must be wrong.
7551 * - the file name arguments must have been located.
7552 * - the length of the argument list wasn't changed by the user.
7553 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007554 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007555 || ArglistW == NULL
7556 || used_file_indexes == NULL
7557 || used_file_count == 0
7558 || used_alist_count != GARGCOUNT)
7559 return;
7560
Bram Moolenaar86b68352004-12-27 21:59:20 +00007561 /* Remember the buffer numbers for the arguments. */
7562 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7563 if (fnum_list == NULL)
7564 return; /* out of memory */
7565 for (i = 0; i < GARGCOUNT; ++i)
7566 fnum_list[i] = GARGLIST[i].ae_fnum;
7567
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007568 /* Clear the argument list. Make room for the new arguments. */
7569 alist_clear(&global_alist);
7570 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007571 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007572
7573 for (i = 0; i < used_file_count; ++i)
7574 {
7575 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007576 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007577 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007578 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007579 int literal = used_file_literal;
7580
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007581# ifdef FEAT_DIFF
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007582 /* When using diff mode may need to concatenate file name to
7583 * directory name. Just like it's done in main(). */
7584 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7585 && !mch_isdir(alist_name(&GARGLIST[0])))
7586 {
7587 char_u *r;
7588
7589 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7590 if (r != NULL)
7591 {
7592 vim_free(str);
7593 str = r;
7594 }
7595 }
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007596# endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007597 /* Re-use the old buffer by renaming it. When not using literal
7598 * names it's done by alist_expand() below. */
7599 if (used_file_literal)
7600 buf_set_name(fnum_list[i], str);
7601
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007602 /* Check backtick literal. backtick literal is already expanded in
7603 * main.c, so this part add str as literal. */
7604 if (literal == FALSE)
7605 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007606 size_t len = STRLEN(str);
7607
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007608 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7609 literal = TRUE;
7610 }
7611 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007612 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007613 }
7614
7615 if (!used_file_literal)
7616 {
7617 /* Now expand wildcards in the arguments. */
7618 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7619 * filename characters but are excluded from 'isfname' to make
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007620 * "gf" work on a file name in parenthesis (e.g.: see vim.h).
7621 * Also, unset wildignore to not be influenced by this option.
7622 * The arguments specified in command-line should be kept even if
7623 * encoding options were changed. */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007624 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007625 do_cmdline_cmd((char_u *)":let SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007626 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007627 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007628 do_cmdline_cmd((char_u *)":let &wig = SaVe_WIG|unlet SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007629 }
7630
7631 /* If wildcard expansion failed, we are editing the first file of the
7632 * arglist and there is no file name: Edit the first argument now. */
7633 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7634 {
7635 do_cmdline_cmd((char_u *)":rewind");
7636 if (GARGCOUNT == 1 && used_file_full_path)
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007637 (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007638 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007639
7640 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007641}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007642
7643 int
7644mch_setenv(char *var, char *value, int x)
7645{
7646 char_u *envbuf;
7647
7648 envbuf = alloc((unsigned)(STRLEN(var) + STRLEN(value) + 2));
7649 if (envbuf == NULL)
7650 return -1;
7651
7652 sprintf((char *)envbuf, "%s=%s", var, value);
7653
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007654 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
7655 {
7656 WCHAR *p = enc_to_utf16(envbuf, NULL);
7657
7658 vim_free(envbuf);
7659 if (p == NULL)
7660 return -1;
7661 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007662#ifdef libintl_wputenv
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007663 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007664#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007665 /* Unlike Un*x systems, we can free the string for _wputenv(). */
7666 vim_free(p);
7667 }
7668 else
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007669 {
7670 _putenv((char *)envbuf);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007671#ifdef libintl_putenv
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007672 libintl_putenv((char *)envbuf);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007673#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007674 /* Unlike Un*x systems, we can free the string for _putenv(). */
7675 vim_free(envbuf);
7676 }
7677
7678 return 0;
7679}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007680
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007681/*
7682 * Support for 256 colors and 24-bit colors was added in Windows 10
7683 * version 1703 (Creators update).
7684 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007685#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7686
7687/*
7688 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007689 * version 1809 (October 2018 update). However, that version is unstable.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007690 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007691#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
7692#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007693
7694 static void
7695vtp_flag_init(void)
7696{
7697 DWORD ver = get_build_number();
Bram Moolenaar4f974752019-02-17 17:44:42 +01007698#ifndef FEAT_GUI_MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007699 DWORD mode;
7700 HANDLE out;
7701
7702 out = GetStdHandle(STD_OUTPUT_HANDLE);
7703
7704 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7705 GetConsoleMode(out, &mode);
7706 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7707 if (SetConsoleMode(out, mode) == 0)
7708 vtp_working = 0;
7709#endif
7710
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007711 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007712 conpty_working = 1;
7713 if (ver >= CONPTY_STABLE_BUILD)
7714 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007715
7716}
7717
Bram Moolenaar4f974752019-02-17 17:44:42 +01007718#if !defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007719
7720 static void
7721vtp_init(void)
7722{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007723 HMODULE hKerneldll;
7724 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007725# ifdef FEAT_TERMGUICOLORS
7726 COLORREF fg, bg;
7727# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007728
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007729 /* Use functions supported from Vista */
7730 hKerneldll = GetModuleHandle("kernel32.dll");
7731 if (hKerneldll != NULL)
7732 {
7733 pGetConsoleScreenBufferInfoEx =
7734 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7735 hKerneldll, "GetConsoleScreenBufferInfoEx");
7736 pSetConsoleScreenBufferInfoEx =
7737 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7738 hKerneldll, "SetConsoleScreenBufferInfoEx");
7739 if (pGetConsoleScreenBufferInfoEx != NULL
7740 && pSetConsoleScreenBufferInfoEx != NULL)
7741 has_csbiex = TRUE;
7742 }
7743
7744 csbi.cbSize = sizeof(csbi);
7745 if (has_csbiex)
7746 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007747 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7748 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
7749
7750# ifdef FEAT_TERMGUICOLORS
7751 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7752 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7753 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7754 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7755 default_console_color_bg = bg;
7756 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007757# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007758
7759 set_console_color_rgb();
7760}
7761
7762 static void
7763vtp_exit(void)
7764{
7765 reset_console_color_rgb();
7766}
7767
7768 static int
7769vtp_printf(
7770 char *format,
7771 ...)
7772{
7773 char_u buf[100];
7774 va_list list;
7775 DWORD result;
7776
7777 va_start(list, format);
7778 vim_vsnprintf((char *)buf, 100, (char *)format, list);
7779 va_end(list);
7780 WriteConsoleA(g_hConOut, buf, (DWORD)STRLEN(buf), &result, NULL);
7781 return (int)result;
7782}
7783
7784 static void
7785vtp_sgr_bulk(
7786 int arg)
7787{
7788 int args[1];
7789
7790 args[0] = arg;
7791 vtp_sgr_bulks(1, args);
7792}
7793
7794 static void
7795vtp_sgr_bulks(
7796 int argc,
7797 int *args
7798)
7799{
7800 /* 2('\033[') + 4('255.') * 16 + NUL */
7801 char_u buf[2 + (4 * 16) + 1];
7802 char_u *p;
7803 int i;
7804
7805 p = buf;
7806 *p++ = '\033';
7807 *p++ = '[';
7808
7809 for (i = 0; i < argc; ++i)
7810 {
7811 p += vim_snprintf((char *)p, 4, "%d", args[i] & 0xff);
7812 *p++ = ';';
7813 }
7814 p--;
7815 *p++ = 'm';
7816 *p = NUL;
7817 vtp_printf((char *)buf);
7818}
7819
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007820# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007821 static int
7822ctermtoxterm(
7823 int cterm)
7824{
Bram Moolenaar9894e392018-05-05 14:29:06 +02007825 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007826
7827 cterm_color2rgb(cterm, &r, &g, &b, &idx);
7828 return (((int)r << 16) | ((int)g << 8) | (int)b);
7829}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007830# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007831
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007832 static void
7833set_console_color_rgb(void)
7834{
7835# ifdef FEAT_TERMGUICOLORS
7836 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7837 int id;
7838 guicolor_T fg = INVALCOLOR;
7839 guicolor_T bg = INVALCOLOR;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007840 int ctermfg;
7841 int ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007842
7843 if (!USE_VTP)
7844 return;
7845
7846 id = syn_name2id((char_u *)"Normal");
Bram Moolenaard5a58862019-03-07 06:40:27 +01007847 if (id > 0 && p_tgc)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007848 syn_id2colors(id, &fg, &bg);
7849 if (fg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007850 {
7851 ctermfg = -1;
7852 if (id > 0)
7853 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007854 fg = ctermfg != -1 ? ctermtoxterm(ctermfg) : default_console_color_fg;
7855 cterm_normal_fg_gui_color = fg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007856 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007857 if (bg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007858 {
7859 ctermbg = -1;
7860 if (id > 0)
7861 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007862 bg = ctermbg != -1 ? ctermtoxterm(ctermbg) : default_console_color_bg;
7863 cterm_normal_bg_gui_color = bg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007864 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007865 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7866 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7867
7868 csbi.cbSize = sizeof(csbi);
7869 if (has_csbiex)
7870 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7871
7872 csbi.cbSize = sizeof(csbi);
7873 csbi.srWindow.Right += 1;
7874 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007875 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
7876 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007877 if (has_csbiex)
7878 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7879# endif
7880}
7881
7882 static void
7883reset_console_color_rgb(void)
7884{
7885# ifdef FEAT_TERMGUICOLORS
7886 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7887
7888 csbi.cbSize = sizeof(csbi);
7889 if (has_csbiex)
7890 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7891
7892 csbi.cbSize = sizeof(csbi);
7893 csbi.srWindow.Right += 1;
7894 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007895 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
7896 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007897 if (has_csbiex)
7898 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7899# endif
7900}
7901
7902 void
7903control_console_color_rgb(void)
7904{
7905 if (USE_VTP)
7906 set_console_color_rgb();
7907 else
7908 reset_console_color_rgb();
7909}
7910
7911 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007912use_vtp(void)
7913{
7914 return USE_VTP;
7915}
7916
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007917 int
7918is_term_win32(void)
7919{
7920 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
7921}
7922
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007923 int
7924has_vtp_working(void)
7925{
7926 return vtp_working;
7927}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007928
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01007929#endif
7930
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007931 int
7932has_conpty_working(void)
7933{
7934 return conpty_working;
7935}
7936
7937 int
7938is_conpty_stable(void)
7939{
7940 return conpty_stable;
7941}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01007942
Bram Moolenaar4f974752019-02-17 17:44:42 +01007943#if !defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01007944 void
7945resize_console_buf(void)
7946{
7947 CONSOLE_SCREEN_BUFFER_INFO csbi;
7948 COORD coord;
7949 SMALL_RECT newsize;
7950
7951 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
7952 {
7953 coord.X = SRWIDTH(csbi.srWindow);
7954 coord.Y = SRHEIGHT(csbi.srWindow);
7955 SetConsoleScreenBufferSize(g_hConOut, coord);
7956
7957 newsize.Left = 0;
7958 newsize.Top = 0;
7959 newsize.Right = coord.X - 1;
7960 newsize.Bottom = coord.Y - 1;
7961 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
7962
7963 SetConsoleScreenBufferSize(g_hConOut, coord);
7964 }
7965}
7966#endif