blob: 9b86478d3e384203712a236ffeecdffc0c76f082 [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
13 * the console version only, so there is a lot of "#ifndef FEAT_GUI_W32".
14 *
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
48# if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
49# 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;
114typedef int KEY_EVENT_RECORD;
115typedef int LOGFONT;
116typedef int LPBOOL;
117typedef int LPCTSTR;
118typedef int LPDWORD;
119typedef int LPSTR;
120typedef int LPTSTR;
121typedef int LPVOID;
122typedef int MOUSE_EVENT_RECORD;
123typedef int PACL;
124typedef int PDWORD;
125typedef int PHANDLE;
126typedef int PRINTDLG;
127typedef int PSECURITY_DESCRIPTOR;
128typedef int PSID;
129typedef int SECURITY_INFORMATION;
130typedef int SHORT;
131typedef int SMALL_RECT;
132typedef int TEXTMETRIC;
133typedef int TOKEN_INFORMATION_CLASS;
134typedef int TRUSTEE;
135typedef int WORD;
136typedef int WCHAR;
137typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100138typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200139typedef int SE_OBJECT_TYPE;
140typedef int PSNSECINFO;
141typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100142typedef int STARTUPINFO;
143typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200144typedef int LPSECURITY_ATTRIBUTES;
145# define __stdcall /* empty */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000146#endif
147
Bram Moolenaar071d4272004-06-13 20:20:40 +0000148#if defined(__BORLANDC__)
149/* Strangely Borland uses a non-standard name. */
150# define wcsicmp(a, b) wcscmpi((a), (b))
151#endif
152
153#ifndef FEAT_GUI_W32
154/* Win32 Console handles for input and output */
155static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
156static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
157
158/* Win32 Screen buffer,coordinate,console I/O information */
159static SMALL_RECT g_srScrollRegion;
160static COORD g_coord; /* 0-based, but external coords are 1-based */
161
162/* The attribute of the screen when the editor was started */
163static WORD g_attrDefault = 7; /* lightgray text on black background */
164static WORD g_attrCurrent;
165
166static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
167static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
168static int g_fForceExit = FALSE; /* set when forcefully exiting */
169
170static void termcap_mode_start(void);
171static void termcap_mode_end(void);
172static void clear_chars(COORD coord, DWORD n);
173static void clear_screen(void);
174static void clear_to_end_of_display(void);
175static void clear_to_end_of_line(void);
176static void scroll(unsigned cLines);
177static void set_scroll_region(unsigned left, unsigned top,
178 unsigned right, unsigned bottom);
179static void insert_lines(unsigned cLines);
180static void delete_lines(unsigned cLines);
181static void gotoxy(unsigned x, unsigned y);
182static void normvideo(void);
183static void textattr(WORD wAttr);
184static void textcolor(WORD wAttr);
185static void textbackground(WORD wAttr);
186static void standout(void);
187static void standend(void);
188static void visual_bell(void);
189static void cursor_visible(BOOL fVisible);
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200190static DWORD write_chars(char_u *pchBuf, DWORD cbToWrite);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000191static void create_conin(void);
192static int s_cursor_visible = TRUE;
193static int did_create_conin = FALSE;
194#else
195static int s_dont_use_vimrun = TRUE;
196static int need_vimrun_warning = FALSE;
197static char *vimrun_path = "vimrun ";
198#endif
199
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200200static int win32_getattrs(char_u *name);
201static int win32_setattrs(char_u *name, int attrs);
202static int win32_set_archive(char_u *name);
203
Bram Moolenaar071d4272004-06-13 20:20:40 +0000204#ifndef FEAT_GUI_W32
205static int suppress_winsize = 1; /* don't fiddle with console */
206#endif
207
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200208static char_u *exe_path = NULL;
209
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100210static BOOL win8_or_later = FALSE;
211
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100212#ifndef FEAT_GUI_W32
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100213/*
214 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100215 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100216 */
217 static BOOL
218read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100219 HANDLE hInput,
220 INPUT_RECORD *lpBuffer,
221 DWORD nLength,
222 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100223{
224 enum
225 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100226 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100227 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100228 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100229 static DWORD s_dwIndex = 0;
230 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100231 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100232 int head;
233 int tail;
234 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100235
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200236 if (nLength == -2)
237 return (s_dwMax > 0) ? TRUE : FALSE;
238
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100239 if (!win8_or_later)
240 {
241 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200242 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
243 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100244 }
245
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100246 if (s_dwMax == 0)
247 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100248 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200249 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
250 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100251 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100252 s_dwIndex = 0;
253 s_dwMax = dwEvents;
254 if (dwEvents == 0)
255 {
256 *lpEvents = 0;
257 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100258 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100259
260 if (s_dwMax > 1)
261 {
262 head = 0;
263 tail = s_dwMax - 1;
264 while (head != tail)
265 {
266 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
267 && s_irCache[head + 1].EventType
268 == WINDOW_BUFFER_SIZE_EVENT)
269 {
270 /* Remove duplicate event to avoid flicker. */
271 for (i = head; i < tail; ++i)
272 s_irCache[i] = s_irCache[i + 1];
273 --tail;
274 continue;
275 }
276 head++;
277 }
278 s_dwMax = tail + 1;
279 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100280 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100281
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100282 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200283 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100284 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100285 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100286 return TRUE;
287}
288
289/*
290 * Version of PeekConsoleInput() that works with IME.
291 */
292 static BOOL
293peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100294 HANDLE hInput,
295 INPUT_RECORD *lpBuffer,
296 DWORD nLength,
297 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100298{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100299 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100300}
301
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100302# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200303 static DWORD
304msg_wait_for_multiple_objects(
305 DWORD nCount,
306 LPHANDLE pHandles,
307 BOOL fWaitAll,
308 DWORD dwMilliseconds,
309 DWORD dwWakeMask)
310{
311 if (read_console_input(NULL, NULL, -2, NULL))
312 return WAIT_OBJECT_0;
313 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
314 dwMilliseconds, dwWakeMask);
315}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100316# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200317
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100318# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200319 static DWORD
320wait_for_single_object(
321 HANDLE hHandle,
322 DWORD dwMilliseconds)
323{
324 if (read_console_input(NULL, NULL, -2, NULL))
325 return WAIT_OBJECT_0;
326 return WaitForSingleObject(hHandle, dwMilliseconds);
327}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100328# endif
329#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200330
Bram Moolenaar071d4272004-06-13 20:20:40 +0000331 static void
332get_exe_name(void)
333{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100334 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
335 * as the maximum length that works (plus a NUL byte). */
336#define MAX_ENV_PATH_LEN 8192
337 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200338 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000339
340 if (exe_name == NULL)
341 {
342 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100343 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000344 if (*temp != NUL)
345 exe_name = FullName_save((char_u *)temp, FALSE);
346 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000347
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200348 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000349 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200350 exe_path = vim_strnsave(exe_name,
351 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200352 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000353 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200354 /* Append our starting directory to $PATH, so that when doing
355 * "!xxd" it's found in our starting directory. Needed because
356 * SearchPath() also looks there. */
357 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100358 if (p == NULL
359 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200360 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100361 if (p == NULL || *p == NUL)
362 temp[0] = NUL;
363 else
364 {
365 STRCPY(temp, p);
366 STRCAT(temp, ";");
367 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200368 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100369 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200370 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000371 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000372 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000373}
374
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200375/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100376 * Unescape characters in "p" that appear in "escaped".
377 */
378 static void
379unescape_shellxquote(char_u *p, char_u *escaped)
380{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100381 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100382 int n;
383
384 while (*p != NUL)
385 {
386 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
387 mch_memmove(p, p + 1, l--);
388#ifdef FEAT_MBYTE
389 n = (*mb_ptr2len)(p);
390#else
391 n = 1;
392#endif
393 p += n;
394 l -= n;
395 }
396}
397
398/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200399 * Load library "name".
400 */
401 HINSTANCE
402vimLoadLib(char *name)
403{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200404 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200405
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200406 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
407 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200408 if (exe_path == NULL)
409 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200410 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200411 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200412 WCHAR old_dirw[MAXPATHL];
413
414 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
415 {
416 /* Change directory to where the executable is, both to make
417 * sure we find a .dll there and to avoid looking for a .dll
418 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100419 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200420 dll = LoadLibrary(name);
421 SetCurrentDirectoryW(old_dirw);
422 return dll;
423 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200424 }
425 return dll;
426}
427
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100428#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
429/*
430 * Get related information about 'funcname' which is imported by 'hInst'.
431 * If 'info' is 0, return the function address.
432 * If 'info' is 1, return the module name which the function is imported from.
433 */
434 static void *
435get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
436{
437 PBYTE pImage = (PBYTE)hInst;
438 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
439 PIMAGE_NT_HEADERS pPE;
440 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
441 PIMAGE_THUNK_DATA pIAT; /* Import Address Table */
442 PIMAGE_THUNK_DATA pINT; /* Import Name Table */
443 PIMAGE_IMPORT_BY_NAME pImpName;
444
445 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
446 return NULL;
447 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
448 if (pPE->Signature != IMAGE_NT_SIGNATURE)
449 return NULL;
450 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
451 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
452 .VirtualAddress);
453 for (; pImpDesc->FirstThunk; ++pImpDesc)
454 {
455 if (!pImpDesc->OriginalFirstThunk)
456 continue;
457 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
458 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
459 for (; pIAT->u1.Function; ++pIAT, ++pINT)
460 {
461 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
462 continue;
463 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
464 + (UINT_PTR)(pINT->u1.AddressOfData));
465 if (strcmp((char *)pImpName->Name, funcname) == 0)
466 {
467 switch (info)
468 {
469 case 0:
470 return (void *)pIAT->u1.Function;
471 case 1:
472 return (void *)(pImage + pImpDesc->Name);
473 default:
474 return NULL;
475 }
476 }
477 }
478 }
479 return NULL;
480}
481
482/*
483 * Get the module handle which 'funcname' in 'hInst' is imported from.
484 */
485 HINSTANCE
486find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
487{
488 char *modulename;
489
490 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
491 if (modulename != NULL)
492 return GetModuleHandleA(modulename);
493 return NULL;
494}
495
496/*
497 * Get the address of 'funcname' which is imported by 'hInst' DLL.
498 */
499 void *
500get_dll_import_func(HINSTANCE hInst, const char *funcname)
501{
502 return get_imported_func_info(hInst, funcname, 0);
503}
504#endif
505
Bram Moolenaar071d4272004-06-13 20:20:40 +0000506#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
507# ifndef GETTEXT_DLL
508# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100509# define GETTEXT_DLL_ALT "libintl-8.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000510# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200511/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000512static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200513static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000514static char *null_libintl_textdomain(const char *);
515static char *null_libintl_bindtextdomain(const char *, const char *);
516static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100517static int null_libintl_putenv(const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000518
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200519static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000520char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200521char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
522 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000523char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
524char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000525 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000526char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
527 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100528int (*dyn_libintl_putenv)(const char *) = null_libintl_putenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000529
530 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100531dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000532{
533 int i;
534 static struct
535 {
536 char *name;
537 FARPROC *ptr;
538 } libintl_entry[] =
539 {
540 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200541 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000542 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
543 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
544 {NULL, NULL}
545 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100546 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000547
548 /* No need to initialize twice. */
549 if (hLibintlDLL)
550 return 1;
551 /* Load gettext library (libintl.dll) */
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100552 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100553#ifdef GETTEXT_DLL_ALT
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100554 if (!hLibintlDLL)
555 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100556#endif
557 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000558 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200559 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000560 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200561 verbose_enter();
562 EMSG2(_(e_loadlib), GETTEXT_DLL);
563 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000564 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200565 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000566 }
567 for (i = 0; libintl_entry[i].name != NULL
568 && libintl_entry[i].ptr != NULL; ++i)
569 {
570 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
571 libintl_entry[i].name)) == NULL)
572 {
573 dyn_libintl_end();
574 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000575 {
576 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000577 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000578 verbose_leave();
579 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000580 return 0;
581 }
582 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000583
584 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000585 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000586 "bind_textdomain_codeset");
587 if (dyn_libintl_bind_textdomain_codeset == NULL)
588 dyn_libintl_bind_textdomain_codeset =
589 null_libintl_bind_textdomain_codeset;
590
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100591 /* _putenv() function for the libintl.dll is optional. */
592 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
593 if (hmsvcrt != NULL)
594 dyn_libintl_putenv = (void *)GetProcAddress(hmsvcrt, "_putenv");
595 if (dyn_libintl_putenv == NULL || dyn_libintl_putenv == putenv)
596 dyn_libintl_putenv = null_libintl_putenv;
597
Bram Moolenaar071d4272004-06-13 20:20:40 +0000598 return 1;
599}
600
601 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100602dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000603{
604 if (hLibintlDLL)
605 FreeLibrary(hLibintlDLL);
606 hLibintlDLL = NULL;
607 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200608 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000609 dyn_libintl_textdomain = null_libintl_textdomain;
610 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000611 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100612 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000613}
614
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000615/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000616 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000617null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000618{
619 return (char*)msgid;
620}
621
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000622/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000623 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200624null_libintl_ngettext(
625 const char *msgid,
626 const char *msgid_plural,
627 unsigned long n)
628{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200629 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200630}
631
632/*ARGSUSED*/
633 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000634null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000635{
636 return NULL;
637}
638
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000639/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000640 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000641null_libintl_bind_textdomain_codeset(const char *domainname,
642 const char *codeset)
643{
644 return NULL;
645}
646
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000647/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000648 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000649null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000650{
651 return NULL;
652}
653
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100654/*ARGSUSED*/
655 int
656null_libintl_putenv(const char *envstring)
657{
658 return 0;
659}
660
Bram Moolenaar071d4272004-06-13 20:20:40 +0000661#endif /* DYNAMIC_GETTEXT */
662
663/* This symbol is not defined in older versions of the SDK or Visual C++ */
664
665#ifndef VER_PLATFORM_WIN32_WINDOWS
666# define VER_PLATFORM_WIN32_WINDOWS 1
667#endif
668
669DWORD g_PlatformId;
670
671#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100672# ifndef PROTO
673# include <aclapi.h>
674# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200675# ifndef PROTECTED_DACL_SECURITY_INFORMATION
676# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
677# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000678#endif
679
Bram Moolenaar27515922013-06-29 15:36:26 +0200680#ifdef HAVE_ACL
681/*
682 * Enables or disables the specified privilege.
683 */
684 static BOOL
685win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
686{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100687 BOOL bResult;
688 LUID luid;
689 HANDLE hToken;
690 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200691
692 if (!OpenProcessToken(GetCurrentProcess(),
693 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
694 return FALSE;
695
696 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
697 {
698 CloseHandle(hToken);
699 return FALSE;
700 }
701
Bram Moolenaar45500912014-07-09 20:51:07 +0200702 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200703 tokenPrivileges.Privileges[0].Luid = luid;
704 tokenPrivileges.Privileges[0].Attributes = bEnable ?
705 SE_PRIVILEGE_ENABLED : 0;
706
707 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
708 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
709
710 CloseHandle(hToken);
711
712 return bResult && GetLastError() == ERROR_SUCCESS;
713}
714#endif
715
Bram Moolenaar071d4272004-06-13 20:20:40 +0000716/*
717 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
718 * VER_PLATFORM_WIN32_WINDOWS (Win95).
719 */
720 void
721PlatformId(void)
722{
723 static int done = FALSE;
724
725 if (!done)
726 {
727 OSVERSIONINFO ovi;
728
729 ovi.dwOSVersionInfoSize = sizeof(ovi);
730 GetVersionEx(&ovi);
731
732 g_PlatformId = ovi.dwPlatformId;
733
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100734 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
735 || ovi.dwMajorVersion > 6)
736 win8_or_later = TRUE;
737
Bram Moolenaar071d4272004-06-13 20:20:40 +0000738#ifdef HAVE_ACL
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200739 /* Enable privilege for getting or setting SACLs. */
740 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000741#endif
742 done = TRUE;
743 }
744}
745
Bram Moolenaar071d4272004-06-13 20:20:40 +0000746#ifndef FEAT_GUI_W32
747
748#define SHIFT (SHIFT_PRESSED)
749#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
750#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
751#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
752
753
754/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
755 * We map function keys to their ANSI terminal equivalents, as produced
756 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
757 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
758 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
759 * combinations of function/arrow/etc keys.
760 */
761
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000762static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000763{
764 WORD wVirtKey;
765 BOOL fAnsiKey;
766 int chAlone;
767 int chShift;
768 int chCtrl;
769 int chAlt;
770} VirtKeyMap[] =
771{
772
773/* Key ANSI alone shift ctrl alt */
774 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
775
776 { VK_F1, TRUE, ';', 'T', '^', 'h', },
777 { VK_F2, TRUE, '<', 'U', '_', 'i', },
778 { VK_F3, TRUE, '=', 'V', '`', 'j', },
779 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
780 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
781 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
782 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
783 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
784 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
785 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
786 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
787 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
788
789 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
790 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
791 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
792 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
793 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
794 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
795 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
796 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
797 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
798 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
799
800 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
801
802#if 0
803 /* Most people don't have F13-F20, but what the hell... */
804 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
805 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
806 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
807 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
808 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
809 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
810 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
811 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
812#endif
813 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
814 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
815 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
816 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
817
818 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
819 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
820 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
821 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
822 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
823 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
824 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
825 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
826 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
827 /* Sorry, out of number space! <negri>*/
828 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
829
830};
831
832
833#ifdef _MSC_VER
834// The ToAscii bug destroys several registers. Need to turn off optimization
835// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000836# pragma warning(push)
837# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000838# pragma optimize("", off)
839#endif
840
841#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200842# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000843#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200844# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000845#endif
846
847/* The return code indicates key code size. */
848 static int
849#ifdef __BORLANDC__
850 __stdcall
851#endif
852win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000853 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000854{
855 UINT uMods = pker->dwControlKeyState;
856 static int s_iIsDead = 0;
857 static WORD awAnsiCode[2];
858 static BYTE abKeystate[256];
859
860
861 if (s_iIsDead == 2)
862 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200863 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000864 s_iIsDead = 0;
865 return 1;
866 }
867
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200868 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000869 return 1;
870
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200871 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000872
Bram Moolenaar071d4272004-06-13 20:20:40 +0000873 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200874 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000875
876 if (uMods & SHIFT_PRESSED)
877 abKeystate[VK_SHIFT] = 0x80;
878 if (uMods & CAPSLOCK_ON)
879 abKeystate[VK_CAPITAL] = 1;
880
881 if ((uMods & ALT_GR) == ALT_GR)
882 {
883 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
884 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
885 }
886
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200887 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
888 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000889
890 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200891 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000892
893 return s_iIsDead;
894}
895
896#ifdef _MSC_VER
897/* MUST switch optimization on again here, otherwise a call to
898 * decode_key_event() may crash (e.g. when hitting caps-lock) */
899# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000900# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000901
902# if (_MSC_VER < 1100)
903/* MUST turn off global optimisation for this next function, or
904 * pressing ctrl-minus in insert mode crashes Vim when built with
905 * VC4.1. -- negri. */
906# pragma optimize("g", off)
907# endif
908#endif
909
910static BOOL g_fJustGotFocus = FALSE;
911
912/*
913 * Decode a KEY_EVENT into one or two keystrokes
914 */
915 static BOOL
916decode_key_event(
917 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200918 WCHAR *pch,
919 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000920 int *pmodifiers,
921 BOOL fDoPost)
922{
923 int i;
924 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
925
926 *pch = *pch2 = NUL;
927 g_fJustGotFocus = FALSE;
928
929 /* ignore key up events */
930 if (!pker->bKeyDown)
931 return FALSE;
932
933 /* ignore some keystrokes */
934 switch (pker->wVirtualKeyCode)
935 {
936 /* modifiers */
937 case VK_SHIFT:
938 case VK_CONTROL:
939 case VK_MENU: /* Alt key */
940 return FALSE;
941
942 default:
943 break;
944 }
945
946 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200947 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000948 {
949 /* Ctrl-6 is Ctrl-^ */
950 if (pker->wVirtualKeyCode == '6')
951 {
952 *pch = Ctrl_HAT;
953 return TRUE;
954 }
955 /* Ctrl-2 is Ctrl-@ */
956 else if (pker->wVirtualKeyCode == '2')
957 {
958 *pch = NUL;
959 return TRUE;
960 }
961 /* Ctrl-- is Ctrl-_ */
962 else if (pker->wVirtualKeyCode == 0xBD)
963 {
964 *pch = Ctrl__;
965 return TRUE;
966 }
967 }
968
969 /* Shift-TAB */
970 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
971 {
972 *pch = K_NUL;
973 *pch2 = '\017';
974 return TRUE;
975 }
976
977 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
978 {
979 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
980 {
981 if (nModifs == 0)
982 *pch = VirtKeyMap[i].chAlone;
983 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
984 *pch = VirtKeyMap[i].chShift;
985 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
986 *pch = VirtKeyMap[i].chCtrl;
987 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
988 *pch = VirtKeyMap[i].chAlt;
989
990 if (*pch != 0)
991 {
992 if (VirtKeyMap[i].fAnsiKey)
993 {
994 *pch2 = *pch;
995 *pch = K_NUL;
996 }
997
998 return TRUE;
999 }
1000 }
1001 }
1002
1003 i = win32_kbd_patch_key(pker);
1004
1005 if (i < 0)
1006 *pch = NUL;
1007 else
1008 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001009 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001010
1011 if (pmodifiers != NULL)
1012 {
1013 /* Pass on the ALT key as a modifier, but only when not combined
1014 * with CTRL (which is ALTGR). */
1015 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1016 *pmodifiers |= MOD_MASK_ALT;
1017
1018 /* Pass on SHIFT only for special keys, because we don't know when
1019 * it's already included with the character. */
1020 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1021 *pmodifiers |= MOD_MASK_SHIFT;
1022
1023 /* Pass on CTRL only for non-special keys, because we don't know
1024 * when it's already included with the character. And not when
1025 * combined with ALT (which is ALTGR). */
1026 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1027 && *pch >= 0x20 && *pch < 0x80)
1028 *pmodifiers |= MOD_MASK_CTRL;
1029 }
1030 }
1031
1032 return (*pch != NUL);
1033}
1034
1035#ifdef _MSC_VER
1036# pragma optimize("", on)
1037#endif
1038
1039#endif /* FEAT_GUI_W32 */
1040
1041
1042#ifdef FEAT_MOUSE
1043
1044/*
1045 * For the GUI the mouse handling is in gui_w32.c.
1046 */
1047# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001048/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001049 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001050mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001051{
1052}
1053# else
1054static int g_fMouseAvail = FALSE; /* mouse present */
1055static int g_fMouseActive = FALSE; /* mouse enabled */
1056static int g_nMouseClick = -1; /* mouse status */
1057static int g_xMouse; /* mouse x coordinate */
1058static int g_yMouse; /* mouse y coordinate */
1059
1060/*
1061 * Enable or disable mouse input
1062 */
1063 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001064mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001065{
1066 DWORD cmodein;
1067
1068 if (!g_fMouseAvail)
1069 return;
1070
1071 g_fMouseActive = on;
1072 GetConsoleMode(g_hConIn, &cmodein);
1073
1074 if (g_fMouseActive)
1075 cmodein |= ENABLE_MOUSE_INPUT;
1076 else
1077 cmodein &= ~ENABLE_MOUSE_INPUT;
1078
1079 SetConsoleMode(g_hConIn, cmodein);
1080}
1081
Bram Moolenaar071d4272004-06-13 20:20:40 +00001082/*
1083 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1084 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1085 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1086 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1087 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1088 * and we return the mouse position in g_xMouse and g_yMouse.
1089 *
1090 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1091 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1092 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1093 *
1094 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1095 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1096 *
1097 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1098 * moves, even if it stays within the same character cell. We ignore
1099 * all MOUSE_MOVED messages if the position hasn't really changed, and
1100 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1101 * we're only interested in MOUSE_DRAG).
1102 *
1103 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1104 * 2-button mouses by pressing the left & right buttons simultaneously.
1105 * In practice, it's almost impossible to click both at the same time,
1106 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1107 * in such cases, if the user is clicking quickly.
1108 */
1109 static BOOL
1110decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001111 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001112{
1113 static int s_nOldButton = -1;
1114 static int s_nOldMouseClick = -1;
1115 static int s_xOldMouse = -1;
1116 static int s_yOldMouse = -1;
1117 static linenr_T s_old_topline = 0;
1118#ifdef FEAT_DIFF
1119 static int s_old_topfill = 0;
1120#endif
1121 static int s_cClicks = 1;
1122 static BOOL s_fReleased = TRUE;
1123 static DWORD s_dwLastClickTime = 0;
1124 static BOOL s_fNextIsMiddle = FALSE;
1125
1126 static DWORD cButtons = 0; /* number of buttons supported */
1127
1128 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1129 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1130 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1131 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1132
1133 int nButton;
1134
1135 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1136 cButtons = 2;
1137
1138 if (!g_fMouseAvail || !g_fMouseActive)
1139 {
1140 g_nMouseClick = -1;
1141 return FALSE;
1142 }
1143
1144 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1145 if (g_fJustGotFocus)
1146 {
1147 g_fJustGotFocus = FALSE;
1148 return FALSE;
1149 }
1150
1151 /* unprocessed mouse click? */
1152 if (g_nMouseClick != -1)
1153 return TRUE;
1154
1155 nButton = -1;
1156 g_xMouse = pmer->dwMousePosition.X;
1157 g_yMouse = pmer->dwMousePosition.Y;
1158
1159 if (pmer->dwEventFlags == MOUSE_MOVED)
1160 {
1161 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1162 * events even when the mouse moves only within a char cell.) */
1163 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1164 return FALSE;
1165 }
1166
1167 /* If no buttons are pressed... */
1168 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1169 {
1170 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1171 if (s_fReleased)
1172 return FALSE;
1173
1174 nButton = MOUSE_RELEASE;
1175 s_fReleased = TRUE;
1176 }
1177 else /* one or more buttons pressed */
1178 {
1179 /* on a 2-button mouse, hold down left and right buttons
1180 * simultaneously to get MIDDLE. */
1181
1182 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1183 {
1184 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1185
1186 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001187 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001188 if (dwLR == LEFT || dwLR == RIGHT)
1189 {
1190 for (;;)
1191 {
1192 /* wait a short time for next input event */
1193 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1194 != WAIT_OBJECT_0)
1195 break;
1196 else
1197 {
1198 DWORD cRecords = 0;
1199 INPUT_RECORD ir;
1200 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1201
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001202 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001203
1204 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1205 || !(pmer2->dwButtonState & LEFT_RIGHT))
1206 break;
1207 else
1208 {
1209 if (pmer2->dwEventFlags != MOUSE_MOVED)
1210 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001211 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001212
1213 return decode_mouse_event(pmer2);
1214 }
1215 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1216 s_yOldMouse == pmer2->dwMousePosition.Y)
1217 {
1218 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001219 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001220
1221 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001222 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001223
1224 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1225 break;
1226 }
1227 else
1228 break;
1229 }
1230 }
1231 }
1232 }
1233 }
1234
1235 if (s_fNextIsMiddle)
1236 {
1237 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1238 ? MOUSE_DRAG : MOUSE_MIDDLE;
1239 s_fNextIsMiddle = FALSE;
1240 }
1241 else if (cButtons == 2 &&
1242 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1243 {
1244 nButton = MOUSE_MIDDLE;
1245
1246 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1247 {
1248 s_fNextIsMiddle = TRUE;
1249 nButton = MOUSE_RELEASE;
1250 }
1251 }
1252 else if ((pmer->dwButtonState & LEFT) == LEFT)
1253 nButton = MOUSE_LEFT;
1254 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1255 nButton = MOUSE_MIDDLE;
1256 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1257 nButton = MOUSE_RIGHT;
1258
1259 if (! s_fReleased && ! s_fNextIsMiddle
1260 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1261 return FALSE;
1262
1263 s_fReleased = s_fNextIsMiddle;
1264 }
1265
1266 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1267 {
1268 /* button pressed or released, without mouse moving */
1269 if (nButton != -1 && nButton != MOUSE_RELEASE)
1270 {
1271 DWORD dwCurrentTime = GetTickCount();
1272
1273 if (s_xOldMouse != g_xMouse
1274 || s_yOldMouse != g_yMouse
1275 || s_nOldButton != nButton
1276 || s_old_topline != curwin->w_topline
1277#ifdef FEAT_DIFF
1278 || s_old_topfill != curwin->w_topfill
1279#endif
1280 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1281 {
1282 s_cClicks = 1;
1283 }
1284 else if (++s_cClicks > 4)
1285 {
1286 s_cClicks = 1;
1287 }
1288
1289 s_dwLastClickTime = dwCurrentTime;
1290 }
1291 }
1292 else if (pmer->dwEventFlags == MOUSE_MOVED)
1293 {
1294 if (nButton != -1 && nButton != MOUSE_RELEASE)
1295 nButton = MOUSE_DRAG;
1296
1297 s_cClicks = 1;
1298 }
1299
1300 if (nButton == -1)
1301 return FALSE;
1302
1303 if (nButton != MOUSE_RELEASE)
1304 s_nOldButton = nButton;
1305
1306 g_nMouseClick = nButton;
1307
1308 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1309 g_nMouseClick |= MOUSE_SHIFT;
1310 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1311 g_nMouseClick |= MOUSE_CTRL;
1312 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1313 g_nMouseClick |= MOUSE_ALT;
1314
1315 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1316 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1317
1318 /* only pass on interesting (i.e., different) mouse events */
1319 if (s_xOldMouse == g_xMouse
1320 && s_yOldMouse == g_yMouse
1321 && s_nOldMouseClick == g_nMouseClick)
1322 {
1323 g_nMouseClick = -1;
1324 return FALSE;
1325 }
1326
1327 s_xOldMouse = g_xMouse;
1328 s_yOldMouse = g_yMouse;
1329 s_old_topline = curwin->w_topline;
1330#ifdef FEAT_DIFF
1331 s_old_topfill = curwin->w_topfill;
1332#endif
1333 s_nOldMouseClick = g_nMouseClick;
1334
1335 return TRUE;
1336}
1337
1338# endif /* FEAT_GUI_W32 */
1339#endif /* FEAT_MOUSE */
1340
1341
1342#ifdef MCH_CURSOR_SHAPE
1343/*
1344 * Set the shape of the cursor.
1345 * 'thickness' can be from 1 (thin) to 99 (block)
1346 */
1347 static void
1348mch_set_cursor_shape(int thickness)
1349{
1350 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1351 ConsoleCursorInfo.dwSize = thickness;
1352 ConsoleCursorInfo.bVisible = s_cursor_visible;
1353
1354 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1355 if (s_cursor_visible)
1356 SetConsoleCursorPosition(g_hConOut, g_coord);
1357}
1358
1359 void
1360mch_update_cursor(void)
1361{
1362 int idx;
1363 int thickness;
1364
1365 /*
1366 * How the cursor is drawn depends on the current mode.
1367 */
1368 idx = get_shape_idx(FALSE);
1369
1370 if (shape_table[idx].shape == SHAPE_BLOCK)
1371 thickness = 99; /* 100 doesn't work on W95 */
1372 else
1373 thickness = shape_table[idx].percentage;
1374 mch_set_cursor_shape(thickness);
1375}
1376#endif
1377
1378#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1379/*
1380 * Handle FOCUS_EVENT.
1381 */
1382 static void
1383handle_focus_event(INPUT_RECORD ir)
1384{
1385 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1386 ui_focus_change((int)g_fJustGotFocus);
1387}
1388
1389/*
1390 * Wait until console input from keyboard or mouse is available,
1391 * or the time is up.
1392 * Return TRUE if something is available FALSE if not.
1393 */
1394 static int
1395WaitForChar(long msec)
1396{
1397 DWORD dwNow = 0, dwEndTime = 0;
1398 INPUT_RECORD ir;
1399 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001400 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001401#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001402 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001403#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001404
1405 if (msec > 0)
1406 /* Wait until the specified time has elapsed. */
1407 dwEndTime = GetTickCount() + msec;
1408 else if (msec < 0)
1409 /* Wait forever. */
1410 dwEndTime = INFINITE;
1411
1412 /* We need to loop until the end of the time period, because
1413 * we might get multiple unusable mouse events in that time.
1414 */
1415 for (;;)
1416 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001417#ifdef MESSAGE_QUEUE
1418 parse_queued_messages();
1419#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001420#ifdef FEAT_MZSCHEME
1421 mzvim_check_threads();
1422#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001423#ifdef FEAT_CLIENTSERVER
1424 serverProcessPendingMessages();
1425#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001426
Bram Moolenaar071d4272004-06-13 20:20:40 +00001427 if (0
1428#ifdef FEAT_MOUSE
1429 || g_nMouseClick != -1
1430#endif
1431#ifdef FEAT_CLIENTSERVER
1432 || input_available()
1433#endif
1434 )
1435 return TRUE;
1436
1437 if (msec > 0)
1438 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001439 /* If the specified wait time has passed, return. Beware that
1440 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001441 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001442 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001443 break;
1444 }
1445 if (msec != 0)
1446 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001447 DWORD dwWaitTime = dwEndTime - dwNow;
1448
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001449#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001450 /* Check channel while waiting for input. */
Bram Moolenaar9186a272016-02-23 19:34:01 +01001451 if (dwWaitTime > 100)
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001452 {
Bram Moolenaar9186a272016-02-23 19:34:01 +01001453 dwWaitTime = 100;
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001454 /* If there is readahead then parse_queued_messages() timed out
1455 * and we should call it again soon. */
1456 if (channel_any_readahead())
1457 dwWaitTime = 10;
1458 }
Bram Moolenaar9186a272016-02-23 19:34:01 +01001459#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001460#ifdef FEAT_MZSCHEME
1461 if (mzthreads_allowed() && p_mzq > 0
1462 && (msec < 0 || (long)dwWaitTime > p_mzq))
1463 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1464#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001465#ifdef FEAT_TIMERS
1466 {
1467 long due_time;
1468
1469 /* When waiting very briefly don't trigger timers. */
1470 if (dwWaitTime > 10)
1471 {
1472 /* Trigger timers and then get the time in msec until the
1473 * next one is due. Wait up to that time. */
1474 due_time = check_due_timer();
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001475 if (typebuf.tb_change_cnt != tb_change_cnt)
1476 {
1477 /* timer may have used feedkeys() */
1478 return FALSE;
1479 }
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001480 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1481 dwWaitTime = due_time;
1482 }
1483 }
1484#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001485#ifdef FEAT_CLIENTSERVER
1486 /* Wait for either an event on the console input or a message in
1487 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001488 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001489 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001490#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001491 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001492#endif
1493 continue;
1494 }
1495
1496 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001497 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001498
1499#ifdef FEAT_MBYTE_IME
1500 if (State & CMDLINE && msg_row == Rows - 1)
1501 {
1502 CONSOLE_SCREEN_BUFFER_INFO csbi;
1503
1504 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1505 {
1506 if (csbi.dwCursorPosition.Y != msg_row)
1507 {
1508 /* The screen is now messed up, must redraw the
1509 * command line and later all the windows. */
1510 redraw_all_later(CLEAR);
1511 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1512 redrawcmd();
1513 }
1514 }
1515 }
1516#endif
1517
1518 if (cRecords > 0)
1519 {
1520 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1521 {
1522#ifdef FEAT_MBYTE_IME
1523 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1524 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001525 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001526 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1527 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001528 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001529 continue;
1530 }
1531#endif
1532 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1533 NULL, FALSE))
1534 return TRUE;
1535 }
1536
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001537 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001538
1539 if (ir.EventType == FOCUS_EVENT)
1540 handle_focus_event(ir);
1541 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1542 shell_resized();
1543#ifdef FEAT_MOUSE
1544 else if (ir.EventType == MOUSE_EVENT
1545 && decode_mouse_event(&ir.Event.MouseEvent))
1546 return TRUE;
1547#endif
1548 }
1549 else if (msec == 0)
1550 break;
1551 }
1552
1553#ifdef FEAT_CLIENTSERVER
1554 /* Something might have been received while we were waiting. */
1555 if (input_available())
1556 return TRUE;
1557#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001558
Bram Moolenaar071d4272004-06-13 20:20:40 +00001559 return FALSE;
1560}
1561
1562#ifndef FEAT_GUI_MSWIN
1563/*
1564 * return non-zero if a character is available
1565 */
1566 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001567mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001568{
1569 return WaitForChar(0L);
1570}
1571#endif
1572
1573/*
1574 * Create the console input. Used when reading stdin doesn't work.
1575 */
1576 static void
1577create_conin(void)
1578{
1579 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1580 FILE_SHARE_READ|FILE_SHARE_WRITE,
1581 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001582 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001583 did_create_conin = TRUE;
1584}
1585
1586/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001587 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001588 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001589 static WCHAR
1590tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001591{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001592 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001593
1594 for (;;)
1595 {
1596 INPUT_RECORD ir;
1597 DWORD cRecords = 0;
1598
1599#ifdef FEAT_CLIENTSERVER
1600 (void)WaitForChar(-1L);
1601 if (input_available())
1602 return 0;
1603# ifdef FEAT_MOUSE
1604 if (g_nMouseClick != -1)
1605 return 0;
1606# endif
1607#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001608 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001609 {
1610 if (did_create_conin)
1611 read_error_exit();
1612 create_conin();
1613 continue;
1614 }
1615
1616 if (ir.EventType == KEY_EVENT)
1617 {
1618 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1619 pmodifiers, TRUE))
1620 return ch;
1621 }
1622 else if (ir.EventType == FOCUS_EVENT)
1623 handle_focus_event(ir);
1624 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1625 shell_resized();
1626#ifdef FEAT_MOUSE
1627 else if (ir.EventType == MOUSE_EVENT)
1628 {
1629 if (decode_mouse_event(&ir.Event.MouseEvent))
1630 return 0;
1631 }
1632#endif
1633 }
1634}
1635#endif /* !FEAT_GUI_W32 */
1636
1637
1638/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001639 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001640 * Get one or more characters from the keyboard or the mouse.
1641 * If time == 0, do not wait for characters.
1642 * If time == n, wait a short time for characters.
1643 * If time == -1, wait forever for characters.
1644 * Returns the number of characters read into buf.
1645 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001646/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001647 int
1648mch_inchar(
1649 char_u *buf,
1650 int maxlen,
1651 long time,
1652 int tb_change_cnt)
1653{
1654#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1655
1656 int len;
1657 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001658#define TYPEAHEADLEN 20
1659 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1660 static int typeaheadlen = 0;
1661
1662 /* First use any typeahead that was kept because "buf" was too small. */
1663 if (typeaheadlen > 0)
1664 goto theend;
1665
Bram Moolenaar071d4272004-06-13 20:20:40 +00001666 if (time >= 0)
1667 {
1668 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001669 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001670 }
1671 else /* time == -1, wait forever */
1672 {
1673 mch_set_winsize_now(); /* Allow winsize changes from now on */
1674
Bram Moolenaar3918c952005-03-15 22:34:55 +00001675 /*
1676 * If there is no character available within 2 seconds (default)
1677 * write the autoscript file to disk. Or cause the CursorHold event
1678 * to be triggered.
1679 */
1680 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001681 {
1682#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001683 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001684 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001685 buf[0] = K_SPECIAL;
1686 buf[1] = KS_EXTRA;
1687 buf[2] = (int)KE_CURSORHOLD;
1688 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001689 }
1690#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001691 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001692 }
1693 }
1694
1695 /*
1696 * Try to read as many characters as there are, until the buffer is full.
1697 */
1698
1699 /* we will get at least one key. Get more if they are available. */
1700 g_fCBrkPressed = FALSE;
1701
1702#ifdef MCH_WRITE_DUMP
1703 if (fdDump)
1704 fputc('[', fdDump);
1705#endif
1706
1707 /* Keep looping until there is something in the typeahead buffer and more
1708 * to get and still room in the buffer (up to two bytes for a char and
1709 * three bytes for a modifier). */
1710 while ((typeaheadlen == 0 || WaitForChar(0L))
1711 && typeaheadlen + 5 <= TYPEAHEADLEN)
1712 {
1713 if (typebuf_changed(tb_change_cnt))
1714 {
1715 /* "buf" may be invalid now if a client put something in the
1716 * typeahead buffer and "buf" is in the typeahead buffer. */
1717 typeaheadlen = 0;
1718 break;
1719 }
1720#ifdef FEAT_MOUSE
1721 if (g_nMouseClick != -1)
1722 {
1723# ifdef MCH_WRITE_DUMP
1724 if (fdDump)
1725 fprintf(fdDump, "{%02x @ %d, %d}",
1726 g_nMouseClick, g_xMouse, g_yMouse);
1727# endif
1728 typeahead[typeaheadlen++] = ESC + 128;
1729 typeahead[typeaheadlen++] = 'M';
1730 typeahead[typeaheadlen++] = g_nMouseClick;
1731 typeahead[typeaheadlen++] = g_xMouse + '!';
1732 typeahead[typeaheadlen++] = g_yMouse + '!';
1733 g_nMouseClick = -1;
1734 }
1735 else
1736#endif
1737 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001738 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001739 int modifiers = 0;
1740
1741 c = tgetch(&modifiers, &ch2);
1742
1743 if (typebuf_changed(tb_change_cnt))
1744 {
1745 /* "buf" may be invalid now if a client put something in the
1746 * typeahead buffer and "buf" is in the typeahead buffer. */
1747 typeaheadlen = 0;
1748 break;
1749 }
1750
1751 if (c == Ctrl_C && ctrl_c_interrupts)
1752 {
1753#if defined(FEAT_CLIENTSERVER)
1754 trash_input_buf();
1755#endif
1756 got_int = TRUE;
1757 }
1758
1759#ifdef FEAT_MOUSE
1760 if (g_nMouseClick == -1)
1761#endif
1762 {
1763 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001764 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001765
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001766#ifdef FEAT_MBYTE
1767 if (ch2 == NUL)
1768 {
1769 int i;
1770 char_u *p;
1771 WCHAR ch[2];
1772
1773 ch[0] = c;
1774 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1775 {
1776 ch[1] = tgetch(&modifiers, &ch2);
1777 n++;
1778 }
1779 p = utf16_to_enc(ch, &n);
1780 if (p != NULL)
1781 {
1782 for (i = 0; i < n; i++)
1783 typeahead[typeaheadlen + i] = p[i];
1784 vim_free(p);
1785 }
1786 }
1787 else
1788#endif
1789 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001790 if (ch2 != NUL)
1791 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001792 typeahead[typeaheadlen + n] = 3;
1793 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
Bram Moolenaar45500912014-07-09 20:51:07 +02001794 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001795 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001796
Bram Moolenaar45500912014-07-09 20:51:07 +02001797 if (conv)
1798 {
1799 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001800
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001801 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001802 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001803 char_u *e = typeahead + TYPEAHEADLEN;
1804
1805 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001806 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001807 if (*p == K_NUL)
1808 {
1809 ++p;
1810 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1811 *p = 3;
1812 ++n;
1813 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001814 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001815 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001816 }
1817 }
1818
Bram Moolenaar071d4272004-06-13 20:20:40 +00001819 /* Use the ALT key to set the 8th bit of the character
1820 * when it's one byte, the 8th bit isn't set yet and not
1821 * using a double-byte encoding (would become a lead
1822 * byte). */
1823 if ((modifiers & MOD_MASK_ALT)
1824 && n == 1
1825 && (typeahead[typeaheadlen] & 0x80) == 0
1826#ifdef FEAT_MBYTE
1827 && !enc_dbcs
1828#endif
1829 )
1830 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001831#ifdef FEAT_MBYTE
1832 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1833 typeahead + typeaheadlen);
1834#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001835 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001836#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001837 modifiers &= ~MOD_MASK_ALT;
1838 }
1839
1840 if (modifiers != 0)
1841 {
1842 /* Prepend modifiers to the character. */
1843 mch_memmove(typeahead + typeaheadlen + 3,
1844 typeahead + typeaheadlen, n);
1845 typeahead[typeaheadlen++] = K_SPECIAL;
1846 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1847 typeahead[typeaheadlen++] = modifiers;
1848 }
1849
1850 typeaheadlen += n;
1851
1852#ifdef MCH_WRITE_DUMP
1853 if (fdDump)
1854 fputc(c, fdDump);
1855#endif
1856 }
1857 }
1858 }
1859
1860#ifdef MCH_WRITE_DUMP
1861 if (fdDump)
1862 {
1863 fputs("]\n", fdDump);
1864 fflush(fdDump);
1865 }
1866#endif
1867
Bram Moolenaar071d4272004-06-13 20:20:40 +00001868theend:
1869 /* Move typeahead to "buf", as much as fits. */
1870 len = 0;
1871 while (len < maxlen && typeaheadlen > 0)
1872 {
1873 buf[len++] = typeahead[0];
1874 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1875 }
1876 return len;
1877
1878#else /* FEAT_GUI_W32 */
1879 return 0;
1880#endif /* FEAT_GUI_W32 */
1881}
1882
Bram Moolenaar82881492012-11-20 16:53:39 +01001883#ifndef PROTO
1884# ifndef __MINGW32__
1885# include <shellapi.h> /* required for FindExecutable() */
1886# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001887#endif
1888
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001889/*
1890 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001891 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001892 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001893 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001894executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001895{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001896 char *dum;
1897 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001898 char *curpath, *newpath;
1899 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001900
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001901#ifdef FEAT_MBYTE
1902 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001903 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001904 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001905 WCHAR fnamew[_MAX_PATH];
1906 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001907 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001908
1909 if (p != NULL)
1910 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001911 wcurpath = _wgetenv(L"PATH");
1912 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1913 * sizeof(WCHAR));
1914 if (wnewpath == NULL)
1915 return FALSE;
1916 wcscpy(wnewpath, L".;");
1917 wcscat(wnewpath, wcurpath);
1918 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1919 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001920 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02001921 if (n == 0)
1922 return FALSE;
1923 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1924 return FALSE;
1925 if (path != NULL)
1926 *path = utf16_to_enc(fnamew, NULL);
1927 return TRUE;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001928 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001929 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001930#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001931
1932 curpath = getenv("PATH");
1933 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1934 if (newpath == NULL)
1935 return FALSE;
1936 STRCPY(newpath, ".;");
1937 STRCAT(newpath, curpath);
1938 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
1939 vim_free(newpath);
1940 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001941 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001942 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001943 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001944 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001945 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001946 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001947}
1948
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001949#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001950 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001951/*
1952 * Bad parameter handler.
1953 *
1954 * Certain MS CRT functions will intentionally crash when passed invalid
1955 * parameters to highlight possible security holes. Setting this function as
1956 * the bad parameter handler will prevent the crash.
1957 *
1958 * In debug builds the parameters contain CRT information that might help track
1959 * down the source of a problem, but in non-debug builds the arguments are all
1960 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1961 * worth allowing these to make debugging of issues easier.
1962 */
1963 static void
1964bad_param_handler(const wchar_t *expression,
1965 const wchar_t *function,
1966 const wchar_t *file,
1967 unsigned int line,
1968 uintptr_t pReserved)
1969{
1970}
1971
1972# define SET_INVALID_PARAM_HANDLER \
1973 ((void)_set_invalid_parameter_handler(bad_param_handler))
1974#else
1975# define SET_INVALID_PARAM_HANDLER
1976#endif
1977
Bram Moolenaar071d4272004-06-13 20:20:40 +00001978#ifdef FEAT_GUI_W32
1979
1980/*
1981 * GUI version of mch_init().
1982 */
1983 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001984mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001985{
1986#ifndef __MINGW32__
1987 extern int _fmode;
1988#endif
1989
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001990 /* Silently handle invalid parameters to CRT functions */
1991 SET_INVALID_PARAM_HANDLER;
1992
Bram Moolenaar071d4272004-06-13 20:20:40 +00001993 /* Let critical errors result in a failure, not in a dialog box. Required
1994 * for the timestamp test to work on removed floppies. */
1995 SetErrorMode(SEM_FAILCRITICALERRORS);
1996
1997 _fmode = O_BINARY; /* we do our own CR-LF translation */
1998
1999 /* Specify window size. Is there a place to get the default from? */
2000 Rows = 25;
2001 Columns = 80;
2002
2003 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002004 {
2005 char_u vimrun_location[_MAX_PATH + 4];
2006
2007 /* First try in same directory as gvim.exe */
2008 STRCPY(vimrun_location, exe_name);
2009 STRCPY(gettail(vimrun_location), "vimrun.exe");
2010 if (mch_getperm(vimrun_location) >= 0)
2011 {
2012 if (*skiptowhite(vimrun_location) != NUL)
2013 {
2014 /* Enclose path with white space in double quotes. */
2015 mch_memmove(vimrun_location + 1, vimrun_location,
2016 STRLEN(vimrun_location) + 1);
2017 *vimrun_location = '"';
2018 STRCPY(gettail(vimrun_location), "vimrun\" ");
2019 }
2020 else
2021 STRCPY(gettail(vimrun_location), "vimrun ");
2022
2023 vimrun_path = (char *)vim_strsave(vimrun_location);
2024 s_dont_use_vimrun = FALSE;
2025 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002026 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002027 s_dont_use_vimrun = FALSE;
2028
2029 /* Don't give the warning for a missing vimrun.exe right now, but only
2030 * when vimrun was supposed to be used. Don't bother people that do
2031 * not need vimrun.exe. */
2032 if (s_dont_use_vimrun)
2033 need_vimrun_warning = TRUE;
2034 }
2035
2036 /*
2037 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2038 * Otherwise the default "findstr /n" is used.
2039 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002040 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002041 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2042
2043#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002044 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002045#endif
2046}
2047
2048
2049#else /* FEAT_GUI_W32 */
2050
2051#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2052#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2053
2054/*
2055 * ClearConsoleBuffer()
2056 * Description:
2057 * Clears the entire contents of the console screen buffer, using the
2058 * specified attribute.
2059 * Returns:
2060 * TRUE on success
2061 */
2062 static BOOL
2063ClearConsoleBuffer(WORD wAttribute)
2064{
2065 CONSOLE_SCREEN_BUFFER_INFO csbi;
2066 COORD coord;
2067 DWORD NumCells, dummy;
2068
2069 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2070 return FALSE;
2071
2072 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2073 coord.X = 0;
2074 coord.Y = 0;
2075 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2076 coord, &dummy))
2077 {
2078 return FALSE;
2079 }
2080 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2081 coord, &dummy))
2082 {
2083 return FALSE;
2084 }
2085
2086 return TRUE;
2087}
2088
2089/*
2090 * FitConsoleWindow()
2091 * Description:
2092 * Checks if the console window will fit within given buffer dimensions.
2093 * Also, if requested, will shrink the window to fit.
2094 * Returns:
2095 * TRUE on success
2096 */
2097 static BOOL
2098FitConsoleWindow(
2099 COORD dwBufferSize,
2100 BOOL WantAdjust)
2101{
2102 CONSOLE_SCREEN_BUFFER_INFO csbi;
2103 COORD dwWindowSize;
2104 BOOL NeedAdjust = FALSE;
2105
2106 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2107 {
2108 /*
2109 * A buffer resize will fail if the current console window does
2110 * not lie completely within that buffer. To avoid this, we might
2111 * have to move and possibly shrink the window.
2112 */
2113 if (csbi.srWindow.Right >= dwBufferSize.X)
2114 {
2115 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2116 if (dwWindowSize.X > dwBufferSize.X)
2117 dwWindowSize.X = dwBufferSize.X;
2118 csbi.srWindow.Right = dwBufferSize.X - 1;
2119 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2120 NeedAdjust = TRUE;
2121 }
2122 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2123 {
2124 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2125 if (dwWindowSize.Y > dwBufferSize.Y)
2126 dwWindowSize.Y = dwBufferSize.Y;
2127 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2128 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2129 NeedAdjust = TRUE;
2130 }
2131 if (NeedAdjust && WantAdjust)
2132 {
2133 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2134 return FALSE;
2135 }
2136 return TRUE;
2137 }
2138
2139 return FALSE;
2140}
2141
2142typedef struct ConsoleBufferStruct
2143{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002144 BOOL IsValid;
2145 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002146 PCHAR_INFO Buffer;
2147 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002148} ConsoleBuffer;
2149
2150/*
2151 * SaveConsoleBuffer()
2152 * Description:
2153 * Saves important information about the console buffer, including the
2154 * actual buffer contents. The saved information is suitable for later
2155 * restoration by RestoreConsoleBuffer().
2156 * Returns:
2157 * TRUE if all information was saved; FALSE otherwise
2158 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2159 */
2160 static BOOL
2161SaveConsoleBuffer(
2162 ConsoleBuffer *cb)
2163{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002164 DWORD NumCells;
2165 COORD BufferCoord;
2166 SMALL_RECT ReadRegion;
2167 WORD Y, Y_incr;
2168
Bram Moolenaar071d4272004-06-13 20:20:40 +00002169 if (cb == NULL)
2170 return FALSE;
2171
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002172 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002173 {
2174 cb->IsValid = FALSE;
2175 return FALSE;
2176 }
2177 cb->IsValid = TRUE;
2178
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002179 /*
2180 * Allocate a buffer large enough to hold the entire console screen
2181 * buffer. If this ConsoleBuffer structure has already been initialized
2182 * with a buffer of the correct size, then just use that one.
2183 */
2184 if (!cb->IsValid || cb->Buffer == NULL ||
2185 cb->BufferSize.X != cb->Info.dwSize.X ||
2186 cb->BufferSize.Y != cb->Info.dwSize.Y)
2187 {
2188 cb->BufferSize.X = cb->Info.dwSize.X;
2189 cb->BufferSize.Y = cb->Info.dwSize.Y;
2190 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2191 vim_free(cb->Buffer);
2192 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2193 if (cb->Buffer == NULL)
2194 return FALSE;
2195 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002196
2197 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002198 * We will now copy the console screen buffer into our buffer.
2199 * ReadConsoleOutput() seems to be limited as far as how much you
2200 * can read at a time. Empirically, this number seems to be about
2201 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2202 * in chunks until it is all copied. The chunks will all have the
2203 * same horizontal characteristics, so initialize them now. The
2204 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002205 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002206 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002207 ReadRegion.Left = 0;
2208 ReadRegion.Right = cb->Info.dwSize.X - 1;
2209 Y_incr = 12000 / cb->Info.dwSize.X;
2210 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002211 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002212 /*
2213 * Read into position (0, Y) in our buffer.
2214 */
2215 BufferCoord.Y = Y;
2216 /*
2217 * Read the region whose top left corner is (0, Y) and whose bottom
2218 * right corner is (width - 1, Y + Y_incr - 1). This should define
2219 * a region of size width by Y_incr. Don't worry if this region is
2220 * too large for the remaining buffer; it will be cropped.
2221 */
2222 ReadRegion.Top = Y;
2223 ReadRegion.Bottom = Y + Y_incr - 1;
2224 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2225 cb->Buffer, /* our buffer */
2226 cb->BufferSize, /* dimensions of our buffer */
2227 BufferCoord, /* offset in our buffer */
2228 &ReadRegion)) /* region to save */
2229 {
2230 vim_free(cb->Buffer);
2231 cb->Buffer = NULL;
2232 return FALSE;
2233 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002234 }
2235
2236 return TRUE;
2237}
2238
2239/*
2240 * RestoreConsoleBuffer()
2241 * Description:
2242 * Restores important information about the console buffer, including the
2243 * actual buffer contents, if desired. The information to restore is in
2244 * the same format used by SaveConsoleBuffer().
2245 * Returns:
2246 * TRUE on success
2247 */
2248 static BOOL
2249RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002250 ConsoleBuffer *cb,
2251 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002252{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002253 COORD BufferCoord;
2254 SMALL_RECT WriteRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002255
2256 if (cb == NULL || !cb->IsValid)
2257 return FALSE;
2258
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002259 /*
2260 * Before restoring the buffer contents, clear the current buffer, and
2261 * restore the cursor position and window information. Doing this now
2262 * prevents old buffer contents from "flashing" onto the screen.
2263 */
2264 if (RestoreScreen)
2265 ClearConsoleBuffer(cb->Info.wAttributes);
2266
2267 FitConsoleWindow(cb->Info.dwSize, TRUE);
2268 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2269 return FALSE;
2270 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2271 return FALSE;
2272
2273 if (!RestoreScreen)
2274 {
2275 /*
2276 * No need to restore the screen buffer contents, so we're done.
2277 */
2278 return TRUE;
2279 }
2280
2281 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2282 return FALSE;
2283 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2284 return FALSE;
2285
2286 /*
2287 * Restore the screen buffer contents.
2288 */
2289 if (cb->Buffer != NULL)
2290 {
2291 BufferCoord.X = 0;
2292 BufferCoord.Y = 0;
2293 WriteRegion.Left = 0;
2294 WriteRegion.Top = 0;
2295 WriteRegion.Right = cb->Info.dwSize.X - 1;
2296 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2297 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2298 cb->Buffer, /* our buffer */
2299 cb->BufferSize, /* dimensions of our buffer */
2300 BufferCoord, /* offset in our buffer */
2301 &WriteRegion)) /* region to restore */
2302 {
2303 return FALSE;
2304 }
2305 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002306
2307 return TRUE;
2308}
2309
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002310#define FEAT_RESTORE_ORIG_SCREEN
2311#ifdef FEAT_RESTORE_ORIG_SCREEN
2312static ConsoleBuffer g_cbOrig = { 0 };
2313#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002314static ConsoleBuffer g_cbNonTermcap = { 0 };
2315static ConsoleBuffer g_cbTermcap = { 0 };
2316
2317#ifdef FEAT_TITLE
2318#ifdef __BORLANDC__
2319typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2320#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002321typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002322#endif
2323char g_szOrigTitle[256] = { 0 };
2324HWND g_hWnd = NULL; /* also used in os_mswin.c */
2325static HICON g_hOrigIconSmall = NULL;
2326static HICON g_hOrigIcon = NULL;
2327static HICON g_hVimIcon = NULL;
2328static BOOL g_fCanChangeIcon = FALSE;
2329
2330/* ICON* are not defined in VC++ 4.0 */
2331#ifndef ICON_SMALL
2332#define ICON_SMALL 0
2333#endif
2334#ifndef ICON_BIG
2335#define ICON_BIG 1
2336#endif
2337/*
2338 * GetConsoleIcon()
2339 * Description:
2340 * Attempts to retrieve the small icon and/or the big icon currently in
2341 * use by a given window.
2342 * Returns:
2343 * TRUE on success
2344 */
2345 static BOOL
2346GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002347 HWND hWnd,
2348 HICON *phIconSmall,
2349 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002350{
2351 if (hWnd == NULL)
2352 return FALSE;
2353
2354 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002355 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2356 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002357 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002358 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2359 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002360 return TRUE;
2361}
2362
2363/*
2364 * SetConsoleIcon()
2365 * Description:
2366 * Attempts to change the small icon and/or the big icon currently in
2367 * use by a given window.
2368 * Returns:
2369 * TRUE on success
2370 */
2371 static BOOL
2372SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002373 HWND hWnd,
2374 HICON hIconSmall,
2375 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002376{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002377 if (hWnd == NULL)
2378 return FALSE;
2379
2380 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002381 SendMessage(hWnd, WM_SETICON,
2382 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002383 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002384 SendMessage(hWnd, WM_SETICON,
2385 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002386 return TRUE;
2387}
2388
2389/*
2390 * SaveConsoleTitleAndIcon()
2391 * Description:
2392 * Saves the current console window title in g_szOrigTitle, for later
2393 * restoration. Also, attempts to obtain a handle to the console window,
2394 * and use it to save the small and big icons currently in use by the
2395 * console window. This is not always possible on some versions of Windows;
2396 * nor is it possible when running Vim remotely using Telnet (since the
2397 * console window the user sees is owned by a remote process).
2398 */
2399 static void
2400SaveConsoleTitleAndIcon(void)
2401{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002402 /* Save the original title. */
2403 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2404 return;
2405
2406 /*
2407 * Obtain a handle to the console window using GetConsoleWindow() from
2408 * KERNEL32.DLL; we need to handle in order to change the window icon.
2409 * This function only exists on NT-based Windows, starting with Windows
2410 * 2000. On older operating systems, we can't change the window icon
2411 * anyway.
2412 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002413 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002414 if (g_hWnd == NULL)
2415 return;
2416
2417 /* Save the original console window icon. */
2418 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2419 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2420 return;
2421
2422 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002423 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002424 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002425 if (g_hVimIcon != NULL)
2426 g_fCanChangeIcon = TRUE;
2427}
2428#endif
2429
2430static int g_fWindInitCalled = FALSE;
2431static int g_fTermcapMode = FALSE;
2432static CONSOLE_CURSOR_INFO g_cci;
2433static DWORD g_cmodein = 0;
2434static DWORD g_cmodeout = 0;
2435
2436/*
2437 * non-GUI version of mch_init().
2438 */
2439 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002440mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002441{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002442#ifndef FEAT_RESTORE_ORIG_SCREEN
2443 CONSOLE_SCREEN_BUFFER_INFO csbi;
2444#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002445#ifndef __MINGW32__
2446 extern int _fmode;
2447#endif
2448
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002449 /* Silently handle invalid parameters to CRT functions */
2450 SET_INVALID_PARAM_HANDLER;
2451
Bram Moolenaar071d4272004-06-13 20:20:40 +00002452 /* Let critical errors result in a failure, not in a dialog box. Required
2453 * for the timestamp test to work on removed floppies. */
2454 SetErrorMode(SEM_FAILCRITICALERRORS);
2455
2456 _fmode = O_BINARY; /* we do our own CR-LF translation */
2457 out_flush();
2458
2459 /* Obtain handles for the standard Console I/O devices */
2460 if (read_cmd_fd == 0)
2461 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2462 else
2463 create_conin();
2464 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2465
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002466#ifdef FEAT_RESTORE_ORIG_SCREEN
2467 /* Save the initial console buffer for later restoration */
2468 SaveConsoleBuffer(&g_cbOrig);
2469 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2470#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002471 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002472 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2473 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2474#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002475 if (cterm_normal_fg_color == 0)
2476 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2477 if (cterm_normal_bg_color == 0)
2478 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2479
2480 /* set termcap codes to current text attributes */
2481 update_tcap(g_attrCurrent);
2482
2483 GetConsoleCursorInfo(g_hConOut, &g_cci);
2484 GetConsoleMode(g_hConIn, &g_cmodein);
2485 GetConsoleMode(g_hConOut, &g_cmodeout);
2486
2487#ifdef FEAT_TITLE
2488 SaveConsoleTitleAndIcon();
2489 /*
2490 * Set both the small and big icons of the console window to Vim's icon.
2491 * Note that Vim presently only has one size of icon (32x32), but it
2492 * automatically gets scaled down to 16x16 when setting the small icon.
2493 */
2494 if (g_fCanChangeIcon)
2495 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2496#endif
2497
2498 ui_get_shellsize();
2499
2500#ifdef MCH_WRITE_DUMP
2501 fdDump = fopen("dump", "wt");
2502
2503 if (fdDump)
2504 {
2505 time_t t;
2506
2507 time(&t);
2508 fputs(ctime(&t), fdDump);
2509 fflush(fdDump);
2510 }
2511#endif
2512
2513 g_fWindInitCalled = TRUE;
2514
2515#ifdef FEAT_MOUSE
2516 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2517#endif
2518
2519#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002520 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002521#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002522}
2523
2524/*
2525 * non-GUI version of mch_exit().
2526 * Shut down and exit with status `r'
2527 * Careful: mch_exit() may be called before mch_init()!
2528 */
2529 void
2530mch_exit(int r)
2531{
2532 stoptermcap();
2533
2534 if (g_fWindInitCalled)
2535 settmode(TMODE_COOK);
2536
2537 ml_close_all(TRUE); /* remove all memfiles */
2538
2539 if (g_fWindInitCalled)
2540 {
2541#ifdef FEAT_TITLE
2542 mch_restore_title(3);
2543 /*
2544 * Restore both the small and big icons of the console window to
2545 * what they were at startup. Don't do this when the window is
2546 * closed, Vim would hang here.
2547 */
2548 if (g_fCanChangeIcon && !g_fForceExit)
2549 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2550#endif
2551
2552#ifdef MCH_WRITE_DUMP
2553 if (fdDump)
2554 {
2555 time_t t;
2556
2557 time(&t);
2558 fputs(ctime(&t), fdDump);
2559 fclose(fdDump);
2560 }
2561 fdDump = NULL;
2562#endif
2563 }
2564
2565 SetConsoleCursorInfo(g_hConOut, &g_cci);
2566 SetConsoleMode(g_hConIn, g_cmodein);
2567 SetConsoleMode(g_hConOut, g_cmodeout);
2568
2569#ifdef DYNAMIC_GETTEXT
2570 dyn_libintl_end();
2571#endif
2572
2573 exit(r);
2574}
2575#endif /* !FEAT_GUI_W32 */
2576
Bram Moolenaar071d4272004-06-13 20:20:40 +00002577/*
2578 * Do we have an interactive window?
2579 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002580/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002581 int
2582mch_check_win(
2583 int argc,
2584 char **argv)
2585{
2586 get_exe_name();
2587
2588#ifdef FEAT_GUI_W32
2589 return OK; /* GUI always has a tty */
2590#else
2591 if (isatty(1))
2592 return OK;
2593 return FAIL;
2594#endif
2595}
2596
2597
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002598#ifdef FEAT_MBYTE
2599/*
2600 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2601 * if it already exists. When "len" is > 0, also expand short to long
2602 * filenames.
2603 * Return FAIL if wide functions are not available, OK otherwise.
2604 * NOTE: much of this is identical to fname_case(), keep in sync!
2605 */
2606 static int
2607fname_casew(
2608 WCHAR *name,
2609 int len)
2610{
2611 WCHAR szTrueName[_MAX_PATH + 2];
2612 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2613 WCHAR *ptrue, *ptruePrev;
2614 WCHAR *porig, *porigPrev;
2615 int flen;
2616 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002617 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002618 int c;
2619 int slen;
2620
2621 flen = (int)wcslen(name);
2622 if (flen > _MAX_PATH)
2623 return OK;
2624
2625 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2626
2627 /* Build the new name in szTrueName[] one component at a time. */
2628 porig = name;
2629 ptrue = szTrueName;
2630
2631 if (iswalpha(porig[0]) && porig[1] == L':')
2632 {
2633 /* copy leading drive letter */
2634 *ptrue++ = *porig++;
2635 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002636 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002637 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002638
2639 while (*porig != NUL)
2640 {
2641 /* copy \ characters */
2642 while (*porig == psepc)
2643 *ptrue++ = *porig++;
2644
2645 ptruePrev = ptrue;
2646 porigPrev = porig;
2647 while (*porig != NUL && *porig != psepc)
2648 {
2649 *ptrue++ = *porig++;
2650 }
2651 *ptrue = NUL;
2652
2653 /* To avoid a slow failure append "\*" when searching a directory,
2654 * server or network share. */
2655 wcscpy(szTrueNameTemp, szTrueName);
2656 slen = (int)wcslen(szTrueNameTemp);
2657 if (*porig == psepc && slen + 2 < _MAX_PATH)
2658 wcscpy(szTrueNameTemp + slen, L"\\*");
2659
2660 /* Skip "", "." and "..". */
2661 if (ptrue > ptruePrev
2662 && (ptruePrev[0] != L'.'
2663 || (ptruePrev[1] != NUL
2664 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2665 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2666 != INVALID_HANDLE_VALUE)
2667 {
2668 c = *porig;
2669 *porig = NUL;
2670
2671 /* Only use the match when it's the same name (ignoring case) or
2672 * expansion is allowed and there is a match with the short name
2673 * and there is enough room. */
2674 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2675 || (len > 0
2676 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2677 && (int)(ptruePrev - szTrueName)
2678 + (int)wcslen(fb.cFileName) < len)))
2679 {
2680 wcscpy(ptruePrev, fb.cFileName);
2681
2682 /* Look for exact match and prefer it if found. Must be a
2683 * long name, otherwise there would be only one match. */
2684 while (FindNextFileW(hFind, &fb))
2685 {
2686 if (*fb.cAlternateFileName != NUL
2687 && (wcscoll(porigPrev, fb.cFileName) == 0
2688 || (len > 0
2689 && (_wcsicoll(porigPrev,
2690 fb.cAlternateFileName) == 0
2691 && (int)(ptruePrev - szTrueName)
2692 + (int)wcslen(fb.cFileName) < len))))
2693 {
2694 wcscpy(ptruePrev, fb.cFileName);
2695 break;
2696 }
2697 }
2698 }
2699 FindClose(hFind);
2700 *porig = c;
2701 ptrue = ptruePrev + wcslen(ptruePrev);
2702 }
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002703 }
2704
2705 wcscpy(name, szTrueName);
2706 return OK;
2707}
2708#endif
2709
Bram Moolenaar071d4272004-06-13 20:20:40 +00002710/*
2711 * fname_case(): Set the case of the file name, if it already exists.
2712 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002713 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002714 */
2715 void
2716fname_case(
2717 char_u *name,
2718 int len)
2719{
2720 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002721 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002722 char *ptrue, *ptruePrev;
2723 char *porig, *porigPrev;
2724 int flen;
2725 WIN32_FIND_DATA fb;
2726 HANDLE hFind;
2727 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002728 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002729
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002730 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002731 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002732 return;
2733
2734 slash_adjust(name);
2735
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002736#ifdef FEAT_MBYTE
2737 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2738 {
2739 WCHAR *p = enc_to_utf16(name, NULL);
2740
2741 if (p != NULL)
2742 {
2743 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002744 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002745
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002746 wcsncpy(buf, p, _MAX_PATH);
2747 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002748 vim_free(p);
2749
2750 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2751 {
2752 q = utf16_to_enc(buf, NULL);
2753 if (q != NULL)
2754 {
2755 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2756 vim_free(q);
2757 return;
2758 }
2759 }
2760 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002761 return;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002762 }
2763#endif
2764
2765 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2766 * So we should check this after calling wide function. */
2767 if (flen > _MAX_PATH)
2768 return;
2769
Bram Moolenaar071d4272004-06-13 20:20:40 +00002770 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002771 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002772 ptrue = szTrueName;
2773
2774 if (isalpha(porig[0]) && porig[1] == ':')
2775 {
2776 /* copy leading drive letter */
2777 *ptrue++ = *porig++;
2778 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002779 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002780 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002781
2782 while (*porig != NUL)
2783 {
2784 /* copy \ characters */
2785 while (*porig == psepc)
2786 *ptrue++ = *porig++;
2787
2788 ptruePrev = ptrue;
2789 porigPrev = porig;
2790 while (*porig != NUL && *porig != psepc)
2791 {
2792#ifdef FEAT_MBYTE
2793 int l;
2794
2795 if (enc_dbcs)
2796 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002797 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002798 while (--l >= 0)
2799 *ptrue++ = *porig++;
2800 }
2801 else
2802#endif
2803 *ptrue++ = *porig++;
2804 }
2805 *ptrue = NUL;
2806
Bram Moolenaar464c9252010-10-13 20:37:41 +02002807 /* To avoid a slow failure append "\*" when searching a directory,
2808 * server or network share. */
2809 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002810 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002811 if (*porig == psepc && slen + 2 < _MAX_PATH)
2812 STRCPY(szTrueNameTemp + slen, "\\*");
2813
Bram Moolenaar071d4272004-06-13 20:20:40 +00002814 /* Skip "", "." and "..". */
2815 if (ptrue > ptruePrev
2816 && (ptruePrev[0] != '.'
2817 || (ptruePrev[1] != NUL
2818 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002819 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002820 != INVALID_HANDLE_VALUE)
2821 {
2822 c = *porig;
2823 *porig = NUL;
2824
2825 /* Only use the match when it's the same name (ignoring case) or
2826 * expansion is allowed and there is a match with the short name
2827 * and there is enough room. */
2828 if (_stricoll(porigPrev, fb.cFileName) == 0
2829 || (len > 0
2830 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2831 && (int)(ptruePrev - szTrueName)
2832 + (int)strlen(fb.cFileName) < len)))
2833 {
2834 STRCPY(ptruePrev, fb.cFileName);
2835
2836 /* Look for exact match and prefer it if found. Must be a
2837 * long name, otherwise there would be only one match. */
2838 while (FindNextFile(hFind, &fb))
2839 {
2840 if (*fb.cAlternateFileName != NUL
2841 && (strcoll(porigPrev, fb.cFileName) == 0
2842 || (len > 0
2843 && (_stricoll(porigPrev,
2844 fb.cAlternateFileName) == 0
2845 && (int)(ptruePrev - szTrueName)
2846 + (int)strlen(fb.cFileName) < len))))
2847 {
2848 STRCPY(ptruePrev, fb.cFileName);
2849 break;
2850 }
2851 }
2852 }
2853 FindClose(hFind);
2854 *porig = c;
2855 ptrue = ptruePrev + strlen(ptruePrev);
2856 }
2857 }
2858
2859 STRCPY(name, szTrueName);
2860}
2861
2862
2863/*
2864 * Insert user name in s[len].
2865 */
2866 int
2867mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002868 char_u *s,
2869 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002870{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002871 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002872 DWORD cch = sizeof szUserName;
2873
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002874#ifdef FEAT_MBYTE
2875 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2876 {
2877 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2878 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2879
2880 if (GetUserNameW(wszUserName, &wcch))
2881 {
2882 char_u *p = utf16_to_enc(wszUserName, NULL);
2883
2884 if (p != NULL)
2885 {
2886 vim_strncpy(s, p, len - 1);
2887 vim_free(p);
2888 return OK;
2889 }
2890 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002891 }
2892#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002893 if (GetUserName(szUserName, &cch))
2894 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002895 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002896 return OK;
2897 }
2898 s[0] = NUL;
2899 return FAIL;
2900}
2901
2902
2903/*
2904 * Insert host name in s[len].
2905 */
2906 void
2907mch_get_host_name(
2908 char_u *s,
2909 int len)
2910{
2911 DWORD cch = len;
2912
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002913#ifdef FEAT_MBYTE
2914 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2915 {
2916 WCHAR wszHostName[256 + 1];
2917 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2918
2919 if (GetComputerNameW(wszHostName, &wcch))
2920 {
2921 char_u *p = utf16_to_enc(wszHostName, NULL);
2922
2923 if (p != NULL)
2924 {
2925 vim_strncpy(s, p, len - 1);
2926 vim_free(p);
2927 return;
2928 }
2929 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002930 }
2931#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002932 if (!GetComputerName((LPSTR)s, &cch))
2933 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002934}
2935
2936
2937/*
2938 * return process ID
2939 */
2940 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002941mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002942{
2943 return (long)GetCurrentProcessId();
2944}
2945
2946
2947/*
2948 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2949 * Return OK for success, FAIL for failure.
2950 */
2951 int
2952mch_dirname(
2953 char_u *buf,
2954 int len)
2955{
2956 /*
2957 * Originally this was:
2958 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2959 * But the Win32s known bug list says that getcwd() doesn't work
2960 * so use the Win32 system call instead. <Negri>
2961 */
2962#ifdef FEAT_MBYTE
2963 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2964 {
2965 WCHAR wbuf[_MAX_PATH + 1];
2966
2967 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2968 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002969 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002970
2971 if (p != NULL)
2972 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002973 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002974 vim_free(p);
2975 return OK;
2976 }
2977 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002978 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002979 }
2980#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002981 return (GetCurrentDirectory(len, (LPSTR)buf) != 0 ? OK : FAIL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002982}
2983
2984/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01002985 * Get file permissions for "name".
2986 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002987 */
2988 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002989mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002990{
Bram Moolenaar8767f522016-07-01 17:17:39 +02002991 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01002992 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002993
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002994 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01002995 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002996}
2997
2998
2999/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003000 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003001 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003002 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003003 */
3004 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003005mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003006{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003007 long n = -1;
3008
Bram Moolenaar071d4272004-06-13 20:20:40 +00003009#ifdef FEAT_MBYTE
3010 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3011 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003012 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003013
3014 if (p != NULL)
3015 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003016 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003017 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003018 if (n == -1)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003019 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003020 }
3021 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003022 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003023#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003024 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003025 if (n == -1)
3026 return FAIL;
3027
3028 win32_set_archive(name);
3029
3030 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003031}
3032
3033/*
3034 * Set hidden flag for "name".
3035 */
3036 void
3037mch_hide(char_u *name)
3038{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003039 int attrs = win32_getattrs(name);
3040 if (attrs == -1)
3041 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003042
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003043 attrs |= FILE_ATTRIBUTE_HIDDEN;
3044 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003045}
3046
3047/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003048 * Return TRUE if file "name" exists and is hidden.
3049 */
3050 int
3051mch_ishidden(char_u *name)
3052{
3053 int f = win32_getattrs(name);
3054
3055 if (f == -1)
3056 return FALSE; /* file does not exist at all */
3057
3058 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3059}
3060
3061/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003062 * return TRUE if "name" is a directory
3063 * return FALSE if "name" is not a directory or upon error
3064 */
3065 int
3066mch_isdir(char_u *name)
3067{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003068 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003069
3070 if (f == -1)
3071 return FALSE; /* file does not exist at all */
3072
3073 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3074}
3075
3076/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003077 * return TRUE if "name" is a directory, NOT a symlink to a directory
3078 * return FALSE if "name" is not a directory
3079 * return FALSE for error
3080 */
3081 int
3082mch_isrealdir(char_u *name)
3083{
3084 return mch_isdir(name) && !mch_is_symbolic_link(name);
3085}
3086
3087/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003088 * Create directory "name".
3089 * Return 0 on success, -1 on error.
3090 */
3091 int
3092mch_mkdir(char_u *name)
3093{
3094#ifdef FEAT_MBYTE
3095 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3096 {
3097 WCHAR *p;
3098 int retval;
3099
3100 p = enc_to_utf16(name, NULL);
3101 if (p == NULL)
3102 return -1;
3103 retval = _wmkdir(p);
3104 vim_free(p);
3105 return retval;
3106 }
3107#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003108 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003109}
3110
3111/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003112 * Delete directory "name".
3113 * Return 0 on success, -1 on error.
3114 */
3115 int
3116mch_rmdir(char_u *name)
3117{
3118#ifdef FEAT_MBYTE
3119 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3120 {
3121 WCHAR *p;
3122 int retval;
3123
3124 p = enc_to_utf16(name, NULL);
3125 if (p == NULL)
3126 return -1;
3127 retval = _wrmdir(p);
3128 vim_free(p);
3129 return retval;
3130 }
3131#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003132 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003133}
3134
3135/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003136 * Return TRUE if file "fname" has more than one link.
3137 */
3138 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003139mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003140{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003141 BY_HANDLE_FILE_INFORMATION info;
3142
3143 return win32_fileinfo(fname, &info) == FILEINFO_OK
3144 && info.nNumberOfLinks > 1;
3145}
3146
3147/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003148 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003149 */
3150 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003151mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003152{
3153 HANDLE hFind;
3154 int res = FALSE;
3155 WIN32_FIND_DATAA findDataA;
3156 DWORD fileFlags = 0, reparseTag = 0;
3157#ifdef FEAT_MBYTE
3158 WCHAR *wn = NULL;
3159 WIN32_FIND_DATAW findDataW;
3160
3161 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003162 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003163 if (wn != NULL)
3164 {
3165 hFind = FindFirstFileW(wn, &findDataW);
3166 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003167 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003168 {
3169 fileFlags = findDataW.dwFileAttributes;
3170 reparseTag = findDataW.dwReserved0;
3171 }
3172 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003173 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003174#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003175 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003176 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003177 if (hFind != INVALID_HANDLE_VALUE)
3178 {
3179 fileFlags = findDataA.dwFileAttributes;
3180 reparseTag = findDataA.dwReserved0;
3181 }
3182 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003183
3184 if (hFind != INVALID_HANDLE_VALUE)
3185 FindClose(hFind);
3186
3187 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003188 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3189 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003190 res = TRUE;
3191
3192 return res;
3193}
3194
3195/*
3196 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3197 * link.
3198 */
3199 int
3200mch_is_linked(char_u *fname)
3201{
3202 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3203 return TRUE;
3204 return FALSE;
3205}
3206
3207/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003208 * Get the by-handle-file-information for "fname".
3209 * Returns FILEINFO_OK when OK.
3210 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3211 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3212 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3213 */
3214 int
3215win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3216{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003217 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003218 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003219#ifdef FEAT_MBYTE
3220 WCHAR *wn = NULL;
3221
3222 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003223 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003224 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003225 if (wn == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003226 return FILEINFO_ENC_FAIL;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003227 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003228 if (wn != NULL)
3229 {
3230 hFile = CreateFileW(wn, /* file name */
3231 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003232 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003233 NULL, /* security descriptor */
3234 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003235 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003236 NULL); /* handle to template file */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003237 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003238 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003239 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003240#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003241 hFile = CreateFile((LPCSTR)fname, /* file name */
3242 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003243 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003244 NULL, /* security descriptor */
3245 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003246 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003247 NULL); /* handle to template file */
3248
3249 if (hFile != INVALID_HANDLE_VALUE)
3250 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003251 if (GetFileInformationByHandle(hFile, info) != 0)
3252 res = FILEINFO_OK;
3253 else
3254 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003255 CloseHandle(hFile);
3256 }
3257
Bram Moolenaar03f48552006-02-28 23:52:23 +00003258 return res;
3259}
3260
3261/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003262 * get file attributes for `name'
3263 * -1 : error
3264 * else FILE_ATTRIBUTE_* defined in winnt.h
3265 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003266 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003267win32_getattrs(char_u *name)
3268{
3269 int attr;
3270#ifdef FEAT_MBYTE
3271 WCHAR *p = NULL;
3272
3273 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3274 p = enc_to_utf16(name, NULL);
3275
3276 if (p != NULL)
3277 {
3278 attr = GetFileAttributesW(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003279 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003280 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003281 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003282#endif
3283 attr = GetFileAttributes((char *)name);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003284
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003285 return attr;
3286}
3287
3288/*
3289 * set file attributes for `name' to `attrs'
3290 *
3291 * return -1 for failure, 0 otherwise
3292 */
3293 static
3294 int
3295win32_setattrs(char_u *name, int attrs)
3296{
3297 int res;
3298#ifdef FEAT_MBYTE
3299 WCHAR *p = NULL;
3300
3301 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3302 p = enc_to_utf16(name, NULL);
3303
3304 if (p != NULL)
3305 {
3306 res = SetFileAttributesW(p, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003307 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003308 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003309 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003310#endif
3311 res = SetFileAttributes((char *)name, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003312
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003313 return res ? 0 : -1;
3314}
3315
3316/*
3317 * Set archive flag for "name".
3318 */
3319 static
3320 int
3321win32_set_archive(char_u *name)
3322{
3323 int attrs = win32_getattrs(name);
3324 if (attrs == -1)
3325 return -1;
3326
3327 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3328 return win32_setattrs(name, attrs);
3329}
3330
3331/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003332 * Return TRUE if file or directory "name" is writable (not readonly).
3333 * Strange semantics of Win32: a readonly directory is writable, but you can't
3334 * delete a file. Let's say this means it is writable.
3335 */
3336 int
3337mch_writable(char_u *name)
3338{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003339 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003340
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003341 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3342 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003343}
3344
Bram Moolenaar071d4272004-06-13 20:20:40 +00003345/*
3346 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003347 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003348 * Return -1 if unknown.
3349 */
3350 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003351mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003352{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003353 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003354 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003355 char_u *p;
3356
3357 if (len >= _MAX_PATH) /* safety check */
3358 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003359 if (!use_path)
3360 {
3361 /* TODO: check if file is really executable. */
3362 return mch_getperm(name) != -1 && !mch_isdir(name);
3363 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003364
3365 /* If there already is an extension try using the name directly. Also do
3366 * this with a Unix-shell like 'shell'. */
3367 if (vim_strchr(gettail(name), '.') != NULL
3368 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003369 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003370 return TRUE;
3371
3372 /*
3373 * Loop over all extensions in $PATHEXT.
3374 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003375 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003376 p = mch_getenv("PATHEXT");
3377 if (p == NULL)
3378 p = (char_u *)".com;.exe;.bat;.cmd";
3379 while (*p)
3380 {
3381 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3382 {
3383 /* A single "." means no extension is added. */
3384 buf[len] = NUL;
3385 ++p;
3386 if (*p)
3387 ++p;
3388 }
3389 else
3390 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003391 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003392 return TRUE;
3393 }
3394 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003395}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003396
3397/*
3398 * Check what "name" is:
3399 * NODE_NORMAL: file or directory (or doesn't exist)
3400 * NODE_WRITABLE: writable device, socket, fifo, etc.
3401 * NODE_OTHER: non-writable things
3402 */
3403 int
3404mch_nodetype(char_u *name)
3405{
3406 HANDLE hFile;
3407 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003408#ifdef FEAT_MBYTE
3409 WCHAR *wn = NULL;
3410#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003411
Bram Moolenaar043545e2006-10-10 16:44:07 +00003412 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3413 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3414 * here. */
3415 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3416 return NODE_WRITABLE;
3417
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003418#ifdef FEAT_MBYTE
3419 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003420 wn = enc_to_utf16(name, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003421
3422 if (wn != NULL)
3423 {
3424 hFile = CreateFileW(wn, /* file name */
3425 GENERIC_WRITE, /* access mode */
3426 0, /* share mode */
3427 NULL, /* security descriptor */
3428 OPEN_EXISTING, /* creation disposition */
3429 0, /* file attributes */
3430 NULL); /* handle to template file */
3431 vim_free(wn);
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003432 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003433 else
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003434#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003435 hFile = CreateFile((LPCSTR)name, /* file name */
3436 GENERIC_WRITE, /* access mode */
3437 0, /* share mode */
3438 NULL, /* security descriptor */
3439 OPEN_EXISTING, /* creation disposition */
3440 0, /* file attributes */
3441 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003442
3443 if (hFile == INVALID_HANDLE_VALUE)
3444 return NODE_NORMAL;
3445
3446 type = GetFileType(hFile);
3447 CloseHandle(hFile);
3448 if (type == FILE_TYPE_CHAR)
3449 return NODE_WRITABLE;
3450 if (type == FILE_TYPE_DISK)
3451 return NODE_NORMAL;
3452 return NODE_OTHER;
3453}
3454
3455#ifdef HAVE_ACL
3456struct my_acl
3457{
3458 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3459 PSID pSidOwner;
3460 PSID pSidGroup;
3461 PACL pDacl;
3462 PACL pSacl;
3463};
3464#endif
3465
3466/*
3467 * Return a pointer to the ACL of file "fname" in allocated memory.
3468 * Return NULL if the ACL is not available for whatever reason.
3469 */
3470 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003471mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003472{
3473#ifndef HAVE_ACL
3474 return (vim_acl_T)NULL;
3475#else
3476 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003477 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003478
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003479 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3480 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003481 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003482# ifdef FEAT_MBYTE
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003483 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003484
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003485 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3486 wn = enc_to_utf16(fname, NULL);
3487 if (wn != NULL)
3488 {
3489 /* Try to retrieve the entire security descriptor. */
3490 err = GetNamedSecurityInfoW(
3491 wn, // Abstract filename
3492 SE_FILE_OBJECT, // File Object
3493 OWNER_SECURITY_INFORMATION |
3494 GROUP_SECURITY_INFORMATION |
3495 DACL_SECURITY_INFORMATION |
3496 SACL_SECURITY_INFORMATION,
3497 &p->pSidOwner, // Ownership information.
3498 &p->pSidGroup, // Group membership.
3499 &p->pDacl, // Discretionary information.
3500 &p->pSacl, // For auditing purposes.
3501 &p->pSecurityDescriptor);
3502 if (err == ERROR_ACCESS_DENIED ||
3503 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003504 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003505 /* Retrieve only DACL. */
3506 (void)GetNamedSecurityInfoW(
3507 wn,
3508 SE_FILE_OBJECT,
3509 DACL_SECURITY_INFORMATION,
3510 NULL,
3511 NULL,
3512 &p->pDacl,
3513 NULL,
3514 &p->pSecurityDescriptor);
Bram Moolenaar27515922013-06-29 15:36:26 +02003515 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003516 if (p->pSecurityDescriptor == NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003517 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003518 mch_free_acl((vim_acl_T)p);
3519 p = NULL;
3520 }
3521 vim_free(wn);
3522 }
3523 else
3524# endif
3525 {
3526 /* Try to retrieve the entire security descriptor. */
3527 err = GetNamedSecurityInfo(
3528 (LPSTR)fname, // Abstract filename
3529 SE_FILE_OBJECT, // File Object
3530 OWNER_SECURITY_INFORMATION |
3531 GROUP_SECURITY_INFORMATION |
3532 DACL_SECURITY_INFORMATION |
3533 SACL_SECURITY_INFORMATION,
3534 &p->pSidOwner, // Ownership information.
3535 &p->pSidGroup, // Group membership.
3536 &p->pDacl, // Discretionary information.
3537 &p->pSacl, // For auditing purposes.
3538 &p->pSecurityDescriptor);
3539 if (err == ERROR_ACCESS_DENIED ||
3540 err == ERROR_PRIVILEGE_NOT_HELD)
3541 {
3542 /* Retrieve only DACL. */
3543 (void)GetNamedSecurityInfo(
3544 (LPSTR)fname,
3545 SE_FILE_OBJECT,
3546 DACL_SECURITY_INFORMATION,
3547 NULL,
3548 NULL,
3549 &p->pDacl,
3550 NULL,
3551 &p->pSecurityDescriptor);
3552 }
3553 if (p->pSecurityDescriptor == NULL)
3554 {
3555 mch_free_acl((vim_acl_T)p);
3556 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003557 }
3558 }
3559 }
3560
3561 return (vim_acl_T)p;
3562#endif
3563}
3564
Bram Moolenaar27515922013-06-29 15:36:26 +02003565#ifdef HAVE_ACL
3566/*
3567 * Check if "acl" contains inherited ACE.
3568 */
3569 static BOOL
3570is_acl_inherited(PACL acl)
3571{
3572 DWORD i;
3573 ACL_SIZE_INFORMATION acl_info;
3574 PACCESS_ALLOWED_ACE ace;
3575
3576 acl_info.AceCount = 0;
3577 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3578 for (i = 0; i < acl_info.AceCount; i++)
3579 {
3580 GetAce(acl, i, (LPVOID *)&ace);
3581 if (ace->Header.AceFlags & INHERITED_ACE)
3582 return TRUE;
3583 }
3584 return FALSE;
3585}
3586#endif
3587
Bram Moolenaar071d4272004-06-13 20:20:40 +00003588/*
3589 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3590 * Errors are ignored.
3591 * This must only be called with "acl" equal to what mch_get_acl() returned.
3592 */
3593 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003594mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003595{
3596#ifdef HAVE_ACL
3597 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003598 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003599
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003600 if (p != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003601 {
3602# ifdef FEAT_MBYTE
3603 WCHAR *wn = NULL;
3604# endif
3605
3606 /* Set security flags */
3607 if (p->pSidOwner)
3608 sec_info |= OWNER_SECURITY_INFORMATION;
3609 if (p->pSidGroup)
3610 sec_info |= GROUP_SECURITY_INFORMATION;
3611 if (p->pDacl)
3612 {
3613 sec_info |= DACL_SECURITY_INFORMATION;
3614 /* Do not inherit its parent's DACL.
3615 * If the DACL is inherited, Cygwin permissions would be changed.
3616 */
3617 if (!is_acl_inherited(p->pDacl))
3618 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3619 }
3620 if (p->pSacl)
3621 sec_info |= SACL_SECURITY_INFORMATION;
3622
3623# ifdef FEAT_MBYTE
3624 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3625 wn = enc_to_utf16(fname, NULL);
3626 if (wn != NULL)
3627 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003628 (void)SetNamedSecurityInfoW(
Bram Moolenaar27515922013-06-29 15:36:26 +02003629 wn, // Abstract filename
3630 SE_FILE_OBJECT, // File Object
3631 sec_info,
3632 p->pSidOwner, // Ownership information.
3633 p->pSidGroup, // Group membership.
3634 p->pDacl, // Discretionary information.
3635 p->pSacl // For auditing purposes.
3636 );
3637 vim_free(wn);
3638 }
3639 else
3640# endif
3641 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003642 (void)SetNamedSecurityInfo(
Bram Moolenaar27515922013-06-29 15:36:26 +02003643 (LPSTR)fname, // Abstract filename
3644 SE_FILE_OBJECT, // File Object
3645 sec_info,
3646 p->pSidOwner, // Ownership information.
3647 p->pSidGroup, // Group membership.
3648 p->pDacl, // Discretionary information.
3649 p->pSacl // For auditing purposes.
3650 );
3651 }
3652 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003653#endif
3654}
3655
3656 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003657mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003658{
3659#ifdef HAVE_ACL
3660 struct my_acl *p = (struct my_acl *)acl;
3661
3662 if (p != NULL)
3663 {
3664 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3665 vim_free(p);
3666 }
3667#endif
3668}
3669
3670#ifndef FEAT_GUI_W32
3671
3672/*
3673 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3674 */
3675 static BOOL WINAPI
3676handler_routine(
3677 DWORD dwCtrlType)
3678{
3679 switch (dwCtrlType)
3680 {
3681 case CTRL_C_EVENT:
3682 if (ctrl_c_interrupts)
3683 g_fCtrlCPressed = TRUE;
3684 return TRUE;
3685
3686 case CTRL_BREAK_EVENT:
3687 g_fCBrkPressed = TRUE;
3688 return TRUE;
3689
3690 /* fatal events: shut down gracefully */
3691 case CTRL_CLOSE_EVENT:
3692 case CTRL_LOGOFF_EVENT:
3693 case CTRL_SHUTDOWN_EVENT:
3694 windgoto((int)Rows - 1, 0);
3695 g_fForceExit = TRUE;
3696
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003697 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003698 (dwCtrlType == CTRL_CLOSE_EVENT
3699 ? _("close")
3700 : dwCtrlType == CTRL_LOGOFF_EVENT
3701 ? _("logoff")
3702 : _("shutdown")));
3703#ifdef DEBUG
3704 OutputDebugString(IObuff);
3705#endif
3706
3707 preserve_exit(); /* output IObuff, preserve files and exit */
3708
3709 return TRUE; /* not reached */
3710
3711 default:
3712 return FALSE;
3713 }
3714}
3715
3716
3717/*
3718 * set the tty in (raw) ? "raw" : "cooked" mode
3719 */
3720 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003721mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003722{
3723 DWORD cmodein;
3724 DWORD cmodeout;
3725 BOOL bEnableHandler;
3726
3727 GetConsoleMode(g_hConIn, &cmodein);
3728 GetConsoleMode(g_hConOut, &cmodeout);
3729 if (tmode == TMODE_RAW)
3730 {
3731 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3732 ENABLE_ECHO_INPUT);
3733#ifdef FEAT_MOUSE
3734 if (g_fMouseActive)
3735 cmodein |= ENABLE_MOUSE_INPUT;
3736#endif
3737 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3738 bEnableHandler = TRUE;
3739 }
3740 else /* cooked */
3741 {
3742 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3743 ENABLE_ECHO_INPUT);
3744 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3745 bEnableHandler = FALSE;
3746 }
3747 SetConsoleMode(g_hConIn, cmodein);
3748 SetConsoleMode(g_hConOut, cmodeout);
3749 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3750
3751#ifdef MCH_WRITE_DUMP
3752 if (fdDump)
3753 {
3754 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3755 tmode == TMODE_RAW ? "raw" :
3756 tmode == TMODE_COOK ? "cooked" : "normal",
3757 cmodein, cmodeout);
3758 fflush(fdDump);
3759 }
3760#endif
3761}
3762
3763
3764/*
3765 * Get the size of the current window in `Rows' and `Columns'
3766 * Return OK when size could be determined, FAIL otherwise.
3767 */
3768 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003769mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003770{
3771 CONSOLE_SCREEN_BUFFER_INFO csbi;
3772
3773 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3774 {
3775 /*
3776 * For some reason, we are trying to get the screen dimensions
3777 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3778 * variables are really intended to mean the size of Vim screen
3779 * while in termcap mode.
3780 */
3781 Rows = g_cbTermcap.Info.dwSize.Y;
3782 Columns = g_cbTermcap.Info.dwSize.X;
3783 }
3784 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3785 {
3786 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3787 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3788 }
3789 else
3790 {
3791 Rows = 25;
3792 Columns = 80;
3793 }
3794 return OK;
3795}
3796
3797/*
3798 * Set a console window to `xSize' * `ySize'
3799 */
3800 static void
3801ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003802 HANDLE hConsole,
3803 int xSize,
3804 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003805{
3806 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3807 SMALL_RECT srWindowRect; /* hold the new console size */
3808 COORD coordScreen;
3809
3810#ifdef MCH_WRITE_DUMP
3811 if (fdDump)
3812 {
3813 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3814 fflush(fdDump);
3815 }
3816#endif
3817
3818 /* get the largest size we can size the console window to */
3819 coordScreen = GetLargestConsoleWindowSize(hConsole);
3820
3821 /* define the new console window size and scroll position */
3822 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3823 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3824 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3825
3826 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3827 {
3828 int sx, sy;
3829
3830 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3831 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3832 if (sy < ySize || sx < xSize)
3833 {
3834 /*
3835 * Increasing number of lines/columns, do buffer first.
3836 * Use the maximal size in x and y direction.
3837 */
3838 if (sy < ySize)
3839 coordScreen.Y = ySize;
3840 else
3841 coordScreen.Y = sy;
3842 if (sx < xSize)
3843 coordScreen.X = xSize;
3844 else
3845 coordScreen.X = sx;
3846 SetConsoleScreenBufferSize(hConsole, coordScreen);
3847 }
3848 }
3849
3850 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3851 {
3852#ifdef MCH_WRITE_DUMP
3853 if (fdDump)
3854 {
3855 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3856 GetLastError());
3857 fflush(fdDump);
3858 }
3859#endif
3860 }
3861
3862 /* define the new console buffer size */
3863 coordScreen.X = xSize;
3864 coordScreen.Y = ySize;
3865
3866 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3867 {
3868#ifdef MCH_WRITE_DUMP
3869 if (fdDump)
3870 {
3871 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3872 GetLastError());
3873 fflush(fdDump);
3874 }
3875#endif
3876 }
3877}
3878
3879
3880/*
3881 * Set the console window to `Rows' * `Columns'
3882 */
3883 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003884mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003885{
3886 COORD coordScreen;
3887
3888 /* Don't change window size while still starting up */
3889 if (suppress_winsize != 0)
3890 {
3891 suppress_winsize = 2;
3892 return;
3893 }
3894
3895 if (term_console)
3896 {
3897 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3898
3899 /* Clamp Rows and Columns to reasonable values */
3900 if (Rows > coordScreen.Y)
3901 Rows = coordScreen.Y;
3902 if (Columns > coordScreen.X)
3903 Columns = coordScreen.X;
3904
3905 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3906 }
3907}
3908
3909/*
3910 * Rows and/or Columns has changed.
3911 */
3912 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003913mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003914{
3915 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3916}
3917
3918
3919/*
3920 * Called when started up, to set the winsize that was delayed.
3921 */
3922 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003923mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003924{
3925 if (suppress_winsize == 2)
3926 {
3927 suppress_winsize = 0;
3928 mch_set_shellsize();
3929 shell_resized();
3930 }
3931 suppress_winsize = 0;
3932}
3933#endif /* FEAT_GUI_W32 */
3934
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003935 static BOOL
3936vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003937 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003938 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01003939 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003940 STARTUPINFO *si,
3941 PROCESS_INFORMATION *pi)
3942{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003943#ifdef FEAT_MBYTE
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003944 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3945 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003946 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003947
3948 if (wcmd != NULL)
3949 {
3950 BOOL ret;
3951 ret = CreateProcessW(
3952 NULL, /* Executable name */
3953 wcmd, /* Command to execute */
3954 NULL, /* Process security attributes */
3955 NULL, /* Thread security attributes */
3956 inherit_handles, /* Inherit handles */
3957 flags, /* Creation flags */
3958 NULL, /* Environment */
3959 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003960 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003961 pi); /* Process information */
3962 vim_free(wcmd);
3963 return ret;
3964 }
3965 }
3966#endif
3967 return CreateProcess(
3968 NULL, /* Executable name */
3969 cmd, /* Command to execute */
3970 NULL, /* Process security attributes */
3971 NULL, /* Thread security attributes */
3972 inherit_handles, /* Inherit handles */
3973 flags, /* Creation flags */
3974 NULL, /* Environment */
3975 NULL, /* Current directory */
3976 si, /* Startup information */
3977 pi); /* Process information */
3978}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003979
3980
3981#if defined(FEAT_GUI_W32) || defined(PROTO)
3982
3983/*
3984 * Specialised version of system() for Win32 GUI mode.
3985 * This version proceeds as follows:
3986 * 1. Create a console window for use by the subprocess
3987 * 2. Run the subprocess (it gets the allocated console by default)
3988 * 3. Wait for the subprocess to terminate and get its exit code
3989 * 4. Prompt the user to press a key to close the console window
3990 */
3991 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003992mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003993{
3994 STARTUPINFO si;
3995 PROCESS_INFORMATION pi;
3996 DWORD ret = 0;
3997 HWND hwnd = GetFocus();
3998
3999 si.cb = sizeof(si);
4000 si.lpReserved = NULL;
4001 si.lpDesktop = NULL;
4002 si.lpTitle = NULL;
4003 si.dwFlags = STARTF_USESHOWWINDOW;
4004 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004005 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004006 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004007 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004008 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004009 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004010 else
4011 si.wShowWindow = SW_SHOWNORMAL;
4012 si.cbReserved2 = 0;
4013 si.lpReserved2 = NULL;
4014
Bram Moolenaar071d4272004-06-13 20:20:40 +00004015 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004016 vim_create_process(cmd, FALSE,
4017 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004018
4019 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004020 {
4021#ifdef FEAT_GUI
4022 int delay = 1;
4023
4024 /* Keep updating the window while waiting for the shell to finish. */
4025 for (;;)
4026 {
4027 MSG msg;
4028
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004029 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004030 {
4031 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004032 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004033 delay = 1;
4034 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004035 }
4036 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4037 break;
4038
4039 /* We start waiting for a very short time and then increase it, so
4040 * that we respond quickly when the process is quick, and don't
4041 * consume too much overhead when it's slow. */
4042 if (delay < 50)
4043 delay += 10;
4044 }
4045#else
4046 WaitForSingleObject(pi.hProcess, INFINITE);
4047#endif
4048
4049 /* Get the command exit code */
4050 GetExitCodeProcess(pi.hProcess, &ret);
4051 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004052
4053 /* Close the handles to the subprocess, so that it goes away */
4054 CloseHandle(pi.hThread);
4055 CloseHandle(pi.hProcess);
4056
4057 /* Try to get input focus back. Doesn't always work though. */
4058 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4059
4060 return ret;
4061}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004062
4063/*
4064 * Thread launched by the gui to send the current buffer data to the
4065 * process. This way avoid to hang up vim totally if the children
4066 * process take a long time to process the lines.
4067 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004068 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004069sub_process_writer(LPVOID param)
4070{
4071 HANDLE g_hChildStd_IN_Wr = param;
4072 linenr_T lnum = curbuf->b_op_start.lnum;
4073 DWORD len = 0;
4074 DWORD l;
4075 char_u *lp = ml_get(lnum);
4076 char_u *s;
4077 int written = 0;
4078
4079 for (;;)
4080 {
4081 l = (DWORD)STRLEN(lp + written);
4082 if (l == 0)
4083 len = 0;
4084 else if (lp[written] == NL)
4085 {
4086 /* NL -> NUL translation */
4087 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4088 }
4089 else
4090 {
4091 s = vim_strchr(lp + written, NL);
4092 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4093 s == NULL ? l : (DWORD)(s - (lp + written)),
4094 &len, NULL);
4095 }
4096 if (len == (int)l)
4097 {
4098 /* Finished a line, add a NL, unless this line should not have
4099 * one. */
4100 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004101 || (!curbuf->b_p_bin
4102 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004103 || (lnum != curbuf->b_no_eol_lnum
4104 && (lnum != curbuf->b_ml.ml_line_count
4105 || curbuf->b_p_eol)))
4106 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004107 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004108 }
4109
4110 ++lnum;
4111 if (lnum > curbuf->b_op_end.lnum)
4112 break;
4113
4114 lp = ml_get(lnum);
4115 written = 0;
4116 }
4117 else if (len > 0)
4118 written += len;
4119 }
4120
4121 /* finished all the lines, close pipe */
4122 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004123 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004124}
4125
4126
4127# define BUFLEN 100 /* length for buffer, stolen from unix version */
4128
4129/*
4130 * This function read from the children's stdout and write the
4131 * data on screen or in the buffer accordingly.
4132 */
4133 static void
4134dump_pipe(int options,
4135 HANDLE g_hChildStd_OUT_Rd,
4136 garray_T *ga,
4137 char_u buffer[],
4138 DWORD *buffer_off)
4139{
4140 DWORD availableBytes = 0;
4141 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004142 int ret;
4143 DWORD len;
4144 DWORD toRead;
4145 int repeatCount;
4146
4147 /* we query the pipe to see if there is any data to read
4148 * to avoid to perform a blocking read */
4149 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4150 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004151 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004152 NULL, /* number of read bytes */
4153 &availableBytes, /* available bytes total */
4154 NULL); /* byteLeft */
4155
4156 repeatCount = 0;
4157 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004158 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004159 {
4160 repeatCount++;
4161 toRead =
4162# ifdef FEAT_MBYTE
4163 (DWORD)(BUFLEN - *buffer_off);
4164# else
4165 (DWORD)BUFLEN;
4166# endif
4167 toRead = availableBytes < toRead ? availableBytes : toRead;
4168 ReadFile(g_hChildStd_OUT_Rd, buffer
4169# ifdef FEAT_MBYTE
4170 + *buffer_off, toRead
4171# else
4172 , toRead
4173# endif
4174 , &len, NULL);
4175
4176 /* If we haven't read anything, there is a problem */
4177 if (len == 0)
4178 break;
4179
4180 availableBytes -= len;
4181
4182 if (options & SHELL_READ)
4183 {
4184 /* Do NUL -> NL translation, append NL separated
4185 * lines to the current buffer. */
4186 for (i = 0; i < len; ++i)
4187 {
4188 if (buffer[i] == NL)
4189 append_ga_line(ga);
4190 else if (buffer[i] == NUL)
4191 ga_append(ga, NL);
4192 else
4193 ga_append(ga, buffer[i]);
4194 }
4195 }
4196# ifdef FEAT_MBYTE
4197 else if (has_mbyte)
4198 {
4199 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004200 int c;
4201 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004202
4203 len += *buffer_off;
4204 buffer[len] = NUL;
4205
4206 /* Check if the last character in buffer[] is
4207 * incomplete, keep these bytes for the next
4208 * round. */
4209 for (p = buffer; p < buffer + len; p += l)
4210 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004211 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004212 if (l == 0)
4213 l = 1; /* NUL byte? */
4214 else if (MB_BYTE2LEN(*p) != l)
4215 break;
4216 }
4217 if (p == buffer) /* no complete character */
4218 {
4219 /* avoid getting stuck at an illegal byte */
4220 if (len >= 12)
4221 ++p;
4222 else
4223 {
4224 *buffer_off = len;
4225 return;
4226 }
4227 }
4228 c = *p;
4229 *p = NUL;
4230 msg_puts(buffer);
4231 if (p < buffer + len)
4232 {
4233 *p = c;
4234 *buffer_off = (DWORD)((buffer + len) - p);
4235 mch_memmove(buffer, p, *buffer_off);
4236 return;
4237 }
4238 *buffer_off = 0;
4239 }
4240# endif /* FEAT_MBYTE */
4241 else
4242 {
4243 buffer[len] = NUL;
4244 msg_puts(buffer);
4245 }
4246
4247 windgoto(msg_row, msg_col);
4248 cursor_on();
4249 out_flush();
4250 }
4251}
4252
4253/*
4254 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4255 * for communication and doesn't open any new window.
4256 */
4257 static int
4258mch_system_piped(char *cmd, int options)
4259{
4260 STARTUPINFO si;
4261 PROCESS_INFORMATION pi;
4262 DWORD ret = 0;
4263
4264 HANDLE g_hChildStd_IN_Rd = NULL;
4265 HANDLE g_hChildStd_IN_Wr = NULL;
4266 HANDLE g_hChildStd_OUT_Rd = NULL;
4267 HANDLE g_hChildStd_OUT_Wr = NULL;
4268
4269 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4270 DWORD len;
4271
4272 /* buffer used to receive keys */
4273 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4274 int ta_len = 0; /* valid bytes in ta_buf[] */
4275
4276 DWORD i;
4277 int c;
4278 int noread_cnt = 0;
4279 garray_T ga;
4280 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004281 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004282 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004283
4284 SECURITY_ATTRIBUTES saAttr;
4285
4286 /* Set the bInheritHandle flag so pipe handles are inherited. */
4287 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4288 saAttr.bInheritHandle = TRUE;
4289 saAttr.lpSecurityDescriptor = NULL;
4290
4291 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4292 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004293 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004294 /* Create a pipe for the child process's STDIN. */
4295 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4296 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004297 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004298 {
4299 CloseHandle(g_hChildStd_IN_Rd);
4300 CloseHandle(g_hChildStd_IN_Wr);
4301 CloseHandle(g_hChildStd_OUT_Rd);
4302 CloseHandle(g_hChildStd_OUT_Wr);
4303 MSG_PUTS(_("\nCannot create pipes\n"));
4304 }
4305
4306 si.cb = sizeof(si);
4307 si.lpReserved = NULL;
4308 si.lpDesktop = NULL;
4309 si.lpTitle = NULL;
4310 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4311
4312 /* set-up our file redirection */
4313 si.hStdError = g_hChildStd_OUT_Wr;
4314 si.hStdOutput = g_hChildStd_OUT_Wr;
4315 si.hStdInput = g_hChildStd_IN_Rd;
4316 si.wShowWindow = SW_HIDE;
4317 si.cbReserved2 = 0;
4318 si.lpReserved2 = NULL;
4319
4320 if (options & SHELL_READ)
4321 ga_init2(&ga, 1, BUFLEN);
4322
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004323 if (cmd != NULL)
4324 {
4325 p = (char *)vim_strsave((char_u *)cmd);
4326 if (p != NULL)
4327 unescape_shellxquote((char_u *)p, p_sxe);
4328 else
4329 p = cmd;
4330 }
4331
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004332 /* Now, run the command.
4333 * About "Inherit handles" being TRUE: this command can be litigious,
4334 * handle inheritance was deactivated for pending temp file, but, if we
4335 * deactivate it, the pipes don't work for some reason. */
4336 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004337
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004338 if (p != cmd)
4339 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004340
4341 /* Close our unused side of the pipes */
4342 CloseHandle(g_hChildStd_IN_Rd);
4343 CloseHandle(g_hChildStd_OUT_Wr);
4344
4345 if (options & SHELL_WRITE)
4346 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004347 HANDLE thread = (HANDLE)
4348 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004349 0, /* default stack size */
4350 sub_process_writer, /* function to be executed */
4351 g_hChildStd_IN_Wr, /* parameter */
4352 0, /* creation flag, start immediately */
4353 NULL); /* we don't care about thread id */
4354 CloseHandle(thread);
4355 g_hChildStd_IN_Wr = NULL;
4356 }
4357
4358 /* Keep updating the window while waiting for the shell to finish. */
4359 for (;;)
4360 {
4361 MSG msg;
4362
Bram Moolenaar175d0702013-12-11 18:36:33 +01004363 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004364 {
4365 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004366 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004367 }
4368
4369 /* write pipe information in the window */
4370 if ((options & (SHELL_READ|SHELL_WRITE))
4371# ifdef FEAT_GUI
4372 || gui.in_use
4373# endif
4374 )
4375 {
4376 len = 0;
4377 if (!(options & SHELL_EXPAND)
4378 && ((options &
4379 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4380 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4381# ifdef FEAT_GUI
4382 || gui.in_use
4383# endif
4384 )
4385 && (ta_len > 0 || noread_cnt > 4))
4386 {
4387 if (ta_len == 0)
4388 {
4389 /* Get extra characters when we don't have any. Reset the
4390 * counter and timer. */
4391 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004392 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4393 }
4394 if (ta_len > 0 || len > 0)
4395 {
4396 /*
4397 * For pipes: Check for CTRL-C: send interrupt signal to
4398 * child. Check for CTRL-D: EOF, close pipe to child.
4399 */
4400 if (len == 1 && cmd != NULL)
4401 {
4402 if (ta_buf[ta_len] == Ctrl_C)
4403 {
4404 /* Learn what exit code is expected, for
4405 * now put 9 as SIGKILL */
4406 TerminateProcess(pi.hProcess, 9);
4407 }
4408 if (ta_buf[ta_len] == Ctrl_D)
4409 {
4410 CloseHandle(g_hChildStd_IN_Wr);
4411 g_hChildStd_IN_Wr = NULL;
4412 }
4413 }
4414
4415 /* replace K_BS by <BS> and K_DEL by <DEL> */
4416 for (i = ta_len; i < ta_len + len; ++i)
4417 {
4418 if (ta_buf[i] == CSI && len - i > 2)
4419 {
4420 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4421 if (c == K_DEL || c == K_KDEL || c == K_BS)
4422 {
4423 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4424 (size_t)(len - i - 2));
4425 if (c == K_DEL || c == K_KDEL)
4426 ta_buf[i] = DEL;
4427 else
4428 ta_buf[i] = Ctrl_H;
4429 len -= 2;
4430 }
4431 }
4432 else if (ta_buf[i] == '\r')
4433 ta_buf[i] = '\n';
4434# ifdef FEAT_MBYTE
4435 if (has_mbyte)
4436 i += (*mb_ptr2len_len)(ta_buf + i,
4437 ta_len + len - i) - 1;
4438# endif
4439 }
4440
4441 /*
4442 * For pipes: echo the typed characters. For a pty this
4443 * does not seem to work.
4444 */
4445 for (i = ta_len; i < ta_len + len; ++i)
4446 {
4447 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4448 msg_putchar(ta_buf[i]);
4449# ifdef FEAT_MBYTE
4450 else if (has_mbyte)
4451 {
4452 int l = (*mb_ptr2len)(ta_buf + i);
4453
4454 msg_outtrans_len(ta_buf + i, l);
4455 i += l - 1;
4456 }
4457# endif
4458 else
4459 msg_outtrans_len(ta_buf + i, 1);
4460 }
4461 windgoto(msg_row, msg_col);
4462 out_flush();
4463
4464 ta_len += len;
4465
4466 /*
4467 * Write the characters to the child, unless EOF has been
4468 * typed for pipes. Write one character at a time, to
4469 * avoid losing too much typeahead. When writing buffer
4470 * lines, drop the typed characters (only check for
4471 * CTRL-C).
4472 */
4473 if (options & SHELL_WRITE)
4474 ta_len = 0;
4475 else if (g_hChildStd_IN_Wr != NULL)
4476 {
4477 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4478 1, &len, NULL);
4479 // if we are typing in, we want to keep things reactive
4480 delay = 1;
4481 if (len > 0)
4482 {
4483 ta_len -= len;
4484 mch_memmove(ta_buf, ta_buf + len, ta_len);
4485 }
4486 }
4487 }
4488 }
4489 }
4490
4491 if (ta_len)
4492 ui_inchar_undo(ta_buf, ta_len);
4493
4494 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4495 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004496 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004497 break;
4498 }
4499
4500 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004501 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004502
4503 /* We start waiting for a very short time and then increase it, so
4504 * that we respond quickly when the process is quick, and don't
4505 * consume too much overhead when it's slow. */
4506 if (delay < 50)
4507 delay += 10;
4508 }
4509
4510 /* Close the pipe */
4511 CloseHandle(g_hChildStd_OUT_Rd);
4512 if (g_hChildStd_IN_Wr != NULL)
4513 CloseHandle(g_hChildStd_IN_Wr);
4514
4515 WaitForSingleObject(pi.hProcess, INFINITE);
4516
4517 /* Get the command exit code */
4518 GetExitCodeProcess(pi.hProcess, &ret);
4519
4520 if (options & SHELL_READ)
4521 {
4522 if (ga.ga_len > 0)
4523 {
4524 append_ga_line(&ga);
4525 /* remember that the NL was missing */
4526 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4527 }
4528 else
4529 curbuf->b_no_eol_lnum = 0;
4530 ga_clear(&ga);
4531 }
4532
4533 /* Close the handles to the subprocess, so that it goes away */
4534 CloseHandle(pi.hThread);
4535 CloseHandle(pi.hProcess);
4536
4537 return ret;
4538}
4539
4540 static int
4541mch_system(char *cmd, int options)
4542{
4543 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004544 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004545 return mch_system_piped(cmd, options);
4546 else
4547 return mch_system_classic(cmd, options);
4548}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004549#else
4550
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004551# ifdef FEAT_MBYTE
4552 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004553mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004554{
4555 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4556 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004557 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004558 if (wcmd != NULL)
4559 {
4560 int ret = _wsystem(wcmd);
4561 vim_free(wcmd);
4562 return ret;
4563 }
4564 }
4565 return system(cmd);
4566}
4567# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004568# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004569# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004570
4571#endif
4572
4573/*
4574 * Either execute a command by calling the shell or start a new shell
4575 */
4576 int
4577mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004578 char_u *cmd,
4579 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004580{
4581 int x = 0;
4582 int tmode = cur_tmode;
4583#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004584 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004585# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004586 int did_set_title = FALSE;
4587
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004588 /* Change the title to reflect that we are in a subshell. */
4589 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4590 {
4591 WCHAR szShellTitle[512];
4592
4593 if (GetConsoleTitleW(szShellTitle,
4594 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4595 {
4596 if (cmd == NULL)
4597 wcscat(szShellTitle, L" :sh");
4598 else
4599 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004600 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004601
4602 if (wn != NULL)
4603 {
4604 wcscat(szShellTitle, L" - !");
4605 if ((wcslen(szShellTitle) + wcslen(wn) <
4606 sizeof(szShellTitle)/sizeof(WCHAR)))
4607 wcscat(szShellTitle, wn);
4608 SetConsoleTitleW(szShellTitle);
4609 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004610 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004611 }
4612 }
4613 }
4614 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004615 if (!did_set_title)
4616# endif
4617 /* Change the title to reflect that we are in a subshell. */
4618 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004619 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004620 if (cmd == NULL)
4621 strcat(szShellTitle, " :sh");
4622 else
4623 {
4624 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004625 if ((strlen(szShellTitle) + strlen((char *)cmd)
4626 < sizeof(szShellTitle)))
4627 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004628 }
4629 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004630 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004631#endif
4632
4633 out_flush();
4634
4635#ifdef MCH_WRITE_DUMP
4636 if (fdDump)
4637 {
4638 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4639 fflush(fdDump);
4640 }
4641#endif
4642
4643 /*
4644 * Catch all deadly signals while running the external command, because a
4645 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4646 */
4647 signal(SIGINT, SIG_IGN);
4648#if defined(__GNUC__) && !defined(__MINGW32__)
4649 signal(SIGKILL, SIG_IGN);
4650#else
4651 signal(SIGBREAK, SIG_IGN);
4652#endif
4653 signal(SIGILL, SIG_IGN);
4654 signal(SIGFPE, SIG_IGN);
4655 signal(SIGSEGV, SIG_IGN);
4656 signal(SIGTERM, SIG_IGN);
4657 signal(SIGABRT, SIG_IGN);
4658
4659 if (options & SHELL_COOKED)
4660 settmode(TMODE_COOK); /* set to normal mode */
4661
4662 if (cmd == NULL)
4663 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004664 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004665 }
4666 else
4667 {
4668 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004669 char_u *newcmd = NULL;
4670 char_u *cmdbase = cmd;
4671 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004672
4673 /* Skip a leading ", ( and "(. */
4674 if (*cmdbase == '"' )
4675 ++cmdbase;
4676 if (*cmdbase == '(')
4677 ++cmdbase;
4678
4679 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4680 {
4681 STARTUPINFO si;
4682 PROCESS_INFORMATION pi;
4683 DWORD flags = CREATE_NEW_CONSOLE;
4684 char_u *p;
4685
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004686 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004687 si.cb = sizeof(si);
4688 si.lpReserved = NULL;
4689 si.lpDesktop = NULL;
4690 si.lpTitle = NULL;
4691 si.dwFlags = 0;
4692 si.cbReserved2 = 0;
4693 si.lpReserved2 = NULL;
4694
4695 cmdbase = skipwhite(cmdbase + 5);
4696 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4697 && vim_iswhite(cmdbase[4]))
4698 {
4699 cmdbase = skipwhite(cmdbase + 4);
4700 si.dwFlags = STARTF_USESHOWWINDOW;
4701 si.wShowWindow = SW_SHOWMINNOACTIVE;
4702 }
4703 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4704 && vim_iswhite(cmdbase[2]))
4705 {
4706 cmdbase = skipwhite(cmdbase + 2);
4707 flags = CREATE_NO_WINDOW;
4708 si.dwFlags = STARTF_USESTDHANDLES;
4709 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004710 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004711 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004712 NULL, // Security att.
4713 OPEN_EXISTING, // Open flags
4714 FILE_ATTRIBUTE_NORMAL, // File att.
4715 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004716 si.hStdOutput = si.hStdInput;
4717 si.hStdError = si.hStdInput;
4718 }
4719
4720 /* Remove a trailing ", ) and )" if they have a match
4721 * at the start of the command. */
4722 if (cmdbase > cmd)
4723 {
4724 p = cmdbase + STRLEN(cmdbase);
4725 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4726 *--p = NUL;
4727 if (p > cmdbase && p[-1] == ')'
4728 && (*cmd =='(' || cmd[1] == '('))
4729 *--p = NUL;
4730 }
4731
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004732 newcmd = cmdbase;
4733 unescape_shellxquote(cmdbase, p_sxe);
4734
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004735 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004736 * If creating new console, arguments are passed to the
4737 * 'cmd.exe' as-is. If it's not, arguments are not treated
4738 * correctly for current 'cmd.exe'. So unescape characters in
4739 * shellxescape except '|' for avoiding to be treated as
4740 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004741 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004742 if (flags != CREATE_NEW_CONSOLE)
4743 {
4744 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004745 char_u *cmd_shell = mch_getenv("COMSPEC");
4746
4747 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004748 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004749
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004750 subcmd = vim_strsave_escaped_ext(cmdbase,
4751 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004752 if (subcmd != NULL)
4753 {
4754 /* make "cmd.exe /c arguments" */
4755 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004756 newcmd = lalloc(cmdlen, TRUE);
4757 if (newcmd != NULL)
4758 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004759 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004760 else
4761 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004762 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004763 }
4764 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004765
4766 /*
4767 * Now, start the command as a process, so that it doesn't
4768 * inherit our handles which causes unpleasant dangling swap
4769 * files if we exit before the spawned process
4770 */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004771 if (vim_create_process((char *)newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004772 x = 0;
4773 else
4774 {
4775 x = -1;
4776#ifdef FEAT_GUI_W32
4777 EMSG(_("E371: Command not found"));
4778#endif
4779 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004780
4781 if (newcmd != cmdbase)
4782 vim_free(newcmd);
4783
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004784 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004785 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004786 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004787 CloseHandle(si.hStdInput);
4788 }
4789 /* Close the handles to the subprocess, so that it goes away */
4790 CloseHandle(pi.hThread);
4791 CloseHandle(pi.hProcess);
4792 }
4793 else
4794 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004795 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004796#ifdef FEAT_GUI_W32
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004797 (!p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004798#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004799 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4800
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004801 newcmd = lalloc(cmdlen, TRUE);
4802 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004803 {
4804#if defined(FEAT_GUI_W32)
4805 if (need_vimrun_warning)
4806 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01004807 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
4808 "External commands will not pause after completion.\n"
4809 "See :help win32-vimrun for more information.");
4810 char *title = _("Vim Warning");
4811# ifdef FEAT_MBYTE
4812 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4813 {
4814 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
4815 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
4816
4817 if (wmsg != NULL && wtitle != NULL)
4818 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
4819 vim_free(wmsg);
4820 vim_free(wtitle);
4821 }
4822 else
4823# endif
4824 MessageBox(NULL, msg, title, MB_ICONWARNING);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004825 need_vimrun_warning = FALSE;
4826 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004827 if (!s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004828 /* Use vimrun to execute the command. It opens a console
4829 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004830 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004831 vimrun_path,
4832 (msg_silent != 0 || (options & SHELL_DOOUT))
4833 ? "-s " : "",
4834 p_sh, p_shcf, cmd);
4835 else
4836#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004837 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004838 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004839 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004840 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004841 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004842 }
4843 }
4844
4845 if (tmode == TMODE_RAW)
4846 settmode(TMODE_RAW); /* set to raw mode */
4847
4848 /* Print the return value, unless "vimrun" was used. */
4849 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4850#if defined(FEAT_GUI_W32)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004851 && ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004852#endif
4853 )
4854 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004855 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004856 msg_putchar('\n');
4857 }
4858#ifdef FEAT_TITLE
4859 resettitle();
4860#endif
4861
4862 signal(SIGINT, SIG_DFL);
4863#if defined(__GNUC__) && !defined(__MINGW32__)
4864 signal(SIGKILL, SIG_DFL);
4865#else
4866 signal(SIGBREAK, SIG_DFL);
4867#endif
4868 signal(SIGILL, SIG_DFL);
4869 signal(SIGFPE, SIG_DFL);
4870 signal(SIGSEGV, SIG_DFL);
4871 signal(SIGTERM, SIG_DFL);
4872 signal(SIGABRT, SIG_DFL);
4873
4874 return x;
4875}
4876
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01004877#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004878 static HANDLE
4879job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01004880 char_u *fname,
4881 DWORD dwDesiredAccess,
4882 DWORD dwShareMode,
4883 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
4884 DWORD dwCreationDisposition,
4885 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004886{
4887 HANDLE h;
4888# ifdef FEAT_MBYTE
4889 WCHAR *wn = NULL;
4890 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4891 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +01004892 wn = enc_to_utf16(fname, NULL);
4893 if (wn != NULL)
4894 {
4895 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
4896 lpSecurityAttributes, dwCreationDisposition,
4897 dwFlagsAndAttributes, NULL);
4898 vim_free(wn);
4899 }
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004900 }
4901 if (wn == NULL)
4902# endif
Bram Moolenaar972c3b82017-01-12 21:44:49 +01004903 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
4904 lpSecurityAttributes, dwCreationDisposition,
4905 dwFlagsAndAttributes, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004906 return h;
4907}
4908
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004909 void
Bram Moolenaar9a6e33a2016-02-16 19:25:12 +01004910mch_start_job(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004911{
4912 STARTUPINFO si;
4913 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02004914 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004915 SECURITY_ATTRIBUTES saAttr;
4916 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01004917 HANDLE ifd[2];
4918 HANDLE ofd[2];
4919 HANDLE efd[2];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004920
4921 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
4922 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
4923 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
4924 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
4925 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
4926 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
4927 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
4928
4929 if (use_out_for_err && use_null_for_out)
4930 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01004931
4932 ifd[0] = INVALID_HANDLE_VALUE;
4933 ifd[1] = INVALID_HANDLE_VALUE;
4934 ofd[0] = INVALID_HANDLE_VALUE;
4935 ofd[1] = INVALID_HANDLE_VALUE;
4936 efd[0] = INVALID_HANDLE_VALUE;
4937 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004938
Bram Moolenaar14207f42016-10-27 21:13:10 +02004939 jo = CreateJobObject(NULL, NULL);
4940 if (jo == NULL)
4941 {
4942 job->jv_status = JOB_FAILED;
4943 goto failed;
4944 }
4945
Bram Moolenaar76467df2016-02-12 19:30:26 +01004946 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004947 ZeroMemory(&si, sizeof(si));
4948 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01004949 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01004950 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004951
Bram Moolenaard8070362016-02-15 21:56:54 +01004952 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4953 saAttr.bInheritHandle = TRUE;
4954 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01004955
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01004956 if (use_file_for_in)
4957 {
4958 char_u *fname = options->jo_io_name[PART_IN];
4959
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004960 ifd[0] = job_io_file_open(fname, GENERIC_READ,
4961 FILE_SHARE_READ | FILE_SHARE_WRITE,
4962 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
4963 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01004964 {
4965 EMSG2(_(e_notopen), fname);
4966 goto failed;
4967 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01004968 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004969 else if (!use_null_for_in &&
4970 (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004971 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01004972 goto failed;
4973
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01004974 if (use_file_for_out)
4975 {
4976 char_u *fname = options->jo_io_name[PART_OUT];
4977
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004978 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
4979 FILE_SHARE_READ | FILE_SHARE_WRITE,
4980 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
4981 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01004982 {
4983 EMSG2(_(e_notopen), fname);
4984 goto failed;
4985 }
4986 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004987 else if (!use_null_for_out &&
4988 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004989 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01004990 goto failed;
4991
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01004992 if (use_file_for_err)
4993 {
4994 char_u *fname = options->jo_io_name[PART_ERR];
4995
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004996 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
4997 FILE_SHARE_READ | FILE_SHARE_WRITE,
4998 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
4999 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005000 {
5001 EMSG2(_(e_notopen), fname);
5002 goto failed;
5003 }
5004 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005005 else if (!use_out_for_err && !use_null_for_err &&
5006 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005007 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005008 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005009
Bram Moolenaard8070362016-02-15 21:56:54 +01005010 si.dwFlags |= STARTF_USESTDHANDLES;
5011 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005012 si.hStdOutput = ofd[1];
5013 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5014
5015 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5016 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005017 if (options->jo_set & JO_CHANNEL)
5018 {
5019 channel = options->jo_channel;
5020 if (channel != NULL)
5021 ++channel->ch_refcount;
5022 }
5023 else
5024 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005025 if (channel == NULL)
5026 goto failed;
5027 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005028
5029 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005030 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005031 CREATE_DEFAULT_ERROR_MODE |
5032 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005033 CREATE_NEW_CONSOLE,
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005034 &si, &pi))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005035 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005036 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005037 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005038 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005039 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005040
Bram Moolenaar14207f42016-10-27 21:13:10 +02005041 if (!AssignProcessToJobObject(jo, pi.hProcess))
5042 {
5043 /* if failing, switch the way to terminate
5044 * process with TerminateProcess. */
5045 CloseHandle(jo);
5046 jo = NULL;
5047 }
5048 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005049 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005050 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005051 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005052 job->jv_status = JOB_STARTED;
5053
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005054 CloseHandle(ifd[0]);
5055 CloseHandle(ofd[1]);
5056 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005057 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005058
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005059 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005060 if (channel != NULL)
5061 {
5062 channel_set_pipes(channel,
5063 use_file_for_in || use_null_for_in
5064 ? INVALID_FD : (sock_T)ifd[1],
5065 use_file_for_out || use_null_for_out
5066 ? INVALID_FD : (sock_T)ofd[0],
5067 use_out_for_err || use_file_for_err || use_null_for_err
5068 ? INVALID_FD : (sock_T)efd[0]);
5069 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005070 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005071 return;
5072
5073failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005074 CloseHandle(ifd[0]);
5075 CloseHandle(ofd[0]);
5076 CloseHandle(efd[0]);
5077 CloseHandle(ifd[1]);
5078 CloseHandle(ofd[1]);
5079 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005080 channel_unref(channel);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005081}
5082
5083 char *
5084mch_job_status(job_T *job)
5085{
5086 DWORD dwExitCode = 0;
5087
Bram Moolenaar76467df2016-02-12 19:30:26 +01005088 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5089 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005090 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005091 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005092 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005093 {
5094 ch_log(job->jv_channel, "Job ended");
5095 job->jv_status = JOB_ENDED;
5096 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005097 return "dead";
5098 }
5099 return "run";
5100}
5101
Bram Moolenaar97792de2016-10-15 18:36:49 +02005102 job_T *
5103mch_detect_ended_job(job_T *job_list)
5104{
5105 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5106 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5107 job_T *job = job_list;
5108
5109 while (job != NULL)
5110 {
5111 DWORD n;
5112 DWORD result;
5113
5114 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5115 && job != NULL; job = job->jv_next)
5116 {
5117 if (job->jv_status == JOB_STARTED)
5118 {
5119 jobHandles[n] = job->jv_proc_info.hProcess;
5120 jobArray[n] = job;
5121 ++n;
5122 }
5123 }
5124 if (n == 0)
5125 continue;
5126 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5127 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5128 {
5129 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5130
5131 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5132 return wait_job;
5133 }
5134 }
5135 return NULL;
5136}
5137
Bram Moolenaarfb630902016-10-29 14:55:00 +02005138 static BOOL
5139terminate_all(HANDLE process, int code)
5140{
5141 PROCESSENTRY32 pe;
5142 HANDLE h = INVALID_HANDLE_VALUE;
5143 DWORD pid = GetProcessId(process);
5144
5145 if (pid != 0)
5146 {
5147 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5148 if (h != INVALID_HANDLE_VALUE)
5149 {
5150 pe.dwSize = sizeof(PROCESSENTRY32);
5151 if (!Process32First(h, &pe))
5152 goto theend;
5153
5154 do
5155 {
5156 if (pe.th32ParentProcessID == pid)
5157 {
5158 HANDLE ph = OpenProcess(
5159 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5160 if (ph != NULL)
5161 {
5162 terminate_all(ph, code);
5163 CloseHandle(ph);
5164 }
5165 }
5166 } while (Process32Next(h, &pe));
5167
5168 CloseHandle(h);
5169 }
5170 }
5171
5172theend:
5173 return TerminateProcess(process, code);
5174}
5175
5176/*
5177 * Send a (deadly) signal to "job".
5178 * Return FAIL if it didn't work.
5179 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005180 int
5181mch_stop_job(job_T *job, char_u *how)
5182{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005183 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005184
Bram Moolenaar923d9262016-02-25 20:56:01 +01005185 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005186 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005187 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005188 if (job->jv_job_object != NULL)
5189 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaarfb630902016-10-29 14:55:00 +02005190 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005191 }
5192
5193 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5194 return FAIL;
5195 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005196 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5197 job->jv_proc_info.dwProcessId)
5198 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005199 FreeConsole();
5200 return ret;
5201}
5202
5203/*
5204 * Clear the data related to "job".
5205 */
5206 void
5207mch_clear_job(job_T *job)
5208{
5209 if (job->jv_status != JOB_FAILED)
5210 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005211 if (job->jv_job_object != NULL)
5212 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005213 CloseHandle(job->jv_proc_info.hProcess);
5214 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005215}
5216#endif
5217
Bram Moolenaar071d4272004-06-13 20:20:40 +00005218
5219#ifndef FEAT_GUI_W32
5220
5221/*
5222 * Start termcap mode
5223 */
5224 static void
5225termcap_mode_start(void)
5226{
5227 DWORD cmodein;
5228
5229 if (g_fTermcapMode)
5230 return;
5231
5232 SaveConsoleBuffer(&g_cbNonTermcap);
5233
5234 if (g_cbTermcap.IsValid)
5235 {
5236 /*
5237 * We've been in termcap mode before. Restore certain screen
5238 * characteristics, including the buffer size and the window
5239 * size. Since we will be redrawing the screen, we don't need
5240 * to restore the actual contents of the buffer.
5241 */
5242 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5243 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5244 Rows = g_cbTermcap.Info.dwSize.Y;
5245 Columns = g_cbTermcap.Info.dwSize.X;
5246 }
5247 else
5248 {
5249 /*
5250 * This is our first time entering termcap mode. Clear the console
5251 * screen buffer, and resize the buffer to match the current window
5252 * size. We will use this as the size of our editing environment.
5253 */
5254 ClearConsoleBuffer(g_attrCurrent);
5255 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5256 }
5257
5258#ifdef FEAT_TITLE
5259 resettitle();
5260#endif
5261
5262 GetConsoleMode(g_hConIn, &cmodein);
5263#ifdef FEAT_MOUSE
5264 if (g_fMouseActive)
5265 cmodein |= ENABLE_MOUSE_INPUT;
5266 else
5267 cmodein &= ~ENABLE_MOUSE_INPUT;
5268#endif
5269 cmodein |= ENABLE_WINDOW_INPUT;
5270 SetConsoleMode(g_hConIn, cmodein);
5271
5272 redraw_later_clear();
5273 g_fTermcapMode = TRUE;
5274}
5275
5276
5277/*
5278 * End termcap mode
5279 */
5280 static void
5281termcap_mode_end(void)
5282{
5283 DWORD cmodein;
5284 ConsoleBuffer *cb;
5285 COORD coord;
5286 DWORD dwDummy;
5287
5288 if (!g_fTermcapMode)
5289 return;
5290
5291 SaveConsoleBuffer(&g_cbTermcap);
5292
5293 GetConsoleMode(g_hConIn, &cmodein);
5294 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5295 SetConsoleMode(g_hConIn, cmodein);
5296
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005297#ifdef FEAT_RESTORE_ORIG_SCREEN
5298 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5299#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005300 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005301#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005302 RestoreConsoleBuffer(cb, p_rs);
5303 SetConsoleCursorInfo(g_hConOut, &g_cci);
5304
5305 if (p_rs || exiting)
5306 {
5307 /*
5308 * Clear anything that happens to be on the current line.
5309 */
5310 coord.X = 0;
5311 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5312 FillConsoleOutputCharacter(g_hConOut, ' ',
5313 cb->Info.dwSize.X, coord, &dwDummy);
5314 /*
5315 * The following is just for aesthetics. If we are exiting without
5316 * restoring the screen, then we want to have a prompt string
5317 * appear at the bottom line. However, the command interpreter
5318 * seems to always advance the cursor one line before displaying
5319 * the prompt string, which causes the screen to scroll. To
5320 * counter this, move the cursor up one line before exiting.
5321 */
5322 if (exiting && !p_rs)
5323 coord.Y--;
5324 /*
5325 * Position the cursor at the leftmost column of the desired row.
5326 */
5327 SetConsoleCursorPosition(g_hConOut, coord);
5328 }
5329
5330 g_fTermcapMode = FALSE;
5331}
5332#endif /* FEAT_GUI_W32 */
5333
5334
5335#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005336/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005337 void
5338mch_write(
5339 char_u *s,
5340 int len)
5341{
5342 /* never used */
5343}
5344
5345#else
5346
5347/*
5348 * clear `n' chars, starting from `coord'
5349 */
5350 static void
5351clear_chars(
5352 COORD coord,
5353 DWORD n)
5354{
5355 DWORD dwDummy;
5356
5357 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5358 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5359}
5360
5361
5362/*
5363 * Clear the screen
5364 */
5365 static void
5366clear_screen(void)
5367{
5368 g_coord.X = g_coord.Y = 0;
5369 clear_chars(g_coord, Rows * Columns);
5370}
5371
5372
5373/*
5374 * Clear to end of display
5375 */
5376 static void
5377clear_to_end_of_display(void)
5378{
5379 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5380 * Columns + (Columns - g_coord.X));
5381}
5382
5383
5384/*
5385 * Clear to end of line
5386 */
5387 static void
5388clear_to_end_of_line(void)
5389{
5390 clear_chars(g_coord, Columns - g_coord.X);
5391}
5392
5393
5394/*
5395 * Scroll the scroll region up by `cLines' lines
5396 */
5397 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005398scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005399{
5400 COORD oldcoord = g_coord;
5401
5402 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5403 delete_lines(cLines);
5404
5405 g_coord = oldcoord;
5406}
5407
5408
5409/*
5410 * Set the scroll region
5411 */
5412 static void
5413set_scroll_region(
5414 unsigned left,
5415 unsigned top,
5416 unsigned right,
5417 unsigned bottom)
5418{
5419 if (left >= right
5420 || top >= bottom
5421 || right > (unsigned) Columns - 1
5422 || bottom > (unsigned) Rows - 1)
5423 return;
5424
5425 g_srScrollRegion.Left = left;
5426 g_srScrollRegion.Top = top;
5427 g_srScrollRegion.Right = right;
5428 g_srScrollRegion.Bottom = bottom;
5429}
5430
5431
5432/*
5433 * Insert `cLines' lines at the current cursor position
5434 */
5435 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005436insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005437{
5438 SMALL_RECT source;
5439 COORD dest;
5440 CHAR_INFO fill;
5441
5442 dest.X = 0;
5443 dest.Y = g_coord.Y + cLines;
5444
5445 source.Left = 0;
5446 source.Top = g_coord.Y;
5447 source.Right = g_srScrollRegion.Right;
5448 source.Bottom = g_srScrollRegion.Bottom - cLines;
5449
5450 fill.Char.AsciiChar = ' ';
5451 fill.Attributes = g_attrCurrent;
5452
5453 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5454
5455 /* Here we have to deal with a win32 console flake: If the scroll
5456 * region looks like abc and we scroll c to a and fill with d we get
5457 * cbd... if we scroll block c one line at a time to a, we get cdd...
5458 * vim expects cdd consistently... So we have to deal with that
5459 * here... (this also occurs scrolling the same way in the other
5460 * direction). */
5461
5462 if (source.Bottom < dest.Y)
5463 {
5464 COORD coord;
5465
5466 coord.X = 0;
5467 coord.Y = source.Bottom;
5468 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5469 }
5470}
5471
5472
5473/*
5474 * Delete `cLines' lines at the current cursor position
5475 */
5476 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005477delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005478{
5479 SMALL_RECT source;
5480 COORD dest;
5481 CHAR_INFO fill;
5482 int nb;
5483
5484 dest.X = 0;
5485 dest.Y = g_coord.Y;
5486
5487 source.Left = 0;
5488 source.Top = g_coord.Y + cLines;
5489 source.Right = g_srScrollRegion.Right;
5490 source.Bottom = g_srScrollRegion.Bottom;
5491
5492 fill.Char.AsciiChar = ' ';
5493 fill.Attributes = g_attrCurrent;
5494
5495 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5496
5497 /* Here we have to deal with a win32 console flake: If the scroll
5498 * region looks like abc and we scroll c to a and fill with d we get
5499 * cbd... if we scroll block c one line at a time to a, we get cdd...
5500 * vim expects cdd consistently... So we have to deal with that
5501 * here... (this also occurs scrolling the same way in the other
5502 * direction). */
5503
5504 nb = dest.Y + (source.Bottom - source.Top) + 1;
5505
5506 if (nb < source.Top)
5507 {
5508 COORD coord;
5509
5510 coord.X = 0;
5511 coord.Y = nb;
5512 clear_chars(coord, Columns * (source.Top - nb));
5513 }
5514}
5515
5516
5517/*
5518 * Set the cursor position
5519 */
5520 static void
5521gotoxy(
5522 unsigned x,
5523 unsigned y)
5524{
5525 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5526 return;
5527
5528 /* external cursor coords are 1-based; internal are 0-based */
5529 g_coord.X = x - 1;
5530 g_coord.Y = y - 1;
5531 SetConsoleCursorPosition(g_hConOut, g_coord);
5532}
5533
5534
5535/*
5536 * Set the current text attribute = (foreground | background)
5537 * See ../doc/os_win32.txt for the numbers.
5538 */
5539 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005540textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005541{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005542 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005543
5544 SetConsoleTextAttribute(g_hConOut, wAttr);
5545}
5546
5547
5548 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005549textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005550{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005551 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005552
5553 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5554}
5555
5556
5557 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005558textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005559{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005560 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005561
5562 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5563}
5564
5565
5566/*
5567 * restore the default text attribute (whatever we started with)
5568 */
5569 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005570normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005571{
5572 textattr(g_attrDefault);
5573}
5574
5575
5576static WORD g_attrPreStandout = 0;
5577
5578/*
5579 * Make the text standout, by brightening it
5580 */
5581 static void
5582standout(void)
5583{
5584 g_attrPreStandout = g_attrCurrent;
5585 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5586}
5587
5588
5589/*
5590 * Turn off standout mode
5591 */
5592 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005593standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005594{
5595 if (g_attrPreStandout)
5596 {
5597 textattr(g_attrPreStandout);
5598 g_attrPreStandout = 0;
5599 }
5600}
5601
5602
5603/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005604 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005605 */
5606 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005607mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005608{
5609 char_u *p;
5610 int n;
5611
5612 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5613 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5614 if (T_ME[0] == ESC && T_ME[1] == '|')
5615 {
5616 p = T_ME + 2;
5617 n = getdigits(&p);
5618 if (*p == 'm' && n > 0)
5619 {
5620 cterm_normal_fg_color = (n & 0xf) + 1;
5621 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5622 }
5623 }
5624}
5625
5626
5627/*
5628 * visual bell: flash the screen
5629 */
5630 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005631visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005632{
5633 COORD coordOrigin = {0, 0};
5634 WORD attrFlash = ~g_attrCurrent & 0xff;
5635
5636 DWORD dwDummy;
5637 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5638
5639 if (oldattrs == NULL)
5640 return;
5641 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5642 coordOrigin, &dwDummy);
5643 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5644 coordOrigin, &dwDummy);
5645
5646 Sleep(15); /* wait for 15 msec */
5647 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5648 coordOrigin, &dwDummy);
5649 vim_free(oldattrs);
5650}
5651
5652
5653/*
5654 * Make the cursor visible or invisible
5655 */
5656 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005657cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005658{
5659 s_cursor_visible = fVisible;
5660#ifdef MCH_CURSOR_SHAPE
5661 mch_update_cursor();
5662#endif
5663}
5664
5665
5666/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005667 * write `cbToWrite' bytes in `pchBuf' to the screen
5668 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005669 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005670 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005671write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005672 char_u *pchBuf,
5673 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005674{
5675 COORD coord = g_coord;
5676 DWORD written;
5677
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005678#ifdef FEAT_MBYTE
5679 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5680 {
5681 static WCHAR *unicodebuf = NULL;
5682 static int unibuflen = 0;
5683 int length;
5684 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005685
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005686 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5687 if (unicodebuf == NULL || length > unibuflen)
5688 {
5689 vim_free(unicodebuf);
5690 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5691 unibuflen = length;
5692 }
5693 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5694 unicodebuf, unibuflen);
5695
5696 cells = mb_string2cells(pchBuf, cbToWrite);
5697 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5698 coord, &written);
5699 /* When writing fails or didn't write a single character, pretend one
5700 * character was written, otherwise we get stuck. */
5701 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5702 coord, &cchwritten) == 0
5703 || cchwritten == 0)
5704 cchwritten = 1;
5705
5706 if (cchwritten == length)
5707 {
5708 written = cbToWrite;
5709 g_coord.X += (SHORT)cells;
5710 }
5711 else
5712 {
5713 char_u *p = pchBuf;
5714 for (n = 0; n < cchwritten; n++)
5715 mb_cptr_adv(p);
5716 written = p - pchBuf;
5717 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5718 }
5719 }
5720 else
5721#endif
5722 {
5723 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5724 coord, &written);
5725 /* When writing fails or didn't write a single character, pretend one
5726 * character was written, otherwise we get stuck. */
5727 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5728 coord, &written) == 0
5729 || written == 0)
5730 written = 1;
5731
5732 g_coord.X += (SHORT) written;
5733 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005734
5735 while (g_coord.X > g_srScrollRegion.Right)
5736 {
5737 g_coord.X -= (SHORT) Columns;
5738 if (g_coord.Y < g_srScrollRegion.Bottom)
5739 g_coord.Y++;
5740 }
5741
5742 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5743
5744 return written;
5745}
5746
5747
5748/*
5749 * mch_write(): write the output buffer to the screen, translating ESC
5750 * sequences into calls to console output routines.
5751 */
5752 void
5753mch_write(
5754 char_u *s,
5755 int len)
5756{
5757 s[len] = NUL;
5758
5759 if (!term_console)
5760 {
5761 write(1, s, (unsigned)len);
5762 return;
5763 }
5764
5765 /* translate ESC | sequences into faked bios calls */
5766 while (len--)
5767 {
5768 /* optimization: use one single write_chars for runs of text,
5769 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005770 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005771
5772 if (p_wd)
5773 {
5774 WaitForChar(p_wd);
5775 if (prefix != 0)
5776 prefix = 1;
5777 }
5778
5779 if (prefix != 0)
5780 {
5781 DWORD nWritten;
5782
5783 nWritten = write_chars(s, prefix);
5784#ifdef MCH_WRITE_DUMP
5785 if (fdDump)
5786 {
5787 fputc('>', fdDump);
5788 fwrite(s, sizeof(char_u), nWritten, fdDump);
5789 fputs("<\n", fdDump);
5790 }
5791#endif
5792 len -= (nWritten - 1);
5793 s += nWritten;
5794 }
5795 else if (s[0] == '\n')
5796 {
5797 /* \n, newline: go to the beginning of the next line or scroll */
5798 if (g_coord.Y == g_srScrollRegion.Bottom)
5799 {
5800 scroll(1);
5801 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5802 }
5803 else
5804 {
5805 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5806 }
5807#ifdef MCH_WRITE_DUMP
5808 if (fdDump)
5809 fputs("\\n\n", fdDump);
5810#endif
5811 s++;
5812 }
5813 else if (s[0] == '\r')
5814 {
5815 /* \r, carriage return: go to beginning of line */
5816 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5817#ifdef MCH_WRITE_DUMP
5818 if (fdDump)
5819 fputs("\\r\n", fdDump);
5820#endif
5821 s++;
5822 }
5823 else if (s[0] == '\b')
5824 {
5825 /* \b, backspace: move cursor one position left */
5826 if (g_coord.X > g_srScrollRegion.Left)
5827 g_coord.X--;
5828 else if (g_coord.Y > g_srScrollRegion.Top)
5829 {
5830 g_coord.X = g_srScrollRegion.Right;
5831 g_coord.Y--;
5832 }
5833 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5834#ifdef MCH_WRITE_DUMP
5835 if (fdDump)
5836 fputs("\\b\n", fdDump);
5837#endif
5838 s++;
5839 }
5840 else if (s[0] == '\a')
5841 {
5842 /* \a, bell */
5843 MessageBeep(0xFFFFFFFF);
5844#ifdef MCH_WRITE_DUMP
5845 if (fdDump)
5846 fputs("\\a\n", fdDump);
5847#endif
5848 s++;
5849 }
5850 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5851 {
5852#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005853 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005854#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005855 char_u *p;
5856 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005857
5858 switch (s[2])
5859 {
5860 /* one or two numeric arguments, separated by ';' */
5861
5862 case '0': case '1': case '2': case '3': case '4':
5863 case '5': case '6': case '7': case '8': case '9':
5864 p = s + 2;
5865 arg1 = getdigits(&p); /* no check for length! */
5866 if (p > s + len)
5867 break;
5868
5869 if (*p == ';')
5870 {
5871 ++p;
5872 arg2 = getdigits(&p); /* no check for length! */
5873 if (p > s + len)
5874 break;
5875
5876 if (*p == 'H')
5877 gotoxy(arg2, arg1);
5878 else if (*p == 'r')
5879 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5880 }
5881 else if (*p == 'A')
5882 {
5883 /* move cursor up arg1 lines in same column */
5884 gotoxy(g_coord.X + 1,
5885 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5886 }
5887 else if (*p == 'C')
5888 {
5889 /* move cursor right arg1 columns in same line */
5890 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5891 g_coord.Y + 1);
5892 }
5893 else if (*p == 'H')
5894 {
5895 gotoxy(1, arg1);
5896 }
5897 else if (*p == 'L')
5898 {
5899 insert_lines(arg1);
5900 }
5901 else if (*p == 'm')
5902 {
5903 if (arg1 == 0)
5904 normvideo();
5905 else
5906 textattr((WORD) arg1);
5907 }
5908 else if (*p == 'f')
5909 {
5910 textcolor((WORD) arg1);
5911 }
5912 else if (*p == 'b')
5913 {
5914 textbackground((WORD) arg1);
5915 }
5916 else if (*p == 'M')
5917 {
5918 delete_lines(arg1);
5919 }
5920
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005921 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005922 s = p + 1;
5923 break;
5924
5925
5926 /* Three-character escape sequences */
5927
5928 case 'A':
5929 /* move cursor up one line in same column */
5930 gotoxy(g_coord.X + 1,
5931 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5932 goto got3;
5933
5934 case 'B':
5935 visual_bell();
5936 goto got3;
5937
5938 case 'C':
5939 /* move cursor right one column in same line */
5940 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5941 g_coord.Y + 1);
5942 goto got3;
5943
5944 case 'E':
5945 termcap_mode_end();
5946 goto got3;
5947
5948 case 'F':
5949 standout();
5950 goto got3;
5951
5952 case 'f':
5953 standend();
5954 goto got3;
5955
5956 case 'H':
5957 gotoxy(1, 1);
5958 goto got3;
5959
5960 case 'j':
5961 clear_to_end_of_display();
5962 goto got3;
5963
5964 case 'J':
5965 clear_screen();
5966 goto got3;
5967
5968 case 'K':
5969 clear_to_end_of_line();
5970 goto got3;
5971
5972 case 'L':
5973 insert_lines(1);
5974 goto got3;
5975
5976 case 'M':
5977 delete_lines(1);
5978 goto got3;
5979
5980 case 'S':
5981 termcap_mode_start();
5982 goto got3;
5983
5984 case 'V':
5985 cursor_visible(TRUE);
5986 goto got3;
5987
5988 case 'v':
5989 cursor_visible(FALSE);
5990 goto got3;
5991
5992 got3:
5993 s += 3;
5994 len -= 2;
5995 }
5996
5997#ifdef MCH_WRITE_DUMP
5998 if (fdDump)
5999 {
6000 fputs("ESC | ", fdDump);
6001 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6002 fputc('\n', fdDump);
6003 }
6004#endif
6005 }
6006 else
6007 {
6008 /* Write a single character */
6009 DWORD nWritten;
6010
6011 nWritten = write_chars(s, 1);
6012#ifdef MCH_WRITE_DUMP
6013 if (fdDump)
6014 {
6015 fputc('>', fdDump);
6016 fwrite(s, sizeof(char_u), nWritten, fdDump);
6017 fputs("<\n", fdDump);
6018 }
6019#endif
6020
6021 len -= (nWritten - 1);
6022 s += nWritten;
6023 }
6024 }
6025
6026#ifdef MCH_WRITE_DUMP
6027 if (fdDump)
6028 fflush(fdDump);
6029#endif
6030}
6031
6032#endif /* FEAT_GUI_W32 */
6033
6034
6035/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006036 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006037 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006038/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00006039 void
6040mch_delay(
6041 long msec,
6042 int ignoreinput)
6043{
6044#ifdef FEAT_GUI_W32
6045 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006046#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006047 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006048# ifdef FEAT_MZSCHEME
6049 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6050 {
6051 int towait = p_mzq;
6052
6053 /* if msec is large enough, wait by portions in p_mzq */
6054 while (msec > 0)
6055 {
6056 mzvim_check_threads();
6057 if (msec < towait)
6058 towait = msec;
6059 Sleep(towait);
6060 msec -= towait;
6061 }
6062 }
6063 else
6064# endif
6065 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006066 else
6067 WaitForChar(msec);
6068#endif
6069}
6070
6071
6072/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006073 * This version of remove is not scared by a readonly (backup) file.
6074 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006075 * Return 0 for success, -1 for failure.
6076 */
6077 int
6078mch_remove(char_u *name)
6079{
6080#ifdef FEAT_MBYTE
6081 WCHAR *wn = NULL;
6082 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006083#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006084
Bram Moolenaar203258c2016-01-17 22:15:16 +01006085 /*
6086 * On Windows, deleting a directory's symbolic link is done by
6087 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6088 */
6089 if (mch_isdir(name) && mch_is_symbolic_link(name))
6090 return mch_rmdir(name);
6091
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006092 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6093
6094#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006095 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6096 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006097 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006098 if (wn != NULL)
6099 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006100 n = DeleteFileW(wn) ? 0 : -1;
6101 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006102 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006103 }
6104 }
6105#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006106 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006107}
6108
6109
6110/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006111 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006112 */
6113 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006114mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006115{
6116#ifndef FEAT_GUI_W32 /* never used */
6117 if (g_fCtrlCPressed || g_fCBrkPressed)
6118 {
6119 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6120 got_int = TRUE;
6121 }
6122#endif
6123}
6124
Bram Moolenaaree273972016-01-02 21:11:51 +01006125/* physical RAM to leave for the OS */
6126#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006127
6128/*
6129 * How much main memory in KiB that can be used by VIM.
6130 */
6131/*ARGSUSED*/
6132 long_u
6133mch_total_mem(int special)
6134{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006135 MEMORYSTATUSEX ms;
6136
Bram Moolenaaree273972016-01-02 21:11:51 +01006137 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006138 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6139 * what fits in 32 bits. But it's not always available. */
6140 ms.dwLength = sizeof(MEMORYSTATUSEX);
6141 GlobalMemoryStatusEx(&ms);
6142 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006143 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006144 /* Process address space fits in physical RAM, use all of it. */
6145 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006146 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006147 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006148 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006149 /* Catch old NT box or perverse hardware setup. */
6150 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006151 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006152 /* Use physical RAM less reserve for OS + data. */
6153 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006154}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006155
Bram Moolenaar071d4272004-06-13 20:20:40 +00006156#ifdef FEAT_MBYTE
6157/*
6158 * Same code as below, but with wide functions and no comments.
6159 * Return 0 for success, non-zero for failure.
6160 */
6161 int
6162mch_wrename(WCHAR *wold, WCHAR *wnew)
6163{
6164 WCHAR *p;
6165 int i;
6166 WCHAR szTempFile[_MAX_PATH + 1];
6167 WCHAR szNewPath[_MAX_PATH + 1];
6168 HANDLE hf;
6169
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006170 p = wold;
6171 for (i = 0; wold[i] != NUL; ++i)
6172 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6173 && wold[i + 1] != 0)
6174 p = wold + i + 1;
6175 if ((int)(wold + i - p) < 8 || p[6] != '~')
6176 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006177
6178 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6179 return -1;
6180 *p = NUL;
6181
6182 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6183 return -2;
6184
6185 if (!DeleteFileW(szTempFile))
6186 return -3;
6187
6188 if (!MoveFileW(wold, szTempFile))
6189 return -4;
6190
6191 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6192 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6193 return -5;
6194 if (!CloseHandle(hf))
6195 return -6;
6196
6197 if (!MoveFileW(szTempFile, wnew))
6198 {
6199 (void)MoveFileW(szTempFile, wold);
6200 return -7;
6201 }
6202
6203 DeleteFileW(szTempFile);
6204
6205 if (!DeleteFileW(wold))
6206 return -8;
6207
6208 return 0;
6209}
6210#endif
6211
6212
6213/*
6214 * mch_rename() works around a bug in rename (aka MoveFile) in
6215 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6216 * file whose short file name is "FOO.BAR" (its long file name will
6217 * be correct: "foo.bar~"). Because a file can be accessed by
6218 * either its SFN or its LFN, "foo.bar" has effectively been
6219 * renamed to "foo.bar", which is not at all what was wanted. This
6220 * seems to happen only when renaming files with three-character
6221 * extensions by appending a suffix that does not include ".".
6222 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6223 *
6224 * There is another problem, which isn't really a bug but isn't right either:
6225 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6226 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6227 * service pack 6. Doesn't seem to happen on Windows 98.
6228 *
6229 * Like rename(), returns 0 upon success, non-zero upon failure.
6230 * Should probably set errno appropriately when errors occur.
6231 */
6232 int
6233mch_rename(
6234 const char *pszOldFile,
6235 const char *pszNewFile)
6236{
6237 char szTempFile[_MAX_PATH+1];
6238 char szNewPath[_MAX_PATH+1];
6239 char *pszFilePart;
6240 HANDLE hf;
6241#ifdef FEAT_MBYTE
6242 WCHAR *wold = NULL;
6243 WCHAR *wnew = NULL;
6244 int retval = -1;
6245
6246 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6247 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006248 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6249 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006250 if (wold != NULL && wnew != NULL)
6251 retval = mch_wrename(wold, wnew);
6252 vim_free(wold);
6253 vim_free(wnew);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006254 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006255 }
6256#endif
6257
6258 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006259 * No need to play tricks unless the file name contains a "~" as the
6260 * seventh character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006261 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006262 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6263 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6264 return rename(pszOldFile, pszNewFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006265
6266 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6267 * a directory, no error is returned and pszFilePart will be NULL. */
6268 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6269 || pszFilePart == NULL)
6270 return -1;
6271 *pszFilePart = NUL;
6272
6273 /* Get (and create) a unique temporary file name in directory of new file */
6274 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6275 return -2;
6276
6277 /* blow the temp file away */
6278 if (!DeleteFile(szTempFile))
6279 return -3;
6280
6281 /* rename old file to the temp file */
6282 if (!MoveFile(pszOldFile, szTempFile))
6283 return -4;
6284
6285 /* now create an empty file called pszOldFile; this prevents the operating
6286 * system using pszOldFile as an alias (SFN) if we're renaming within the
6287 * same directory. For example, we're editing a file called
6288 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6289 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6290 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006291 * cause all sorts of problems later in buf_write(). So, we create an
6292 * empty file called filena~1.txt and the system will have to find some
6293 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006294 */
6295 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6296 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6297 return -5;
6298 if (!CloseHandle(hf))
6299 return -6;
6300
6301 /* rename the temp file to the new file */
6302 if (!MoveFile(szTempFile, pszNewFile))
6303 {
6304 /* Renaming failed. Rename the file back to its old name, so that it
6305 * looks like nothing happened. */
6306 (void)MoveFile(szTempFile, pszOldFile);
6307
6308 return -7;
6309 }
6310
6311 /* Seems to be left around on Novell filesystems */
6312 DeleteFile(szTempFile);
6313
6314 /* finally, remove the empty old file */
6315 if (!DeleteFile(pszOldFile))
6316 return -8;
6317
6318 return 0; /* success */
6319}
6320
6321/*
6322 * Get the default shell for the current hardware platform
6323 */
6324 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006325default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006326{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006327 PlatformId();
6328
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006329 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006330}
6331
6332/*
6333 * mch_access() extends access() to do more detailed check on network drives.
6334 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6335 */
6336 int
6337mch_access(char *n, int p)
6338{
6339 HANDLE hFile;
6340 DWORD am;
6341 int retval = -1; /* default: fail */
6342#ifdef FEAT_MBYTE
6343 WCHAR *wn = NULL;
6344
6345 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006346 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006347#endif
6348
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006349 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006350 {
6351 char TempName[_MAX_PATH + 16] = "";
6352#ifdef FEAT_MBYTE
6353 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6354#endif
6355
6356 if (p & R_OK)
6357 {
6358 /* Read check is performed by seeing if we can do a find file on
6359 * the directory for any file. */
6360#ifdef FEAT_MBYTE
6361 if (wn != NULL)
6362 {
6363 int i;
6364 WIN32_FIND_DATAW d;
6365
6366 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6367 TempNameW[i] = wn[i];
6368 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6369 TempNameW[i++] = '\\';
6370 TempNameW[i++] = '*';
6371 TempNameW[i++] = 0;
6372
6373 hFile = FindFirstFileW(TempNameW, &d);
6374 if (hFile == INVALID_HANDLE_VALUE)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006375 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006376 else
6377 (void)FindClose(hFile);
6378 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006379 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006380#endif
6381 {
6382 char *pch;
6383 WIN32_FIND_DATA d;
6384
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006385 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006386 pch = TempName + STRLEN(TempName) - 1;
6387 if (*pch != '\\' && *pch != '/')
6388 *++pch = '\\';
6389 *++pch = '*';
6390 *++pch = NUL;
6391
6392 hFile = FindFirstFile(TempName, &d);
6393 if (hFile == INVALID_HANDLE_VALUE)
6394 goto getout;
6395 (void)FindClose(hFile);
6396 }
6397 }
6398
6399 if (p & W_OK)
6400 {
6401 /* Trying to create a temporary file in the directory should catch
6402 * directories on read-only network shares. However, in
6403 * directories whose ACL allows writes but denies deletes will end
6404 * up keeping the temporary file :-(. */
6405#ifdef FEAT_MBYTE
6406 if (wn != NULL)
6407 {
6408 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006409 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006410 else
6411 DeleteFileW(TempNameW);
6412 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006413 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006414#endif
6415 {
6416 if (!GetTempFileName(n, "VIM", 0, TempName))
6417 goto getout;
6418 mch_remove((char_u *)TempName);
6419 }
6420 }
6421 }
6422 else
6423 {
6424 /* Trying to open the file for the required access does ACL, read-only
6425 * network share, and file attribute checks. */
6426 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6427 | ((p & R_OK) ? GENERIC_READ : 0);
6428#ifdef FEAT_MBYTE
6429 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006430 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006431 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006432#endif
6433 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6434 if (hFile == INVALID_HANDLE_VALUE)
6435 goto getout;
6436 CloseHandle(hFile);
6437 }
6438
6439 retval = 0; /* success */
6440getout:
6441#ifdef FEAT_MBYTE
6442 vim_free(wn);
6443#endif
6444 return retval;
6445}
6446
6447#if defined(FEAT_MBYTE) || defined(PROTO)
6448/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006449 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006450 */
6451 int
6452mch_open(char *name, int flags, int mode)
6453{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006454 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6455# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006456 WCHAR *wn;
6457 int f;
6458
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006459 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006460 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006461 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006462 if (wn != NULL)
6463 {
6464 f = _wopen(wn, flags, mode);
6465 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006466 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006467 }
6468 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006469# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006470
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006471 /* open() can open a file which name is longer than _MAX_PATH bytes
6472 * and shorter than _MAX_PATH characters successfully, but sometimes it
6473 * causes unexpected error in another part. We make it an error explicitly
6474 * here. */
6475 if (strlen(name) >= _MAX_PATH)
6476 return -1;
6477
Bram Moolenaar071d4272004-06-13 20:20:40 +00006478 return open(name, flags, mode);
6479}
6480
6481/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006482 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006483 */
6484 FILE *
6485mch_fopen(char *name, char *mode)
6486{
6487 WCHAR *wn, *wm;
6488 FILE *f = NULL;
6489
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006490 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006491 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006492# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006493 /* Work around an annoying assertion in the Microsoft debug CRT
6494 * when mode's text/binary setting doesn't match _get_fmode(). */
6495 char newMode = mode[strlen(mode) - 1];
6496 int oldMode = 0;
6497
6498 _get_fmode(&oldMode);
6499 if (newMode == 't')
6500 _set_fmode(_O_TEXT);
6501 else if (newMode == 'b')
6502 _set_fmode(_O_BINARY);
6503# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006504 wn = enc_to_utf16((char_u *)name, NULL);
6505 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006506 if (wn != NULL && wm != NULL)
6507 f = _wfopen(wn, wm);
6508 vim_free(wn);
6509 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006510
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006511# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006512 _set_fmode(oldMode);
6513# endif
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006514 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006515 }
6516
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006517 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6518 * and shorter than _MAX_PATH characters successfully, but sometimes it
6519 * causes unexpected error in another part. We make it an error explicitly
6520 * here. */
6521 if (strlen(name) >= _MAX_PATH)
6522 return NULL;
6523
Bram Moolenaar071d4272004-06-13 20:20:40 +00006524 return fopen(name, mode);
6525}
6526#endif
6527
6528#ifdef FEAT_MBYTE
6529/*
6530 * SUB STREAM (aka info stream) handling:
6531 *
6532 * NTFS can have sub streams for each file. Normal contents of file is
6533 * stored in the main stream, and extra contents (author information and
6534 * title and so on) can be stored in sub stream. After Windows 2000, user
6535 * can access and store those informations in sub streams via explorer's
6536 * property menuitem in right click menu. Those informations in sub streams
6537 * were lost when copying only the main stream. So we have to copy sub
6538 * streams.
6539 *
6540 * Incomplete explanation:
6541 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6542 * More useful info and an example:
6543 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6544 */
6545
6546/*
6547 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6548 * and write to stream "substream" of file "to".
6549 * Errors are ignored.
6550 */
6551 static void
6552copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6553{
6554 HANDLE hTo;
6555 WCHAR *to_name;
6556
6557 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6558 wcscpy(to_name, to);
6559 wcscat(to_name, substream);
6560
6561 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6562 FILE_ATTRIBUTE_NORMAL, NULL);
6563 if (hTo != INVALID_HANDLE_VALUE)
6564 {
6565 long done;
6566 DWORD todo;
6567 DWORD readcnt, written;
6568 char buf[4096];
6569
6570 /* Copy block of bytes at a time. Abort when something goes wrong. */
6571 for (done = 0; done < len; done += written)
6572 {
6573 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006574 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6575 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006576 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6577 FALSE, FALSE, context)
6578 || readcnt != todo
6579 || !WriteFile(hTo, buf, todo, &written, NULL)
6580 || written != todo)
6581 break;
6582 }
6583 CloseHandle(hTo);
6584 }
6585
6586 free(to_name);
6587}
6588
6589/*
6590 * Copy info streams from file "from" to file "to".
6591 */
6592 static void
6593copy_infostreams(char_u *from, char_u *to)
6594{
6595 WCHAR *fromw;
6596 WCHAR *tow;
6597 HANDLE sh;
6598 WIN32_STREAM_ID sid;
6599 int headersize;
6600 WCHAR streamname[_MAX_PATH];
6601 DWORD readcount;
6602 void *context = NULL;
6603 DWORD lo, hi;
6604 int len;
6605
6606 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006607 fromw = enc_to_utf16(from, NULL);
6608 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006609 if (fromw != NULL && tow != NULL)
6610 {
6611 /* Open the file for reading. */
6612 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6613 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6614 if (sh != INVALID_HANDLE_VALUE)
6615 {
6616 /* Use BackupRead() to find the info streams. Repeat until we
6617 * have done them all.*/
6618 for (;;)
6619 {
6620 /* Get the header to find the length of the stream name. If
6621 * the "readcount" is zero we have done all info streams. */
6622 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006623 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006624 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6625 &readcount, FALSE, FALSE, &context)
6626 || readcount == 0)
6627 break;
6628
6629 /* We only deal with streams that have a name. The normal
6630 * file data appears to be without a name, even though docs
6631 * suggest it is called "::$DATA". */
6632 if (sid.dwStreamNameSize > 0)
6633 {
6634 /* Read the stream name. */
6635 if (!BackupRead(sh, (LPBYTE)streamname,
6636 sid.dwStreamNameSize,
6637 &readcount, FALSE, FALSE, &context))
6638 break;
6639
6640 /* Copy an info stream with a name ":anything:$DATA".
6641 * Skip "::$DATA", it has no stream name (examples suggest
6642 * it might be used for the normal file contents).
6643 * Note that BackupRead() counts bytes, but the name is in
6644 * wide characters. */
6645 len = readcount / sizeof(WCHAR);
6646 streamname[len] = 0;
6647 if (len > 7 && wcsicmp(streamname + len - 6,
6648 L":$DATA") == 0)
6649 {
6650 streamname[len - 6] = 0;
6651 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006652 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006653 }
6654 }
6655
6656 /* Advance to the next stream. We might try seeking too far,
6657 * but BackupSeek() doesn't skip over stream borders, thus
6658 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006659 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006660 &lo, &hi, &context);
6661 }
6662
6663 /* Clear the context. */
6664 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6665
6666 CloseHandle(sh);
6667 }
6668 }
6669 vim_free(fromw);
6670 vim_free(tow);
6671}
6672#endif
6673
6674/*
6675 * Copy file attributes from file "from" to file "to".
6676 * For Windows NT and later we copy info streams.
6677 * Always returns zero, errors are ignored.
6678 */
6679 int
6680mch_copy_file_attribute(char_u *from, char_u *to)
6681{
6682#ifdef FEAT_MBYTE
6683 /* File streams only work on Windows NT and later. */
6684 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006685 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006686#endif
6687 return 0;
6688}
6689
6690#if defined(MYRESETSTKOFLW) || defined(PROTO)
6691/*
6692 * Recreate a destroyed stack guard page in win32.
6693 * Written by Benjamin Peterson.
6694 */
6695
6696/* These magic numbers are from the MS header files */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006697#define MIN_STACK_WINNT 2
6698
6699/*
6700 * This function does the same thing as _resetstkoflw(), which is only
6701 * available in DevStudio .net and later.
6702 * Returns 0 for failure, 1 for success.
6703 */
6704 int
6705myresetstkoflw(void)
6706{
6707 BYTE *pStackPtr;
6708 BYTE *pGuardPage;
6709 BYTE *pStackBase;
6710 BYTE *pLowestPossiblePage;
6711 MEMORY_BASIC_INFORMATION mbi;
6712 SYSTEM_INFO si;
6713 DWORD nPageSize;
6714 DWORD dummy;
6715
Bram Moolenaar071d4272004-06-13 20:20:40 +00006716 PlatformId();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006717
6718 /* We need to know the system page size. */
6719 GetSystemInfo(&si);
6720 nPageSize = si.dwPageSize;
6721
6722 /* ...and the current stack pointer */
6723 pStackPtr = (BYTE*)_alloca(1);
6724
6725 /* ...and the base of the stack. */
6726 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6727 return 0;
6728 pStackBase = (BYTE*)mbi.AllocationBase;
6729
6730 /* ...and the page thats min_stack_req pages away from stack base; this is
6731 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006732 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006733
Bram Moolenaar071d4272004-06-13 20:20:40 +00006734 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006735 /* We want the first committed page in the stack Start at the stack
6736 * base and move forward through memory until we find a committed block.
6737 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006738 BYTE *pBlock = pStackBase;
6739
Bram Moolenaara466c992005-07-09 21:03:22 +00006740 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006741 {
6742 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6743 return 0;
6744
6745 pBlock += mbi.RegionSize;
6746
6747 if (mbi.State & MEM_COMMIT)
6748 break;
6749 }
6750
6751 /* mbi now describes the first committed block in the stack. */
6752 if (mbi.Protect & PAGE_GUARD)
6753 return 1;
6754
6755 /* decide where the guard page should start */
6756 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6757 pGuardPage = pLowestPossiblePage;
6758 else
6759 pGuardPage = (BYTE*)mbi.BaseAddress;
6760
6761 /* allocate the guard page */
6762 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6763 return 0;
6764
6765 /* apply the guard attribute to the page */
6766 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6767 &dummy))
6768 return 0;
6769 }
6770
6771 return 1;
6772}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006773#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006774
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006775
6776#if defined(FEAT_MBYTE) || defined(PROTO)
6777/*
6778 * The command line arguments in UCS2
6779 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006780static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006781static LPWSTR *ArglistW = NULL;
6782static int global_argc = 0;
6783static char **global_argv;
6784
6785static int used_file_argc = 0; /* last argument in global_argv[] used
6786 for the argument list. */
6787static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6788 command line arguments added to
6789 the argument list */
6790static int used_file_count = 0; /* nr of entries in used_file_indexes */
6791static int used_file_literal = FALSE; /* take file names literally */
6792static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006793static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006794static int used_alist_count = 0;
6795
6796
6797/*
6798 * Get the command line arguments. Unicode version.
6799 * Returns argc. Zero when something fails.
6800 */
6801 int
6802get_cmd_argsW(char ***argvp)
6803{
6804 char **argv = NULL;
6805 int argc = 0;
6806 int i;
6807
Bram Moolenaar14993322014-09-09 12:25:33 +02006808 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006809 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6810 if (ArglistW != NULL)
6811 {
6812 argv = malloc((nArgsW + 1) * sizeof(char *));
6813 if (argv != NULL)
6814 {
6815 argc = nArgsW;
6816 argv[argc] = NULL;
6817 for (i = 0; i < argc; ++i)
6818 {
6819 int len;
6820
6821 /* Convert each Unicode argument to the current codepage. */
6822 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006823 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006824 (LPSTR *)&argv[i], &len, 0, 0);
6825 if (argv[i] == NULL)
6826 {
6827 /* Out of memory, clear everything. */
6828 while (i > 0)
6829 free(argv[--i]);
6830 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006831 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006832 argc = 0;
6833 }
6834 }
6835 }
6836 }
6837
6838 global_argc = argc;
6839 global_argv = argv;
6840 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006841 {
6842 if (used_file_indexes != NULL)
6843 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006844 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006845 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006846
6847 if (argvp != NULL)
6848 *argvp = argv;
6849 return argc;
6850}
6851
6852 void
6853free_cmd_argsW(void)
6854{
6855 if (ArglistW != NULL)
6856 {
6857 GlobalFree(ArglistW);
6858 ArglistW = NULL;
6859 }
6860}
6861
6862/*
6863 * Remember "name" is an argument that was added to the argument list.
6864 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6865 * is called.
6866 */
6867 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006868used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006869{
6870 int i;
6871
6872 if (used_file_indexes == NULL)
6873 return;
6874 for (i = used_file_argc + 1; i < global_argc; ++i)
6875 if (STRCMP(global_argv[i], name) == 0)
6876 {
6877 used_file_argc = i;
6878 used_file_indexes[used_file_count++] = i;
6879 break;
6880 }
6881 used_file_literal = literal;
6882 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006883 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006884}
6885
6886/*
6887 * Remember the length of the argument list as it was. If it changes then we
6888 * leave it alone when 'encoding' is set.
6889 */
6890 void
6891set_alist_count(void)
6892{
6893 used_alist_count = GARGCOUNT;
6894}
6895
6896/*
6897 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6898 * has been changed while starting up. Use the UCS-2 command line arguments
6899 * and convert them to 'encoding'.
6900 */
6901 void
6902fix_arg_enc(void)
6903{
6904 int i;
6905 int idx;
6906 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006907 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006908
6909 /* Safety checks:
6910 * - if argument count differs between the wide and non-wide argument
6911 * list, something must be wrong.
6912 * - the file name arguments must have been located.
6913 * - the length of the argument list wasn't changed by the user.
6914 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006915 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006916 || ArglistW == NULL
6917 || used_file_indexes == NULL
6918 || used_file_count == 0
6919 || used_alist_count != GARGCOUNT)
6920 return;
6921
Bram Moolenaar86b68352004-12-27 21:59:20 +00006922 /* Remember the buffer numbers for the arguments. */
6923 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6924 if (fnum_list == NULL)
6925 return; /* out of memory */
6926 for (i = 0; i < GARGCOUNT; ++i)
6927 fnum_list[i] = GARGLIST[i].ae_fnum;
6928
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006929 /* Clear the argument list. Make room for the new arguments. */
6930 alist_clear(&global_alist);
6931 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006932 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006933
6934 for (i = 0; i < used_file_count; ++i)
6935 {
6936 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006937 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006938 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006939 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006940#ifdef FEAT_DIFF
6941 /* When using diff mode may need to concatenate file name to
6942 * directory name. Just like it's done in main(). */
6943 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6944 && !mch_isdir(alist_name(&GARGLIST[0])))
6945 {
6946 char_u *r;
6947
6948 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6949 if (r != NULL)
6950 {
6951 vim_free(str);
6952 str = r;
6953 }
6954 }
6955#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006956 /* Re-use the old buffer by renaming it. When not using literal
6957 * names it's done by alist_expand() below. */
6958 if (used_file_literal)
6959 buf_set_name(fnum_list[i], str);
6960
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006961 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006962 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006963 }
6964
6965 if (!used_file_literal)
6966 {
6967 /* Now expand wildcards in the arguments. */
6968 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6969 * filename characters but are excluded from 'isfname' to make
6970 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6971 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006972 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006973 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6974 }
6975
6976 /* If wildcard expansion failed, we are editing the first file of the
6977 * arglist and there is no file name: Edit the first argument now. */
6978 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6979 {
6980 do_cmdline_cmd((char_u *)":rewind");
6981 if (GARGCOUNT == 1 && used_file_full_path)
6982 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6983 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006984
6985 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006986}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006987#endif