blob: 790f75efd796fb342f165928ed1e38b37b4000d6 [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
12 * Used for both the console version and the Win32 GUI. A lot of code is for
Bram Moolenaar4f974752019-02-17 17:44:42 +010013 * the console version only, so there is a lot of "#ifndef FEAT_GUI_MSWIN".
Bram Moolenaar071d4272004-06-13 20:20:40 +000014 *
15 * Win32 (Windows NT and Windows 95) system-dependent routines.
16 * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17 * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18 *
19 * George V. Reilly <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
Bram Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010032
33/* cproto fails on missing include files */
34#ifndef PROTO
35# include <process.h>
36#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000037
38#undef chdir
39#ifdef __GNUC__
40# ifndef __MINGW32__
41# include <dirent.h>
42# endif
43#else
44# include <direct.h>
45#endif
46
Bram Moolenaar82881492012-11-20 16:53:39 +010047#ifndef PROTO
Bram Moolenaar4f974752019-02-17 17:44:42 +010048# if defined(FEAT_TITLE) && !defined(FEAT_GUI_MSWIN)
Bram Moolenaar82881492012-11-20 16:53:39 +010049# include <shellapi.h>
50# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000051#endif
52
Bram Moolenaarfb630902016-10-29 14:55:00 +020053#ifdef FEAT_JOB_CHANNEL
54# include <tlhelp32.h>
55#endif
56
Bram Moolenaar071d4272004-06-13 20:20:40 +000057#ifdef __MINGW32__
58# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
59# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
60# endif
61# ifndef RIGHTMOST_BUTTON_PRESSED
62# define RIGHTMOST_BUTTON_PRESSED 0x0002
63# endif
64# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
65# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
66# endif
67# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
68# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
69# endif
70# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
71# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
72# endif
73
74/*
75 * EventFlags
76 */
77# ifndef MOUSE_MOVED
78# define MOUSE_MOVED 0x0001
79# endif
80# ifndef DOUBLE_CLICK
81# define DOUBLE_CLICK 0x0002
82# endif
83#endif
84
85/* Record all output and all keyboard & mouse input */
86/* #define MCH_WRITE_DUMP */
87
88#ifdef MCH_WRITE_DUMP
89FILE* fdDump = NULL;
90#endif
91
92/*
93 * When generating prototypes for Win32 on Unix, these lines make the syntax
94 * errors disappear. They do not need to be correct.
95 */
96#ifdef PROTO
97#define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000098typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000099typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000100typedef int ACCESS_MASK;
101typedef int BOOL;
102typedef int COLORREF;
103typedef int CONSOLE_CURSOR_INFO;
104typedef int COORD;
105typedef int DWORD;
106typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100107typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000108typedef int HDC;
109typedef int HFONT;
110typedef int HICON;
111typedef int HINSTANCE;
112typedef int HWND;
113typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200114typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000115typedef int KEY_EVENT_RECORD;
116typedef int LOGFONT;
117typedef int LPBOOL;
118typedef int LPCTSTR;
119typedef int LPDWORD;
120typedef int LPSTR;
121typedef int LPTSTR;
122typedef int LPVOID;
123typedef int MOUSE_EVENT_RECORD;
124typedef int PACL;
125typedef int PDWORD;
126typedef int PHANDLE;
127typedef int PRINTDLG;
128typedef int PSECURITY_DESCRIPTOR;
129typedef int PSID;
130typedef int SECURITY_INFORMATION;
131typedef int SHORT;
132typedef int SMALL_RECT;
133typedef int TEXTMETRIC;
134typedef int TOKEN_INFORMATION_CLASS;
135typedef int TRUSTEE;
136typedef int WORD;
137typedef int WCHAR;
138typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100139typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200140typedef int SE_OBJECT_TYPE;
141typedef int PSNSECINFO;
142typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100143typedef int STARTUPINFO;
144typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200145typedef int LPSECURITY_ATTRIBUTES;
146# define __stdcall /* empty */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000147#endif
148
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200149#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000150/* Win32 Console handles for input and output */
151static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
152static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
153
154/* Win32 Screen buffer,coordinate,console I/O information */
155static SMALL_RECT g_srScrollRegion;
156static COORD g_coord; /* 0-based, but external coords are 1-based */
157
158/* The attribute of the screen when the editor was started */
159static WORD g_attrDefault = 7; /* lightgray text on black background */
160static WORD g_attrCurrent;
161
162static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
163static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
164static int g_fForceExit = FALSE; /* set when forcefully exiting */
165
Bram Moolenaar071d4272004-06-13 20:20:40 +0000166static void scroll(unsigned cLines);
167static void set_scroll_region(unsigned left, unsigned top,
168 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100169static void set_scroll_region_tb(unsigned top, unsigned bottom);
170static void set_scroll_region_lr(unsigned left, unsigned right);
171static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000172static void delete_lines(unsigned cLines);
173static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000174static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000175static int s_cursor_visible = TRUE;
176static int did_create_conin = FALSE;
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200177#endif
178#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000179static int s_dont_use_vimrun = TRUE;
180static int need_vimrun_warning = FALSE;
181static char *vimrun_path = "vimrun ";
182#endif
183
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200184static int win32_getattrs(char_u *name);
185static int win32_setattrs(char_u *name, int attrs);
186static int win32_set_archive(char_u *name);
187
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100188static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200189static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100190static int conpty_stable = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100191static void vtp_flag_init();
192
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200193#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100194static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100195static void vtp_init();
196static void vtp_exit();
197static int vtp_printf(char *format, ...);
198static void vtp_sgr_bulk(int arg);
199static void vtp_sgr_bulks(int argc, int *argv);
200
201static guicolor_T save_console_bg_rgb;
202static guicolor_T save_console_fg_rgb;
203
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200204static int g_color_index_bg = 0;
205static int g_color_index_fg = 7;
206
207# ifdef FEAT_TERMGUICOLORS
208static int default_console_color_bg = 0x000000; // black
209static int default_console_color_fg = 0xc0c0c0; // white
210# endif
211
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100212# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200213# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100214# else
215# define USE_VTP 0
216# endif
217
218static void set_console_color_rgb(void);
219static void reset_console_color_rgb(void);
220#endif
221
222/* This flag is newly created from Windows 10 */
223#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
224# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
225#endif
226
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200227#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000228static int suppress_winsize = 1; /* don't fiddle with console */
229#endif
230
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200231static char_u *exe_path = NULL;
232
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100233static BOOL win8_or_later = FALSE;
234
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200235#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100236/* Dynamic loading for portability */
237typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
238{
239 ULONG cbSize;
240 COORD dwSize;
241 COORD dwCursorPosition;
242 WORD wAttributes;
243 SMALL_RECT srWindow;
244 COORD dwMaximumWindowSize;
245 WORD wPopupAttributes;
246 BOOL bFullscreenSupported;
247 COLORREF ColorTable[16];
248} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
249typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
250static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
251typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
252static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
253static BOOL has_csbiex = FALSE;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100254#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100255
256/*
257 * Get version number including build number
258 */
259typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
260# define MAKE_VER(major, minor, build) \
261 (((major) << 24) | ((minor) << 16) | (build))
262
263 static DWORD
264get_build_number(void)
265{
266 OSVERSIONINFOW osver = {sizeof(OSVERSIONINFOW)};
267 HMODULE hNtdll;
268 PfnRtlGetVersion pRtlGetVersion;
269 DWORD ver = MAKE_VER(0, 0, 0);
270
271 hNtdll = GetModuleHandle("ntdll.dll");
272 if (hNtdll != NULL)
273 {
274 pRtlGetVersion =
275 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
276 pRtlGetVersion(&osver);
277 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
278 min(osver.dwMinorVersion, 255),
279 min(osver.dwBuildNumber, 32767));
280 }
281 return ver;
282}
283
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200284#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100285/*
286 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100287 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100288 */
289 static BOOL
290read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100291 HANDLE hInput,
292 INPUT_RECORD *lpBuffer,
293 DWORD nLength,
294 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100295{
296 enum
297 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100298 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100299 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100300 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100301 static DWORD s_dwIndex = 0;
302 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100303 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100304 int head;
305 int tail;
306 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100307
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200308 if (nLength == -2)
309 return (s_dwMax > 0) ? TRUE : FALSE;
310
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100311 if (!win8_or_later)
312 {
313 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200314 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
315 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100316 }
317
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100318 if (s_dwMax == 0)
319 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100320 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200321 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
322 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100323 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100324 s_dwIndex = 0;
325 s_dwMax = dwEvents;
326 if (dwEvents == 0)
327 {
328 *lpEvents = 0;
329 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100330 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100331
332 if (s_dwMax > 1)
333 {
334 head = 0;
335 tail = s_dwMax - 1;
336 while (head != tail)
337 {
338 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
339 && s_irCache[head + 1].EventType
340 == WINDOW_BUFFER_SIZE_EVENT)
341 {
342 /* Remove duplicate event to avoid flicker. */
343 for (i = head; i < tail; ++i)
344 s_irCache[i] = s_irCache[i + 1];
345 --tail;
346 continue;
347 }
348 head++;
349 }
350 s_dwMax = tail + 1;
351 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100352 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100353
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100354 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200355 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100356 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100357 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100358 return TRUE;
359}
360
361/*
362 * Version of PeekConsoleInput() that works with IME.
363 */
364 static BOOL
365peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100366 HANDLE hInput,
367 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200368 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100369 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100370{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100371 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100372}
373
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100374# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200375 static DWORD
376msg_wait_for_multiple_objects(
377 DWORD nCount,
378 LPHANDLE pHandles,
379 BOOL fWaitAll,
380 DWORD dwMilliseconds,
381 DWORD dwWakeMask)
382{
383 if (read_console_input(NULL, NULL, -2, NULL))
384 return WAIT_OBJECT_0;
385 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
386 dwMilliseconds, dwWakeMask);
387}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100388# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200389
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100390# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200391 static DWORD
392wait_for_single_object(
393 HANDLE hHandle,
394 DWORD dwMilliseconds)
395{
396 if (read_console_input(NULL, NULL, -2, NULL))
397 return WAIT_OBJECT_0;
398 return WaitForSingleObject(hHandle, dwMilliseconds);
399}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100400# endif
401#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200402
Bram Moolenaar071d4272004-06-13 20:20:40 +0000403 static void
404get_exe_name(void)
405{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100406 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
407 * as the maximum length that works (plus a NUL byte). */
408#define MAX_ENV_PATH_LEN 8192
409 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200410 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000411
412 if (exe_name == NULL)
413 {
414 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100415 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000416 if (*temp != NUL)
417 exe_name = FullName_save((char_u *)temp, FALSE);
418 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000419
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200420 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000421 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200422 exe_path = vim_strnsave(exe_name,
423 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200424 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000425 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200426 /* Append our starting directory to $PATH, so that when doing
427 * "!xxd" it's found in our starting directory. Needed because
428 * SearchPath() also looks there. */
429 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100430 if (p == NULL
431 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200432 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100433 if (p == NULL || *p == NUL)
434 temp[0] = NUL;
435 else
436 {
437 STRCPY(temp, p);
438 STRCAT(temp, ";");
439 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200440 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100441 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200442 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000443 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000444 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000445}
446
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200447/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100448 * Unescape characters in "p" that appear in "escaped".
449 */
450 static void
451unescape_shellxquote(char_u *p, char_u *escaped)
452{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100453 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100454 int n;
455
456 while (*p != NUL)
457 {
458 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
459 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100460 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100461 p += n;
462 l -= n;
463 }
464}
465
466/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200467 * Load library "name".
468 */
469 HINSTANCE
470vimLoadLib(char *name)
471{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200472 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200473
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200474 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
475 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200476 if (exe_path == NULL)
477 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200478 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200479 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200480 WCHAR old_dirw[MAXPATHL];
481
482 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
483 {
484 /* Change directory to where the executable is, both to make
485 * sure we find a .dll there and to avoid looking for a .dll
486 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100487 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200488 dll = LoadLibrary(name);
489 SetCurrentDirectoryW(old_dirw);
490 return dll;
491 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200492 }
493 return dll;
494}
495
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200496#if defined(VIMDLL) || defined(PROTO)
497/*
498 * Check if the current executable file is for the GUI subsystem.
499 */
500 int
501mch_is_gui_executable(void)
502{
503 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
504 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
505 PIMAGE_NT_HEADERS pPE;
506
507 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
508 return FALSE;
509 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
510 if (pPE->Signature != IMAGE_NT_SIGNATURE)
511 return FALSE;
512 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
513 return TRUE;
514 return FALSE;
515}
516#endif
517
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100518#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
519/*
520 * Get related information about 'funcname' which is imported by 'hInst'.
521 * If 'info' is 0, return the function address.
522 * If 'info' is 1, return the module name which the function is imported from.
523 */
524 static void *
525get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
526{
527 PBYTE pImage = (PBYTE)hInst;
528 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
529 PIMAGE_NT_HEADERS pPE;
530 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
531 PIMAGE_THUNK_DATA pIAT; /* Import Address Table */
532 PIMAGE_THUNK_DATA pINT; /* Import Name Table */
533 PIMAGE_IMPORT_BY_NAME pImpName;
534
535 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
536 return NULL;
537 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
538 if (pPE->Signature != IMAGE_NT_SIGNATURE)
539 return NULL;
540 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
541 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
542 .VirtualAddress);
543 for (; pImpDesc->FirstThunk; ++pImpDesc)
544 {
545 if (!pImpDesc->OriginalFirstThunk)
546 continue;
547 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
548 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
549 for (; pIAT->u1.Function; ++pIAT, ++pINT)
550 {
551 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
552 continue;
553 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
554 + (UINT_PTR)(pINT->u1.AddressOfData));
555 if (strcmp((char *)pImpName->Name, funcname) == 0)
556 {
557 switch (info)
558 {
559 case 0:
560 return (void *)pIAT->u1.Function;
561 case 1:
562 return (void *)(pImage + pImpDesc->Name);
563 default:
564 return NULL;
565 }
566 }
567 }
568 }
569 return NULL;
570}
571
572/*
573 * Get the module handle which 'funcname' in 'hInst' is imported from.
574 */
575 HINSTANCE
576find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
577{
578 char *modulename;
579
580 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
581 if (modulename != NULL)
582 return GetModuleHandleA(modulename);
583 return NULL;
584}
585
586/*
587 * Get the address of 'funcname' which is imported by 'hInst' DLL.
588 */
589 void *
590get_dll_import_func(HINSTANCE hInst, const char *funcname)
591{
592 return get_imported_func_info(hInst, funcname, 0);
593}
594#endif
595
Bram Moolenaar071d4272004-06-13 20:20:40 +0000596#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
597# ifndef GETTEXT_DLL
598# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200599# define GETTEXT_DLL_ALT1 "libintl-8.dll"
600# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000601# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200602/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000603static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200604static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000605static char *null_libintl_textdomain(const char *);
606static char *null_libintl_bindtextdomain(const char *, const char *);
607static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100608static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000609
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200610static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000611char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200612char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
613 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000614char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
615char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000616 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000617char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
618 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100619int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000620
621 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100622dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000623{
624 int i;
625 static struct
626 {
627 char *name;
628 FARPROC *ptr;
629 } libintl_entry[] =
630 {
631 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200632 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000633 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
634 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
635 {NULL, NULL}
636 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100637 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000638
Bram Moolenaar7554c542018-10-06 15:03:15 +0200639 // No need to initialize twice.
640 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000641 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200642 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100643 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar7554c542018-10-06 15:03:15 +0200644#ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100645 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200646 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
647#endif
648#ifdef GETTEXT_DLL_ALT2
649 if (!hLibintlDLL)
650 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100651#endif
652 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000653 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200654 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000655 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200656 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100657 semsg(_(e_loadlib), GETTEXT_DLL);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200658 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000659 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200660 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000661 }
662 for (i = 0; libintl_entry[i].name != NULL
663 && libintl_entry[i].ptr != NULL; ++i)
664 {
665 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
666 libintl_entry[i].name)) == NULL)
667 {
668 dyn_libintl_end();
669 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000670 {
671 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100672 semsg(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000673 verbose_leave();
674 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000675 return 0;
676 }
677 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000678
679 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000680 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000681 "bind_textdomain_codeset");
682 if (dyn_libintl_bind_textdomain_codeset == NULL)
683 dyn_libintl_bind_textdomain_codeset =
684 null_libintl_bind_textdomain_codeset;
685
Bram Moolenaar0eb035c2019-04-02 22:15:55 +0200686 /* _wputenv() function for the libintl.dll is optional. */
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100687 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
688 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100689 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100690 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
691 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100692
Bram Moolenaar071d4272004-06-13 20:20:40 +0000693 return 1;
694}
695
696 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100697dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000698{
699 if (hLibintlDLL)
700 FreeLibrary(hLibintlDLL);
701 hLibintlDLL = NULL;
702 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200703 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000704 dyn_libintl_textdomain = null_libintl_textdomain;
705 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000706 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100707 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000708}
709
710 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000711null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000712{
713 return (char*)msgid;
714}
715
716 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200717null_libintl_ngettext(
718 const char *msgid,
719 const char *msgid_plural,
720 unsigned long n)
721{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200722 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200723}
724
Bram Moolenaaree695f72016-08-03 22:08:45 +0200725 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100726null_libintl_bindtextdomain(
727 const char *domainname UNUSED,
728 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000729{
730 return NULL;
731}
732
733 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100734null_libintl_bind_textdomain_codeset(
735 const char *domainname UNUSED,
736 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000737{
738 return NULL;
739}
740
741 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100742null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000743{
744 return NULL;
745}
746
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200747 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100748null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100749{
750 return 0;
751}
752
Bram Moolenaar071d4272004-06-13 20:20:40 +0000753#endif /* DYNAMIC_GETTEXT */
754
755/* This symbol is not defined in older versions of the SDK or Visual C++ */
756
757#ifndef VER_PLATFORM_WIN32_WINDOWS
758# define VER_PLATFORM_WIN32_WINDOWS 1
759#endif
760
761DWORD g_PlatformId;
762
763#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100764# ifndef PROTO
765# include <aclapi.h>
766# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200767# ifndef PROTECTED_DACL_SECURITY_INFORMATION
768# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
769# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000770#endif
771
Bram Moolenaar27515922013-06-29 15:36:26 +0200772#ifdef HAVE_ACL
773/*
774 * Enables or disables the specified privilege.
775 */
776 static BOOL
777win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
778{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100779 BOOL bResult;
780 LUID luid;
781 HANDLE hToken;
782 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200783
784 if (!OpenProcessToken(GetCurrentProcess(),
785 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
786 return FALSE;
787
788 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
789 {
790 CloseHandle(hToken);
791 return FALSE;
792 }
793
Bram Moolenaar45500912014-07-09 20:51:07 +0200794 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200795 tokenPrivileges.Privileges[0].Luid = luid;
796 tokenPrivileges.Privileges[0].Attributes = bEnable ?
797 SE_PRIVILEGE_ENABLED : 0;
798
799 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
800 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
801
802 CloseHandle(hToken);
803
804 return bResult && GetLastError() == ERROR_SUCCESS;
805}
806#endif
807
Bram Moolenaar071d4272004-06-13 20:20:40 +0000808/*
809 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
810 * VER_PLATFORM_WIN32_WINDOWS (Win95).
811 */
812 void
813PlatformId(void)
814{
815 static int done = FALSE;
816
817 if (!done)
818 {
819 OSVERSIONINFO ovi;
820
821 ovi.dwOSVersionInfoSize = sizeof(ovi);
822 GetVersionEx(&ovi);
823
824 g_PlatformId = ovi.dwPlatformId;
825
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100826 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
827 || ovi.dwMajorVersion > 6)
828 win8_or_later = TRUE;
829
Bram Moolenaar071d4272004-06-13 20:20:40 +0000830#ifdef HAVE_ACL
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200831 /* Enable privilege for getting or setting SACLs. */
832 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000833#endif
834 done = TRUE;
835 }
836}
837
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200838#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000839
840#define SHIFT (SHIFT_PRESSED)
841#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
842#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
843#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
844
845
846/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
847 * We map function keys to their ANSI terminal equivalents, as produced
848 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
849 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
850 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
851 * combinations of function/arrow/etc keys.
852 */
853
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000854static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000855{
856 WORD wVirtKey;
857 BOOL fAnsiKey;
858 int chAlone;
859 int chShift;
860 int chCtrl;
861 int chAlt;
862} VirtKeyMap[] =
863{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200864// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000865 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
866
867 { VK_F1, TRUE, ';', 'T', '^', 'h', },
868 { VK_F2, TRUE, '<', 'U', '_', 'i', },
869 { VK_F3, TRUE, '=', 'V', '`', 'j', },
870 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
871 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
872 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
873 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
874 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
875 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
876 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200877 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
878 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000879
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200880 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
881 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
882 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
883 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
884 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
885 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
886 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
887 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
888 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
889 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100890 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000891
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200892 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000893
894#if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200895 // Most people don't have F13-F20, but what the hell...
896 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
897 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
898 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
899 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
900 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
901 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
902 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
903 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000904#endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200905 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
906 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
907 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
908 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000909
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200910 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
911 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
912 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
913 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
914 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
915 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
916 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
917 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
918 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
919 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100920 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000921};
922
923
924#ifdef _MSC_VER
925// The ToAscii bug destroys several registers. Need to turn off optimization
926// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000927# pragma warning(push)
928# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000929# pragma optimize("", off)
930#endif
931
932#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200933# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000934#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200935# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000936#endif
937
938/* The return code indicates key code size. */
939 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +0000940win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000941 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000942{
943 UINT uMods = pker->dwControlKeyState;
944 static int s_iIsDead = 0;
945 static WORD awAnsiCode[2];
946 static BYTE abKeystate[256];
947
948
949 if (s_iIsDead == 2)
950 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200951 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000952 s_iIsDead = 0;
953 return 1;
954 }
955
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200956 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000957 return 1;
958
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200959 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000960
Bram Moolenaar071d4272004-06-13 20:20:40 +0000961 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200962 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000963
964 if (uMods & SHIFT_PRESSED)
965 abKeystate[VK_SHIFT] = 0x80;
966 if (uMods & CAPSLOCK_ON)
967 abKeystate[VK_CAPITAL] = 1;
968
969 if ((uMods & ALT_GR) == ALT_GR)
970 {
971 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
972 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
973 }
974
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200975 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
976 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000977
978 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200979 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000980
981 return s_iIsDead;
982}
983
984#ifdef _MSC_VER
985/* MUST switch optimization on again here, otherwise a call to
986 * decode_key_event() may crash (e.g. when hitting caps-lock) */
987# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000988# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000989
990# if (_MSC_VER < 1100)
991/* MUST turn off global optimisation for this next function, or
992 * pressing ctrl-minus in insert mode crashes Vim when built with
993 * VC4.1. -- negri. */
994# pragma optimize("g", off)
995# endif
996#endif
997
998static BOOL g_fJustGotFocus = FALSE;
999
1000/*
1001 * Decode a KEY_EVENT into one or two keystrokes
1002 */
1003 static BOOL
1004decode_key_event(
1005 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001006 WCHAR *pch,
1007 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001008 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001009 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001010{
1011 int i;
1012 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1013
1014 *pch = *pch2 = NUL;
1015 g_fJustGotFocus = FALSE;
1016
1017 /* ignore key up events */
1018 if (!pker->bKeyDown)
1019 return FALSE;
1020
1021 /* ignore some keystrokes */
1022 switch (pker->wVirtualKeyCode)
1023 {
1024 /* modifiers */
1025 case VK_SHIFT:
1026 case VK_CONTROL:
1027 case VK_MENU: /* Alt key */
1028 return FALSE;
1029
1030 default:
1031 break;
1032 }
1033
1034 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001035 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001036 {
1037 /* Ctrl-6 is Ctrl-^ */
1038 if (pker->wVirtualKeyCode == '6')
1039 {
1040 *pch = Ctrl_HAT;
1041 return TRUE;
1042 }
1043 /* Ctrl-2 is Ctrl-@ */
1044 else if (pker->wVirtualKeyCode == '2')
1045 {
1046 *pch = NUL;
1047 return TRUE;
1048 }
1049 /* Ctrl-- is Ctrl-_ */
1050 else if (pker->wVirtualKeyCode == 0xBD)
1051 {
1052 *pch = Ctrl__;
1053 return TRUE;
1054 }
1055 }
1056
1057 /* Shift-TAB */
1058 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1059 {
1060 *pch = K_NUL;
1061 *pch2 = '\017';
1062 return TRUE;
1063 }
1064
1065 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1066 {
1067 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1068 {
1069 if (nModifs == 0)
1070 *pch = VirtKeyMap[i].chAlone;
1071 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1072 *pch = VirtKeyMap[i].chShift;
1073 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1074 *pch = VirtKeyMap[i].chCtrl;
1075 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1076 *pch = VirtKeyMap[i].chAlt;
1077
1078 if (*pch != 0)
1079 {
1080 if (VirtKeyMap[i].fAnsiKey)
1081 {
1082 *pch2 = *pch;
1083 *pch = K_NUL;
1084 }
1085
1086 return TRUE;
1087 }
1088 }
1089 }
1090
1091 i = win32_kbd_patch_key(pker);
1092
1093 if (i < 0)
1094 *pch = NUL;
1095 else
1096 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001097 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001098
1099 if (pmodifiers != NULL)
1100 {
1101 /* Pass on the ALT key as a modifier, but only when not combined
1102 * with CTRL (which is ALTGR). */
1103 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1104 *pmodifiers |= MOD_MASK_ALT;
1105
1106 /* Pass on SHIFT only for special keys, because we don't know when
1107 * it's already included with the character. */
1108 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1109 *pmodifiers |= MOD_MASK_SHIFT;
1110
1111 /* Pass on CTRL only for non-special keys, because we don't know
1112 * when it's already included with the character. And not when
1113 * combined with ALT (which is ALTGR). */
1114 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1115 && *pch >= 0x20 && *pch < 0x80)
1116 *pmodifiers |= MOD_MASK_CTRL;
1117 }
1118 }
1119
1120 return (*pch != NUL);
1121}
1122
1123#ifdef _MSC_VER
1124# pragma optimize("", on)
1125#endif
1126
Bram Moolenaar4f974752019-02-17 17:44:42 +01001127#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001128
1129
1130#ifdef FEAT_MOUSE
1131
1132/*
1133 * For the GUI the mouse handling is in gui_w32.c.
1134 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001135# if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001136 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001137mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001138{
1139}
1140# else
1141static int g_fMouseAvail = FALSE; /* mouse present */
1142static int g_fMouseActive = FALSE; /* mouse enabled */
1143static int g_nMouseClick = -1; /* mouse status */
1144static int g_xMouse; /* mouse x coordinate */
1145static int g_yMouse; /* mouse y coordinate */
1146
1147/*
1148 * Enable or disable mouse input
1149 */
1150 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001151mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001152{
1153 DWORD cmodein;
1154
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001155# ifdef VIMDLL
1156 if (gui.in_use)
1157 return;
1158# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001159 if (!g_fMouseAvail)
1160 return;
1161
1162 g_fMouseActive = on;
1163 GetConsoleMode(g_hConIn, &cmodein);
1164
1165 if (g_fMouseActive)
1166 cmodein |= ENABLE_MOUSE_INPUT;
1167 else
1168 cmodein &= ~ENABLE_MOUSE_INPUT;
1169
1170 SetConsoleMode(g_hConIn, cmodein);
1171}
1172
Bram Moolenaar157d8132018-03-06 17:09:20 +01001173
1174#if defined(FEAT_BEVAL_TERM) || defined(PROTO)
1175/*
1176 * Called when 'balloonevalterm' changed.
1177 */
1178 void
1179mch_bevalterm_changed(void)
1180{
1181 mch_setmouse(g_fMouseActive);
1182}
1183#endif
1184
Bram Moolenaar071d4272004-06-13 20:20:40 +00001185/*
1186 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1187 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1188 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1189 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1190 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1191 * and we return the mouse position in g_xMouse and g_yMouse.
1192 *
1193 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1194 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1195 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1196 *
1197 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1198 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1199 *
1200 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1201 * moves, even if it stays within the same character cell. We ignore
1202 * all MOUSE_MOVED messages if the position hasn't really changed, and
1203 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1204 * we're only interested in MOUSE_DRAG).
1205 *
1206 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1207 * 2-button mouses by pressing the left & right buttons simultaneously.
1208 * In practice, it's almost impossible to click both at the same time,
1209 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1210 * in such cases, if the user is clicking quickly.
1211 */
1212 static BOOL
1213decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001214 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001215{
1216 static int s_nOldButton = -1;
1217 static int s_nOldMouseClick = -1;
1218 static int s_xOldMouse = -1;
1219 static int s_yOldMouse = -1;
1220 static linenr_T s_old_topline = 0;
1221#ifdef FEAT_DIFF
1222 static int s_old_topfill = 0;
1223#endif
1224 static int s_cClicks = 1;
1225 static BOOL s_fReleased = TRUE;
1226 static DWORD s_dwLastClickTime = 0;
1227 static BOOL s_fNextIsMiddle = FALSE;
1228
1229 static DWORD cButtons = 0; /* number of buttons supported */
1230
1231 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1232 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1233 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1234 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1235
1236 int nButton;
1237
1238 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1239 cButtons = 2;
1240
1241 if (!g_fMouseAvail || !g_fMouseActive)
1242 {
1243 g_nMouseClick = -1;
1244 return FALSE;
1245 }
1246
1247 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1248 if (g_fJustGotFocus)
1249 {
1250 g_fJustGotFocus = FALSE;
1251 return FALSE;
1252 }
1253
1254 /* unprocessed mouse click? */
1255 if (g_nMouseClick != -1)
1256 return TRUE;
1257
1258 nButton = -1;
1259 g_xMouse = pmer->dwMousePosition.X;
1260 g_yMouse = pmer->dwMousePosition.Y;
1261
1262 if (pmer->dwEventFlags == MOUSE_MOVED)
1263 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001264 /* Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
Bram Moolenaar071d4272004-06-13 20:20:40 +00001265 * events even when the mouse moves only within a char cell.) */
1266 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1267 return FALSE;
1268 }
1269
1270 /* If no buttons are pressed... */
1271 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1272 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001273 nButton = MOUSE_RELEASE;
1274
Bram Moolenaar071d4272004-06-13 20:20:40 +00001275 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1276 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001277 {
1278#ifdef FEAT_BEVAL_TERM
1279 /* do return mouse move events when we want them */
1280 if (p_bevalterm)
1281 nButton = MOUSE_DRAG;
1282 else
1283#endif
1284 return FALSE;
1285 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001286
Bram Moolenaar071d4272004-06-13 20:20:40 +00001287 s_fReleased = TRUE;
1288 }
1289 else /* one or more buttons pressed */
1290 {
1291 /* on a 2-button mouse, hold down left and right buttons
1292 * simultaneously to get MIDDLE. */
1293
1294 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1295 {
1296 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1297
1298 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001299 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001300 if (dwLR == LEFT || dwLR == RIGHT)
1301 {
1302 for (;;)
1303 {
1304 /* wait a short time for next input event */
1305 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1306 != WAIT_OBJECT_0)
1307 break;
1308 else
1309 {
1310 DWORD cRecords = 0;
1311 INPUT_RECORD ir;
1312 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1313
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001314 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001315
1316 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1317 || !(pmer2->dwButtonState & LEFT_RIGHT))
1318 break;
1319 else
1320 {
1321 if (pmer2->dwEventFlags != MOUSE_MOVED)
1322 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001323 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001324
1325 return decode_mouse_event(pmer2);
1326 }
1327 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1328 s_yOldMouse == pmer2->dwMousePosition.Y)
1329 {
1330 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001331 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001332
1333 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001334 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001335
1336 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1337 break;
1338 }
1339 else
1340 break;
1341 }
1342 }
1343 }
1344 }
1345 }
1346
1347 if (s_fNextIsMiddle)
1348 {
1349 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1350 ? MOUSE_DRAG : MOUSE_MIDDLE;
1351 s_fNextIsMiddle = FALSE;
1352 }
1353 else if (cButtons == 2 &&
1354 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1355 {
1356 nButton = MOUSE_MIDDLE;
1357
1358 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1359 {
1360 s_fNextIsMiddle = TRUE;
1361 nButton = MOUSE_RELEASE;
1362 }
1363 }
1364 else if ((pmer->dwButtonState & LEFT) == LEFT)
1365 nButton = MOUSE_LEFT;
1366 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1367 nButton = MOUSE_MIDDLE;
1368 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1369 nButton = MOUSE_RIGHT;
1370
1371 if (! s_fReleased && ! s_fNextIsMiddle
1372 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1373 return FALSE;
1374
1375 s_fReleased = s_fNextIsMiddle;
1376 }
1377
1378 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1379 {
1380 /* button pressed or released, without mouse moving */
1381 if (nButton != -1 && nButton != MOUSE_RELEASE)
1382 {
1383 DWORD dwCurrentTime = GetTickCount();
1384
1385 if (s_xOldMouse != g_xMouse
1386 || s_yOldMouse != g_yMouse
1387 || s_nOldButton != nButton
1388 || s_old_topline != curwin->w_topline
1389#ifdef FEAT_DIFF
1390 || s_old_topfill != curwin->w_topfill
1391#endif
1392 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1393 {
1394 s_cClicks = 1;
1395 }
1396 else if (++s_cClicks > 4)
1397 {
1398 s_cClicks = 1;
1399 }
1400
1401 s_dwLastClickTime = dwCurrentTime;
1402 }
1403 }
1404 else if (pmer->dwEventFlags == MOUSE_MOVED)
1405 {
1406 if (nButton != -1 && nButton != MOUSE_RELEASE)
1407 nButton = MOUSE_DRAG;
1408
1409 s_cClicks = 1;
1410 }
1411
1412 if (nButton == -1)
1413 return FALSE;
1414
1415 if (nButton != MOUSE_RELEASE)
1416 s_nOldButton = nButton;
1417
1418 g_nMouseClick = nButton;
1419
1420 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1421 g_nMouseClick |= MOUSE_SHIFT;
1422 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1423 g_nMouseClick |= MOUSE_CTRL;
1424 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1425 g_nMouseClick |= MOUSE_ALT;
1426
1427 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1428 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1429
1430 /* only pass on interesting (i.e., different) mouse events */
1431 if (s_xOldMouse == g_xMouse
1432 && s_yOldMouse == g_yMouse
1433 && s_nOldMouseClick == g_nMouseClick)
1434 {
1435 g_nMouseClick = -1;
1436 return FALSE;
1437 }
1438
1439 s_xOldMouse = g_xMouse;
1440 s_yOldMouse = g_yMouse;
1441 s_old_topline = curwin->w_topline;
1442#ifdef FEAT_DIFF
1443 s_old_topfill = curwin->w_topfill;
1444#endif
1445 s_nOldMouseClick = g_nMouseClick;
1446
1447 return TRUE;
1448}
1449
Bram Moolenaar4f974752019-02-17 17:44:42 +01001450# endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001451#endif /* FEAT_MOUSE */
1452
1453
1454#ifdef MCH_CURSOR_SHAPE
1455/*
1456 * Set the shape of the cursor.
1457 * 'thickness' can be from 1 (thin) to 99 (block)
1458 */
1459 static void
1460mch_set_cursor_shape(int thickness)
1461{
1462 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1463 ConsoleCursorInfo.dwSize = thickness;
1464 ConsoleCursorInfo.bVisible = s_cursor_visible;
1465
1466 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1467 if (s_cursor_visible)
1468 SetConsoleCursorPosition(g_hConOut, g_coord);
1469}
1470
1471 void
1472mch_update_cursor(void)
1473{
1474 int idx;
1475 int thickness;
1476
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001477# ifdef VIMDLL
1478 if (gui.in_use)
1479 return;
1480# endif
1481
Bram Moolenaar071d4272004-06-13 20:20:40 +00001482 /*
1483 * How the cursor is drawn depends on the current mode.
1484 */
1485 idx = get_shape_idx(FALSE);
1486
1487 if (shape_table[idx].shape == SHAPE_BLOCK)
1488 thickness = 99; /* 100 doesn't work on W95 */
1489 else
1490 thickness = shape_table[idx].percentage;
1491 mch_set_cursor_shape(thickness);
1492}
1493#endif
1494
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001495#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001496/*
1497 * Handle FOCUS_EVENT.
1498 */
1499 static void
1500handle_focus_event(INPUT_RECORD ir)
1501{
1502 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1503 ui_focus_change((int)g_fJustGotFocus);
1504}
1505
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001506static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1507
Bram Moolenaar071d4272004-06-13 20:20:40 +00001508/*
1509 * Wait until console input from keyboard or mouse is available,
1510 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001511 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001512 * Return TRUE if something is available FALSE if not.
1513 */
1514 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001515WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001516{
1517 DWORD dwNow = 0, dwEndTime = 0;
1518 INPUT_RECORD ir;
1519 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001520 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001521#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001522 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001523#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001524
1525 if (msec > 0)
1526 /* Wait until the specified time has elapsed. */
1527 dwEndTime = GetTickCount() + msec;
1528 else if (msec < 0)
1529 /* Wait forever. */
1530 dwEndTime = INFINITE;
1531
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001532 // We need to loop until the end of the time period, because
1533 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001534 for (;;)
1535 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001536 // Only process messages when waiting.
1537 if (msec != 0)
1538 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001539#ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001540 parse_queued_messages();
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001541#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001542#ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001543 mzvim_check_threads();
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001544#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001545#ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001546 serverProcessPendingMessages();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001547#endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001548 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001549
Bram Moolenaar071d4272004-06-13 20:20:40 +00001550 if (0
1551#ifdef FEAT_MOUSE
1552 || g_nMouseClick != -1
1553#endif
1554#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001555 || (!ignore_input && input_available())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001556#endif
1557 )
1558 return TRUE;
1559
1560 if (msec > 0)
1561 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001562 /* If the specified wait time has passed, return. Beware that
1563 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001564 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001565 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001566 break;
1567 }
1568 if (msec != 0)
1569 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001570 DWORD dwWaitTime = dwEndTime - dwNow;
1571
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001572#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001573 /* Check channel while waiting for input. */
Bram Moolenaar9186a272016-02-23 19:34:01 +01001574 if (dwWaitTime > 100)
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001575 {
Bram Moolenaar9186a272016-02-23 19:34:01 +01001576 dwWaitTime = 100;
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001577 /* If there is readahead then parse_queued_messages() timed out
1578 * and we should call it again soon. */
1579 if (channel_any_readahead())
1580 dwWaitTime = 10;
1581 }
Bram Moolenaar9186a272016-02-23 19:34:01 +01001582#endif
Bram Moolenaarc3719bd2017-11-18 22:13:31 +01001583#ifdef FEAT_BEVAL_GUI
Bram Moolenaar59716a22017-03-01 20:32:44 +01001584 if (p_beval && dwWaitTime > 100)
1585 /* The 'balloonexpr' may indirectly invoke a callback while
1586 * waiting for a character, need to check often. */
1587 dwWaitTime = 100;
1588#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001589#ifdef FEAT_MZSCHEME
1590 if (mzthreads_allowed() && p_mzq > 0
1591 && (msec < 0 || (long)dwWaitTime > p_mzq))
1592 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1593#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001594#ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001595 // When waiting very briefly don't trigger timers.
1596 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001597 {
1598 long due_time;
1599
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001600 // Trigger timers and then get the time in msec until the next
1601 // one is due. Wait up to that time.
1602 due_time = check_due_timer();
1603 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001604 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001605 // timer may have used feedkeys().
1606 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001607 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001608 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1609 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001610 }
1611#endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001612 if (
Bram Moolenaar071d4272004-06-13 20:20:40 +00001613#ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001614 // Wait for either an event on the console input or a
1615 // message in the client-server window.
1616 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1617 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001618#else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001619 wait_for_single_object(g_hConIn, dwWaitTime)
1620 != WAIT_OBJECT_0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001621#endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001622 )
1623 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001624 }
1625
1626 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001627 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001628
1629#ifdef FEAT_MBYTE_IME
1630 if (State & CMDLINE && msg_row == Rows - 1)
1631 {
1632 CONSOLE_SCREEN_BUFFER_INFO csbi;
1633
1634 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1635 {
1636 if (csbi.dwCursorPosition.Y != msg_row)
1637 {
1638 /* The screen is now messed up, must redraw the
1639 * command line and later all the windows. */
1640 redraw_all_later(CLEAR);
1641 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1642 redrawcmd();
1643 }
1644 }
1645 }
1646#endif
1647
1648 if (cRecords > 0)
1649 {
1650 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1651 {
1652#ifdef FEAT_MBYTE_IME
1653 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1654 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001655 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001656 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1657 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001658 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001659 continue;
1660 }
1661#endif
1662 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1663 NULL, FALSE))
1664 return TRUE;
1665 }
1666
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001667 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001668
1669 if (ir.EventType == FOCUS_EVENT)
1670 handle_focus_event(ir);
1671 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001672 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001673 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1674
1675 // Only call shell_resized() when the size actually change to
1676 // avoid the screen is cleard.
1677 if (dwSize.X != Columns || dwSize.Y != Rows)
1678 {
1679 CONSOLE_SCREEN_BUFFER_INFO csbi;
1680 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
1681 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
1682 ResizeConBuf(g_hConOut, dwSize);
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001683 shell_resized();
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001684 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001685 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001686#ifdef FEAT_MOUSE
1687 else if (ir.EventType == MOUSE_EVENT
1688 && decode_mouse_event(&ir.Event.MouseEvent))
1689 return TRUE;
1690#endif
1691 }
1692 else if (msec == 0)
1693 break;
1694 }
1695
1696#ifdef FEAT_CLIENTSERVER
1697 /* Something might have been received while we were waiting. */
1698 if (input_available())
1699 return TRUE;
1700#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001701
Bram Moolenaar071d4272004-06-13 20:20:40 +00001702 return FALSE;
1703}
1704
Bram Moolenaar071d4272004-06-13 20:20:40 +00001705/*
1706 * return non-zero if a character is available
1707 */
1708 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001709mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001710{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001711# ifdef VIMDLL
1712 if (gui.in_use)
1713 return TRUE;
1714# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001715 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001716}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001717
1718# if defined(FEAT_TERMINAL) || defined(PROTO)
1719/*
1720 * Check for any pending input or messages.
1721 */
1722 int
1723mch_check_messages(void)
1724{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001725# ifdef VIMDLL
1726 if (gui.in_use)
1727 return TRUE;
1728# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001729 return WaitForChar(0L, TRUE);
1730}
1731# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001732
1733/*
1734 * Create the console input. Used when reading stdin doesn't work.
1735 */
1736 static void
1737create_conin(void)
1738{
1739 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1740 FILE_SHARE_READ|FILE_SHARE_WRITE,
1741 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001742 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001743 did_create_conin = TRUE;
1744}
1745
1746/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001747 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001748 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001749 static WCHAR
1750tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001751{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001752 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001753
1754 for (;;)
1755 {
1756 INPUT_RECORD ir;
1757 DWORD cRecords = 0;
1758
1759#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001760 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001761 if (input_available())
1762 return 0;
1763# ifdef FEAT_MOUSE
1764 if (g_nMouseClick != -1)
1765 return 0;
1766# endif
1767#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001768 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001769 {
1770 if (did_create_conin)
1771 read_error_exit();
1772 create_conin();
1773 continue;
1774 }
1775
1776 if (ir.EventType == KEY_EVENT)
1777 {
1778 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1779 pmodifiers, TRUE))
1780 return ch;
1781 }
1782 else if (ir.EventType == FOCUS_EVENT)
1783 handle_focus_event(ir);
1784 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1785 shell_resized();
1786#ifdef FEAT_MOUSE
1787 else if (ir.EventType == MOUSE_EVENT)
1788 {
1789 if (decode_mouse_event(&ir.Event.MouseEvent))
1790 return 0;
1791 }
1792#endif
1793 }
1794}
Bram Moolenaar4f974752019-02-17 17:44:42 +01001795#endif /* !FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001796
1797
1798/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001799 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001800 * Get one or more characters from the keyboard or the mouse.
1801 * If time == 0, do not wait for characters.
1802 * If time == n, wait a short time for characters.
1803 * If time == -1, wait forever for characters.
1804 * Returns the number of characters read into buf.
1805 */
1806 int
1807mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001808 char_u *buf UNUSED,
1809 int maxlen UNUSED,
1810 long time UNUSED,
1811 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001812{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001813#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001814
1815 int len;
1816 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001817#define TYPEAHEADLEN 20
1818 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1819 static int typeaheadlen = 0;
1820
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001821# ifdef VIMDLL
1822 if (gui.in_use)
1823 return 0;
1824# endif
1825
Bram Moolenaar071d4272004-06-13 20:20:40 +00001826 /* First use any typeahead that was kept because "buf" was too small. */
1827 if (typeaheadlen > 0)
1828 goto theend;
1829
Bram Moolenaar071d4272004-06-13 20:20:40 +00001830 if (time >= 0)
1831 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001832 if (!WaitForChar(time, FALSE)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001833 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001834 }
1835 else /* time == -1, wait forever */
1836 {
1837 mch_set_winsize_now(); /* Allow winsize changes from now on */
1838
Bram Moolenaar3918c952005-03-15 22:34:55 +00001839 /*
1840 * If there is no character available within 2 seconds (default)
1841 * write the autoscript file to disk. Or cause the CursorHold event
1842 * to be triggered.
1843 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001844 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001845 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001846 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001847 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001848 buf[0] = K_SPECIAL;
1849 buf[1] = KS_EXTRA;
1850 buf[2] = (int)KE_CURSORHOLD;
1851 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001852 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001853 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001854 }
1855 }
1856
1857 /*
1858 * Try to read as many characters as there are, until the buffer is full.
1859 */
1860
1861 /* we will get at least one key. Get more if they are available. */
1862 g_fCBrkPressed = FALSE;
1863
1864#ifdef MCH_WRITE_DUMP
1865 if (fdDump)
1866 fputc('[', fdDump);
1867#endif
1868
1869 /* Keep looping until there is something in the typeahead buffer and more
1870 * to get and still room in the buffer (up to two bytes for a char and
1871 * three bytes for a modifier). */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001872 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001873 && typeaheadlen + 5 <= TYPEAHEADLEN)
1874 {
1875 if (typebuf_changed(tb_change_cnt))
1876 {
1877 /* "buf" may be invalid now if a client put something in the
1878 * typeahead buffer and "buf" is in the typeahead buffer. */
1879 typeaheadlen = 0;
1880 break;
1881 }
1882#ifdef FEAT_MOUSE
1883 if (g_nMouseClick != -1)
1884 {
1885# ifdef MCH_WRITE_DUMP
1886 if (fdDump)
1887 fprintf(fdDump, "{%02x @ %d, %d}",
1888 g_nMouseClick, g_xMouse, g_yMouse);
1889# endif
1890 typeahead[typeaheadlen++] = ESC + 128;
1891 typeahead[typeaheadlen++] = 'M';
1892 typeahead[typeaheadlen++] = g_nMouseClick;
1893 typeahead[typeaheadlen++] = g_xMouse + '!';
1894 typeahead[typeaheadlen++] = g_yMouse + '!';
1895 g_nMouseClick = -1;
1896 }
1897 else
1898#endif
1899 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001900 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001901 int modifiers = 0;
1902
1903 c = tgetch(&modifiers, &ch2);
1904
1905 if (typebuf_changed(tb_change_cnt))
1906 {
1907 /* "buf" may be invalid now if a client put something in the
1908 * typeahead buffer and "buf" is in the typeahead buffer. */
1909 typeaheadlen = 0;
1910 break;
1911 }
1912
1913 if (c == Ctrl_C && ctrl_c_interrupts)
1914 {
1915#if defined(FEAT_CLIENTSERVER)
1916 trash_input_buf();
1917#endif
1918 got_int = TRUE;
1919 }
1920
1921#ifdef FEAT_MOUSE
1922 if (g_nMouseClick == -1)
1923#endif
1924 {
1925 int n = 1;
1926
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001927 if (ch2 == NUL)
1928 {
1929 int i;
1930 char_u *p;
1931 WCHAR ch[2];
1932
1933 ch[0] = c;
1934 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1935 {
1936 ch[1] = tgetch(&modifiers, &ch2);
1937 n++;
1938 }
1939 p = utf16_to_enc(ch, &n);
1940 if (p != NULL)
1941 {
1942 for (i = 0; i < n; i++)
1943 typeahead[typeaheadlen + i] = p[i];
1944 vim_free(p);
1945 }
1946 }
1947 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001948 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001949 if (ch2 != NUL)
1950 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001951 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001952 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001953 switch (ch2)
1954 {
1955 case (WCHAR)'\324': // SHIFT+Insert
1956 case (WCHAR)'\325': // CTRL+Insert
1957 case (WCHAR)'\327': // SHIFT+Delete
1958 case (WCHAR)'\330': // CTRL+Delete
1959 typeahead[typeaheadlen + n] = (char_u)ch2;
1960 n++;
1961 break;
1962
1963 default:
1964 typeahead[typeaheadlen + n] = 3;
1965 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1966 n += 2;
1967 break;
1968 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001969 }
1970 else
1971 {
1972 typeahead[typeaheadlen + n] = 3;
1973 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1974 n += 2;
1975 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001976 }
1977
Bram Moolenaar071d4272004-06-13 20:20:40 +00001978 /* Use the ALT key to set the 8th bit of the character
1979 * when it's one byte, the 8th bit isn't set yet and not
1980 * using a double-byte encoding (would become a lead
1981 * byte). */
1982 if ((modifiers & MOD_MASK_ALT)
1983 && n == 1
1984 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001985 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00001986 )
1987 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001988 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1989 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001990 modifiers &= ~MOD_MASK_ALT;
1991 }
1992
1993 if (modifiers != 0)
1994 {
1995 /* Prepend modifiers to the character. */
1996 mch_memmove(typeahead + typeaheadlen + 3,
1997 typeahead + typeaheadlen, n);
1998 typeahead[typeaheadlen++] = K_SPECIAL;
1999 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2000 typeahead[typeaheadlen++] = modifiers;
2001 }
2002
2003 typeaheadlen += n;
2004
2005#ifdef MCH_WRITE_DUMP
2006 if (fdDump)
2007 fputc(c, fdDump);
2008#endif
2009 }
2010 }
2011 }
2012
2013#ifdef MCH_WRITE_DUMP
2014 if (fdDump)
2015 {
2016 fputs("]\n", fdDump);
2017 fflush(fdDump);
2018 }
2019#endif
2020
Bram Moolenaar071d4272004-06-13 20:20:40 +00002021theend:
2022 /* Move typeahead to "buf", as much as fits. */
2023 len = 0;
2024 while (len < maxlen && typeaheadlen > 0)
2025 {
2026 buf[len++] = typeahead[0];
2027 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2028 }
2029 return len;
2030
Bram Moolenaar4f974752019-02-17 17:44:42 +01002031#else /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002032 return 0;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002033#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002034}
2035
Bram Moolenaar82881492012-11-20 16:53:39 +01002036#ifndef PROTO
2037# ifndef __MINGW32__
2038# include <shellapi.h> /* required for FindExecutable() */
2039# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002040#endif
2041
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002042/*
Bram Moolenaar43663192017-03-05 14:29:12 +01002043 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2044 * If "use_path" is FALSE: Return TRUE if "name" exists.
2045 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2046 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002047 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002048 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002049 static int
Bram Moolenaar43663192017-03-05 14:29:12 +01002050executable_exists(char *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002051{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002052 WCHAR *p;
2053 WCHAR fnamew[_MAX_PATH];
2054 WCHAR *dumw;
2055 WCHAR *wcurpath, *wnewpath;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002056 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057
Bram Moolenaar43663192017-03-05 14:29:12 +01002058 if (!use_path)
2059 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002060 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01002061 {
2062 if (path != NULL)
Bram Moolenaar066029e2017-03-05 15:19:32 +01002063 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002064 if (mch_isFullName((char_u *)name))
Bram Moolenaar066029e2017-03-05 15:19:32 +01002065 *path = vim_strsave((char_u *)name);
2066 else
2067 *path = FullName_save((char_u *)name, FALSE);
2068 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002069 return TRUE;
2070 }
2071 return FALSE;
2072 }
2073
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002074 p = enc_to_utf16((char_u *)name, NULL);
2075 if (p == NULL)
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002076 return FALSE;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002077
2078 wcurpath = _wgetenv(L"PATH");
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002079 wnewpath = ALLOC_MULT(WCHAR, wcslen(wcurpath) + 3);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002080 if (wnewpath == NULL)
2081 return FALSE;
2082 wcscpy(wnewpath, L".;");
2083 wcscat(wnewpath, wcurpath);
2084 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
2085 vim_free(wnewpath);
2086 vim_free(p);
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002087 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002088 return FALSE;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002089 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002090 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002091 if (path != NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002092 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002093 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002094}
2095
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002096#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2097 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002098/*
2099 * Bad parameter handler.
2100 *
2101 * Certain MS CRT functions will intentionally crash when passed invalid
2102 * parameters to highlight possible security holes. Setting this function as
2103 * the bad parameter handler will prevent the crash.
2104 *
2105 * In debug builds the parameters contain CRT information that might help track
2106 * down the source of a problem, but in non-debug builds the arguments are all
2107 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2108 * worth allowing these to make debugging of issues easier.
2109 */
2110 static void
2111bad_param_handler(const wchar_t *expression,
2112 const wchar_t *function,
2113 const wchar_t *file,
2114 unsigned int line,
2115 uintptr_t pReserved)
2116{
2117}
2118
2119# define SET_INVALID_PARAM_HANDLER \
2120 ((void)_set_invalid_parameter_handler(bad_param_handler))
2121#else
2122# define SET_INVALID_PARAM_HANDLER
2123#endif
2124
Bram Moolenaar4f974752019-02-17 17:44:42 +01002125#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002126
2127/*
2128 * GUI version of mch_init().
2129 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002130 static void
2131mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002132{
2133#ifndef __MINGW32__
2134 extern int _fmode;
2135#endif
2136
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002137 /* Silently handle invalid parameters to CRT functions */
2138 SET_INVALID_PARAM_HANDLER;
2139
Bram Moolenaar071d4272004-06-13 20:20:40 +00002140 /* Let critical errors result in a failure, not in a dialog box. Required
2141 * for the timestamp test to work on removed floppies. */
2142 SetErrorMode(SEM_FAILCRITICALERRORS);
2143
2144 _fmode = O_BINARY; /* we do our own CR-LF translation */
2145
2146 /* Specify window size. Is there a place to get the default from? */
2147 Rows = 25;
2148 Columns = 80;
2149
2150 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002151 {
2152 char_u vimrun_location[_MAX_PATH + 4];
2153
2154 /* First try in same directory as gvim.exe */
2155 STRCPY(vimrun_location, exe_name);
2156 STRCPY(gettail(vimrun_location), "vimrun.exe");
2157 if (mch_getperm(vimrun_location) >= 0)
2158 {
2159 if (*skiptowhite(vimrun_location) != NUL)
2160 {
2161 /* Enclose path with white space in double quotes. */
2162 mch_memmove(vimrun_location + 1, vimrun_location,
2163 STRLEN(vimrun_location) + 1);
2164 *vimrun_location = '"';
2165 STRCPY(gettail(vimrun_location), "vimrun\" ");
2166 }
2167 else
2168 STRCPY(gettail(vimrun_location), "vimrun ");
2169
2170 vimrun_path = (char *)vim_strsave(vimrun_location);
2171 s_dont_use_vimrun = FALSE;
2172 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002173 else if (executable_exists("vimrun.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002174 s_dont_use_vimrun = FALSE;
2175
2176 /* Don't give the warning for a missing vimrun.exe right now, but only
2177 * when vimrun was supposed to be used. Don't bother people that do
2178 * not need vimrun.exe. */
2179 if (s_dont_use_vimrun)
2180 need_vimrun_warning = TRUE;
2181 }
2182
2183 /*
2184 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2185 * Otherwise the default "findstr /n" is used.
2186 */
Bram Moolenaar43663192017-03-05 14:29:12 +01002187 if (!executable_exists("findstr.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002188 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2189
2190#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002191 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002192#endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002193
2194 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002195}
2196
2197
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002198#endif /* FEAT_GUI_MSWIN */
2199
2200#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002201
2202#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2203#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2204
2205/*
2206 * ClearConsoleBuffer()
2207 * Description:
2208 * Clears the entire contents of the console screen buffer, using the
2209 * specified attribute.
2210 * Returns:
2211 * TRUE on success
2212 */
2213 static BOOL
2214ClearConsoleBuffer(WORD wAttribute)
2215{
2216 CONSOLE_SCREEN_BUFFER_INFO csbi;
2217 COORD coord;
2218 DWORD NumCells, dummy;
2219
2220 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2221 return FALSE;
2222
2223 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2224 coord.X = 0;
2225 coord.Y = 0;
2226 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2227 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002228 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002229 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2230 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002231 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002232
2233 return TRUE;
2234}
2235
2236/*
2237 * FitConsoleWindow()
2238 * Description:
2239 * Checks if the console window will fit within given buffer dimensions.
2240 * Also, if requested, will shrink the window to fit.
2241 * Returns:
2242 * TRUE on success
2243 */
2244 static BOOL
2245FitConsoleWindow(
2246 COORD dwBufferSize,
2247 BOOL WantAdjust)
2248{
2249 CONSOLE_SCREEN_BUFFER_INFO csbi;
2250 COORD dwWindowSize;
2251 BOOL NeedAdjust = FALSE;
2252
2253 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2254 {
2255 /*
2256 * A buffer resize will fail if the current console window does
2257 * not lie completely within that buffer. To avoid this, we might
2258 * have to move and possibly shrink the window.
2259 */
2260 if (csbi.srWindow.Right >= dwBufferSize.X)
2261 {
2262 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2263 if (dwWindowSize.X > dwBufferSize.X)
2264 dwWindowSize.X = dwBufferSize.X;
2265 csbi.srWindow.Right = dwBufferSize.X - 1;
2266 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2267 NeedAdjust = TRUE;
2268 }
2269 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2270 {
2271 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2272 if (dwWindowSize.Y > dwBufferSize.Y)
2273 dwWindowSize.Y = dwBufferSize.Y;
2274 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2275 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2276 NeedAdjust = TRUE;
2277 }
2278 if (NeedAdjust && WantAdjust)
2279 {
2280 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2281 return FALSE;
2282 }
2283 return TRUE;
2284 }
2285
2286 return FALSE;
2287}
2288
2289typedef struct ConsoleBufferStruct
2290{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002291 BOOL IsValid;
2292 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002293 PCHAR_INFO Buffer;
2294 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002295 PSMALL_RECT Regions;
2296 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002297} ConsoleBuffer;
2298
2299/*
2300 * SaveConsoleBuffer()
2301 * Description:
2302 * Saves important information about the console buffer, including the
2303 * actual buffer contents. The saved information is suitable for later
2304 * restoration by RestoreConsoleBuffer().
2305 * Returns:
2306 * TRUE if all information was saved; FALSE otherwise
2307 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2308 */
2309 static BOOL
2310SaveConsoleBuffer(
2311 ConsoleBuffer *cb)
2312{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002313 DWORD NumCells;
2314 COORD BufferCoord;
2315 SMALL_RECT ReadRegion;
2316 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002317 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002318
Bram Moolenaar071d4272004-06-13 20:20:40 +00002319 if (cb == NULL)
2320 return FALSE;
2321
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002322 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002323 {
2324 cb->IsValid = FALSE;
2325 return FALSE;
2326 }
2327 cb->IsValid = TRUE;
2328
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002329 /*
2330 * Allocate a buffer large enough to hold the entire console screen
2331 * buffer. If this ConsoleBuffer structure has already been initialized
2332 * with a buffer of the correct size, then just use that one.
2333 */
2334 if (!cb->IsValid || cb->Buffer == NULL ||
2335 cb->BufferSize.X != cb->Info.dwSize.X ||
2336 cb->BufferSize.Y != cb->Info.dwSize.Y)
2337 {
2338 cb->BufferSize.X = cb->Info.dwSize.X;
2339 cb->BufferSize.Y = cb->Info.dwSize.Y;
2340 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2341 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002342 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002343 if (cb->Buffer == NULL)
2344 return FALSE;
2345 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002346
2347 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002348 * We will now copy the console screen buffer into our buffer.
2349 * ReadConsoleOutput() seems to be limited as far as how much you
2350 * can read at a time. Empirically, this number seems to be about
2351 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2352 * in chunks until it is all copied. The chunks will all have the
2353 * same horizontal characteristics, so initialize them now. The
2354 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002355 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002356 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002357 ReadRegion.Left = 0;
2358 ReadRegion.Right = cb->Info.dwSize.X - 1;
2359 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002360
2361 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2362 if (cb->Regions == NULL || numregions != cb->NumRegions)
2363 {
2364 cb->NumRegions = numregions;
2365 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002366 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002367 if (cb->Regions == NULL)
2368 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002369 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002370 return FALSE;
2371 }
2372 }
2373
2374 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002375 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002376 /*
2377 * Read into position (0, Y) in our buffer.
2378 */
2379 BufferCoord.Y = Y;
2380 /*
2381 * Read the region whose top left corner is (0, Y) and whose bottom
2382 * right corner is (width - 1, Y + Y_incr - 1). This should define
2383 * a region of size width by Y_incr. Don't worry if this region is
2384 * too large for the remaining buffer; it will be cropped.
2385 */
2386 ReadRegion.Top = Y;
2387 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002388 if (!ReadConsoleOutputW(g_hConOut, /* output handle */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002389 cb->Buffer, /* our buffer */
2390 cb->BufferSize, /* dimensions of our buffer */
2391 BufferCoord, /* offset in our buffer */
2392 &ReadRegion)) /* region to save */
2393 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002394 VIM_CLEAR(cb->Buffer);
2395 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002396 return FALSE;
2397 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002398 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002399 }
2400
2401 return TRUE;
2402}
2403
2404/*
2405 * RestoreConsoleBuffer()
2406 * Description:
2407 * Restores important information about the console buffer, including the
2408 * actual buffer contents, if desired. The information to restore is in
2409 * the same format used by SaveConsoleBuffer().
2410 * Returns:
2411 * TRUE on success
2412 */
2413 static BOOL
2414RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002415 ConsoleBuffer *cb,
2416 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002417{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002418 COORD BufferCoord;
2419 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002420 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002421
2422 if (cb == NULL || !cb->IsValid)
2423 return FALSE;
2424
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002425 /*
2426 * Before restoring the buffer contents, clear the current buffer, and
2427 * restore the cursor position and window information. Doing this now
2428 * prevents old buffer contents from "flashing" onto the screen.
2429 */
2430 if (RestoreScreen)
2431 ClearConsoleBuffer(cb->Info.wAttributes);
2432
2433 FitConsoleWindow(cb->Info.dwSize, TRUE);
2434 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2435 return FALSE;
2436 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2437 return FALSE;
2438
2439 if (!RestoreScreen)
2440 {
2441 /*
2442 * No need to restore the screen buffer contents, so we're done.
2443 */
2444 return TRUE;
2445 }
2446
2447 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2448 return FALSE;
2449 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2450 return FALSE;
2451
2452 /*
2453 * Restore the screen buffer contents.
2454 */
2455 if (cb->Buffer != NULL)
2456 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002457 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002458 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002459 BufferCoord.X = cb->Regions[i].Left;
2460 BufferCoord.Y = cb->Regions[i].Top;
2461 WriteRegion = cb->Regions[i];
2462 if (!WriteConsoleOutputW(g_hConOut, /* output handle */
2463 cb->Buffer, /* our buffer */
2464 cb->BufferSize, /* dimensions of our buffer */
2465 BufferCoord, /* offset in our buffer */
2466 &WriteRegion)) /* region to restore */
Bram Moolenaar444fda22017-08-11 20:37:00 +02002467 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002468 }
2469 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002470
2471 return TRUE;
2472}
2473
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002474#define FEAT_RESTORE_ORIG_SCREEN
2475#ifdef FEAT_RESTORE_ORIG_SCREEN
2476static ConsoleBuffer g_cbOrig = { 0 };
2477#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002478static ConsoleBuffer g_cbNonTermcap = { 0 };
2479static ConsoleBuffer g_cbTermcap = { 0 };
2480
2481#ifdef FEAT_TITLE
Bram Moolenaar071d4272004-06-13 20:20:40 +00002482char g_szOrigTitle[256] = { 0 };
2483HWND g_hWnd = NULL; /* also used in os_mswin.c */
2484static HICON g_hOrigIconSmall = NULL;
2485static HICON g_hOrigIcon = NULL;
2486static HICON g_hVimIcon = NULL;
2487static BOOL g_fCanChangeIcon = FALSE;
2488
2489/* ICON* are not defined in VC++ 4.0 */
2490#ifndef ICON_SMALL
2491#define ICON_SMALL 0
2492#endif
2493#ifndef ICON_BIG
2494#define ICON_BIG 1
2495#endif
2496/*
2497 * GetConsoleIcon()
2498 * Description:
2499 * Attempts to retrieve the small icon and/or the big icon currently in
2500 * use by a given window.
2501 * Returns:
2502 * TRUE on success
2503 */
2504 static BOOL
2505GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002506 HWND hWnd,
2507 HICON *phIconSmall,
2508 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002509{
2510 if (hWnd == NULL)
2511 return FALSE;
2512
2513 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002514 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2515 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002516 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002517 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2518 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519 return TRUE;
2520}
2521
2522/*
2523 * SetConsoleIcon()
2524 * Description:
2525 * Attempts to change the small icon and/or the big icon currently in
2526 * use by a given window.
2527 * Returns:
2528 * TRUE on success
2529 */
2530 static BOOL
2531SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002532 HWND hWnd,
2533 HICON hIconSmall,
2534 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002535{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002536 if (hWnd == NULL)
2537 return FALSE;
2538
2539 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002540 SendMessage(hWnd, WM_SETICON,
2541 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002542 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002543 SendMessage(hWnd, WM_SETICON,
2544 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002545 return TRUE;
2546}
2547
2548/*
2549 * SaveConsoleTitleAndIcon()
2550 * Description:
2551 * Saves the current console window title in g_szOrigTitle, for later
2552 * restoration. Also, attempts to obtain a handle to the console window,
2553 * and use it to save the small and big icons currently in use by the
2554 * console window. This is not always possible on some versions of Windows;
2555 * nor is it possible when running Vim remotely using Telnet (since the
2556 * console window the user sees is owned by a remote process).
2557 */
2558 static void
2559SaveConsoleTitleAndIcon(void)
2560{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002561 /* Save the original title. */
2562 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2563 return;
2564
2565 /*
2566 * Obtain a handle to the console window using GetConsoleWindow() from
2567 * KERNEL32.DLL; we need to handle in order to change the window icon.
2568 * This function only exists on NT-based Windows, starting with Windows
2569 * 2000. On older operating systems, we can't change the window icon
2570 * anyway.
2571 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002572 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002573 if (g_hWnd == NULL)
2574 return;
2575
2576 /* Save the original console window icon. */
2577 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2578 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2579 return;
2580
2581 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002582 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002583 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002584 if (g_hVimIcon != NULL)
2585 g_fCanChangeIcon = TRUE;
2586}
2587#endif
2588
2589static int g_fWindInitCalled = FALSE;
2590static int g_fTermcapMode = FALSE;
2591static CONSOLE_CURSOR_INFO g_cci;
2592static DWORD g_cmodein = 0;
2593static DWORD g_cmodeout = 0;
2594
2595/*
2596 * non-GUI version of mch_init().
2597 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002598 static void
2599mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002600{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002601#ifndef FEAT_RESTORE_ORIG_SCREEN
2602 CONSOLE_SCREEN_BUFFER_INFO csbi;
2603#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002604#ifndef __MINGW32__
2605 extern int _fmode;
2606#endif
2607
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002608 /* Silently handle invalid parameters to CRT functions */
2609 SET_INVALID_PARAM_HANDLER;
2610
Bram Moolenaar071d4272004-06-13 20:20:40 +00002611 /* Let critical errors result in a failure, not in a dialog box. Required
2612 * for the timestamp test to work on removed floppies. */
2613 SetErrorMode(SEM_FAILCRITICALERRORS);
2614
2615 _fmode = O_BINARY; /* we do our own CR-LF translation */
2616 out_flush();
2617
2618 /* Obtain handles for the standard Console I/O devices */
2619 if (read_cmd_fd == 0)
2620 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2621 else
2622 create_conin();
2623 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2624
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002625#ifdef FEAT_RESTORE_ORIG_SCREEN
2626 /* Save the initial console buffer for later restoration */
2627 SaveConsoleBuffer(&g_cbOrig);
2628 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2629#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002630 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002631 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2632 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2633#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002634 if (cterm_normal_fg_color == 0)
2635 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2636 if (cterm_normal_bg_color == 0)
2637 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2638
Bram Moolenaarbdace832019-03-02 10:13:42 +01002639 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002640 g_color_index_fg = g_attrDefault & 0xf;
2641 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2642
Bram Moolenaar071d4272004-06-13 20:20:40 +00002643 /* set termcap codes to current text attributes */
2644 update_tcap(g_attrCurrent);
2645
2646 GetConsoleCursorInfo(g_hConOut, &g_cci);
2647 GetConsoleMode(g_hConIn, &g_cmodein);
2648 GetConsoleMode(g_hConOut, &g_cmodeout);
2649
2650#ifdef FEAT_TITLE
2651 SaveConsoleTitleAndIcon();
2652 /*
2653 * Set both the small and big icons of the console window to Vim's icon.
2654 * Note that Vim presently only has one size of icon (32x32), but it
2655 * automatically gets scaled down to 16x16 when setting the small icon.
2656 */
2657 if (g_fCanChangeIcon)
2658 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2659#endif
2660
2661 ui_get_shellsize();
2662
2663#ifdef MCH_WRITE_DUMP
2664 fdDump = fopen("dump", "wt");
2665
2666 if (fdDump)
2667 {
2668 time_t t;
2669
2670 time(&t);
2671 fputs(ctime(&t), fdDump);
2672 fflush(fdDump);
2673 }
2674#endif
2675
2676 g_fWindInitCalled = TRUE;
2677
2678#ifdef FEAT_MOUSE
2679 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2680#endif
2681
2682#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002683 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002684#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002685
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002686 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002687 vtp_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002688}
2689
2690/*
2691 * non-GUI version of mch_exit().
2692 * Shut down and exit with status `r'
2693 * Careful: mch_exit() may be called before mch_init()!
2694 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002695 static void
2696mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002697{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002698 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002699
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002700 vtp_exit();
2701
Bram Moolenaar955f1982017-02-05 15:10:51 +01002702 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002703 if (g_fWindInitCalled)
2704 settmode(TMODE_COOK);
2705
2706 ml_close_all(TRUE); /* remove all memfiles */
2707
2708 if (g_fWindInitCalled)
2709 {
2710#ifdef FEAT_TITLE
Bram Moolenaar40385db2018-08-07 22:31:44 +02002711 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002712 /*
2713 * Restore both the small and big icons of the console window to
2714 * what they were at startup. Don't do this when the window is
2715 * closed, Vim would hang here.
2716 */
2717 if (g_fCanChangeIcon && !g_fForceExit)
2718 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2719#endif
2720
2721#ifdef MCH_WRITE_DUMP
2722 if (fdDump)
2723 {
2724 time_t t;
2725
2726 time(&t);
2727 fputs(ctime(&t), fdDump);
2728 fclose(fdDump);
2729 }
2730 fdDump = NULL;
2731#endif
2732 }
2733
2734 SetConsoleCursorInfo(g_hConOut, &g_cci);
2735 SetConsoleMode(g_hConIn, g_cmodein);
2736 SetConsoleMode(g_hConOut, g_cmodeout);
2737
2738#ifdef DYNAMIC_GETTEXT
2739 dyn_libintl_end();
2740#endif
2741
2742 exit(r);
2743}
Bram Moolenaar4f974752019-02-17 17:44:42 +01002744#endif /* !FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002745
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002746 void
2747mch_init(void)
2748{
2749#ifdef VIMDLL
2750 if (gui.starting)
2751 mch_init_g();
2752 else
2753 mch_init_c();
2754#elif defined(FEAT_GUI_MSWIN)
2755 mch_init_g();
2756#else
2757 mch_init_c();
2758#endif
2759}
2760
2761 void
2762mch_exit(int r)
2763{
2764#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02002765 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002766 mch_exit_g(r);
2767 else
2768 mch_exit_c(r);
2769#elif defined(FEAT_GUI_MSWIN)
2770 mch_exit_g(r);
2771#else
2772 mch_exit_c(r);
2773#endif
2774}
2775
Bram Moolenaar071d4272004-06-13 20:20:40 +00002776/*
2777 * Do we have an interactive window?
2778 */
2779 int
2780mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002781 int argc UNUSED,
2782 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002783{
2784 get_exe_name();
2785
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002786#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002787 return OK; /* GUI always has a tty */
2788#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002789# ifdef VIMDLL
2790 if (gui.in_use)
2791 return OK;
2792# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002793 if (isatty(1))
2794 return OK;
2795 return FAIL;
2796#endif
2797}
2798
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002799/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002800 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002801 * When "len" is > 0, also expand short to long filenames.
2802 */
2803 void
2804fname_case(
2805 char_u *name,
2806 int len)
2807{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002808 int flen;
2809 WCHAR *p;
2810 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002811
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002812 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002813 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002814 return;
2815
2816 slash_adjust(name);
2817
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002818 p = enc_to_utf16(name, NULL);
2819 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002820 return;
2821
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002822 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002823 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002824 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002825
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002826 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002827 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002828 if (len > 0 || flen >= (int)STRLEN(q))
2829 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2830 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002831 }
2832 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002833 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002834}
2835
2836
2837/*
2838 * Insert user name in s[len].
2839 */
2840 int
2841mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002842 char_u *s,
2843 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002844{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002845 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2846 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002847
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002848 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002849 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002850 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002851
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002852 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002853 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002854 vim_strncpy(s, p, len - 1);
2855 vim_free(p);
2856 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002857 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002858 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002859 s[0] = NUL;
2860 return FAIL;
2861}
2862
2863
2864/*
2865 * Insert host name in s[len].
2866 */
2867 void
2868mch_get_host_name(
2869 char_u *s,
2870 int len)
2871{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002872 WCHAR wszHostName[256 + 1];
2873 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002874
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002875 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002876 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002877 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002878
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002879 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002880 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002881 vim_strncpy(s, p, len - 1);
2882 vim_free(p);
2883 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002884 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002885 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002886}
2887
2888
2889/*
2890 * return process ID
2891 */
2892 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002893mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002894{
2895 return (long)GetCurrentProcessId();
2896}
2897
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02002898/*
2899 * return TRUE if process "pid" is still running
2900 */
2901 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02002902mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02002903{
2904 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
2905 DWORD status = 0;
2906 int ret = FALSE;
2907
2908 if (hProcess == NULL)
2909 return FALSE; // might not have access
2910 if (GetExitCodeProcess(hProcess, &status) )
2911 ret = status == STILL_ACTIVE;
2912 CloseHandle(hProcess);
2913 return ret;
2914}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002915
2916/*
2917 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2918 * Return OK for success, FAIL for failure.
2919 */
2920 int
2921mch_dirname(
2922 char_u *buf,
2923 int len)
2924{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002925 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002926
Bram Moolenaar071d4272004-06-13 20:20:40 +00002927 /*
2928 * Originally this was:
2929 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2930 * But the Win32s known bug list says that getcwd() doesn't work
2931 * so use the Win32 system call instead. <Negri>
2932 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002933 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002934 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002935 WCHAR wcbuf[_MAX_PATH + 1];
2936 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002937
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002938 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002939 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002940 p = utf16_to_enc(wcbuf, NULL);
2941 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02002942 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002943 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00002944 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002945 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002946 }
2947 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002948 if (p == NULL)
2949 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002950
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002951 if (p != NULL)
2952 {
2953 vim_strncpy(buf, p, len - 1);
2954 vim_free(p);
2955 return OK;
2956 }
2957 }
2958 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002959}
2960
2961/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01002962 * Get file permissions for "name".
2963 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002964 */
2965 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002966mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002967{
Bram Moolenaar8767f522016-07-01 17:17:39 +02002968 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01002969 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002970
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002971 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01002972 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002973}
2974
2975
2976/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002977 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002978 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002979 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002980 */
2981 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002982mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002983{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002984 long n;
2985 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002986
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002987 p = enc_to_utf16(name, NULL);
2988 if (p == NULL)
2989 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002990
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002991 n = _wchmod(p, perm);
2992 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002993 if (n == -1)
2994 return FAIL;
2995
2996 win32_set_archive(name);
2997
2998 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002999}
3000
3001/*
3002 * Set hidden flag for "name".
3003 */
3004 void
3005mch_hide(char_u *name)
3006{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003007 int attrs = win32_getattrs(name);
3008 if (attrs == -1)
3009 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003010
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003011 attrs |= FILE_ATTRIBUTE_HIDDEN;
3012 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003013}
3014
3015/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003016 * Return TRUE if file "name" exists and is hidden.
3017 */
3018 int
3019mch_ishidden(char_u *name)
3020{
3021 int f = win32_getattrs(name);
3022
3023 if (f == -1)
3024 return FALSE; /* file does not exist at all */
3025
3026 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3027}
3028
3029/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003030 * return TRUE if "name" is a directory
3031 * return FALSE if "name" is not a directory or upon error
3032 */
3033 int
3034mch_isdir(char_u *name)
3035{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003036 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003037
3038 if (f == -1)
3039 return FALSE; /* file does not exist at all */
3040
3041 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3042}
3043
3044/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003045 * return TRUE if "name" is a directory, NOT a symlink to a directory
3046 * return FALSE if "name" is not a directory
3047 * return FALSE for error
3048 */
3049 int
3050mch_isrealdir(char_u *name)
3051{
3052 return mch_isdir(name) && !mch_is_symbolic_link(name);
3053}
3054
3055/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003056 * Create directory "name".
3057 * Return 0 on success, -1 on error.
3058 */
3059 int
3060mch_mkdir(char_u *name)
3061{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003062 WCHAR *p;
3063 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003064
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003065 p = enc_to_utf16(name, NULL);
3066 if (p == NULL)
3067 return -1;
3068 retval = _wmkdir(p);
3069 vim_free(p);
3070 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003071}
3072
3073/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003074 * Delete directory "name".
3075 * Return 0 on success, -1 on error.
3076 */
3077 int
3078mch_rmdir(char_u *name)
3079{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003080 WCHAR *p;
3081 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003082
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003083 p = enc_to_utf16(name, NULL);
3084 if (p == NULL)
3085 return -1;
3086 retval = _wrmdir(p);
3087 vim_free(p);
3088 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003089}
3090
3091/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003092 * Return TRUE if file "fname" has more than one link.
3093 */
3094 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003095mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003096{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003097 BY_HANDLE_FILE_INFORMATION info;
3098
3099 return win32_fileinfo(fname, &info) == FILEINFO_OK
3100 && info.nNumberOfLinks > 1;
3101}
3102
3103/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003104 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003105 */
3106 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003107mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003108{
3109 HANDLE hFind;
3110 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003111 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003112 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003113 WIN32_FIND_DATAW findDataW;
3114
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003115 wn = enc_to_utf16(name, NULL);
3116 if (wn == NULL)
3117 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003118
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003119 hFind = FindFirstFileW(wn, &findDataW);
3120 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003121 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003122 {
3123 fileFlags = findDataW.dwFileAttributes;
3124 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003125 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003126 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003127
3128 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003129 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3130 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003131 res = TRUE;
3132
3133 return res;
3134}
3135
3136/*
3137 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3138 * link.
3139 */
3140 int
3141mch_is_linked(char_u *fname)
3142{
3143 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3144 return TRUE;
3145 return FALSE;
3146}
3147
3148/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003149 * Get the by-handle-file-information for "fname".
3150 * Returns FILEINFO_OK when OK.
3151 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3152 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3153 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3154 */
3155 int
3156win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3157{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003158 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003159 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003160 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003161
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003162 wn = enc_to_utf16(fname, NULL);
3163 if (wn == NULL)
3164 return FILEINFO_ENC_FAIL;
3165
3166 hFile = CreateFileW(wn, // file name
3167 GENERIC_READ, // access mode
3168 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3169 NULL, // security descriptor
3170 OPEN_EXISTING, // creation disposition
3171 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3172 NULL); // handle to template file
3173 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003174
3175 if (hFile != INVALID_HANDLE_VALUE)
3176 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003177 if (GetFileInformationByHandle(hFile, info) != 0)
3178 res = FILEINFO_OK;
3179 else
3180 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003181 CloseHandle(hFile);
3182 }
3183
Bram Moolenaar03f48552006-02-28 23:52:23 +00003184 return res;
3185}
3186
3187/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003188 * get file attributes for `name'
3189 * -1 : error
3190 * else FILE_ATTRIBUTE_* defined in winnt.h
3191 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003192 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003193win32_getattrs(char_u *name)
3194{
3195 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003196 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003197
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003198 p = enc_to_utf16(name, NULL);
3199 if (p == NULL)
3200 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003201
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003202 attr = GetFileAttributesW(p);
3203 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003204
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003205 return attr;
3206}
3207
3208/*
3209 * set file attributes for `name' to `attrs'
3210 *
3211 * return -1 for failure, 0 otherwise
3212 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003213 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003214win32_setattrs(char_u *name, int attrs)
3215{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003216 int res;
3217 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003218
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003219 p = enc_to_utf16(name, NULL);
3220 if (p == NULL)
3221 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003222
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003223 res = SetFileAttributesW(p, attrs);
3224 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003225
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003226 return res ? 0 : -1;
3227}
3228
3229/*
3230 * Set archive flag for "name".
3231 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003232 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003233win32_set_archive(char_u *name)
3234{
3235 int attrs = win32_getattrs(name);
3236 if (attrs == -1)
3237 return -1;
3238
3239 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3240 return win32_setattrs(name, attrs);
3241}
3242
3243/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003244 * Return TRUE if file or directory "name" is writable (not readonly).
3245 * Strange semantics of Win32: a readonly directory is writable, but you can't
3246 * delete a file. Let's say this means it is writable.
3247 */
3248 int
3249mch_writable(char_u *name)
3250{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003251 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003252
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003253 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3254 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003255}
3256
Bram Moolenaar071d4272004-06-13 20:20:40 +00003257/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003258 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003259 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003260 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3261 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003262 */
3263 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003264mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003265{
Bram Moolenaar86621892019-03-30 21:51:28 +01003266 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
3267 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
3268 // UTF-8.
3269 char_u buf[_MAX_PATH * 3];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003270 int len = (int)STRLEN(name);
Bram Moolenaar82956662018-10-06 15:18:45 +02003271 char_u *p, *saved;
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003272
Bram Moolenaar86621892019-03-30 21:51:28 +01003273 if (len >= sizeof(buf)) // safety check
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003274 return FALSE;
3275
Bram Moolenaar86621892019-03-30 21:51:28 +01003276 // Try using the name directly when a Unix-shell like 'shell'.
Bram Moolenaar82956662018-10-06 15:18:45 +02003277 if (strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaar43663192017-03-05 14:29:12 +01003278 if (executable_exists((char *)name, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003279 return TRUE;
3280
3281 /*
3282 * Loop over all extensions in $PATHEXT.
3283 */
Bram Moolenaar82956662018-10-06 15:18:45 +02003284 p = mch_getenv("PATHEXT");
3285 if (p == NULL)
3286 p = (char_u *)".com;.exe;.bat;.cmd";
3287 saved = vim_strsave(p);
3288 if (saved == NULL)
3289 return FALSE;
3290 p = saved;
3291 while (*p)
3292 {
3293 char_u *tmp = vim_strchr(p, ';');
3294
3295 if (tmp != NULL)
3296 *tmp = NUL;
3297 if (_stricoll((char *)name + len - STRLEN(p), (char *)p) == 0
3298 && executable_exists((char *)name, path, use_path))
3299 {
3300 vim_free(saved);
3301 return TRUE;
3302 }
3303 if (tmp == NULL)
3304 break;
3305 p = tmp + 1;
3306 }
3307 vim_free(saved);
3308
Bram Moolenaar86621892019-03-30 21:51:28 +01003309 vim_strncpy(buf, name, sizeof(buf) - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003310 p = mch_getenv("PATHEXT");
3311 if (p == NULL)
3312 p = (char_u *)".com;.exe;.bat;.cmd";
3313 while (*p)
3314 {
3315 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3316 {
3317 /* A single "." means no extension is added. */
3318 buf[len] = NUL;
3319 ++p;
3320 if (*p)
3321 ++p;
3322 }
3323 else
Bram Moolenaar86621892019-03-30 21:51:28 +01003324 copy_option_part(&p, buf + len, sizeof(buf) - len, ";");
Bram Moolenaar43663192017-03-05 14:29:12 +01003325 if (executable_exists((char *)buf, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003326 return TRUE;
3327 }
3328 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003329}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003330
3331/*
3332 * Check what "name" is:
3333 * NODE_NORMAL: file or directory (or doesn't exist)
3334 * NODE_WRITABLE: writable device, socket, fifo, etc.
3335 * NODE_OTHER: non-writable things
3336 */
3337 int
3338mch_nodetype(char_u *name)
3339{
3340 HANDLE hFile;
3341 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003342 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003343
Bram Moolenaar043545e2006-10-10 16:44:07 +00003344 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3345 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3346 * here. */
3347 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3348 return NODE_WRITABLE;
3349
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003350 wn = enc_to_utf16(name, NULL);
3351 if (wn == NULL)
3352 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003353
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003354 hFile = CreateFileW(wn, // file name
3355 GENERIC_WRITE, // access mode
3356 0, // share mode
3357 NULL, // security descriptor
3358 OPEN_EXISTING, // creation disposition
3359 0, // file attributes
3360 NULL); // handle to template file
3361 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003362 if (hFile == INVALID_HANDLE_VALUE)
3363 return NODE_NORMAL;
3364
3365 type = GetFileType(hFile);
3366 CloseHandle(hFile);
3367 if (type == FILE_TYPE_CHAR)
3368 return NODE_WRITABLE;
3369 if (type == FILE_TYPE_DISK)
3370 return NODE_NORMAL;
3371 return NODE_OTHER;
3372}
3373
3374#ifdef HAVE_ACL
3375struct my_acl
3376{
3377 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3378 PSID pSidOwner;
3379 PSID pSidGroup;
3380 PACL pDacl;
3381 PACL pSacl;
3382};
3383#endif
3384
3385/*
3386 * Return a pointer to the ACL of file "fname" in allocated memory.
3387 * Return NULL if the ACL is not available for whatever reason.
3388 */
3389 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003390mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003391{
3392#ifndef HAVE_ACL
3393 return (vim_acl_T)NULL;
3394#else
3395 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003396 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003397
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003398 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003399 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003400 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003401 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003402
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003403 wn = enc_to_utf16(fname, NULL);
3404 if (wn == NULL)
3405 return NULL;
3406
3407 // Try to retrieve the entire security descriptor.
3408 err = GetNamedSecurityInfoW(
3409 wn, // Abstract filename
3410 SE_FILE_OBJECT, // File Object
3411 OWNER_SECURITY_INFORMATION |
3412 GROUP_SECURITY_INFORMATION |
3413 DACL_SECURITY_INFORMATION |
3414 SACL_SECURITY_INFORMATION,
3415 &p->pSidOwner, // Ownership information.
3416 &p->pSidGroup, // Group membership.
3417 &p->pDacl, // Discretionary information.
3418 &p->pSacl, // For auditing purposes.
3419 &p->pSecurityDescriptor);
3420 if (err == ERROR_ACCESS_DENIED ||
3421 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003422 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003423 // Retrieve only DACL.
3424 (void)GetNamedSecurityInfoW(
3425 wn,
3426 SE_FILE_OBJECT,
3427 DACL_SECURITY_INFORMATION,
3428 NULL,
3429 NULL,
3430 &p->pDacl,
3431 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003432 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003433 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003434 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003435 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003436 mch_free_acl((vim_acl_T)p);
3437 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003438 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003439 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003440 }
3441
3442 return (vim_acl_T)p;
3443#endif
3444}
3445
Bram Moolenaar27515922013-06-29 15:36:26 +02003446#ifdef HAVE_ACL
3447/*
3448 * Check if "acl" contains inherited ACE.
3449 */
3450 static BOOL
3451is_acl_inherited(PACL acl)
3452{
3453 DWORD i;
3454 ACL_SIZE_INFORMATION acl_info;
3455 PACCESS_ALLOWED_ACE ace;
3456
3457 acl_info.AceCount = 0;
3458 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3459 for (i = 0; i < acl_info.AceCount; i++)
3460 {
3461 GetAce(acl, i, (LPVOID *)&ace);
3462 if (ace->Header.AceFlags & INHERITED_ACE)
3463 return TRUE;
3464 }
3465 return FALSE;
3466}
3467#endif
3468
Bram Moolenaar071d4272004-06-13 20:20:40 +00003469/*
3470 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3471 * Errors are ignored.
3472 * This must only be called with "acl" equal to what mch_get_acl() returned.
3473 */
3474 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003475mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003476{
3477#ifdef HAVE_ACL
3478 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003479 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003480 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003481
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003482 if (p == NULL)
3483 return;
3484
3485 wn = enc_to_utf16(fname, NULL);
3486 if (wn == NULL)
3487 return;
3488
3489 // Set security flags
3490 if (p->pSidOwner)
3491 sec_info |= OWNER_SECURITY_INFORMATION;
3492 if (p->pSidGroup)
3493 sec_info |= GROUP_SECURITY_INFORMATION;
3494 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003495 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003496 sec_info |= DACL_SECURITY_INFORMATION;
3497 // Do not inherit its parent's DACL.
3498 // If the DACL is inherited, Cygwin permissions would be changed.
3499 if (!is_acl_inherited(p->pDacl))
3500 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003501 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003502 if (p->pSacl)
3503 sec_info |= SACL_SECURITY_INFORMATION;
3504
3505 (void)SetNamedSecurityInfoW(
3506 wn, // Abstract filename
3507 SE_FILE_OBJECT, // File Object
3508 sec_info,
3509 p->pSidOwner, // Ownership information.
3510 p->pSidGroup, // Group membership.
3511 p->pDacl, // Discretionary information.
3512 p->pSacl // For auditing purposes.
3513 );
3514 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003515#endif
3516}
3517
3518 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003519mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003520{
3521#ifdef HAVE_ACL
3522 struct my_acl *p = (struct my_acl *)acl;
3523
3524 if (p != NULL)
3525 {
3526 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3527 vim_free(p);
3528 }
3529#endif
3530}
3531
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003532#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003533
3534/*
3535 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3536 */
3537 static BOOL WINAPI
3538handler_routine(
3539 DWORD dwCtrlType)
3540{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003541 INPUT_RECORD ir;
3542 DWORD out;
3543
Bram Moolenaar071d4272004-06-13 20:20:40 +00003544 switch (dwCtrlType)
3545 {
3546 case CTRL_C_EVENT:
3547 if (ctrl_c_interrupts)
3548 g_fCtrlCPressed = TRUE;
3549 return TRUE;
3550
3551 case CTRL_BREAK_EVENT:
3552 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003553 ctrl_break_was_pressed = TRUE;
3554 /* ReadConsoleInput is blocking, send a key event to continue. */
3555 ir.EventType = KEY_EVENT;
3556 ir.Event.KeyEvent.bKeyDown = TRUE;
3557 ir.Event.KeyEvent.wRepeatCount = 1;
3558 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3559 ir.Event.KeyEvent.wVirtualScanCode = 0;
3560 ir.Event.KeyEvent.dwControlKeyState = 0;
3561 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3562 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003563 return TRUE;
3564
3565 /* fatal events: shut down gracefully */
3566 case CTRL_CLOSE_EVENT:
3567 case CTRL_LOGOFF_EVENT:
3568 case CTRL_SHUTDOWN_EVENT:
3569 windgoto((int)Rows - 1, 0);
3570 g_fForceExit = TRUE;
3571
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003572 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003573 (dwCtrlType == CTRL_CLOSE_EVENT
3574 ? _("close")
3575 : dwCtrlType == CTRL_LOGOFF_EVENT
3576 ? _("logoff")
3577 : _("shutdown")));
3578#ifdef DEBUG
3579 OutputDebugString(IObuff);
3580#endif
3581
3582 preserve_exit(); /* output IObuff, preserve files and exit */
3583
3584 return TRUE; /* not reached */
3585
3586 default:
3587 return FALSE;
3588 }
3589}
3590
3591
3592/*
3593 * set the tty in (raw) ? "raw" : "cooked" mode
3594 */
3595 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003596mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003597{
3598 DWORD cmodein;
3599 DWORD cmodeout;
3600 BOOL bEnableHandler;
3601
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003602# ifdef VIMDLL
3603 if (gui.in_use)
3604 return;
3605# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003606 GetConsoleMode(g_hConIn, &cmodein);
3607 GetConsoleMode(g_hConOut, &cmodeout);
3608 if (tmode == TMODE_RAW)
3609 {
3610 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3611 ENABLE_ECHO_INPUT);
3612#ifdef FEAT_MOUSE
3613 if (g_fMouseActive)
3614 cmodein |= ENABLE_MOUSE_INPUT;
3615#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003616 cmodeout &= ~(
3617#ifdef FEAT_TERMGUICOLORS
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003618 /* Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003619 * VTP. */
3620 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
3621#else
3622 ENABLE_PROCESSED_OUTPUT |
3623#endif
3624 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003625 bEnableHandler = TRUE;
3626 }
3627 else /* cooked */
3628 {
3629 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3630 ENABLE_ECHO_INPUT);
3631 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3632 bEnableHandler = FALSE;
3633 }
3634 SetConsoleMode(g_hConIn, cmodein);
3635 SetConsoleMode(g_hConOut, cmodeout);
3636 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3637
3638#ifdef MCH_WRITE_DUMP
3639 if (fdDump)
3640 {
3641 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3642 tmode == TMODE_RAW ? "raw" :
3643 tmode == TMODE_COOK ? "cooked" : "normal",
3644 cmodein, cmodeout);
3645 fflush(fdDump);
3646 }
3647#endif
3648}
3649
3650
3651/*
3652 * Get the size of the current window in `Rows' and `Columns'
3653 * Return OK when size could be determined, FAIL otherwise.
3654 */
3655 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003656mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003657{
3658 CONSOLE_SCREEN_BUFFER_INFO csbi;
3659
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003660# ifdef VIMDLL
3661 if (gui.in_use)
3662 return OK;
3663# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003664 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3665 {
3666 /*
3667 * For some reason, we are trying to get the screen dimensions
3668 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3669 * variables are really intended to mean the size of Vim screen
3670 * while in termcap mode.
3671 */
3672 Rows = g_cbTermcap.Info.dwSize.Y;
3673 Columns = g_cbTermcap.Info.dwSize.X;
3674 }
3675 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3676 {
3677 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3678 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3679 }
3680 else
3681 {
3682 Rows = 25;
3683 Columns = 80;
3684 }
3685 return OK;
3686}
3687
3688/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003689 * Resize console buffer to 'COORD'
3690 */
3691 static void
3692ResizeConBuf(
3693 HANDLE hConsole,
3694 COORD coordScreen)
3695{
3696 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3697 {
3698#ifdef MCH_WRITE_DUMP
3699 if (fdDump)
3700 {
3701 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3702 GetLastError());
3703 fflush(fdDump);
3704 }
3705#endif
3706 }
3707}
3708
3709/*
3710 * Resize console window size to 'srWindowRect'
3711 */
3712 static void
3713ResizeWindow(
3714 HANDLE hConsole,
3715 SMALL_RECT srWindowRect)
3716{
3717 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
3718 {
3719#ifdef MCH_WRITE_DUMP
3720 if (fdDump)
3721 {
3722 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3723 GetLastError());
3724 fflush(fdDump);
3725 }
3726#endif
3727 }
3728}
3729
3730/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003731 * Set a console window to `xSize' * `ySize'
3732 */
3733 static void
3734ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003735 HANDLE hConsole,
3736 int xSize,
3737 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003738{
3739 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3740 SMALL_RECT srWindowRect; /* hold the new console size */
3741 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003742 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02003743 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003744
3745#ifdef MCH_WRITE_DUMP
3746 if (fdDump)
3747 {
3748 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3749 fflush(fdDump);
3750 }
3751#endif
3752
3753 /* get the largest size we can size the console window to */
3754 coordScreen = GetLargestConsoleWindowSize(hConsole);
3755
3756 /* define the new console window size and scroll position */
3757 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3758 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3759 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3760
3761 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3762 {
3763 int sx, sy;
3764
3765 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3766 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3767 if (sy < ySize || sx < xSize)
3768 {
3769 /*
3770 * Increasing number of lines/columns, do buffer first.
3771 * Use the maximal size in x and y direction.
3772 */
3773 if (sy < ySize)
3774 coordScreen.Y = ySize;
3775 else
3776 coordScreen.Y = sy;
3777 if (sx < xSize)
3778 coordScreen.X = xSize;
3779 else
3780 coordScreen.X = sx;
3781 SetConsoleScreenBufferSize(hConsole, coordScreen);
3782 }
3783 }
3784
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003785 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003786 coordScreen.X = xSize;
3787 coordScreen.Y = ySize;
3788
Bram Moolenaar2551c032018-08-23 22:38:31 +02003789 // In the new console call API, only the first time in reverse order
3790 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003791 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003792 ResizeWindow(hConsole, srWindowRect);
3793 ResizeConBuf(hConsole, coordScreen);
3794 }
3795 else
3796 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003797 // Workaround for a Windows 10 bug
3798 cursor.X = srWindowRect.Left;
3799 cursor.Y = srWindowRect.Top;
3800 SetConsoleCursorPosition(hConsole, cursor);
3801
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003802 ResizeConBuf(hConsole, coordScreen);
3803 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02003804 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003805 }
3806}
3807
3808
3809/*
3810 * Set the console window to `Rows' * `Columns'
3811 */
3812 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003813mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003814{
3815 COORD coordScreen;
3816
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003817# ifdef VIMDLL
3818 if (gui.in_use)
3819 return;
3820# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003821 /* Don't change window size while still starting up */
3822 if (suppress_winsize != 0)
3823 {
3824 suppress_winsize = 2;
3825 return;
3826 }
3827
3828 if (term_console)
3829 {
3830 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3831
3832 /* Clamp Rows and Columns to reasonable values */
3833 if (Rows > coordScreen.Y)
3834 Rows = coordScreen.Y;
3835 if (Columns > coordScreen.X)
3836 Columns = coordScreen.X;
3837
3838 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3839 }
3840}
3841
3842/*
3843 * Rows and/or Columns has changed.
3844 */
3845 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003846mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003847{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003848# ifdef VIMDLL
3849 if (gui.in_use)
3850 return;
3851# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003852 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3853}
3854
3855
3856/*
3857 * Called when started up, to set the winsize that was delayed.
3858 */
3859 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003860mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003861{
3862 if (suppress_winsize == 2)
3863 {
3864 suppress_winsize = 0;
3865 mch_set_shellsize();
3866 shell_resized();
3867 }
3868 suppress_winsize = 0;
3869}
Bram Moolenaar4f974752019-02-17 17:44:42 +01003870#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003871
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003872 static BOOL
3873vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003874 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003875 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01003876 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003877 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003878 PROCESS_INFORMATION *pi,
3879 LPVOID *env,
3880 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003881{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003882 BOOL ret = FALSE;
3883 WCHAR *wcmd, *wcwd = NULL;
3884
3885 wcmd = enc_to_utf16((char_u *)cmd, NULL);
3886 if (wcmd == NULL)
3887 return FALSE;
3888 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003889 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003890 wcwd = enc_to_utf16((char_u *)cwd, NULL);
3891 if (wcwd == NULL)
3892 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003893 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003894
3895 ret = CreateProcessW(
3896 NULL, // Executable name
3897 wcmd, // Command to execute
3898 NULL, // Process security attributes
3899 NULL, // Thread security attributes
3900 inherit_handles, // Inherit handles
3901 flags, // Creation flags
3902 env, // Environment
3903 wcwd, // Current directory
3904 (LPSTARTUPINFOW)si, // Startup information
3905 pi); // Process information
3906theend:
3907 vim_free(wcmd);
3908 vim_free(wcwd);
3909 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003910}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003911
3912
Bram Moolenaarb2964f22017-03-21 19:29:26 +01003913 static HINSTANCE
3914vim_shell_execute(
3915 char *cmd,
3916 INT n_show_cmd)
3917{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003918 HINSTANCE ret;
3919 WCHAR *wcmd;
3920
3921 wcmd = enc_to_utf16((char_u *)cmd, NULL);
3922 if (wcmd == NULL)
3923 return (HINSTANCE) 0;
3924
3925 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
3926 vim_free(wcmd);
3927 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01003928}
3929
3930
Bram Moolenaar4f974752019-02-17 17:44:42 +01003931#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003932
3933/*
3934 * Specialised version of system() for Win32 GUI mode.
3935 * This version proceeds as follows:
3936 * 1. Create a console window for use by the subprocess
3937 * 2. Run the subprocess (it gets the allocated console by default)
3938 * 3. Wait for the subprocess to terminate and get its exit code
3939 * 4. Prompt the user to press a key to close the console window
3940 */
3941 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003942mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003943{
3944 STARTUPINFO si;
3945 PROCESS_INFORMATION pi;
3946 DWORD ret = 0;
3947 HWND hwnd = GetFocus();
3948
3949 si.cb = sizeof(si);
3950 si.lpReserved = NULL;
3951 si.lpDesktop = NULL;
3952 si.lpTitle = NULL;
3953 si.dwFlags = STARTF_USESHOWWINDOW;
3954 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003955 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003956 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003957 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003958 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003959 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003960 else
3961 si.wShowWindow = SW_SHOWNORMAL;
3962 si.cbReserved2 = 0;
3963 si.lpReserved2 = NULL;
3964
Bram Moolenaar071d4272004-06-13 20:20:40 +00003965 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003966 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003967 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
3968 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003969
3970 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003971 {
3972#ifdef FEAT_GUI
3973 int delay = 1;
3974
3975 /* Keep updating the window while waiting for the shell to finish. */
3976 for (;;)
3977 {
3978 MSG msg;
3979
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003980 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003981 {
3982 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003983 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02003984 delay = 1;
3985 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003986 }
3987 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3988 break;
3989
3990 /* We start waiting for a very short time and then increase it, so
3991 * that we respond quickly when the process is quick, and don't
3992 * consume too much overhead when it's slow. */
3993 if (delay < 50)
3994 delay += 10;
3995 }
3996#else
3997 WaitForSingleObject(pi.hProcess, INFINITE);
3998#endif
3999
4000 /* Get the command exit code */
4001 GetExitCodeProcess(pi.hProcess, &ret);
4002 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004003
4004 /* Close the handles to the subprocess, so that it goes away */
4005 CloseHandle(pi.hThread);
4006 CloseHandle(pi.hProcess);
4007
4008 /* Try to get input focus back. Doesn't always work though. */
4009 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4010
4011 return ret;
4012}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004013
4014/*
4015 * Thread launched by the gui to send the current buffer data to the
4016 * process. This way avoid to hang up vim totally if the children
4017 * process take a long time to process the lines.
4018 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004019 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004020sub_process_writer(LPVOID param)
4021{
4022 HANDLE g_hChildStd_IN_Wr = param;
4023 linenr_T lnum = curbuf->b_op_start.lnum;
4024 DWORD len = 0;
4025 DWORD l;
4026 char_u *lp = ml_get(lnum);
4027 char_u *s;
4028 int written = 0;
4029
4030 for (;;)
4031 {
4032 l = (DWORD)STRLEN(lp + written);
4033 if (l == 0)
4034 len = 0;
4035 else if (lp[written] == NL)
4036 {
4037 /* NL -> NUL translation */
4038 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4039 }
4040 else
4041 {
4042 s = vim_strchr(lp + written, NL);
4043 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4044 s == NULL ? l : (DWORD)(s - (lp + written)),
4045 &len, NULL);
4046 }
4047 if (len == (int)l)
4048 {
4049 /* Finished a line, add a NL, unless this line should not have
4050 * one. */
4051 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004052 || (!curbuf->b_p_bin
4053 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004054 || (lnum != curbuf->b_no_eol_lnum
4055 && (lnum != curbuf->b_ml.ml_line_count
4056 || curbuf->b_p_eol)))
4057 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004058 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4059 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004060 }
4061
4062 ++lnum;
4063 if (lnum > curbuf->b_op_end.lnum)
4064 break;
4065
4066 lp = ml_get(lnum);
4067 written = 0;
4068 }
4069 else if (len > 0)
4070 written += len;
4071 }
4072
4073 /* finished all the lines, close pipe */
4074 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004075 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004076}
4077
4078
4079# define BUFLEN 100 /* length for buffer, stolen from unix version */
4080
4081/*
4082 * This function read from the children's stdout and write the
4083 * data on screen or in the buffer accordingly.
4084 */
4085 static void
4086dump_pipe(int options,
4087 HANDLE g_hChildStd_OUT_Rd,
4088 garray_T *ga,
4089 char_u buffer[],
4090 DWORD *buffer_off)
4091{
4092 DWORD availableBytes = 0;
4093 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004094 int ret;
4095 DWORD len;
4096 DWORD toRead;
4097 int repeatCount;
4098
4099 /* we query the pipe to see if there is any data to read
4100 * to avoid to perform a blocking read */
4101 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4102 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004103 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004104 NULL, /* number of read bytes */
4105 &availableBytes, /* available bytes total */
4106 NULL); /* byteLeft */
4107
4108 repeatCount = 0;
4109 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004110 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004111 {
4112 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004113 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004114 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004115 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004116
4117 /* If we haven't read anything, there is a problem */
4118 if (len == 0)
4119 break;
4120
4121 availableBytes -= len;
4122
4123 if (options & SHELL_READ)
4124 {
4125 /* Do NUL -> NL translation, append NL separated
4126 * lines to the current buffer. */
4127 for (i = 0; i < len; ++i)
4128 {
4129 if (buffer[i] == NL)
4130 append_ga_line(ga);
4131 else if (buffer[i] == NUL)
4132 ga_append(ga, NL);
4133 else
4134 ga_append(ga, buffer[i]);
4135 }
4136 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004137 else if (has_mbyte)
4138 {
4139 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004140 int c;
4141 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004142
4143 len += *buffer_off;
4144 buffer[len] = NUL;
4145
4146 /* Check if the last character in buffer[] is
4147 * incomplete, keep these bytes for the next
4148 * round. */
4149 for (p = buffer; p < buffer + len; p += l)
4150 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004151 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004152 if (l == 0)
4153 l = 1; /* NUL byte? */
4154 else if (MB_BYTE2LEN(*p) != l)
4155 break;
4156 }
4157 if (p == buffer) /* no complete character */
4158 {
4159 /* avoid getting stuck at an illegal byte */
4160 if (len >= 12)
4161 ++p;
4162 else
4163 {
4164 *buffer_off = len;
4165 return;
4166 }
4167 }
4168 c = *p;
4169 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004170 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004171 if (p < buffer + len)
4172 {
4173 *p = c;
4174 *buffer_off = (DWORD)((buffer + len) - p);
4175 mch_memmove(buffer, p, *buffer_off);
4176 return;
4177 }
4178 *buffer_off = 0;
4179 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004180 else
4181 {
4182 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004183 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004184 }
4185
4186 windgoto(msg_row, msg_col);
4187 cursor_on();
4188 out_flush();
4189 }
4190}
4191
4192/*
4193 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4194 * for communication and doesn't open any new window.
4195 */
4196 static int
4197mch_system_piped(char *cmd, int options)
4198{
4199 STARTUPINFO si;
4200 PROCESS_INFORMATION pi;
4201 DWORD ret = 0;
4202
4203 HANDLE g_hChildStd_IN_Rd = NULL;
4204 HANDLE g_hChildStd_IN_Wr = NULL;
4205 HANDLE g_hChildStd_OUT_Rd = NULL;
4206 HANDLE g_hChildStd_OUT_Wr = NULL;
4207
4208 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4209 DWORD len;
4210
4211 /* buffer used to receive keys */
4212 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4213 int ta_len = 0; /* valid bytes in ta_buf[] */
4214
4215 DWORD i;
4216 int c;
4217 int noread_cnt = 0;
4218 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004219 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004220 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004221 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004222
4223 SECURITY_ATTRIBUTES saAttr;
4224
4225 /* Set the bInheritHandle flag so pipe handles are inherited. */
4226 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4227 saAttr.bInheritHandle = TRUE;
4228 saAttr.lpSecurityDescriptor = NULL;
4229
4230 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4231 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004232 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004233 /* Create a pipe for the child process's STDIN. */
4234 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4235 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004236 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004237 {
4238 CloseHandle(g_hChildStd_IN_Rd);
4239 CloseHandle(g_hChildStd_IN_Wr);
4240 CloseHandle(g_hChildStd_OUT_Rd);
4241 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004242 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004243 }
4244
4245 si.cb = sizeof(si);
4246 si.lpReserved = NULL;
4247 si.lpDesktop = NULL;
4248 si.lpTitle = NULL;
4249 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4250
4251 /* set-up our file redirection */
4252 si.hStdError = g_hChildStd_OUT_Wr;
4253 si.hStdOutput = g_hChildStd_OUT_Wr;
4254 si.hStdInput = g_hChildStd_IN_Rd;
4255 si.wShowWindow = SW_HIDE;
4256 si.cbReserved2 = 0;
4257 si.lpReserved2 = NULL;
4258
4259 if (options & SHELL_READ)
4260 ga_init2(&ga, 1, BUFLEN);
4261
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004262 if (cmd != NULL)
4263 {
4264 p = (char *)vim_strsave((char_u *)cmd);
4265 if (p != NULL)
4266 unescape_shellxquote((char_u *)p, p_sxe);
4267 else
4268 p = cmd;
4269 }
4270
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004271 /* Now, run the command.
4272 * About "Inherit handles" being TRUE: this command can be litigious,
4273 * handle inheritance was deactivated for pending temp file, but, if we
4274 * deactivate it, the pipes don't work for some reason. */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004275 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4276 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004277
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004278 if (p != cmd)
4279 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004280
4281 /* Close our unused side of the pipes */
4282 CloseHandle(g_hChildStd_IN_Rd);
4283 CloseHandle(g_hChildStd_OUT_Wr);
4284
4285 if (options & SHELL_WRITE)
4286 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004287 HANDLE thread = (HANDLE)
4288 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004289 0, /* default stack size */
4290 sub_process_writer, /* function to be executed */
4291 g_hChildStd_IN_Wr, /* parameter */
4292 0, /* creation flag, start immediately */
4293 NULL); /* we don't care about thread id */
4294 CloseHandle(thread);
4295 g_hChildStd_IN_Wr = NULL;
4296 }
4297
4298 /* Keep updating the window while waiting for the shell to finish. */
4299 for (;;)
4300 {
4301 MSG msg;
4302
Bram Moolenaar175d0702013-12-11 18:36:33 +01004303 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004304 {
4305 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004306 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004307 }
4308
4309 /* write pipe information in the window */
4310 if ((options & (SHELL_READ|SHELL_WRITE))
4311# ifdef FEAT_GUI
4312 || gui.in_use
4313# endif
4314 )
4315 {
4316 len = 0;
4317 if (!(options & SHELL_EXPAND)
4318 && ((options &
4319 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4320 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4321# ifdef FEAT_GUI
4322 || gui.in_use
4323# endif
4324 )
4325 && (ta_len > 0 || noread_cnt > 4))
4326 {
4327 if (ta_len == 0)
4328 {
4329 /* Get extra characters when we don't have any. Reset the
4330 * counter and timer. */
4331 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004332 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4333 }
4334 if (ta_len > 0 || len > 0)
4335 {
4336 /*
4337 * For pipes: Check for CTRL-C: send interrupt signal to
4338 * child. Check for CTRL-D: EOF, close pipe to child.
4339 */
4340 if (len == 1 && cmd != NULL)
4341 {
4342 if (ta_buf[ta_len] == Ctrl_C)
4343 {
4344 /* Learn what exit code is expected, for
4345 * now put 9 as SIGKILL */
4346 TerminateProcess(pi.hProcess, 9);
4347 }
4348 if (ta_buf[ta_len] == Ctrl_D)
4349 {
4350 CloseHandle(g_hChildStd_IN_Wr);
4351 g_hChildStd_IN_Wr = NULL;
4352 }
4353 }
4354
4355 /* replace K_BS by <BS> and K_DEL by <DEL> */
4356 for (i = ta_len; i < ta_len + len; ++i)
4357 {
4358 if (ta_buf[i] == CSI && len - i > 2)
4359 {
4360 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4361 if (c == K_DEL || c == K_KDEL || c == K_BS)
4362 {
4363 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4364 (size_t)(len - i - 2));
4365 if (c == K_DEL || c == K_KDEL)
4366 ta_buf[i] = DEL;
4367 else
4368 ta_buf[i] = Ctrl_H;
4369 len -= 2;
4370 }
4371 }
4372 else if (ta_buf[i] == '\r')
4373 ta_buf[i] = '\n';
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004374 if (has_mbyte)
4375 i += (*mb_ptr2len_len)(ta_buf + i,
4376 ta_len + len - i) - 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004377 }
4378
4379 /*
4380 * For pipes: echo the typed characters. For a pty this
4381 * does not seem to work.
4382 */
4383 for (i = ta_len; i < ta_len + len; ++i)
4384 {
4385 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4386 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004387 else if (has_mbyte)
4388 {
4389 int l = (*mb_ptr2len)(ta_buf + i);
4390
4391 msg_outtrans_len(ta_buf + i, l);
4392 i += l - 1;
4393 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004394 else
4395 msg_outtrans_len(ta_buf + i, 1);
4396 }
4397 windgoto(msg_row, msg_col);
4398 out_flush();
4399
4400 ta_len += len;
4401
4402 /*
4403 * Write the characters to the child, unless EOF has been
4404 * typed for pipes. Write one character at a time, to
4405 * avoid losing too much typeahead. When writing buffer
4406 * lines, drop the typed characters (only check for
4407 * CTRL-C).
4408 */
4409 if (options & SHELL_WRITE)
4410 ta_len = 0;
4411 else if (g_hChildStd_IN_Wr != NULL)
4412 {
4413 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4414 1, &len, NULL);
4415 // if we are typing in, we want to keep things reactive
4416 delay = 1;
4417 if (len > 0)
4418 {
4419 ta_len -= len;
4420 mch_memmove(ta_buf, ta_buf + len, ta_len);
4421 }
4422 }
4423 }
4424 }
4425 }
4426
4427 if (ta_len)
4428 ui_inchar_undo(ta_buf, ta_len);
4429
4430 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4431 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004432 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004433 break;
4434 }
4435
4436 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004437 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004438
4439 /* We start waiting for a very short time and then increase it, so
4440 * that we respond quickly when the process is quick, and don't
4441 * consume too much overhead when it's slow. */
4442 if (delay < 50)
4443 delay += 10;
4444 }
4445
4446 /* Close the pipe */
4447 CloseHandle(g_hChildStd_OUT_Rd);
4448 if (g_hChildStd_IN_Wr != NULL)
4449 CloseHandle(g_hChildStd_IN_Wr);
4450
4451 WaitForSingleObject(pi.hProcess, INFINITE);
4452
4453 /* Get the command exit code */
4454 GetExitCodeProcess(pi.hProcess, &ret);
4455
4456 if (options & SHELL_READ)
4457 {
4458 if (ga.ga_len > 0)
4459 {
4460 append_ga_line(&ga);
4461 /* remember that the NL was missing */
4462 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4463 }
4464 else
4465 curbuf->b_no_eol_lnum = 0;
4466 ga_clear(&ga);
4467 }
4468
4469 /* Close the handles to the subprocess, so that it goes away */
4470 CloseHandle(pi.hThread);
4471 CloseHandle(pi.hProcess);
4472
4473 return ret;
4474}
4475
4476 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004477mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004478{
4479 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004480 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004481 return mch_system_piped(cmd, options);
4482 else
4483 return mch_system_classic(cmd, options);
4484}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004485#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004486
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004487#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004488 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02004489mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004490{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004491 int ret;
4492 WCHAR *wcmd;
4493
4494 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4495 if (wcmd == NULL)
4496 return -1;
4497
4498 ret = _wsystem(wcmd);
4499 vim_free(wcmd);
4500 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004501}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004502
4503#endif
4504
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004505 static int
4506mch_system(char *cmd, int options)
4507{
4508#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004509 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004510 return mch_system_g(cmd, options);
4511 else
4512 return mch_system_c(cmd, options);
4513#elif defined(FEAT_GUI_MSWIN)
4514 return mch_system_g(cmd, options);
4515#else
4516 return mch_system_c(cmd, options);
4517#endif
4518}
4519
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004520#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4521/*
4522 * Use a terminal window to run a shell command in.
4523 */
4524 static int
4525mch_call_shell_terminal(
4526 char_u *cmd,
4527 int options UNUSED) /* SHELL_*, see vim.h */
4528{
4529 jobopt_T opt;
4530 char_u *newcmd = NULL;
4531 typval_T argvar[2];
4532 long_u cmdlen;
4533 int retval = -1;
4534 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004535 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004536 aco_save_T aco;
4537 oparg_T oa; /* operator arguments */
4538
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004539 if (cmd == NULL)
4540 cmdlen = STRLEN(p_sh) + 1;
4541 else
4542 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004543 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004544 if (newcmd == NULL)
4545 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004546 if (cmd == NULL)
4547 {
4548 STRCPY(newcmd, p_sh);
4549 ch_log(NULL, "starting terminal to run a shell");
4550 }
4551 else
4552 {
4553 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4554 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4555 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004556
4557 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004558
4559 argvar[0].v_type = VAR_STRING;
4560 argvar[0].vval.v_string = newcmd;
4561 argvar[1].v_type = VAR_UNKNOWN;
4562 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004563 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004564 {
4565 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004566 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004567 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004568
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004569 job = term_getjob(buf->b_term);
4570 ++job->jv_refcount;
4571
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004572 /* Find a window to make "buf" curbuf. */
4573 aucmd_prepbuf(&aco, buf);
4574
4575 clear_oparg(&oa);
4576 while (term_use_loop())
4577 {
4578 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4579 {
4580 /* If terminal_loop() returns OK we got a key that is handled
4581 * in Normal model. We don't do redrawing anyway. */
4582 if (terminal_loop(TRUE) == OK)
4583 normal_cmd(&oa, TRUE);
4584 }
4585 else
4586 normal_cmd(&oa, TRUE);
4587 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004588 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004589 ch_log(NULL, "system command finished");
4590
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004591 job_unref(job);
4592
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004593 /* restore curwin/curbuf and a few other things */
4594 aucmd_restbuf(&aco);
4595
4596 wait_return(TRUE);
4597 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4598
4599 vim_free(newcmd);
4600 return retval;
4601}
4602#endif
4603
Bram Moolenaar071d4272004-06-13 20:20:40 +00004604/*
4605 * Either execute a command by calling the shell or start a new shell
4606 */
4607 int
4608mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004609 char_u *cmd,
4610 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004611{
4612 int x = 0;
4613 int tmode = cur_tmode;
4614#ifdef FEAT_TITLE
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004615 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004616
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004617 /* Change the title to reflect that we are in a subshell. */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004618 if (GetConsoleTitleW(szShellTitle,
4619 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004620 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004621 if (cmd == NULL)
4622 wcscat(szShellTitle, L" :sh");
4623 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004624 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004625 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004626
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004627 if (wn != NULL)
4628 {
4629 wcscat(szShellTitle, L" - !");
4630 if ((wcslen(szShellTitle) + wcslen(wn) <
4631 sizeof(szShellTitle)/sizeof(WCHAR)))
4632 wcscat(szShellTitle, wn);
4633 SetConsoleTitleW(szShellTitle);
4634 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004635 }
4636 }
4637 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004638#endif
4639
4640 out_flush();
4641
4642#ifdef MCH_WRITE_DUMP
4643 if (fdDump)
4644 {
4645 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4646 fflush(fdDump);
4647 }
4648#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004649#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004650 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004651 if (
4652# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004653 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004654# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004655 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004656 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4657 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004658 char_u *cmdbase = cmd;
4659
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004660 if (cmdbase != NULL)
4661 // Skip a leading quote and (.
4662 while (*cmdbase == '"' || *cmdbase == '(')
4663 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004664
4665 // Check the command does not begin with "start "
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004666 if (cmdbase == NULL
4667 || STRNICMP(cmdbase, "start", 5) != 0 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004668 {
4669 // Use a terminal window to run the command in.
4670 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004671# ifdef FEAT_TITLE
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004672 resettitle();
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004673# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004674 return x;
4675 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004676 }
4677#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004678
4679 /*
4680 * Catch all deadly signals while running the external command, because a
4681 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4682 */
4683 signal(SIGINT, SIG_IGN);
4684#if defined(__GNUC__) && !defined(__MINGW32__)
4685 signal(SIGKILL, SIG_IGN);
4686#else
4687 signal(SIGBREAK, SIG_IGN);
4688#endif
4689 signal(SIGILL, SIG_IGN);
4690 signal(SIGFPE, SIG_IGN);
4691 signal(SIGSEGV, SIG_IGN);
4692 signal(SIGTERM, SIG_IGN);
4693 signal(SIGABRT, SIG_IGN);
4694
4695 if (options & SHELL_COOKED)
4696 settmode(TMODE_COOK); /* set to normal mode */
4697
4698 if (cmd == NULL)
4699 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004700 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004701 }
4702 else
4703 {
4704 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004705 char_u *newcmd = NULL;
4706 char_u *cmdbase = cmd;
4707 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004708
4709 /* Skip a leading ", ( and "(. */
4710 if (*cmdbase == '"' )
4711 ++cmdbase;
4712 if (*cmdbase == '(')
4713 ++cmdbase;
4714
Bram Moolenaar1c465442017-03-12 20:10:05 +01004715 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004716 {
4717 STARTUPINFO si;
4718 PROCESS_INFORMATION pi;
4719 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004720 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004721 char_u *p;
4722
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004723 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004724 si.cb = sizeof(si);
4725 si.lpReserved = NULL;
4726 si.lpDesktop = NULL;
4727 si.lpTitle = NULL;
4728 si.dwFlags = 0;
4729 si.cbReserved2 = 0;
4730 si.lpReserved2 = NULL;
4731
4732 cmdbase = skipwhite(cmdbase + 5);
4733 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004734 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004735 {
4736 cmdbase = skipwhite(cmdbase + 4);
4737 si.dwFlags = STARTF_USESHOWWINDOW;
4738 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004739 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004740 }
4741 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004742 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004743 {
4744 cmdbase = skipwhite(cmdbase + 2);
4745 flags = CREATE_NO_WINDOW;
4746 si.dwFlags = STARTF_USESTDHANDLES;
4747 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004748 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004749 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004750 NULL, // Security att.
4751 OPEN_EXISTING, // Open flags
4752 FILE_ATTRIBUTE_NORMAL, // File att.
4753 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004754 si.hStdOutput = si.hStdInput;
4755 si.hStdError = si.hStdInput;
4756 }
4757
4758 /* Remove a trailing ", ) and )" if they have a match
4759 * at the start of the command. */
4760 if (cmdbase > cmd)
4761 {
4762 p = cmdbase + STRLEN(cmdbase);
4763 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4764 *--p = NUL;
4765 if (p > cmdbase && p[-1] == ')'
4766 && (*cmd =='(' || cmd[1] == '('))
4767 *--p = NUL;
4768 }
4769
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004770 newcmd = cmdbase;
4771 unescape_shellxquote(cmdbase, p_sxe);
4772
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004773 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004774 * If creating new console, arguments are passed to the
4775 * 'cmd.exe' as-is. If it's not, arguments are not treated
4776 * correctly for current 'cmd.exe'. So unescape characters in
4777 * shellxescape except '|' for avoiding to be treated as
4778 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004779 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004780 if (flags != CREATE_NEW_CONSOLE)
4781 {
4782 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004783 char_u *cmd_shell = mch_getenv("COMSPEC");
4784
4785 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004786 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004787
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004788 subcmd = vim_strsave_escaped_ext(cmdbase,
4789 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004790 if (subcmd != NULL)
4791 {
4792 /* make "cmd.exe /c arguments" */
4793 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004794 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004795 if (newcmd != NULL)
4796 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004797 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004798 else
4799 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004800 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004801 }
4802 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004803
4804 /*
4805 * Now, start the command as a process, so that it doesn't
4806 * inherit our handles which causes unpleasant dangling swap
4807 * files if we exit before the spawned process
4808 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004809 if (vim_create_process((char *)newcmd, FALSE, flags,
4810 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004811 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004812 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4813 > (HINSTANCE)32)
4814 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004815 else
4816 {
4817 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01004818#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004819# ifdef VIMDLL
4820 if (gui.in_use)
4821# endif
4822 emsg(_("E371: Command not found"));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004823#endif
4824 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004825
4826 if (newcmd != cmdbase)
4827 vim_free(newcmd);
4828
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004829 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004830 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004831 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004832 CloseHandle(si.hStdInput);
4833 }
4834 /* Close the handles to the subprocess, so that it goes away */
4835 CloseHandle(pi.hThread);
4836 CloseHandle(pi.hProcess);
4837 }
4838 else
4839 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004840 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01004841#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004842 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004843 (!s_dont_use_vimrun && p_stmp ?
4844 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
4845 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004846#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004847 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004848
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004849 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004850 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004851 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01004852#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004853 if (
4854# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004855 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004856# endif
4857 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004858 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01004859 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
4860 "External commands will not pause after completion.\n"
4861 "See :help win32-vimrun for more information.");
4862 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004863 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
4864 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01004865
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004866 if (wmsg != NULL && wtitle != NULL)
4867 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
4868 vim_free(wmsg);
4869 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004870 need_vimrun_warning = FALSE;
4871 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004872 if (
4873# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004874 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004875# endif
4876 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02004877 // Use vimrun to execute the command. It opens a console
4878 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004879 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004880 vimrun_path,
4881 (msg_silent != 0 || (options & SHELL_DOOUT))
4882 ? "-s " : "",
4883 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02004884 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004885# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02004886 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004887# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02004888 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02004889 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004890 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
4891 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004892 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004893#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004894 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004895 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004896 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004897 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004898 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004899 }
4900 }
4901
4902 if (tmode == TMODE_RAW)
4903 settmode(TMODE_RAW); /* set to raw mode */
4904
4905 /* Print the return value, unless "vimrun" was used. */
4906 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01004907#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004908 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004909 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004910#endif
4911 )
4912 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004913 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004914 msg_putchar('\n');
4915 }
4916#ifdef FEAT_TITLE
4917 resettitle();
4918#endif
4919
4920 signal(SIGINT, SIG_DFL);
4921#if defined(__GNUC__) && !defined(__MINGW32__)
4922 signal(SIGKILL, SIG_DFL);
4923#else
4924 signal(SIGBREAK, SIG_DFL);
4925#endif
4926 signal(SIGILL, SIG_DFL);
4927 signal(SIGFPE, SIG_DFL);
4928 signal(SIGSEGV, SIG_DFL);
4929 signal(SIGTERM, SIG_DFL);
4930 signal(SIGABRT, SIG_DFL);
4931
4932 return x;
4933}
4934
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01004935#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004936 static HANDLE
4937job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01004938 char_u *fname,
4939 DWORD dwDesiredAccess,
4940 DWORD dwShareMode,
4941 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
4942 DWORD dwCreationDisposition,
4943 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004944{
4945 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004946 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004947
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004948 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004949 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004950 return INVALID_HANDLE_VALUE;
4951
4952 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
4953 lpSecurityAttributes, dwCreationDisposition,
4954 dwFlagsAndAttributes, NULL);
4955 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004956 return h;
4957}
4958
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004959/*
4960 * Turn the dictionary "env" into a NUL separated list that can be used as the
4961 * environment argument of vim_create_process().
4962 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004963 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004964win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004965{
4966 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004967 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004968 LPVOID base = GetEnvironmentStringsW();
4969
4970 /* for last \0 */
4971 if (ga_grow(gap, 1) == FAIL)
4972 return;
4973
4974 if (base)
4975 {
4976 WCHAR *p = (WCHAR*) base;
4977
4978 /* for last \0 */
4979 if (ga_grow(gap, 1) == FAIL)
4980 return;
4981
4982 while (*p != 0 || *(p + 1) != 0)
4983 {
4984 if (ga_grow(gap, 1) == OK)
4985 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
4986 p++;
4987 }
4988 FreeEnvironmentStrings(base);
4989 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
4990 }
4991
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004992 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004993 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004994 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004995 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004996 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004997 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004998 typval_T *item = &dict_lookup(hi)->di_tv;
4999 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005000 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005001 --todo;
5002 if (wkey != NULL && wval != NULL)
5003 {
5004 size_t n;
5005 size_t lkey = wcslen(wkey);
5006 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005007
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005008 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5009 continue;
5010 for (n = 0; n < lkey; n++)
5011 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5012 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5013 for (n = 0; n < lval; n++)
5014 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5015 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5016 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005017 vim_free(wkey);
5018 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005019 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005020 }
5021 }
5022
Bram Moolenaar493359e2018-06-12 20:25:52 +02005023# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005024 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005025# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005026 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005027 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005028# endif
5029# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005030 char_u *version = get_vim_var_str(VV_VERSION);
5031 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005032# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005033 // size of "VIM_SERVERNAME=" and value,
5034 // plus "VIM_TERMINAL=" and value,
5035 // plus two terminating NULs
5036 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005037# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005038 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005039# endif
5040# ifdef FEAT_TERMINAL
5041 + 13 + version_len + 2
5042# endif
5043 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005044
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005045 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005046 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005047# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005048 for (n = 0; n < 15; n++)
5049 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5050 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005051 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005052 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5053 (WCHAR)servername[n];
5054 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005055# endif
5056# ifdef FEAT_TERMINAL
5057 if (is_terminal)
5058 {
5059 for (n = 0; n < 13; n++)
5060 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5061 (WCHAR)"VIM_TERMINAL="[n];
5062 for (n = 0; n < version_len; n++)
5063 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5064 (WCHAR)version[n];
5065 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5066 }
5067# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005068 }
5069 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005070# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005071}
5072
Bram Moolenaarb091f302019-01-19 14:37:00 +01005073/*
5074 * Create a pair of pipes.
5075 * Return TRUE for success, FALSE for failure.
5076 */
5077 static BOOL
5078create_pipe_pair(HANDLE handles[2])
5079{
5080 static LONG s;
5081 char name[64];
5082 SECURITY_ATTRIBUTES sa;
5083
5084 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5085 GetCurrentProcessId(),
5086 InterlockedIncrement(&s));
5087
5088 // Create named pipe. Max size of named pipe is 65535.
5089 handles[1] = CreateNamedPipe(
5090 name,
5091 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5092 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005093 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005094
5095 if (handles[1] == INVALID_HANDLE_VALUE)
5096 return FALSE;
5097
5098 sa.nLength = sizeof(sa);
5099 sa.bInheritHandle = TRUE;
5100 sa.lpSecurityDescriptor = NULL;
5101
5102 handles[0] = CreateFile(name,
5103 FILE_GENERIC_READ,
5104 FILE_SHARE_READ, &sa,
5105 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5106
5107 if (handles[0] == INVALID_HANDLE_VALUE)
5108 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005109 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005110 return FALSE;
5111 }
5112
5113 return TRUE;
5114}
5115
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005116 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005117mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005118{
5119 STARTUPINFO si;
5120 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005121 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005122 SECURITY_ATTRIBUTES saAttr;
5123 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005124 HANDLE ifd[2];
5125 HANDLE ofd[2];
5126 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005127 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005128
5129 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5130 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5131 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5132 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5133 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5134 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5135 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5136
5137 if (use_out_for_err && use_null_for_out)
5138 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005139
5140 ifd[0] = INVALID_HANDLE_VALUE;
5141 ifd[1] = INVALID_HANDLE_VALUE;
5142 ofd[0] = INVALID_HANDLE_VALUE;
5143 ofd[1] = INVALID_HANDLE_VALUE;
5144 efd[0] = INVALID_HANDLE_VALUE;
5145 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005146 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005147
Bram Moolenaar14207f42016-10-27 21:13:10 +02005148 jo = CreateJobObject(NULL, NULL);
5149 if (jo == NULL)
5150 {
5151 job->jv_status = JOB_FAILED;
5152 goto failed;
5153 }
5154
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005155 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005156 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005157
Bram Moolenaar76467df2016-02-12 19:30:26 +01005158 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005159 ZeroMemory(&si, sizeof(si));
5160 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005161 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005162 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005163
Bram Moolenaard8070362016-02-15 21:56:54 +01005164 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5165 saAttr.bInheritHandle = TRUE;
5166 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005167
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005168 if (use_file_for_in)
5169 {
5170 char_u *fname = options->jo_io_name[PART_IN];
5171
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005172 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5173 FILE_SHARE_READ | FILE_SHARE_WRITE,
5174 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5175 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005176 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005177 semsg(_(e_notopen), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005178 goto failed;
5179 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005180 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005181 else if (!use_null_for_in
5182 && (!create_pipe_pair(ifd)
5183 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005184 goto failed;
5185
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005186 if (use_file_for_out)
5187 {
5188 char_u *fname = options->jo_io_name[PART_OUT];
5189
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005190 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5191 FILE_SHARE_READ | FILE_SHARE_WRITE,
5192 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5193 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005194 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005195 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005196 goto failed;
5197 }
5198 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005199 else if (!use_null_for_out &&
5200 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005201 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005202 goto failed;
5203
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005204 if (use_file_for_err)
5205 {
5206 char_u *fname = options->jo_io_name[PART_ERR];
5207
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005208 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5209 FILE_SHARE_READ | FILE_SHARE_WRITE,
5210 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5211 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005212 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005213 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005214 goto failed;
5215 }
5216 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005217 else if (!use_out_for_err && !use_null_for_err &&
5218 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005219 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005220 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005221
Bram Moolenaard8070362016-02-15 21:56:54 +01005222 si.dwFlags |= STARTF_USESTDHANDLES;
5223 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005224 si.hStdOutput = ofd[1];
5225 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5226
5227 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5228 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005229 if (options->jo_set & JO_CHANNEL)
5230 {
5231 channel = options->jo_channel;
5232 if (channel != NULL)
5233 ++channel->ch_refcount;
5234 }
5235 else
5236 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005237 if (channel == NULL)
5238 goto failed;
5239 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005240
5241 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005242 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005243 CREATE_DEFAULT_ERROR_MODE |
5244 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005245 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005246 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005247 &si, &pi,
5248 ga.ga_data,
5249 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005250 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005251 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005252 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005253 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005254 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005255
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005256 ga_clear(&ga);
5257
Bram Moolenaar14207f42016-10-27 21:13:10 +02005258 if (!AssignProcessToJobObject(jo, pi.hProcess))
5259 {
5260 /* if failing, switch the way to terminate
5261 * process with TerminateProcess. */
5262 CloseHandle(jo);
5263 jo = NULL;
5264 }
5265 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005266 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005267 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005268 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005269 job->jv_status = JOB_STARTED;
5270
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005271 CloseHandle(ifd[0]);
5272 CloseHandle(ofd[1]);
5273 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005274 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005275
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005276 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005277 if (channel != NULL)
5278 {
5279 channel_set_pipes(channel,
5280 use_file_for_in || use_null_for_in
5281 ? INVALID_FD : (sock_T)ifd[1],
5282 use_file_for_out || use_null_for_out
5283 ? INVALID_FD : (sock_T)ofd[0],
5284 use_out_for_err || use_file_for_err || use_null_for_err
5285 ? INVALID_FD : (sock_T)efd[0]);
5286 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005287 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005288 return;
5289
5290failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005291 CloseHandle(ifd[0]);
5292 CloseHandle(ofd[0]);
5293 CloseHandle(efd[0]);
5294 CloseHandle(ifd[1]);
5295 CloseHandle(ofd[1]);
5296 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005297 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005298 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005299}
5300
5301 char *
5302mch_job_status(job_T *job)
5303{
5304 DWORD dwExitCode = 0;
5305
Bram Moolenaar76467df2016-02-12 19:30:26 +01005306 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5307 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005308 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005309 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005310 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005311 {
5312 ch_log(job->jv_channel, "Job ended");
5313 job->jv_status = JOB_ENDED;
5314 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005315 return "dead";
5316 }
5317 return "run";
5318}
5319
Bram Moolenaar97792de2016-10-15 18:36:49 +02005320 job_T *
5321mch_detect_ended_job(job_T *job_list)
5322{
5323 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5324 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5325 job_T *job = job_list;
5326
5327 while (job != NULL)
5328 {
5329 DWORD n;
5330 DWORD result;
5331
5332 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5333 && job != NULL; job = job->jv_next)
5334 {
5335 if (job->jv_status == JOB_STARTED)
5336 {
5337 jobHandles[n] = job->jv_proc_info.hProcess;
5338 jobArray[n] = job;
5339 ++n;
5340 }
5341 }
5342 if (n == 0)
5343 continue;
5344 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5345 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5346 {
5347 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5348
5349 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5350 return wait_job;
5351 }
5352 }
5353 return NULL;
5354}
5355
Bram Moolenaarfb630902016-10-29 14:55:00 +02005356 static BOOL
5357terminate_all(HANDLE process, int code)
5358{
5359 PROCESSENTRY32 pe;
5360 HANDLE h = INVALID_HANDLE_VALUE;
5361 DWORD pid = GetProcessId(process);
5362
5363 if (pid != 0)
5364 {
5365 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5366 if (h != INVALID_HANDLE_VALUE)
5367 {
5368 pe.dwSize = sizeof(PROCESSENTRY32);
5369 if (!Process32First(h, &pe))
5370 goto theend;
5371
5372 do
5373 {
5374 if (pe.th32ParentProcessID == pid)
5375 {
5376 HANDLE ph = OpenProcess(
5377 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5378 if (ph != NULL)
5379 {
5380 terminate_all(ph, code);
5381 CloseHandle(ph);
5382 }
5383 }
5384 } while (Process32Next(h, &pe));
5385
5386 CloseHandle(h);
5387 }
5388 }
5389
5390theend:
5391 return TerminateProcess(process, code);
5392}
5393
5394/*
5395 * Send a (deadly) signal to "job".
5396 * Return FAIL if it didn't work.
5397 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005398 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005399mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005400{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005401 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005402
Bram Moolenaar923d9262016-02-25 20:56:01 +01005403 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005404 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005405 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005406 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005407 {
5408 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5409 job->jv_channel->ch_killing = TRUE;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005410 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005411 }
Bram Moolenaarfb630902016-10-29 14:55:00 +02005412 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005413 }
5414
5415 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5416 return FAIL;
5417 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005418 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5419 job->jv_proc_info.dwProcessId)
5420 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005421 FreeConsole();
5422 return ret;
5423}
5424
5425/*
5426 * Clear the data related to "job".
5427 */
5428 void
5429mch_clear_job(job_T *job)
5430{
5431 if (job->jv_status != JOB_FAILED)
5432 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005433 if (job->jv_job_object != NULL)
5434 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005435 CloseHandle(job->jv_proc_info.hProcess);
5436 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005437}
5438#endif
5439
Bram Moolenaar071d4272004-06-13 20:20:40 +00005440
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005441#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005442
5443/*
5444 * Start termcap mode
5445 */
5446 static void
5447termcap_mode_start(void)
5448{
5449 DWORD cmodein;
5450
5451 if (g_fTermcapMode)
5452 return;
5453
5454 SaveConsoleBuffer(&g_cbNonTermcap);
5455
5456 if (g_cbTermcap.IsValid)
5457 {
5458 /*
5459 * We've been in termcap mode before. Restore certain screen
5460 * characteristics, including the buffer size and the window
5461 * size. Since we will be redrawing the screen, we don't need
5462 * to restore the actual contents of the buffer.
5463 */
5464 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005465 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005466 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5467 Rows = g_cbTermcap.Info.dwSize.Y;
5468 Columns = g_cbTermcap.Info.dwSize.X;
5469 }
5470 else
5471 {
5472 /*
5473 * This is our first time entering termcap mode. Clear the console
5474 * screen buffer, and resize the buffer to match the current window
5475 * size. We will use this as the size of our editing environment.
5476 */
5477 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005478 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005479 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5480 }
5481
5482#ifdef FEAT_TITLE
5483 resettitle();
5484#endif
5485
5486 GetConsoleMode(g_hConIn, &cmodein);
5487#ifdef FEAT_MOUSE
5488 if (g_fMouseActive)
5489 cmodein |= ENABLE_MOUSE_INPUT;
5490 else
5491 cmodein &= ~ENABLE_MOUSE_INPUT;
5492#endif
5493 cmodein |= ENABLE_WINDOW_INPUT;
5494 SetConsoleMode(g_hConIn, cmodein);
5495
5496 redraw_later_clear();
5497 g_fTermcapMode = TRUE;
5498}
5499
5500
5501/*
5502 * End termcap mode
5503 */
5504 static void
5505termcap_mode_end(void)
5506{
5507 DWORD cmodein;
5508 ConsoleBuffer *cb;
5509 COORD coord;
5510 DWORD dwDummy;
5511
5512 if (!g_fTermcapMode)
5513 return;
5514
5515 SaveConsoleBuffer(&g_cbTermcap);
5516
5517 GetConsoleMode(g_hConIn, &cmodein);
5518 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5519 SetConsoleMode(g_hConIn, cmodein);
5520
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005521#ifdef FEAT_RESTORE_ORIG_SCREEN
5522 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5523#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005524 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005525#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005526 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005527 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005528 SetConsoleCursorInfo(g_hConOut, &g_cci);
5529
5530 if (p_rs || exiting)
5531 {
5532 /*
5533 * Clear anything that happens to be on the current line.
5534 */
5535 coord.X = 0;
5536 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5537 FillConsoleOutputCharacter(g_hConOut, ' ',
5538 cb->Info.dwSize.X, coord, &dwDummy);
5539 /*
5540 * The following is just for aesthetics. If we are exiting without
5541 * restoring the screen, then we want to have a prompt string
5542 * appear at the bottom line. However, the command interpreter
5543 * seems to always advance the cursor one line before displaying
5544 * the prompt string, which causes the screen to scroll. To
5545 * counter this, move the cursor up one line before exiting.
5546 */
5547 if (exiting && !p_rs)
5548 coord.Y--;
5549 /*
5550 * Position the cursor at the leftmost column of the desired row.
5551 */
5552 SetConsoleCursorPosition(g_hConOut, coord);
5553 }
5554
5555 g_fTermcapMode = FALSE;
5556}
Bram Moolenaar4f974752019-02-17 17:44:42 +01005557#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005558
5559
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005560#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005561 void
5562mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005563 char_u *s UNUSED,
5564 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005565{
5566 /* never used */
5567}
5568
5569#else
5570
5571/*
5572 * clear `n' chars, starting from `coord'
5573 */
5574 static void
5575clear_chars(
5576 COORD coord,
5577 DWORD n)
5578{
5579 DWORD dwDummy;
5580
5581 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005582
5583 if (!USE_VTP)
5584 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5585 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005586 {
5587 set_console_color_rgb();
5588 gotoxy(coord.X + 1, coord.Y + 1);
5589 vtp_printf("\033[%dX", n);
5590 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005591}
5592
5593
5594/*
5595 * Clear the screen
5596 */
5597 static void
5598clear_screen(void)
5599{
5600 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005601
5602 if (!USE_VTP)
5603 clear_chars(g_coord, Rows * Columns);
5604 else
5605 {
5606 set_console_color_rgb();
5607 gotoxy(1, 1);
5608 vtp_printf("\033[2J");
5609 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005610}
5611
5612
5613/*
5614 * Clear to end of display
5615 */
5616 static void
5617clear_to_end_of_display(void)
5618{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005619 COORD save = g_coord;
5620
5621 if (!USE_VTP)
5622 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005623 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005624 else
5625 {
5626 set_console_color_rgb();
5627 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5628 vtp_printf("\033[0J");
5629
5630 gotoxy(save.X + 1, save.Y + 1);
5631 g_coord = save;
5632 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005633}
5634
5635
5636/*
5637 * Clear to end of line
5638 */
5639 static void
5640clear_to_end_of_line(void)
5641{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005642 COORD save = g_coord;
5643
5644 if (!USE_VTP)
5645 clear_chars(g_coord, Columns - g_coord.X);
5646 else
5647 {
5648 set_console_color_rgb();
5649 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5650 vtp_printf("\033[0K");
5651
5652 gotoxy(save.X + 1, save.Y + 1);
5653 g_coord = save;
5654 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005655}
5656
5657
5658/*
5659 * Scroll the scroll region up by `cLines' lines
5660 */
5661 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005662scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005663{
5664 COORD oldcoord = g_coord;
5665
5666 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5667 delete_lines(cLines);
5668
5669 g_coord = oldcoord;
5670}
5671
5672
5673/*
5674 * Set the scroll region
5675 */
5676 static void
5677set_scroll_region(
5678 unsigned left,
5679 unsigned top,
5680 unsigned right,
5681 unsigned bottom)
5682{
5683 if (left >= right
5684 || top >= bottom
5685 || right > (unsigned) Columns - 1
5686 || bottom > (unsigned) Rows - 1)
5687 return;
5688
5689 g_srScrollRegion.Left = left;
5690 g_srScrollRegion.Top = top;
5691 g_srScrollRegion.Right = right;
5692 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005693}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005694
Bram Moolenaar6982f422019-02-16 16:48:01 +01005695 static void
5696set_scroll_region_tb(
5697 unsigned top,
5698 unsigned bottom)
5699{
5700 if (top >= bottom || bottom > (unsigned)Rows - 1)
5701 return;
5702
5703 g_srScrollRegion.Top = top;
5704 g_srScrollRegion.Bottom = bottom;
5705}
5706
5707 static void
5708set_scroll_region_lr(
5709 unsigned left,
5710 unsigned right)
5711{
5712 if (left >= right || right > (unsigned)Columns - 1)
5713 return;
5714
5715 g_srScrollRegion.Left = left;
5716 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005717}
5718
5719
5720/*
5721 * Insert `cLines' lines at the current cursor position
5722 */
5723 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005724insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005725{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005726 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005727 COORD dest;
5728 CHAR_INFO fill;
5729
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005730 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5731
Bram Moolenaar6982f422019-02-16 16:48:01 +01005732 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005733 dest.Y = g_coord.Y + cLines;
5734
Bram Moolenaar6982f422019-02-16 16:48:01 +01005735 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005736 source.Top = g_coord.Y;
5737 source.Right = g_srScrollRegion.Right;
5738 source.Bottom = g_srScrollRegion.Bottom - cLines;
5739
Bram Moolenaar6982f422019-02-16 16:48:01 +01005740 clip.Left = g_srScrollRegion.Left;
5741 clip.Top = g_coord.Y;
5742 clip.Right = g_srScrollRegion.Right;
5743 clip.Bottom = g_srScrollRegion.Bottom;
5744
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005745 fill.Char.AsciiChar = ' ';
5746 if (!USE_VTP)
5747 fill.Attributes = g_attrCurrent;
5748 else
5749 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005750
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005751 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005752
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005753 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5754
Bram Moolenaar6982f422019-02-16 16:48:01 +01005755 // Here we have to deal with a win32 console flake: If the scroll
5756 // region looks like abc and we scroll c to a and fill with d we get
5757 // cbd... if we scroll block c one line at a time to a, we get cdd...
5758 // vim expects cdd consistently... So we have to deal with that
5759 // here... (this also occurs scrolling the same way in the other
5760 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005761
5762 if (source.Bottom < dest.Y)
5763 {
5764 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005765 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005766
Bram Moolenaar6982f422019-02-16 16:48:01 +01005767 coord.X = source.Left;
5768 for (i = clip.Top; i < dest.Y; ++i)
5769 {
5770 coord.Y = i;
5771 clear_chars(coord, source.Right - source.Left + 1);
5772 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005773 }
5774}
5775
5776
5777/*
5778 * Delete `cLines' lines at the current cursor position
5779 */
5780 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005781delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005782{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005783 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005784 COORD dest;
5785 CHAR_INFO fill;
5786 int nb;
5787
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005788 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5789
Bram Moolenaar6982f422019-02-16 16:48:01 +01005790 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005791 dest.Y = g_coord.Y;
5792
Bram Moolenaar6982f422019-02-16 16:48:01 +01005793 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005794 source.Top = g_coord.Y + cLines;
5795 source.Right = g_srScrollRegion.Right;
5796 source.Bottom = g_srScrollRegion.Bottom;
5797
Bram Moolenaar6982f422019-02-16 16:48:01 +01005798 clip.Left = g_srScrollRegion.Left;
5799 clip.Top = g_coord.Y;
5800 clip.Right = g_srScrollRegion.Right;
5801 clip.Bottom = g_srScrollRegion.Bottom;
5802
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005803 fill.Char.AsciiChar = ' ';
5804 if (!USE_VTP)
5805 fill.Attributes = g_attrCurrent;
5806 else
5807 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005808
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005809 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005810
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005811 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5812
Bram Moolenaar6982f422019-02-16 16:48:01 +01005813 // Here we have to deal with a win32 console flake; See insert_lines()
5814 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005815
5816 nb = dest.Y + (source.Bottom - source.Top) + 1;
5817
5818 if (nb < source.Top)
5819 {
5820 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005821 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005822
Bram Moolenaar6982f422019-02-16 16:48:01 +01005823 coord.X = source.Left;
5824 for (i = nb; i < clip.Bottom; ++i)
5825 {
5826 coord.Y = i;
5827 clear_chars(coord, source.Right - source.Left + 1);
5828 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005829 }
5830}
5831
5832
5833/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02005834 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005835 */
5836 static void
5837gotoxy(
5838 unsigned x,
5839 unsigned y)
5840{
5841 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5842 return;
5843
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005844 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02005845 {
5846 // external cursor coords are 1-based; internal are 0-based
5847 g_coord.X = x - 1;
5848 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005849 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02005850 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005851 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02005852 {
5853 // Move the cursor to the left edge of the screen to prevent screen
5854 // destruction. Insider build bug.
5855 if (conpty_type == 3)
5856 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
5857
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005858 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02005859
5860 g_coord.X = x - 1;
5861 g_coord.Y = y - 1;
5862 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005863}
5864
5865
5866/*
5867 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005868 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005869 */
5870 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005871textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005872{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005873 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005874
5875 SetConsoleTextAttribute(g_hConOut, wAttr);
5876}
5877
5878
5879 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005880textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005881{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005882 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005883
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005884 if (!USE_VTP)
5885 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5886 else
5887 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005888}
5889
5890
5891 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005892textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005893{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005894 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005895
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005896 if (!USE_VTP)
5897 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5898 else
5899 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005900}
5901
5902
5903/*
5904 * restore the default text attribute (whatever we started with)
5905 */
5906 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005907normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005908{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005909 if (!USE_VTP)
5910 textattr(g_attrDefault);
5911 else
5912 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005913}
5914
5915
5916static WORD g_attrPreStandout = 0;
5917
5918/*
5919 * Make the text standout, by brightening it
5920 */
5921 static void
5922standout(void)
5923{
5924 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005925
Bram Moolenaar071d4272004-06-13 20:20:40 +00005926 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5927}
5928
5929
5930/*
5931 * Turn off standout mode
5932 */
5933 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005934standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005935{
5936 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005937 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005938
5939 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005940}
5941
5942
5943/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005944 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005945 */
5946 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005947mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005948{
5949 char_u *p;
5950 int n;
5951
5952 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5953 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005954 if (
5955#ifdef FEAT_TERMGUICOLORS
5956 !p_tgc &&
5957#endif
5958 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005959 {
5960 p = T_ME + 2;
5961 n = getdigits(&p);
5962 if (*p == 'm' && n > 0)
5963 {
5964 cterm_normal_fg_color = (n & 0xf) + 1;
5965 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5966 }
5967 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005968#ifdef FEAT_TERMGUICOLORS
5969 cterm_normal_fg_gui_color = INVALCOLOR;
5970 cterm_normal_bg_gui_color = INVALCOLOR;
5971#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005972}
5973
5974
5975/*
5976 * visual bell: flash the screen
5977 */
5978 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005979visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005980{
5981 COORD coordOrigin = {0, 0};
5982 WORD attrFlash = ~g_attrCurrent & 0xff;
5983
5984 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005985 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005986
5987 if (oldattrs == NULL)
5988 return;
5989 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5990 coordOrigin, &dwDummy);
5991 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5992 coordOrigin, &dwDummy);
5993
5994 Sleep(15); /* wait for 15 msec */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005995 if (!USE_VTP)
5996 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005997 coordOrigin, &dwDummy);
5998 vim_free(oldattrs);
5999}
6000
6001
6002/*
6003 * Make the cursor visible or invisible
6004 */
6005 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006006cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006007{
6008 s_cursor_visible = fVisible;
6009#ifdef MCH_CURSOR_SHAPE
6010 mch_update_cursor();
6011#endif
6012}
6013
6014
6015/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006016 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006017 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006018 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006019 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006020write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006021 char_u *pchBuf,
6022 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006023{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006024 COORD coord = g_coord;
6025 DWORD written;
6026 DWORD n, cchwritten, cells;
6027 static WCHAR *unicodebuf = NULL;
6028 static int unibuflen = 0;
6029 int length;
6030 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006031
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006032 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
6033 if (unicodebuf == NULL || length > unibuflen)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006034 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006035 vim_free(unicodebuf);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006036 unicodebuf = LALLOC_MULT(WCHAR, length);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006037 unibuflen = length;
6038 }
6039 MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6040 unicodebuf, unibuflen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006041
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006042 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006043
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006044 if (!USE_VTP)
6045 {
6046 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6047 coord, &written);
6048 // When writing fails or didn't write a single character, pretend one
6049 // character was written, otherwise we get stuck.
6050 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
6051 coord, &cchwritten) == 0
6052 || cchwritten == 0 || cchwritten == (DWORD)-1)
6053 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006054 }
6055 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006056 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006057 if (WriteConsoleW(g_hConOut, unicodebuf, length, &cchwritten,
6058 NULL) == 0 || cchwritten == 0)
6059 cchwritten = 1;
6060 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006061
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006062 if (cchwritten == length)
6063 {
6064 written = cbToWrite;
6065 g_coord.X += (SHORT)cells;
6066 }
6067 else
6068 {
6069 char_u *p = pchBuf;
6070 for (n = 0; n < cchwritten; n++)
6071 MB_CPTR_ADV(p);
6072 written = p - pchBuf;
6073 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006074 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006075
6076 while (g_coord.X > g_srScrollRegion.Right)
6077 {
6078 g_coord.X -= (SHORT) Columns;
6079 if (g_coord.Y < g_srScrollRegion.Bottom)
6080 g_coord.Y++;
6081 }
6082
6083 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6084
6085 return written;
6086}
6087
6088
6089/*
6090 * mch_write(): write the output buffer to the screen, translating ESC
6091 * sequences into calls to console output routines.
6092 */
6093 void
6094mch_write(
6095 char_u *s,
6096 int len)
6097{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006098# ifdef VIMDLL
6099 if (gui.in_use)
6100 return;
6101# endif
6102
Bram Moolenaar071d4272004-06-13 20:20:40 +00006103 s[len] = NUL;
6104
6105 if (!term_console)
6106 {
6107 write(1, s, (unsigned)len);
6108 return;
6109 }
6110
6111 /* translate ESC | sequences into faked bios calls */
6112 while (len--)
6113 {
6114 /* optimization: use one single write_chars for runs of text,
6115 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006116 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006117
6118 if (p_wd)
6119 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006120 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006121 if (prefix != 0)
6122 prefix = 1;
6123 }
6124
6125 if (prefix != 0)
6126 {
6127 DWORD nWritten;
6128
6129 nWritten = write_chars(s, prefix);
6130#ifdef MCH_WRITE_DUMP
6131 if (fdDump)
6132 {
6133 fputc('>', fdDump);
6134 fwrite(s, sizeof(char_u), nWritten, fdDump);
6135 fputs("<\n", fdDump);
6136 }
6137#endif
6138 len -= (nWritten - 1);
6139 s += nWritten;
6140 }
6141 else if (s[0] == '\n')
6142 {
6143 /* \n, newline: go to the beginning of the next line or scroll */
6144 if (g_coord.Y == g_srScrollRegion.Bottom)
6145 {
6146 scroll(1);
6147 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6148 }
6149 else
6150 {
6151 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6152 }
6153#ifdef MCH_WRITE_DUMP
6154 if (fdDump)
6155 fputs("\\n\n", fdDump);
6156#endif
6157 s++;
6158 }
6159 else if (s[0] == '\r')
6160 {
6161 /* \r, carriage return: go to beginning of line */
6162 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
6163#ifdef MCH_WRITE_DUMP
6164 if (fdDump)
6165 fputs("\\r\n", fdDump);
6166#endif
6167 s++;
6168 }
6169 else if (s[0] == '\b')
6170 {
6171 /* \b, backspace: move cursor one position left */
6172 if (g_coord.X > g_srScrollRegion.Left)
6173 g_coord.X--;
6174 else if (g_coord.Y > g_srScrollRegion.Top)
6175 {
6176 g_coord.X = g_srScrollRegion.Right;
6177 g_coord.Y--;
6178 }
6179 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6180#ifdef MCH_WRITE_DUMP
6181 if (fdDump)
6182 fputs("\\b\n", fdDump);
6183#endif
6184 s++;
6185 }
6186 else if (s[0] == '\a')
6187 {
6188 /* \a, bell */
6189 MessageBeep(0xFFFFFFFF);
6190#ifdef MCH_WRITE_DUMP
6191 if (fdDump)
6192 fputs("\\a\n", fdDump);
6193#endif
6194 s++;
6195 }
6196 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6197 {
6198#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006199 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006200#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006201 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006202 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006203
6204 switch (s[2])
6205 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006206 case '0': case '1': case '2': case '3': case '4':
6207 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006208 p = s + 1;
6209 do
6210 {
6211 ++p;
6212 args[argc] = getdigits(&p);
6213 argc += (argc < 15) ? 1 : 0;
6214 if (p > s + len)
6215 break;
6216 } while (*p == ';');
6217
Bram Moolenaar071d4272004-06-13 20:20:40 +00006218 if (p > s + len)
6219 break;
6220
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006221 arg1 = args[0];
6222 arg2 = args[1];
6223 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006224 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006225 if (argc == 1 && args[0] == 0)
6226 normvideo();
6227 else if (argc == 1)
6228 {
6229 if (USE_VTP)
6230 textcolor((WORD) arg1);
6231 else
6232 textattr((WORD) arg1);
6233 }
6234 else if (USE_VTP)
6235 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006236 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006237 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006238 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006239 gotoxy(arg2, arg1);
6240 }
6241 else if (argc == 2 && *p == 'r')
6242 {
6243 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6244 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006245 else if (argc == 2 && *p == 'R')
6246 {
6247 set_scroll_region_tb(arg1, arg2);
6248 }
6249 else if (argc == 2 && *p == 'V')
6250 {
6251 set_scroll_region_lr(arg1, arg2);
6252 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006253 else if (argc == 1 && *p == 'A')
6254 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006255 gotoxy(g_coord.X + 1,
6256 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6257 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006258 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006259 {
6260 textbackground((WORD) arg1);
6261 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006262 else if (argc == 1 && *p == 'C')
6263 {
6264 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6265 g_coord.Y + 1);
6266 }
6267 else if (argc == 1 && *p == 'f')
6268 {
6269 textcolor((WORD) arg1);
6270 }
6271 else if (argc == 1 && *p == 'H')
6272 {
6273 gotoxy(1, arg1);
6274 }
6275 else if (argc == 1 && *p == 'L')
6276 {
6277 insert_lines(arg1);
6278 }
6279 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006280 {
6281 delete_lines(arg1);
6282 }
6283
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006284 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006285 s = p + 1;
6286 break;
6287
Bram Moolenaar071d4272004-06-13 20:20:40 +00006288 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006289 gotoxy(g_coord.X + 1,
6290 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6291 goto got3;
6292
6293 case 'B':
6294 visual_bell();
6295 goto got3;
6296
6297 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006298 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6299 g_coord.Y + 1);
6300 goto got3;
6301
6302 case 'E':
6303 termcap_mode_end();
6304 goto got3;
6305
6306 case 'F':
6307 standout();
6308 goto got3;
6309
6310 case 'f':
6311 standend();
6312 goto got3;
6313
6314 case 'H':
6315 gotoxy(1, 1);
6316 goto got3;
6317
6318 case 'j':
6319 clear_to_end_of_display();
6320 goto got3;
6321
6322 case 'J':
6323 clear_screen();
6324 goto got3;
6325
6326 case 'K':
6327 clear_to_end_of_line();
6328 goto got3;
6329
6330 case 'L':
6331 insert_lines(1);
6332 goto got3;
6333
6334 case 'M':
6335 delete_lines(1);
6336 goto got3;
6337
6338 case 'S':
6339 termcap_mode_start();
6340 goto got3;
6341
6342 case 'V':
6343 cursor_visible(TRUE);
6344 goto got3;
6345
6346 case 'v':
6347 cursor_visible(FALSE);
6348 goto got3;
6349
6350 got3:
6351 s += 3;
6352 len -= 2;
6353 }
6354
6355#ifdef MCH_WRITE_DUMP
6356 if (fdDump)
6357 {
6358 fputs("ESC | ", fdDump);
6359 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6360 fputc('\n', fdDump);
6361 }
6362#endif
6363 }
6364 else
6365 {
6366 /* Write a single character */
6367 DWORD nWritten;
6368
6369 nWritten = write_chars(s, 1);
6370#ifdef MCH_WRITE_DUMP
6371 if (fdDump)
6372 {
6373 fputc('>', fdDump);
6374 fwrite(s, sizeof(char_u), nWritten, fdDump);
6375 fputs("<\n", fdDump);
6376 }
6377#endif
6378
6379 len -= (nWritten - 1);
6380 s += nWritten;
6381 }
6382 }
6383
6384#ifdef MCH_WRITE_DUMP
6385 if (fdDump)
6386 fflush(fdDump);
6387#endif
6388}
6389
Bram Moolenaar4f974752019-02-17 17:44:42 +01006390#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006391
6392
6393/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006394 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006395 */
6396 void
6397mch_delay(
6398 long msec,
Bram Moolenaar1266d672017-02-01 13:43:36 +01006399 int ignoreinput UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006400{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006401#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006402 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006403#else /* Console */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006404# ifdef VIMDLL
6405 if (gui.in_use)
6406 {
6407 Sleep((int)msec); /* never wait for input */
6408 return;
6409 }
6410# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006411 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006412# ifdef FEAT_MZSCHEME
6413 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6414 {
6415 int towait = p_mzq;
6416
6417 /* if msec is large enough, wait by portions in p_mzq */
6418 while (msec > 0)
6419 {
6420 mzvim_check_threads();
6421 if (msec < towait)
6422 towait = msec;
6423 Sleep(towait);
6424 msec -= towait;
6425 }
6426 }
6427 else
6428# endif
6429 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006430 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006431 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006432#endif
6433}
6434
6435
6436/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006437 * This version of remove is not scared by a readonly (backup) file.
6438 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006439 * Return 0 for success, -1 for failure.
6440 */
6441 int
6442mch_remove(char_u *name)
6443{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006444 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006445 int n;
6446
Bram Moolenaar203258c2016-01-17 22:15:16 +01006447 /*
6448 * On Windows, deleting a directory's symbolic link is done by
6449 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6450 */
6451 if (mch_isdir(name) && mch_is_symbolic_link(name))
6452 return mch_rmdir(name);
6453
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006454 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6455
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006456 wn = enc_to_utf16(name, NULL);
6457 if (wn == NULL)
6458 return -1;
6459
6460 n = DeleteFileW(wn) ? 0 : -1;
6461 vim_free(wn);
6462 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006463}
6464
6465
6466/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006467 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006468 */
6469 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006470mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006471{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006472#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
6473# ifdef VIMDLL
6474 if (!gui.in_use)
6475# endif
6476 if (g_fCtrlCPressed || g_fCBrkPressed)
6477 {
6478 ctrl_break_was_pressed = g_fCBrkPressed;
6479 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6480 got_int = TRUE;
6481 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006482#endif
6483}
6484
Bram Moolenaaree273972016-01-02 21:11:51 +01006485/* physical RAM to leave for the OS */
6486#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006487
6488/*
6489 * How much main memory in KiB that can be used by VIM.
6490 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006491 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006492mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006493{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006494 MEMORYSTATUSEX ms;
6495
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006496 /* Need to use GlobalMemoryStatusEx() when there is more memory than
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006497 * what fits in 32 bits. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006498 ms.dwLength = sizeof(MEMORYSTATUSEX);
6499 GlobalMemoryStatusEx(&ms);
6500 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006501 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006502 /* Process address space fits in physical RAM, use all of it. */
6503 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006504 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006505 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006506 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006507 /* Catch old NT box or perverse hardware setup. */
6508 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006509 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006510 /* Use physical RAM less reserve for OS + data. */
6511 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006512}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006513
Bram Moolenaar071d4272004-06-13 20:20:40 +00006514/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006515 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00006516 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6517 * file whose short file name is "FOO.BAR" (its long file name will
6518 * be correct: "foo.bar~"). Because a file can be accessed by
6519 * either its SFN or its LFN, "foo.bar" has effectively been
6520 * renamed to "foo.bar", which is not at all what was wanted. This
6521 * seems to happen only when renaming files with three-character
6522 * extensions by appending a suffix that does not include ".".
6523 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6524 *
6525 * There is another problem, which isn't really a bug but isn't right either:
6526 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6527 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6528 * service pack 6. Doesn't seem to happen on Windows 98.
6529 *
6530 * Like rename(), returns 0 upon success, non-zero upon failure.
6531 * Should probably set errno appropriately when errors occur.
6532 */
6533 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006534mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006535{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006536 WCHAR *p;
6537 int i;
6538 WCHAR szTempFile[_MAX_PATH + 1];
6539 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006540 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006541
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006542 // No need to play tricks unless the file name contains a "~" as the
6543 // seventh character.
6544 p = wold;
6545 for (i = 0; wold[i] != NUL; ++i)
6546 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6547 && wold[i + 1] != 0)
6548 p = wold + i + 1;
6549 if ((int)(wold + i - p) < 8 || p[6] != '~')
6550 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006551
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006552 // Get base path of new file name. Undocumented feature: If pszNewFile is
6553 // a directory, no error is returned and pszFilePart will be NULL.
6554 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006555 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006556 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006557
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006558 // Get (and create) a unique temporary file name in directory of new file
6559 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006560 return -2;
6561
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006562 // blow the temp file away
6563 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006564 return -3;
6565
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006566 // rename old file to the temp file
6567 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006568 return -4;
6569
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006570 // now create an empty file called pszOldFile; this prevents the operating
6571 // system using pszOldFile as an alias (SFN) if we're renaming within the
6572 // same directory. For example, we're editing a file called
6573 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6574 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
6575 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
6576 // cause all sorts of problems later in buf_write(). So, we create an
6577 // empty file called filena~1.txt and the system will have to find some
6578 // other SFN for filena~1.txt~, such as filena~2.txt
6579 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006580 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6581 return -5;
6582 if (!CloseHandle(hf))
6583 return -6;
6584
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006585 // rename the temp file to the new file
6586 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006587 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006588 // Renaming failed. Rename the file back to its old name, so that it
6589 // looks like nothing happened.
6590 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006591 return -7;
6592 }
6593
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006594 // Seems to be left around on Novell filesystems
6595 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006596
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006597 // finally, remove the empty old file
6598 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006599 return -8;
6600
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006601 return 0;
6602}
6603
6604
6605/*
6606 * Converts the filenames to UTF-16, then call mch_wrename().
6607 * Like rename(), returns 0 upon success, non-zero upon failure.
6608 */
6609 int
6610mch_rename(
6611 const char *pszOldFile,
6612 const char *pszNewFile)
6613{
6614 WCHAR *wold = NULL;
6615 WCHAR *wnew = NULL;
6616 int retval = -1;
6617
6618 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6619 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
6620 if (wold != NULL && wnew != NULL)
6621 retval = mch_wrename(wold, wnew);
6622 vim_free(wold);
6623 vim_free(wnew);
6624 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006625}
6626
6627/*
6628 * Get the default shell for the current hardware platform
6629 */
6630 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006631default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006632{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006633 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006634}
6635
6636/*
6637 * mch_access() extends access() to do more detailed check on network drives.
6638 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6639 */
6640 int
6641mch_access(char *n, int p)
6642{
6643 HANDLE hFile;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006644 int retval = -1; /* default: fail */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006645 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006646
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006647 wn = enc_to_utf16((char_u *)n, NULL);
6648 if (wn == NULL)
6649 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006650
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006651 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006652 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006653 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006654
6655 if (p & R_OK)
6656 {
6657 /* Read check is performed by seeing if we can do a find file on
6658 * the directory for any file. */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006659 int i;
6660 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006661
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006662 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6663 TempNameW[i] = wn[i];
6664 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6665 TempNameW[i++] = '\\';
6666 TempNameW[i++] = '*';
6667 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006668
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006669 hFile = FindFirstFileW(TempNameW, &d);
6670 if (hFile == INVALID_HANDLE_VALUE)
6671 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006672 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006673 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006674 }
6675
6676 if (p & W_OK)
6677 {
6678 /* Trying to create a temporary file in the directory should catch
6679 * directories on read-only network shares. However, in
6680 * directories whose ACL allows writes but denies deletes will end
6681 * up keeping the temporary file :-(. */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006682 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6683 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006684 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006685 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006686 }
6687 }
6688 else
6689 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02006690 // Don't consider a file read-only if another process has opened it.
6691 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
6692
Bram Moolenaar071d4272004-06-13 20:20:40 +00006693 /* Trying to open the file for the required access does ACL, read-only
6694 * network share, and file attribute checks. */
Bram Moolenaar5aa98962018-05-06 17:09:38 +02006695 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
6696 | ((p & R_OK) ? GENERIC_READ : 0);
6697
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006698 hFile = CreateFileW(wn, access_mode, share_mode,
6699 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006700 if (hFile == INVALID_HANDLE_VALUE)
6701 goto getout;
6702 CloseHandle(hFile);
6703 }
6704
6705 retval = 0; /* success */
6706getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00006707 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006708 return retval;
6709}
6710
Bram Moolenaar071d4272004-06-13 20:20:40 +00006711/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006712 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006713 */
6714 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006715mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006716{
6717 WCHAR *wn;
6718 int f;
6719
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006720 wn = enc_to_utf16((char_u *)name, NULL);
6721 if (wn == NULL)
6722 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006723
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006724 f = _wopen(wn, flags, mode);
6725 vim_free(wn);
6726 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006727}
6728
6729/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006730 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006731 */
6732 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006733mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006734{
6735 WCHAR *wn, *wm;
6736 FILE *f = NULL;
6737
Bram Moolenaara12a1612019-01-24 16:39:02 +01006738#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006739 /* Work around an annoying assertion in the Microsoft debug CRT
6740 * when mode's text/binary setting doesn't match _get_fmode(). */
6741 char newMode = mode[strlen(mode) - 1];
6742 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006743
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006744 _get_fmode(&oldMode);
6745 if (newMode == 't')
6746 _set_fmode(_O_TEXT);
6747 else if (newMode == 'b')
6748 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01006749#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006750 wn = enc_to_utf16((char_u *)name, NULL);
6751 wm = enc_to_utf16((char_u *)mode, NULL);
6752 if (wn != NULL && wm != NULL)
6753 f = _wfopen(wn, wm);
6754 vim_free(wn);
6755 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006756
Bram Moolenaara12a1612019-01-24 16:39:02 +01006757#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006758 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01006759#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006760 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006761}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006762
Bram Moolenaar071d4272004-06-13 20:20:40 +00006763/*
6764 * SUB STREAM (aka info stream) handling:
6765 *
6766 * NTFS can have sub streams for each file. Normal contents of file is
6767 * stored in the main stream, and extra contents (author information and
6768 * title and so on) can be stored in sub stream. After Windows 2000, user
6769 * can access and store those informations in sub streams via explorer's
6770 * property menuitem in right click menu. Those informations in sub streams
6771 * were lost when copying only the main stream. So we have to copy sub
6772 * streams.
6773 *
6774 * Incomplete explanation:
6775 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6776 * More useful info and an example:
6777 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6778 */
6779
6780/*
6781 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6782 * and write to stream "substream" of file "to".
6783 * Errors are ignored.
6784 */
6785 static void
6786copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6787{
6788 HANDLE hTo;
6789 WCHAR *to_name;
6790
6791 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6792 wcscpy(to_name, to);
6793 wcscat(to_name, substream);
6794
6795 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6796 FILE_ATTRIBUTE_NORMAL, NULL);
6797 if (hTo != INVALID_HANDLE_VALUE)
6798 {
6799 long done;
6800 DWORD todo;
6801 DWORD readcnt, written;
6802 char buf[4096];
6803
6804 /* Copy block of bytes at a time. Abort when something goes wrong. */
6805 for (done = 0; done < len; done += written)
6806 {
6807 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006808 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6809 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006810 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6811 FALSE, FALSE, context)
6812 || readcnt != todo
6813 || !WriteFile(hTo, buf, todo, &written, NULL)
6814 || written != todo)
6815 break;
6816 }
6817 CloseHandle(hTo);
6818 }
6819
6820 free(to_name);
6821}
6822
6823/*
6824 * Copy info streams from file "from" to file "to".
6825 */
6826 static void
6827copy_infostreams(char_u *from, char_u *to)
6828{
6829 WCHAR *fromw;
6830 WCHAR *tow;
6831 HANDLE sh;
6832 WIN32_STREAM_ID sid;
6833 int headersize;
6834 WCHAR streamname[_MAX_PATH];
6835 DWORD readcount;
6836 void *context = NULL;
6837 DWORD lo, hi;
6838 int len;
6839
6840 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006841 fromw = enc_to_utf16(from, NULL);
6842 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006843 if (fromw != NULL && tow != NULL)
6844 {
6845 /* Open the file for reading. */
6846 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6847 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6848 if (sh != INVALID_HANDLE_VALUE)
6849 {
6850 /* Use BackupRead() to find the info streams. Repeat until we
6851 * have done them all.*/
6852 for (;;)
6853 {
6854 /* Get the header to find the length of the stream name. If
6855 * the "readcount" is zero we have done all info streams. */
6856 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006857 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006858 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6859 &readcount, FALSE, FALSE, &context)
6860 || readcount == 0)
6861 break;
6862
6863 /* We only deal with streams that have a name. The normal
6864 * file data appears to be without a name, even though docs
6865 * suggest it is called "::$DATA". */
6866 if (sid.dwStreamNameSize > 0)
6867 {
6868 /* Read the stream name. */
6869 if (!BackupRead(sh, (LPBYTE)streamname,
6870 sid.dwStreamNameSize,
6871 &readcount, FALSE, FALSE, &context))
6872 break;
6873
6874 /* Copy an info stream with a name ":anything:$DATA".
6875 * Skip "::$DATA", it has no stream name (examples suggest
6876 * it might be used for the normal file contents).
6877 * Note that BackupRead() counts bytes, but the name is in
6878 * wide characters. */
6879 len = readcount / sizeof(WCHAR);
6880 streamname[len] = 0;
6881 if (len > 7 && wcsicmp(streamname + len - 6,
6882 L":$DATA") == 0)
6883 {
6884 streamname[len - 6] = 0;
6885 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006886 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006887 }
6888 }
6889
6890 /* Advance to the next stream. We might try seeking too far,
6891 * but BackupSeek() doesn't skip over stream borders, thus
6892 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006893 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006894 &lo, &hi, &context);
6895 }
6896
6897 /* Clear the context. */
6898 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6899
6900 CloseHandle(sh);
6901 }
6902 }
6903 vim_free(fromw);
6904 vim_free(tow);
6905}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006906
6907/*
6908 * Copy file attributes from file "from" to file "to".
6909 * For Windows NT and later we copy info streams.
6910 * Always returns zero, errors are ignored.
6911 */
6912 int
6913mch_copy_file_attribute(char_u *from, char_u *to)
6914{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006915 /* File streams only work on Windows NT and later. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006916 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006917 return 0;
6918}
6919
6920#if defined(MYRESETSTKOFLW) || defined(PROTO)
6921/*
6922 * Recreate a destroyed stack guard page in win32.
6923 * Written by Benjamin Peterson.
6924 */
6925
6926/* These magic numbers are from the MS header files */
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01006927# define MIN_STACK_WINNT 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00006928
6929/*
6930 * This function does the same thing as _resetstkoflw(), which is only
6931 * available in DevStudio .net and later.
6932 * Returns 0 for failure, 1 for success.
6933 */
6934 int
6935myresetstkoflw(void)
6936{
6937 BYTE *pStackPtr;
6938 BYTE *pGuardPage;
6939 BYTE *pStackBase;
6940 BYTE *pLowestPossiblePage;
6941 MEMORY_BASIC_INFORMATION mbi;
6942 SYSTEM_INFO si;
6943 DWORD nPageSize;
6944 DWORD dummy;
6945
Bram Moolenaar071d4272004-06-13 20:20:40 +00006946 /* We need to know the system page size. */
6947 GetSystemInfo(&si);
6948 nPageSize = si.dwPageSize;
6949
6950 /* ...and the current stack pointer */
6951 pStackPtr = (BYTE*)_alloca(1);
6952
6953 /* ...and the base of the stack. */
6954 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6955 return 0;
6956 pStackBase = (BYTE*)mbi.AllocationBase;
6957
6958 /* ...and the page thats min_stack_req pages away from stack base; this is
6959 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006960 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006961
Bram Moolenaar071d4272004-06-13 20:20:40 +00006962 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006963 /* We want the first committed page in the stack Start at the stack
6964 * base and move forward through memory until we find a committed block.
6965 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006966 BYTE *pBlock = pStackBase;
6967
Bram Moolenaara466c992005-07-09 21:03:22 +00006968 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006969 {
6970 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6971 return 0;
6972
6973 pBlock += mbi.RegionSize;
6974
6975 if (mbi.State & MEM_COMMIT)
6976 break;
6977 }
6978
6979 /* mbi now describes the first committed block in the stack. */
6980 if (mbi.Protect & PAGE_GUARD)
6981 return 1;
6982
6983 /* decide where the guard page should start */
6984 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6985 pGuardPage = pLowestPossiblePage;
6986 else
6987 pGuardPage = (BYTE*)mbi.BaseAddress;
6988
6989 /* allocate the guard page */
6990 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6991 return 0;
6992
6993 /* apply the guard attribute to the page */
6994 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6995 &dummy))
6996 return 0;
6997 }
6998
6999 return 1;
7000}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007001#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007002
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007003
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007004/*
7005 * The command line arguments in UCS2
7006 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007007static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007008static LPWSTR *ArglistW = NULL;
7009static int global_argc = 0;
7010static char **global_argv;
7011
7012static int used_file_argc = 0; /* last argument in global_argv[] used
7013 for the argument list. */
7014static int *used_file_indexes = NULL; /* indexes in global_argv[] for
7015 command line arguments added to
7016 the argument list */
7017static int used_file_count = 0; /* nr of entries in used_file_indexes */
7018static int used_file_literal = FALSE; /* take file names literally */
7019static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007020static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007021static int used_alist_count = 0;
7022
7023
7024/*
7025 * Get the command line arguments. Unicode version.
7026 * Returns argc. Zero when something fails.
7027 */
7028 int
7029get_cmd_argsW(char ***argvp)
7030{
7031 char **argv = NULL;
7032 int argc = 0;
7033 int i;
7034
Bram Moolenaar14993322014-09-09 12:25:33 +02007035 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007036 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7037 if (ArglistW != NULL)
7038 {
7039 argv = malloc((nArgsW + 1) * sizeof(char *));
7040 if (argv != NULL)
7041 {
7042 argc = nArgsW;
7043 argv[argc] = NULL;
7044 for (i = 0; i < argc; ++i)
7045 {
7046 int len;
7047
7048 /* Convert each Unicode argument to the current codepage. */
7049 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007050 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007051 (LPSTR *)&argv[i], &len, 0, 0);
7052 if (argv[i] == NULL)
7053 {
7054 /* Out of memory, clear everything. */
7055 while (i > 0)
7056 free(argv[--i]);
7057 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007058 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007059 argc = 0;
7060 }
7061 }
7062 }
7063 }
7064
7065 global_argc = argc;
7066 global_argv = argv;
7067 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007068 {
7069 if (used_file_indexes != NULL)
7070 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007071 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007072 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007073
7074 if (argvp != NULL)
7075 *argvp = argv;
7076 return argc;
7077}
7078
7079 void
7080free_cmd_argsW(void)
7081{
7082 if (ArglistW != NULL)
7083 {
7084 GlobalFree(ArglistW);
7085 ArglistW = NULL;
7086 }
7087}
7088
7089/*
7090 * Remember "name" is an argument that was added to the argument list.
7091 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7092 * is called.
7093 */
7094 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007095used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007096{
7097 int i;
7098
7099 if (used_file_indexes == NULL)
7100 return;
7101 for (i = used_file_argc + 1; i < global_argc; ++i)
7102 if (STRCMP(global_argv[i], name) == 0)
7103 {
7104 used_file_argc = i;
7105 used_file_indexes[used_file_count++] = i;
7106 break;
7107 }
7108 used_file_literal = literal;
7109 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007110 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007111}
7112
7113/*
7114 * Remember the length of the argument list as it was. If it changes then we
7115 * leave it alone when 'encoding' is set.
7116 */
7117 void
7118set_alist_count(void)
7119{
7120 used_alist_count = GARGCOUNT;
7121}
7122
7123/*
7124 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7125 * has been changed while starting up. Use the UCS-2 command line arguments
7126 * and convert them to 'encoding'.
7127 */
7128 void
7129fix_arg_enc(void)
7130{
7131 int i;
7132 int idx;
7133 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007134 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007135
7136 /* Safety checks:
7137 * - if argument count differs between the wide and non-wide argument
7138 * list, something must be wrong.
7139 * - the file name arguments must have been located.
7140 * - the length of the argument list wasn't changed by the user.
7141 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007142 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007143 || ArglistW == NULL
7144 || used_file_indexes == NULL
7145 || used_file_count == 0
7146 || used_alist_count != GARGCOUNT)
7147 return;
7148
Bram Moolenaar86b68352004-12-27 21:59:20 +00007149 /* Remember the buffer numbers for the arguments. */
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007150 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007151 if (fnum_list == NULL)
7152 return; /* out of memory */
7153 for (i = 0; i < GARGCOUNT; ++i)
7154 fnum_list[i] = GARGLIST[i].ae_fnum;
7155
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007156 /* Clear the argument list. Make room for the new arguments. */
7157 alist_clear(&global_alist);
7158 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007159 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007160
7161 for (i = 0; i < used_file_count; ++i)
7162 {
7163 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007164 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007165 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007166 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007167 int literal = used_file_literal;
7168
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007169# ifdef FEAT_DIFF
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007170 /* When using diff mode may need to concatenate file name to
7171 * directory name. Just like it's done in main(). */
7172 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7173 && !mch_isdir(alist_name(&GARGLIST[0])))
7174 {
7175 char_u *r;
7176
7177 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7178 if (r != NULL)
7179 {
7180 vim_free(str);
7181 str = r;
7182 }
7183 }
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007184# endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007185 /* Re-use the old buffer by renaming it. When not using literal
7186 * names it's done by alist_expand() below. */
7187 if (used_file_literal)
7188 buf_set_name(fnum_list[i], str);
7189
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007190 /* Check backtick literal. backtick literal is already expanded in
7191 * main.c, so this part add str as literal. */
7192 if (literal == FALSE)
7193 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007194 size_t len = STRLEN(str);
7195
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007196 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7197 literal = TRUE;
7198 }
7199 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007200 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007201 }
7202
7203 if (!used_file_literal)
7204 {
7205 /* Now expand wildcards in the arguments. */
7206 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7207 * filename characters but are excluded from 'isfname' to make
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007208 * "gf" work on a file name in parenthesis (e.g.: see vim.h).
7209 * Also, unset wildignore to not be influenced by this option.
7210 * The arguments specified in command-line should be kept even if
7211 * encoding options were changed. */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007212 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007213 do_cmdline_cmd((char_u *)":let SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007214 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007215 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007216 do_cmdline_cmd((char_u *)":let &wig = SaVe_WIG|unlet SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007217 }
7218
7219 /* If wildcard expansion failed, we are editing the first file of the
7220 * arglist and there is no file name: Edit the first argument now. */
7221 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7222 {
7223 do_cmdline_cmd((char_u *)":rewind");
7224 if (GARGCOUNT == 1 && used_file_full_path)
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007225 (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007226 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007227
7228 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007229}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007230
7231 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007232mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007233{
7234 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007235 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007236
Bram Moolenaar964b3742019-05-24 18:54:09 +02007237 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007238 if (envbuf == NULL)
7239 return -1;
7240
7241 sprintf((char *)envbuf, "%s=%s", var, value);
7242
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007243 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007244
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007245 vim_free(envbuf);
7246 if (p == NULL)
7247 return -1;
7248 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007249#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007250 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007251#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007252 // Unlike Un*x systems, we can free the string for _wputenv().
7253 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007254
7255 return 0;
7256}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007257
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007258/*
7259 * Support for 256 colors and 24-bit colors was added in Windows 10
7260 * version 1703 (Creators update).
7261 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007262#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7263
7264/*
7265 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02007266 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007267 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007268#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007269
7270/*
7271 * ConPTY differences between versions, need different logic.
7272 * version 1903 (May 2019 update).
7273 */
7274#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
7275
7276/*
7277 * Confirm until this version. Also the logic changes.
7278 * insider preview.
7279 */
Bram Moolenaar2313b612019-09-27 14:14:32 +02007280#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18990)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007281
7282/*
7283 * Not stable now.
7284 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007285#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007286
7287 static void
7288vtp_flag_init(void)
7289{
7290 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007291#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007292 DWORD mode;
7293 HANDLE out;
7294
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007295# ifdef VIMDLL
7296 if (!gui.in_use)
7297# endif
7298 {
7299 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007300
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007301 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7302 GetConsoleMode(out, &mode);
7303 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7304 if (SetConsoleMode(out, mode) == 0)
7305 vtp_working = 0;
7306 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007307#endif
7308
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007309 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007310 conpty_working = 1;
7311 if (ver >= CONPTY_STABLE_BUILD)
7312 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007313
Bram Moolenaar57da6982019-09-13 22:30:11 +02007314 if (ver <= CONPTY_INSIDER_BUILD)
7315 conpty_type = 3;
7316 if (ver <= CONPTY_1903_BUILD)
7317 conpty_type = 2;
7318 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
7319 conpty_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007320}
7321
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007322#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007323
7324 static void
7325vtp_init(void)
7326{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007327 HMODULE hKerneldll;
7328 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007329# ifdef FEAT_TERMGUICOLORS
7330 COLORREF fg, bg;
7331# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007332
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007333 /* Use functions supported from Vista */
7334 hKerneldll = GetModuleHandle("kernel32.dll");
7335 if (hKerneldll != NULL)
7336 {
7337 pGetConsoleScreenBufferInfoEx =
7338 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7339 hKerneldll, "GetConsoleScreenBufferInfoEx");
7340 pSetConsoleScreenBufferInfoEx =
7341 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7342 hKerneldll, "SetConsoleScreenBufferInfoEx");
7343 if (pGetConsoleScreenBufferInfoEx != NULL
7344 && pSetConsoleScreenBufferInfoEx != NULL)
7345 has_csbiex = TRUE;
7346 }
7347
7348 csbi.cbSize = sizeof(csbi);
7349 if (has_csbiex)
7350 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007351 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7352 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
7353
7354# ifdef FEAT_TERMGUICOLORS
7355 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7356 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7357 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7358 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7359 default_console_color_bg = bg;
7360 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007361# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007362
7363 set_console_color_rgb();
7364}
7365
7366 static void
7367vtp_exit(void)
7368{
7369 reset_console_color_rgb();
7370}
7371
7372 static int
7373vtp_printf(
7374 char *format,
7375 ...)
7376{
7377 char_u buf[100];
7378 va_list list;
7379 DWORD result;
7380
7381 va_start(list, format);
7382 vim_vsnprintf((char *)buf, 100, (char *)format, list);
7383 va_end(list);
7384 WriteConsoleA(g_hConOut, buf, (DWORD)STRLEN(buf), &result, NULL);
7385 return (int)result;
7386}
7387
7388 static void
7389vtp_sgr_bulk(
7390 int arg)
7391{
7392 int args[1];
7393
7394 args[0] = arg;
7395 vtp_sgr_bulks(1, args);
7396}
7397
7398 static void
7399vtp_sgr_bulks(
7400 int argc,
7401 int *args
7402)
7403{
7404 /* 2('\033[') + 4('255.') * 16 + NUL */
7405 char_u buf[2 + (4 * 16) + 1];
7406 char_u *p;
7407 int i;
7408
7409 p = buf;
7410 *p++ = '\033';
7411 *p++ = '[';
7412
7413 for (i = 0; i < argc; ++i)
7414 {
7415 p += vim_snprintf((char *)p, 4, "%d", args[i] & 0xff);
7416 *p++ = ';';
7417 }
7418 p--;
7419 *p++ = 'm';
7420 *p = NUL;
7421 vtp_printf((char *)buf);
7422}
7423
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007424# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007425 static int
7426ctermtoxterm(
7427 int cterm)
7428{
Bram Moolenaar9894e392018-05-05 14:29:06 +02007429 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007430
7431 cterm_color2rgb(cterm, &r, &g, &b, &idx);
7432 return (((int)r << 16) | ((int)g << 8) | (int)b);
7433}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007434# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007435
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007436 static void
7437set_console_color_rgb(void)
7438{
7439# ifdef FEAT_TERMGUICOLORS
7440 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7441 int id;
7442 guicolor_T fg = INVALCOLOR;
7443 guicolor_T bg = INVALCOLOR;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007444 int ctermfg;
7445 int ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007446
7447 if (!USE_VTP)
7448 return;
7449
7450 id = syn_name2id((char_u *)"Normal");
Bram Moolenaard5a58862019-03-07 06:40:27 +01007451 if (id > 0 && p_tgc)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007452 syn_id2colors(id, &fg, &bg);
7453 if (fg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007454 {
7455 ctermfg = -1;
7456 if (id > 0)
7457 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007458 fg = ctermfg != -1 ? ctermtoxterm(ctermfg) : default_console_color_fg;
7459 cterm_normal_fg_gui_color = fg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007460 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007461 if (bg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007462 {
7463 ctermbg = -1;
7464 if (id > 0)
7465 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007466 bg = ctermbg != -1 ? ctermtoxterm(ctermbg) : default_console_color_bg;
7467 cterm_normal_bg_gui_color = bg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007468 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007469 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7470 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7471
7472 csbi.cbSize = sizeof(csbi);
7473 if (has_csbiex)
7474 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7475
7476 csbi.cbSize = sizeof(csbi);
7477 csbi.srWindow.Right += 1;
7478 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007479 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
7480 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007481 if (has_csbiex)
7482 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7483# endif
7484}
7485
7486 static void
7487reset_console_color_rgb(void)
7488{
7489# ifdef FEAT_TERMGUICOLORS
7490 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7491
7492 csbi.cbSize = sizeof(csbi);
7493 if (has_csbiex)
7494 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7495
7496 csbi.cbSize = sizeof(csbi);
7497 csbi.srWindow.Right += 1;
7498 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007499 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
7500 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007501 if (has_csbiex)
7502 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7503# endif
7504}
7505
7506 void
7507control_console_color_rgb(void)
7508{
7509 if (USE_VTP)
7510 set_console_color_rgb();
7511 else
7512 reset_console_color_rgb();
7513}
7514
7515 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007516use_vtp(void)
7517{
7518 return USE_VTP;
7519}
7520
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007521 int
7522is_term_win32(void)
7523{
7524 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
7525}
7526
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007527 int
7528has_vtp_working(void)
7529{
7530 return vtp_working;
7531}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007532
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01007533#endif
7534
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007535 int
7536has_conpty_working(void)
7537{
7538 return conpty_working;
7539}
7540
7541 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02007542get_conpty_type(void)
7543{
7544 return conpty_type;
7545}
7546
7547 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007548is_conpty_stable(void)
7549{
7550 return conpty_stable;
7551}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01007552
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007553#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01007554 void
7555resize_console_buf(void)
7556{
7557 CONSOLE_SCREEN_BUFFER_INFO csbi;
7558 COORD coord;
7559 SMALL_RECT newsize;
7560
7561 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
7562 {
7563 coord.X = SRWIDTH(csbi.srWindow);
7564 coord.Y = SRHEIGHT(csbi.srWindow);
7565 SetConsoleScreenBufferSize(g_hConOut, coord);
7566
7567 newsize.Left = 0;
7568 newsize.Top = 0;
7569 newsize.Right = coord.X - 1;
7570 newsize.Bottom = coord.Y - 1;
7571 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
7572
7573 SetConsoleScreenBufferSize(g_hConOut, coord);
7574 }
7575}
7576#endif